nir/lower_clip_cull: Fix an incorrect assert
[mesa.git] / src / intel / tools / imgui / imgui_memory_editor.h
1 // Mini memory editor for Dear ImGui (to embed in your game/tools)
2 // Animated GIF: https://twitter.com/ocornut/status/894242704317530112
3 // Get latest version at http://www.github.com/ocornut/imgui_club
4 //
5 // Right-click anywhere to access the Options menu!
6 // You can adjust the keyboard repeat delay/rate in ImGuiIO.
7 // The code assume a mono-space font for simplicity! If you don't use the default font, use ImGui::PushFont()/PopFont() to switch to a mono-space font before caling this.
8 //
9 // Usage:
10 // static MemoryEditor mem_edit_1; // store your state somewhere
11 // mem_edit_1.DrawWindow("Memory Editor", mem_block, mem_block_size, 0x0000); // create a window and draw memory editor (if you already have a window, use DrawContents())
12 //
13 // Usage:
14 // static MemoryEditor mem_edit_2;
15 // ImGui::Begin("MyWindow")
16 // mem_edit_2.DrawContents(this, sizeof(*this), (size_t)this);
17 // ImGui::End();
18 //
19 // Changelog:
20 // - v0.10: initial version
21 // - v0.11: always refresh active text input with the latest byte from source memory if it's not being edited.
22 // - v0.12: added OptMidRowsCount to allow extra spacing every XX rows.
23 // - v0.13: added optional ReadFn/WriteFn handlers to access memory via a function. various warning fixes for 64-bits.
24 // - v0.14: added GotoAddr member, added GotoAddrAndHighlight() and highlighting. fixed minor scrollbar glitch when resizing.
25 // - v0.15: added maximum window width. minor optimization.
26 // - v0.16: added OptGreyOutZeroes option. various sizing fixes when resizing using the "Rows" drag.
27 // - v0.17: added HighlightFn handler for optional non-contiguous highlighting.
28 // - v0.18: fixes for displaying 64-bits addresses, fixed mouse click gaps introduced in recent changes, cursor tracking scrolling fixes.
29 // - v0.19: fixed auto-focus of next byte leaving WantCaptureKeyboard=false for one frame. we now capture the keyboard during that transition.
30 // - v0.20: added options menu. added OptShowAscii checkbox. added optional HexII display. split Draw() in DrawWindow()/DrawContents(). fixing glyph width. refactoring/cleaning code.
31 // - v0.21: fixes for using DrawContents() in our own window. fixed HexII to actually be useful and not on the wrong side.
32 // - v0.22: clicking Ascii view select the byte in the Hex view. Ascii view highlight selection.
33 // - v0.23: fixed right-arrow triggering a byte write.
34 // - v0.24: changed DragInt("Rows" to use a %d data format (which is desirable since imgui 1.61).
35 // - v0.25: fixed wording: all occurrences of "Rows" renamed to "Columns".
36 // - v0.26: fixed clicking on hex region
37 // - v0.30: added data preview for common data types
38 //
39 // Todo/Bugs:
40 // - Arrows are being sent to the InputText() about to disappear which for LeftArrow makes the text cursor appear at position 1 for one frame.
41 // - Using InputText() is awkward and maybe overkill here, consider implementing something custom.
42
43 #pragma once
44 #include <stdio.h> // sprintf, scanf
45 #include <stdint.h> // uint8_t, etc.
46
47 #ifdef _MSC_VER
48 #define _PRISizeT "IX"
49 #define snprintf _snprintf
50 #else
51 #define _PRISizeT "zX"
52 #endif
53
54 struct MemoryEditor
55 {
56 typedef unsigned char u8;
57
58 enum DataType
59 {
60 DataType_S8,
61 DataType_U8,
62 DataType_S16,
63 DataType_U16,
64 DataType_S32,
65 DataType_U32,
66 DataType_S64,
67 DataType_U64,
68 DataType_Float,
69 DataType_Double,
70 DataType_COUNT
71 };
72
73 enum DataFormat
74 {
75 DataFormat_Bin = 0,
76 DataFormat_Dec = 1,
77 DataFormat_Hex = 2,
78 DataFormat_COUNT
79 };
80
81 // Settings
82 bool Open; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow
83 bool ReadOnly; // = false // set to true to disable any editing
84 int Cols; // = 16 //
85 bool OptShowDataPreview; // = false //
86 bool OptShowHexII; // = false //
87 bool OptShowAscii; // = true //
88 bool OptGreyOutZeroes; // = true //
89 int OptMidColsCount; // = 8 // set to 0 to disable extra spacing between every mid-cols
90 int OptAddrDigitsCount; // = 0 // number of addr digits to display (default calculated based on maximum displayed addr)
91 ImU32 HighlightColor; // // color of highlight
92 u8 (*ReadFn)(const u8* data, size_t off); // = NULL // optional handler to read bytes
93 void (*WriteFn)(u8* data, size_t off, u8 d); // = NULL // optional handler to write bytes
94 bool (*HighlightFn)(const u8* data, size_t off);//NULL // optional handler to return Highlight property (to support non-contiguous highlighting)
95
96 // State/Internals
97 bool ContentsWidthChanged;
98 size_t DataPreviewAddr;
99 size_t DataEditingAddr;
100 bool DataEditingTakeFocus;
101 char DataInputBuf[32];
102 char AddrInputBuf[32];
103 size_t GotoAddr;
104 size_t HighlightMin, HighlightMax;
105 int PreviewEndianess;
106 DataType PreviewDataType;
107
108 MemoryEditor()
109 {
110 // Settings
111 Open = true;
112 ReadOnly = false;
113 Cols = 16;
114 OptShowDataPreview = false;
115 OptShowHexII = false;
116 OptShowAscii = true;
117 OptGreyOutZeroes = true;
118 OptMidColsCount = 8;
119 OptAddrDigitsCount = 0;
120 HighlightColor = IM_COL32(255, 255, 255, 50);
121 ReadFn = NULL;
122 WriteFn = NULL;
123 HighlightFn = NULL;
124
125 // State/Internals
126 ContentsWidthChanged = false;
127 DataPreviewAddr = DataEditingAddr = (size_t)-1;
128 DataEditingTakeFocus = false;
129 memset(DataInputBuf, 0, sizeof(DataInputBuf));
130 memset(AddrInputBuf, 0, sizeof(AddrInputBuf));
131 GotoAddr = (size_t)-1;
132 HighlightMin = HighlightMax = (size_t)-1;
133 PreviewEndianess = 0;
134 PreviewDataType = DataType_S32;
135 }
136
137 void GotoAddrAndHighlight(size_t addr_min, size_t addr_max)
138 {
139 GotoAddr = addr_min;
140 HighlightMin = addr_min;
141 HighlightMax = addr_max;
142 }
143
144 struct Sizes
145 {
146 int AddrDigitsCount;
147 float LineHeight;
148 float GlyphWidth;
149 float HexCellWidth;
150 float SpacingBetweenMidCols;
151 float PosHexStart;
152 float PosHexEnd;
153 float PosAsciiStart;
154 float PosAsciiEnd;
155 float WindowWidth;
156 };
157
158 void CalcSizes(Sizes& s, size_t mem_size, size_t base_display_addr)
159 {
160 ImGuiStyle& style = ImGui::GetStyle();
161 s.AddrDigitsCount = OptAddrDigitsCount;
162 if (s.AddrDigitsCount == 0)
163 for (size_t n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
164 s.AddrDigitsCount++;
165 s.LineHeight = ImGui::GetTextLineHeight();
166 s.GlyphWidth = ImGui::CalcTextSize("F").x + 1; // We assume the font is mono-space
167 s.HexCellWidth = (float)(int)(s.GlyphWidth * 2.5f); // "FF " we include trailing space in the width to easily catch clicks everywhere
168 s.SpacingBetweenMidCols = (float)(int)(s.HexCellWidth * 0.25f); // Every OptMidColsCount columns we add a bit of extra spacing
169 s.PosHexStart = (s.AddrDigitsCount + 2) * s.GlyphWidth;
170 s.PosHexEnd = s.PosHexStart + (s.HexCellWidth * Cols);
171 s.PosAsciiStart = s.PosAsciiEnd = s.PosHexEnd;
172 if (OptShowAscii)
173 {
174 s.PosAsciiStart = s.PosHexEnd + s.GlyphWidth * 1;
175 if (OptMidColsCount > 0)
176 s.PosAsciiStart += ((Cols + OptMidColsCount - 1) / OptMidColsCount) * s.SpacingBetweenMidCols;
177 s.PosAsciiEnd = s.PosAsciiStart + Cols * s.GlyphWidth;
178 }
179 s.WindowWidth = s.PosAsciiEnd + style.ScrollbarSize + style.WindowPadding.x * 2 + s.GlyphWidth;
180 }
181
182 // Standalone Memory Editor window
183 void DrawWindow(const char* title, u8* mem_data, size_t mem_size, size_t base_display_addr = 0x0000)
184 {
185 Sizes s;
186 CalcSizes(s, mem_size, base_display_addr);
187 ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, 0.0f), ImVec2(s.WindowWidth, FLT_MAX));
188
189 Open = true;
190 if (ImGui::Begin(title, &Open, ImGuiWindowFlags_NoScrollbar))
191 {
192 if (ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) && ImGui::IsMouseClicked(1))
193 ImGui::OpenPopup("context");
194 DrawContents(mem_data, mem_size, base_display_addr);
195 if (ContentsWidthChanged)
196 {
197 CalcSizes(s, mem_size, base_display_addr);
198 ImGui::SetWindowSize(ImVec2(s.WindowWidth, ImGui::GetWindowSize().y));
199 }
200 }
201 ImGui::End();
202 }
203
204 // Memory Editor contents only
205 void DrawContents(u8* mem_data, size_t mem_size, size_t base_display_addr = 0x0000)
206 {
207 Sizes s;
208 CalcSizes(s, mem_size, base_display_addr);
209 ImGuiStyle& style = ImGui::GetStyle();
210
211 // We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window.
212 // This is used as a facility since our main click detection code doesn't assign an ActiveId so the click would normally be caught as a window-move.
213 const float height_separator = style.ItemSpacing.y;
214 float footer_height = height_separator + ImGui::GetFrameHeightWithSpacing() * 1;
215 if (OptShowDataPreview)
216 footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1 + ImGui::GetTextLineHeightWithSpacing() * 3;
217 ImGui::BeginChild("##scrolling", ImVec2(0, -footer_height), false, ImGuiWindowFlags_NoMove);
218 ImDrawList* draw_list = ImGui::GetWindowDrawList();
219
220 ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
221 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
222
223 const int line_total_count = (int)((mem_size + Cols - 1) / Cols);
224 ImGuiListClipper clipper(line_total_count, s.LineHeight);
225 const size_t visible_start_addr = clipper.DisplayStart * Cols;
226 const size_t visible_end_addr = clipper.DisplayEnd * Cols;
227
228 bool data_next = false;
229
230 if (ReadOnly || DataEditingAddr >= mem_size)
231 DataEditingAddr = (size_t)-1;
232 if (DataPreviewAddr >= mem_size)
233 DataPreviewAddr = (size_t)-1;
234
235 size_t preview_data_type_size = OptShowDataPreview ? DataTypeGetSize(PreviewDataType) : 0;
236
237 size_t data_editing_addr_backup = DataEditingAddr;
238 size_t data_editing_addr_next = (size_t)-1;
239 if (DataEditingAddr != (size_t)-1)
240 {
241 // Move cursor but only apply on next frame so scrolling with be synchronized (because currently we can't change the scrolling while the window is being rendered)
242 if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_UpArrow)) && DataEditingAddr >= (size_t)Cols) { data_editing_addr_next = DataEditingAddr - Cols; DataEditingTakeFocus = true; }
243 else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_DownArrow)) && DataEditingAddr < mem_size - Cols) { data_editing_addr_next = DataEditingAddr + Cols; DataEditingTakeFocus = true; }
244 else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_LeftArrow)) && DataEditingAddr > 0) { data_editing_addr_next = DataEditingAddr - 1; DataEditingTakeFocus = true; }
245 else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_RightArrow)) && DataEditingAddr < mem_size - 1) { data_editing_addr_next = DataEditingAddr + 1; DataEditingTakeFocus = true; }
246 }
247 if (data_editing_addr_next != (size_t)-1 && (data_editing_addr_next / Cols) != (data_editing_addr_backup / Cols))
248 {
249 // Track cursor movements
250 const int scroll_offset = ((int)(data_editing_addr_next / Cols) - (int)(data_editing_addr_backup / Cols));
251 const bool scroll_desired = (scroll_offset < 0 && data_editing_addr_next < visible_start_addr + Cols * 2) || (scroll_offset > 0 && data_editing_addr_next > visible_end_addr - Cols * 2);
252 if (scroll_desired)
253 ImGui::SetScrollY(ImGui::GetScrollY() + scroll_offset * s.LineHeight);
254 }
255
256 // Draw vertical separator
257 ImVec2 window_pos = ImGui::GetWindowPos();
258 if (OptShowAscii)
259 draw_list->AddLine(ImVec2(window_pos.x + s.PosAsciiStart - s.GlyphWidth, window_pos.y), ImVec2(window_pos.x + s.PosAsciiStart - s.GlyphWidth, window_pos.y + 9999), ImGui::GetColorU32(ImGuiCol_Border));
260
261 const ImU32 color_text = ImGui::GetColorU32(ImGuiCol_Text);
262 const ImU32 color_disabled = OptGreyOutZeroes ? ImGui::GetColorU32(ImGuiCol_TextDisabled) : color_text;
263
264 for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible lines
265 {
266 size_t addr = (size_t)(line_i * Cols);
267 ImGui::Text("%0*" _PRISizeT ": ", s.AddrDigitsCount, base_display_addr + addr);
268
269 // Draw Hexadecimal
270 for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
271 {
272 float byte_pos_x = s.PosHexStart + s.HexCellWidth * n;
273 if (OptMidColsCount > 0)
274 byte_pos_x += (n / OptMidColsCount) * s.SpacingBetweenMidCols;
275 ImGui::SameLine(byte_pos_x);
276
277 // Draw highlight
278 bool is_highlight_from_user_range = (addr >= HighlightMin && addr < HighlightMax);
279 bool is_highlight_from_user_func = (HighlightFn && HighlightFn(mem_data, addr));
280 bool is_highlight_from_preview = (addr >= DataPreviewAddr && addr < DataPreviewAddr + preview_data_type_size);
281 if (is_highlight_from_user_range || is_highlight_from_user_func || is_highlight_from_preview)
282 {
283 ImVec2 pos = ImGui::GetCursorScreenPos();
284 float highlight_width = s.GlyphWidth * 2;
285 bool is_next_byte_highlighted = (addr + 1 < mem_size) && ((HighlightMax != (size_t)-1 && addr + 1 < HighlightMax) || (HighlightFn && HighlightFn(mem_data, addr + 1)));
286 if (is_next_byte_highlighted || (n + 1 == Cols))
287 {
288 highlight_width = s.HexCellWidth;
289 if (OptMidColsCount > 0 && n > 0 && (n + 1) < Cols && ((n + 1) % OptMidColsCount) == 0)
290 highlight_width += s.SpacingBetweenMidCols;
291 }
292 draw_list->AddRectFilled(pos, ImVec2(pos.x + highlight_width, pos.y + s.LineHeight), HighlightColor);
293 }
294
295 if (DataEditingAddr == addr)
296 {
297 // Display text input on current byte
298 bool data_write = false;
299 ImGui::PushID((void*)addr);
300 if (DataEditingTakeFocus)
301 {
302 ImGui::SetKeyboardFocusHere();
303 ImGui::CaptureKeyboardFromApp(true);
304 sprintf(AddrInputBuf, "%0*" _PRISizeT, s.AddrDigitsCount, base_display_addr + addr);
305 sprintf(DataInputBuf, "%02X", ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
306 }
307 ImGui::PushItemWidth(s.GlyphWidth * 2);
308 struct UserData
309 {
310 // FIXME: We should have a way to retrieve the text edit cursor position more easily in the API, this is rather tedious. This is such a ugly mess we may be better off not using InputText() at all here.
311 static int Callback(ImGuiTextEditCallbackData* data)
312 {
313 UserData* user_data = (UserData*)data->UserData;
314 if (!data->HasSelection())
315 user_data->CursorPos = data->CursorPos;
316 if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen)
317 {
318 // When not editing a byte, always rewrite its content (this is a bit tricky, since InputText technically "owns" the master copy of the buffer we edit it in there)
319 data->DeleteChars(0, data->BufTextLen);
320 data->InsertChars(0, user_data->CurrentBufOverwrite);
321 data->SelectionStart = 0;
322 data->SelectionEnd = data->CursorPos = 2;
323 }
324 return 0;
325 }
326 char CurrentBufOverwrite[3]; // Input
327 int CursorPos; // Output
328 };
329 UserData user_data;
330 user_data.CursorPos = -1;
331 sprintf(user_data.CurrentBufOverwrite, "%02X", ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
332 ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoHorizontalScroll | ImGuiInputTextFlags_AlwaysInsertMode | ImGuiInputTextFlags_CallbackAlways;
333 if (ImGui::InputText("##data", DataInputBuf, 32, flags, UserData::Callback, &user_data))
334 data_write = data_next = true;
335 else if (!DataEditingTakeFocus && !ImGui::IsItemActive())
336 DataEditingAddr = data_editing_addr_next = (size_t)-1;
337 DataEditingTakeFocus = false;
338 ImGui::PopItemWidth();
339 if (user_data.CursorPos >= 2)
340 data_write = data_next = true;
341 if (data_editing_addr_next != (size_t)-1)
342 data_write = data_next = false;
343 int data_input_value;
344 if (data_write && sscanf(DataInputBuf, "%X", &data_input_value) == 1)
345 {
346 if (WriteFn)
347 WriteFn(mem_data, addr, (u8)data_input_value);
348 else
349 mem_data[addr] = (u8)data_input_value;
350 }
351 ImGui::PopID();
352 }
353 else
354 {
355 // NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on.
356 u8 b = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
357
358 if (OptShowHexII)
359 {
360 if ((b >= 32 && b < 128))
361 ImGui::Text(".%c ", b);
362 else if (b == 0xFF && OptGreyOutZeroes)
363 ImGui::TextDisabled("## ");
364 else if (b == 0x00)
365 ImGui::Text(" ");
366 else
367 ImGui::Text("%02X ", b);
368 }
369 else
370 {
371 if (b == 0 && OptGreyOutZeroes)
372 ImGui::TextDisabled("00 ");
373 else
374 ImGui::Text("%02X ", b);
375 }
376 if (!ReadOnly && ImGui::IsItemHovered() && ImGui::IsMouseClicked(0))
377 {
378 DataEditingTakeFocus = true;
379 data_editing_addr_next = addr;
380 }
381 }
382 }
383
384 if (OptShowAscii)
385 {
386 // Draw ASCII values
387 ImGui::SameLine(s.PosAsciiStart);
388 ImVec2 pos = ImGui::GetCursorScreenPos();
389 addr = line_i * Cols;
390 ImGui::PushID(line_i);
391 if (ImGui::InvisibleButton("ascii", ImVec2(s.PosAsciiEnd - s.PosAsciiStart, s.LineHeight)))
392 {
393 DataEditingAddr = DataPreviewAddr = addr + (size_t)((ImGui::GetIO().MousePos.x - pos.x) / s.GlyphWidth);
394 DataEditingTakeFocus = true;
395 }
396 ImGui::PopID();
397 for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
398 {
399 if (addr == DataEditingAddr)
400 {
401 draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_FrameBg));
402 draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_TextSelectedBg));
403 }
404 unsigned char c = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
405 char display_c = (c < 32 || c >= 128) ? '.' : c;
406 draw_list->AddText(pos, (display_c == '.') ? color_disabled : color_text, &display_c, &display_c + 1);
407 pos.x += s.GlyphWidth;
408 }
409 }
410 }
411 clipper.End();
412 ImGui::PopStyleVar(2);
413 ImGui::EndChild();
414
415 if (data_next && DataEditingAddr < mem_size)
416 {
417 DataEditingAddr = DataPreviewAddr = DataEditingAddr + 1;
418 DataEditingTakeFocus = true;
419 }
420 else if (data_editing_addr_next != (size_t)-1)
421 {
422 DataEditingAddr = DataPreviewAddr = data_editing_addr_next;
423 }
424
425 ImGui::Separator();
426
427 // Options menu
428
429 bool next_show_data_preview = OptShowDataPreview;
430 if (ImGui::Button("Options"))
431 ImGui::OpenPopup("context");
432 if (ImGui::BeginPopup("context"))
433 {
434 ImGui::PushItemWidth(56);
435 if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; }
436 ImGui::PopItemWidth();
437 ImGui::Checkbox("Show Data Preview", &next_show_data_preview);
438 ImGui::Checkbox("Show HexII", &OptShowHexII);
439 if (ImGui::Checkbox("Show Ascii", &OptShowAscii)) { ContentsWidthChanged = true; }
440 ImGui::Checkbox("Grey out zeroes", &OptGreyOutZeroes);
441
442 ImGui::EndPopup();
443 }
444
445 ImGui::SameLine();
446 ImGui::Text("Range %0*" _PRISizeT "..%0*" _PRISizeT, s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1);
447 ImGui::SameLine();
448 ImGui::PushItemWidth((s.AddrDigitsCount + 1) * s.GlyphWidth + style.FramePadding.x * 2.0f);
449 if (ImGui::InputText("##addr", AddrInputBuf, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue))
450 {
451 size_t goto_addr;
452 if (sscanf(AddrInputBuf, "%" _PRISizeT, &goto_addr) == 1)
453 {
454 GotoAddr = goto_addr - base_display_addr;
455 HighlightMin = HighlightMax = (size_t)-1;
456 }
457 }
458 ImGui::PopItemWidth();
459
460 if (GotoAddr != (size_t)-1)
461 {
462 if (GotoAddr < mem_size)
463 {
464 ImGui::BeginChild("##scrolling");
465 ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + (GotoAddr / Cols) * ImGui::GetTextLineHeight());
466 ImGui::EndChild();
467 DataEditingAddr = DataPreviewAddr = GotoAddr;
468 DataEditingTakeFocus = true;
469 }
470 GotoAddr = (size_t)-1;
471 }
472
473 if (OptShowDataPreview)
474 {
475 ImGui::Separator();
476 ImGui::AlignTextToFramePadding();
477 ImGui::Text("Preview as:");
478 ImGui::SameLine();
479 ImGui::PushItemWidth((s.GlyphWidth * 10.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
480 if (ImGui::BeginCombo("##combo_type", DataTypeGetDesc(PreviewDataType), ImGuiComboFlags_HeightLargest))
481 {
482 for (int n = 0; n < DataType_COUNT; n++)
483 if (ImGui::Selectable(DataTypeGetDesc((DataType)n), PreviewDataType == n))
484 PreviewDataType = (DataType)n;
485 ImGui::EndCombo();
486 }
487 ImGui::PopItemWidth();
488 ImGui::SameLine();
489 ImGui::PushItemWidth((s.GlyphWidth * 6.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
490 ImGui::Combo("##combo_endianess", &PreviewEndianess, "LE\0BE\0\0");
491 ImGui::PopItemWidth();
492
493 char buf[128];
494 float x = s.GlyphWidth * 6.0f;
495 bool has_value = DataPreviewAddr != (size_t)-1;
496 if (has_value)
497 DisplayPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Dec, buf, (size_t)IM_ARRAYSIZE(buf));
498 ImGui::Text("Dec"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
499 if (has_value)
500 DisplayPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Hex, buf, (size_t)IM_ARRAYSIZE(buf));
501 ImGui::Text("Hex"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
502 if (has_value)
503 DisplayPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Bin, buf, (size_t)IM_ARRAYSIZE(buf));
504 ImGui::Text("Bin"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
505 }
506
507 OptShowDataPreview = next_show_data_preview;
508
509 // Notify the main window of our ideal child content size (FIXME: we are missing an API to get the contents size from the child)
510 ImGui::SetCursorPosX(s.WindowWidth);
511 }
512
513 // Utilities for Data Preview
514 const char* DataTypeGetDesc(DataType data_type) const
515 {
516 const char* descs[] = { "Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64", "Float", "Double" };
517 IM_ASSERT(data_type >= 0 && data_type < DataType_COUNT);
518 return descs[data_type];
519 }
520
521 size_t DataTypeGetSize(DataType data_type) const
522 {
523 const size_t sizes[] = { 1, 1, 2, 2, 4, 4, 8, 8, 4, 8 };
524 IM_ASSERT(data_type >= 0 && data_type < DataType_COUNT);
525 return sizes[data_type];
526 }
527
528 const char* DataFormatGetDesc(DataFormat data_format) const
529 {
530 const char* descs[] = { "Bin", "Dec", "Hex" };
531 IM_ASSERT(data_format >= 0 && data_format < DataFormat_COUNT);
532 return descs[data_format];
533 }
534
535 bool IsBigEndian() const
536 {
537 uint16_t x = 1;
538 char c[2];
539 memcpy(c, &x, 2);
540 return c[0] != 0;
541 }
542
543 static void* EndianessCopyBigEndian(void* _dst, void* _src, size_t s, int is_little_endian)
544 {
545 if (is_little_endian)
546 {
547 uint8_t* dst = (uint8_t*)_dst;
548 uint8_t* src = (uint8_t*)_src + s - 1;
549 for (int i = 0, n = (int)s; i < n; ++i)
550 memcpy(dst++, src--, 1);
551 return _dst;
552 }
553 else
554 {
555 return memcpy(_dst, _src, s);
556 }
557 }
558
559 static void* EndianessCopyLittleEndian(void* _dst, void* _src, size_t s, int is_little_endian)
560 {
561 if (is_little_endian)
562 {
563 return memcpy(_dst, _src, s);
564 }
565 else
566 {
567 uint8_t* dst = (uint8_t*)_dst;
568 uint8_t* src = (uint8_t*)_src + s - 1;
569 for (int i = 0, n = (int)s; i < n; ++i)
570 memcpy(dst++, src--, 1);
571 return _dst;
572 }
573 }
574
575 void* EndianessCopy(void *dst, void *src, size_t size) const
576 {
577 static void *(*fp)(void *, void *, size_t, int) = NULL;
578 if (fp == NULL)
579 fp = IsBigEndian() ? EndianessCopyBigEndian : EndianessCopyLittleEndian;
580 return fp(dst, src, size, PreviewEndianess);
581 }
582
583 const char* FormatBinary(const uint8_t* buf, int width) const
584 {
585 IM_ASSERT(width <= 64);
586 size_t out_n = 0;
587 static char out_buf[64 + 8 + 1];
588 for (int j = 0, n = width / 8; j < n; ++j)
589 {
590 for (int i = 0; i < 8; ++i)
591 out_buf[out_n++] = (buf[j] & (1 << (7 - i))) ? '1' : '0';
592 out_buf[out_n++] = ' ';
593 }
594 out_buf[out_n] = 0;
595 IM_ASSERT(out_n < IM_ARRAYSIZE(out_buf));
596 return out_buf;
597 }
598
599 void DisplayPreviewData(size_t addr, const u8* mem_data, size_t mem_size, DataType data_type, DataFormat data_format, char* out_buf, size_t out_buf_size) const
600 {
601 uint8_t buf[8];
602 int elem_size = DataTypeGetSize(data_type);
603 size_t size = addr + elem_size > mem_size ? mem_size - addr : elem_size;
604 if (ReadFn)
605 for (int i = 0, n = (int)size; i < n; ++i)
606 buf[i] = ReadFn(mem_data, addr + i);
607 else
608 memcpy(buf, mem_data + addr, size);
609
610 if (data_format == DataFormat_Bin)
611 {
612 snprintf(out_buf, out_buf_size, "%s", FormatBinary(buf, size * 8));
613 return;
614 }
615
616 out_buf[0] = 0;
617 switch (data_type)
618 {
619 case DataType_S8:
620 {
621 int8_t int8 = 0;
622 EndianessCopy(&int8, buf, size);
623 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%hhd", int8); return; }
624 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "0x%02x", int8 & 0xFF); return; }
625 break;
626 }
627 case DataType_U8:
628 {
629 uint8_t uint8 = 0;
630 EndianessCopy(&uint8, buf, size);
631 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%hhu", uint8); return; }
632 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "0x%02x", uint8 & 0XFF); return; }
633 break;
634 }
635 case DataType_S16:
636 {
637 int16_t int16 = 0;
638 EndianessCopy(&int16, buf, size);
639 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%hd", int16); return; }
640 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "0x%04x", int16 & 0xFFFF); return; }
641 break;
642 }
643 case DataType_U16:
644 {
645 uint16_t uint16 = 0;
646 EndianessCopy(&uint16, buf, size);
647 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%hu", uint16); return; }
648 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "0x%04x", uint16 & 0xFFFF); return; }
649 break;
650 }
651 case DataType_S32:
652 {
653 int32_t int32 = 0;
654 EndianessCopy(&int32, buf, size);
655 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%d", int32); return; }
656 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "0x%08x", int32); return; }
657 break;
658 }
659 case DataType_U32:
660 {
661 uint32_t uint32 = 0;
662 EndianessCopy(&uint32, buf, size);
663 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%u", uint32); return; }
664 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "0x%08x", uint32); return; }
665 break;
666 }
667 case DataType_S64:
668 {
669 int64_t int64 = 0;
670 EndianessCopy(&int64, buf, size);
671 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%lld", (long long)int64); return; }
672 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "0x%016llx", (long long)int64); return; }
673 break;
674 }
675 case DataType_U64:
676 {
677 uint64_t uint64 = 0;
678 EndianessCopy(&uint64, buf, size);
679 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%llu", (long long)uint64); return; }
680 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "0x%016llx", (long long)uint64); return; }
681 break;
682 }
683 case DataType_Float:
684 {
685 float float32 = 0.0f;
686 EndianessCopy(&float32, buf, size);
687 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%f", float32); return; }
688 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "%a", float32); return; }
689 break;
690 }
691 case DataType_Double:
692 {
693 double float64 = 0.0;
694 EndianessCopy(&float64, buf, size);
695 if (data_format == DataFormat_Dec) { snprintf(out_buf, out_buf_size, "%f", float64); return; }
696 if (data_format == DataFormat_Hex) { snprintf(out_buf, out_buf_size, "%a", float64); return; }
697 break;
698 }
699 } // Switch
700 IM_ASSERT(0); // Shouldn't reach
701 }
702 };
703
704 #undef _PRISizeT