ScummVM API documentation
imgui_memory_editor.h
1 // Mini memory editor for Dear ImGui (to embed in your game/tools)
2 // Get latest version at http://www.github.com/ocornut/imgui_club
3 //
4 // Right-click anywhere to access the Options menu!
5 // You can adjust the keyboard repeat delay/rate in ImGuiIO.
6 // The code assume a mono-space font for simplicity!
7 // If you don't use the default font, use ImGui::PushFont()/PopFont() to switch to a mono-space font before calling this.
8 //
9 // Usage:
10 // // Create a window and draw memory editor inside it:
11 // static MemoryEditor mem_edit_1;
12 // static char data[0x10000];
13 // size_t data_size = 0x10000;
14 // mem_edit_1.DrawWindow("Memory Editor", data, data_size);
15 //
16 // Usage:
17 // // If you already have a window, use DrawContents() instead:
18 // static MemoryEditor mem_edit_2;
19 // ImGui::Begin("MyWindow")
20 // mem_edit_2.DrawContents(this, sizeof(*this), (size_t)this);
21 // ImGui::End();
22 //
23 // Changelog:
24 // - v0.10: initial version
25 // - v0.23 (2017/08/17): added to github. fixed right-arrow triggering a byte write.
26 // - v0.24 (2018/06/02): changed DragInt("Rows" to use a %d data format (which is desirable since imgui 1.61).
27 // - v0.25 (2018/07/11): fixed wording: all occurrences of "Rows" renamed to "Columns".
28 // - v0.26 (2018/08/02): fixed clicking on hex region
29 // - v0.30 (2018/08/02): added data preview for common data types
30 // - v0.31 (2018/10/10): added OptUpperCaseHex option to select lower/upper casing display [@samhocevar]
31 // - v0.32 (2018/10/10): changed signatures to use void* instead of unsigned char*
32 // - v0.33 (2018/10/10): added OptShowOptions option to hide all the interactive option setting.
33 // - v0.34 (2019/05/07): binary preview now applies endianness setting [@nicolasnoble]
34 // - v0.35 (2020/01/29): using ImGuiDataType available since Dear ImGui 1.69.
35 // - v0.36 (2020/05/05): minor tweaks, minor refactor.
36 // - v0.40 (2020/10/04): fix misuse of ImGuiListClipper API, broke with Dear ImGui 1.79. made cursor position appears on left-side of edit box. option popup appears on mouse release. fix MSVC warnings where _CRT_SECURE_NO_WARNINGS wasn't working in recent versions.
37 // - v0.41 (2020/10/05): fix when using with keyboard/gamepad navigation enabled.
38 // - v0.42 (2020/10/14): fix for . character in ASCII view always being greyed out.
39 // - v0.43 (2021/03/12): added OptFooterExtraHeight to allow for custom drawing at the bottom of the editor [@leiradel]
40 // - v0.44 (2021/03/12): use ImGuiInputTextFlags_AlwaysOverwrite in 1.82 + fix hardcoded width.
41 // - v0.50 (2021/11/12): various fixes for recent dear imgui versions (fixed misuse of clipper, relying on SetKeyboardFocusHere() handling scrolling from 1.85). added default size.
42 // - v0.51 (2024/02/22): fix for layout change in 1.89 when using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#34)
43 // - v0.52 (2024/03/08): removed unnecessary GetKeyIndex() calls, they are a no-op since 1.87.
44 //
45 // Todo/Bugs:
46 // - This is generally old/crappy code, it should work but isn't very good.. to be rewritten some day.
47 // - PageUp/PageDown are not supported because we use _NoNav. This is a good test scenario for working out idioms of how to mix natural nav and our own...
48 // - Arrows are being sent to the InputText() about to disappear which for LeftArrow makes the text cursor appear at position 1 for one frame.
49 // - Using InputText() is awkward and maybe overkill here, consider implementing something custom.
50 
51 #pragma once
52 
53 #include <stdio.h> // sprintf, scanf
54 #include <stdint.h> // uint8_t, etc.
55 
56 #ifdef _MSC_VER
57 #define _PRISizeT "I"
58 #define ImSnprintf _snprintf
59 #else
60 #define _PRISizeT "z"
61 #define ImSnprintf snprintf
62 #endif
63 
64 #ifdef _MSC_VER
65 #pragma warning (push)
66 #pragma warning (disable: 4996) // warning C4996: 'sprintf': This function or variable may be unsafe.
67 #endif
68 
70 {
71  enum DataFormat
72  {
73  DataFormat_Bin = 0,
74  DataFormat_Dec = 1,
75  DataFormat_Hex = 2,
76  DataFormat_COUNT
77  };
78 
79  // Settings
80  bool Open; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow().
81  bool ReadOnly; // = false // disable any editing.
82  int Cols; // = 16 // number of columns to display.
83  bool OptShowOptions; // = true // display options button/context menu. when disabled, options will be locked unless you provide your own UI for them.
84  bool OptShowDataPreview; // = false // display a footer previewing the decimal/binary/hex/float representation of the currently selected bytes.
85  bool OptShowHexII; // = false // display values in HexII representation instead of regular hexadecimal: hide null/zero bytes, ascii values as ".X".
86  bool OptShowAscii; // = true // display ASCII representation on the right side.
87  bool OptGreyOutZeroes; // = true // display null/zero bytes using the TextDisabled color.
88  bool OptUpperCaseHex; // = true // display hexadecimal values as "FF" instead of "ff".
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  float OptFooterExtraHeight; // = 0 // space to reserve at the bottom of the widget to add custom widgets
92  ImU32 HighlightColor; // // background color of highlighted bytes.
93  ImU8 (*ReadFn)(const ImU8* data, size_t off); // = 0 // optional handler to read bytes.
94  void (*WriteFn)(ImU8* data, size_t off, ImU8 d); // = 0 // optional handler to write bytes.
95  bool (*HighlightFn)(const ImU8* data, size_t off);//= 0 // optional handler to return Highlight property (to support non-contiguous highlighting).
96 
97  // [Internal State]
98  bool ContentsWidthChanged;
99  size_t DataPreviewAddr;
100  size_t DataEditingAddr;
101  bool DataEditingTakeFocus;
102  char DataInputBuf[32];
103  char AddrInputBuf[32];
104  size_t GotoAddr;
105  size_t HighlightMin, HighlightMax;
106  int PreviewEndianness;
107  ImGuiDataType PreviewDataType;
108 
109  MemoryEditor()
110  {
111  // Settings
112  Open = true;
113  ReadOnly = false;
114  Cols = 16;
115  OptShowOptions = true;
116  OptShowDataPreview = false;
117  OptShowHexII = false;
118  OptShowAscii = true;
119  OptGreyOutZeroes = true;
120  OptUpperCaseHex = true;
121  OptMidColsCount = 8;
122  OptAddrDigitsCount = 0;
123  OptFooterExtraHeight = 0.0f;
124  HighlightColor = IM_COL32(255, 255, 255, 50);
125  ReadFn = NULL;
126  WriteFn = NULL;
127  HighlightFn = NULL;
128 
129  // State/Internals
130  ContentsWidthChanged = false;
131  DataPreviewAddr = DataEditingAddr = (size_t)-1;
132  DataEditingTakeFocus = false;
133  memset(DataInputBuf, 0, sizeof(DataInputBuf));
134  memset(AddrInputBuf, 0, sizeof(AddrInputBuf));
135  GotoAddr = (size_t)-1;
136  HighlightMin = HighlightMax = (size_t)-1;
137  PreviewEndianness = 0;
138  PreviewDataType = ImGuiDataType_S32;
139  }
140 
141  void GotoAddrAndHighlight(size_t addr_min, size_t addr_max)
142  {
143  GotoAddr = addr_min;
144  HighlightMin = addr_min;
145  HighlightMax = addr_max;
146  }
147 
148  struct Sizes
149  {
150  int AddrDigitsCount;
151  float LineHeight;
152  float GlyphWidth;
153  float HexCellWidth;
154  float SpacingBetweenMidCols;
155  float PosHexStart;
156  float PosHexEnd;
157  float PosAsciiStart;
158  float PosAsciiEnd;
159  float WindowWidth;
160 
161  Sizes() { memset(this, 0, sizeof(*this)); }
162  };
163 
164  void CalcSizes(Sizes& s, size_t mem_size, size_t base_display_addr)
165  {
166  ImGuiStyle& style = ImGui::GetStyle();
167  s.AddrDigitsCount = OptAddrDigitsCount;
168  if (s.AddrDigitsCount == 0)
169  for (size_t n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
170  s.AddrDigitsCount++;
171  s.LineHeight = ImGui::GetTextLineHeight();
172  s.GlyphWidth = ImGui::CalcTextSize("F").x + 1; // We assume the font is mono-space
173  s.HexCellWidth = (float)(int)(s.GlyphWidth * 2.5f); // "FF " we include trailing space in the width to easily catch clicks everywhere
174  s.SpacingBetweenMidCols = (float)(int)(s.HexCellWidth * 0.25f); // Every OptMidColsCount columns we add a bit of extra spacing
175  s.PosHexStart = (s.AddrDigitsCount + 2) * s.GlyphWidth;
176  s.PosHexEnd = s.PosHexStart + (s.HexCellWidth * Cols);
177  s.PosAsciiStart = s.PosAsciiEnd = s.PosHexEnd;
178  if (OptShowAscii)
179  {
180  s.PosAsciiStart = s.PosHexEnd + s.GlyphWidth * 1;
181  if (OptMidColsCount > 0)
182  s.PosAsciiStart += (float)((Cols + OptMidColsCount - 1) / OptMidColsCount) * s.SpacingBetweenMidCols;
183  s.PosAsciiEnd = s.PosAsciiStart + Cols * s.GlyphWidth;
184  }
185  s.WindowWidth = s.PosAsciiEnd + style.ScrollbarSize + style.WindowPadding.x * 2 + s.GlyphWidth;
186  }
187 
188  // Standalone Memory Editor window
189  void DrawWindow(const char* title, void* mem_data, size_t mem_size, size_t base_display_addr = 0x0000)
190  {
191  Sizes s;
192  CalcSizes(s, mem_size, base_display_addr);
193  ImGui::SetNextWindowSize(ImVec2(s.WindowWidth, s.WindowWidth * 0.60f), ImGuiCond_FirstUseEver);
194  ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, 0.0f), ImVec2(s.WindowWidth, FLT_MAX));
195 
196  Open = true;
197  if (ImGui::Begin(title, &Open, ImGuiWindowFlags_NoScrollbar))
198  {
199  if (ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) && ImGui::IsMouseReleased(ImGuiMouseButton_Right))
200  ImGui::OpenPopup("context");
201  DrawContents(mem_data, mem_size, base_display_addr);
202  if (ContentsWidthChanged)
203  {
204  CalcSizes(s, mem_size, base_display_addr);
205  ImGui::SetWindowSize(ImVec2(s.WindowWidth, ImGui::GetWindowSize().y));
206  }
207  }
208  ImGui::End();
209  }
210 
211  // Memory Editor contents only
212  void DrawContents(void* mem_data_void, size_t mem_size, size_t base_display_addr = 0x0000)
213  {
214  if (Cols < 1)
215  Cols = 1;
216 
217  ImU8* mem_data = (ImU8*)mem_data_void;
218  Sizes s;
219  CalcSizes(s, mem_size, base_display_addr);
220  ImGuiStyle& style = ImGui::GetStyle();
221 
222  // We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window.
223  // 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.
224  const float height_separator = style.ItemSpacing.y;
225  float footer_height = OptFooterExtraHeight;
226  if (OptShowOptions)
227  footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1;
228  if (OptShowDataPreview)
229  footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1 + ImGui::GetTextLineHeightWithSpacing() * 3;
230  ImGui::BeginChild("##scrolling", ImVec2(0, -footer_height), false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNav);
231  ImDrawList* draw_list = ImGui::GetWindowDrawList();
232 
233  ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
234  ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
235 
236  // We are not really using the clipper API correctly here, because we rely on visible_start_addr/visible_end_addr for our scrolling function.
237  const int line_total_count = (int)((mem_size + Cols - 1) / Cols);
238  ImGuiListClipper clipper;
239  clipper.Begin(line_total_count, s.LineHeight);
240 
241  bool data_next = false;
242 
243  if (ReadOnly || DataEditingAddr >= mem_size)
244  DataEditingAddr = (size_t)-1;
245  if (DataPreviewAddr >= mem_size)
246  DataPreviewAddr = (size_t)-1;
247 
248  size_t preview_data_type_size = OptShowDataPreview ? DataTypeGetSize(PreviewDataType) : 0;
249 
250  size_t data_editing_addr_next = (size_t)-1;
251  if (DataEditingAddr != (size_t)-1)
252  {
253  // 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)
254  if (ImGui::IsKeyPressed(ImGuiKey_UpArrow) && (ptrdiff_t)DataEditingAddr >= (ptrdiff_t)Cols) { data_editing_addr_next = DataEditingAddr - Cols; }
255  else if (ImGui::IsKeyPressed(ImGuiKey_DownArrow) && (ptrdiff_t)DataEditingAddr < (ptrdiff_t)mem_size - Cols){ data_editing_addr_next = DataEditingAddr + Cols; }
256  else if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow) && (ptrdiff_t)DataEditingAddr > (ptrdiff_t)0) { data_editing_addr_next = DataEditingAddr - 1; }
257  else if (ImGui::IsKeyPressed(ImGuiKey_RightArrow) && (ptrdiff_t)DataEditingAddr < (ptrdiff_t)mem_size - 1) { data_editing_addr_next = DataEditingAddr + 1; }
258  }
259 
260  // Draw vertical separator
261  ImVec2 window_pos = ImGui::GetWindowPos();
262  if (OptShowAscii)
263  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));
264 
265  const ImU32 color_text = ImGui::GetColorU32(ImGuiCol_Text);
266  const ImU32 color_disabled = OptGreyOutZeroes ? ImGui::GetColorU32(ImGuiCol_TextDisabled) : color_text;
267 
268  const char* format_address = OptUpperCaseHex ? "%0*" _PRISizeT "X: " : "%0*" _PRISizeT "x: ";
269  const char* format_data = OptUpperCaseHex ? "%0*" _PRISizeT "X" : "%0*" _PRISizeT "x";
270  const char* format_byte = OptUpperCaseHex ? "%02X" : "%02x";
271  const char* format_byte_space = OptUpperCaseHex ? "%02X " : "%02x ";
272 
273  while (clipper.Step())
274  for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible lines
275  {
276  size_t addr = (size_t)(line_i * Cols);
277  ImGui::Text(format_address, s.AddrDigitsCount, base_display_addr + addr);
278 
279  // Draw Hexadecimal
280  for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
281  {
282  float byte_pos_x = s.PosHexStart + s.HexCellWidth * n;
283  if (OptMidColsCount > 0)
284  byte_pos_x += (float)(n / OptMidColsCount) * s.SpacingBetweenMidCols;
285  ImGui::SameLine(byte_pos_x);
286 
287  // Draw highlight
288  bool is_highlight_from_user_range = (addr >= HighlightMin && addr < HighlightMax);
289  bool is_highlight_from_user_func = (HighlightFn && HighlightFn(mem_data, addr));
290  bool is_highlight_from_preview = (addr >= DataPreviewAddr && addr < DataPreviewAddr + preview_data_type_size);
291  if (is_highlight_from_user_range || is_highlight_from_user_func || is_highlight_from_preview)
292  {
293  ImVec2 pos = ImGui::GetCursorScreenPos();
294  float highlight_width = s.GlyphWidth * 2;
295  bool is_next_byte_highlighted = (addr + 1 < mem_size) && ((HighlightMax != (size_t)-1 && addr + 1 < HighlightMax) || (HighlightFn && HighlightFn(mem_data, addr + 1)));
296  if (is_next_byte_highlighted || (n + 1 == Cols))
297  {
298  highlight_width = s.HexCellWidth;
299  if (OptMidColsCount > 0 && n > 0 && (n + 1) < Cols && ((n + 1) % OptMidColsCount) == 0)
300  highlight_width += s.SpacingBetweenMidCols;
301  }
302  draw_list->AddRectFilled(pos, ImVec2(pos.x + highlight_width, pos.y + s.LineHeight), HighlightColor);
303  }
304 
305  if (DataEditingAddr == addr)
306  {
307  // Display text input on current byte
308  bool data_write = false;
309  ImGui::PushID((void*)addr);
310  if (DataEditingTakeFocus)
311  {
312  ImGui::SetKeyboardFocusHere(0);
313  snprintf(AddrInputBuf, 32, format_data, s.AddrDigitsCount, base_display_addr + addr);
314  snprintf(DataInputBuf, 32, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
315  }
316  struct UserData
317  {
318  // 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.
319  static int Callback(ImGuiInputTextCallbackData* data)
320  {
321  UserData* user_data = (UserData*)data->UserData;
322  if (!data->HasSelection())
323  user_data->CursorPos = data->CursorPos;
324  if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen)
325  {
326  // When not editing a byte, always refresh its InputText content pulled from underlying memory data
327  // (this is a bit tricky, since InputText technically "owns" the master copy of the buffer we edit it in there)
328  data->DeleteChars(0, data->BufTextLen);
329  data->InsertChars(0, user_data->CurrentBufOverwrite);
330  data->SelectionStart = 0;
331  data->SelectionEnd = 2;
332  data->CursorPos = 0;
333  }
334  return 0;
335  }
336  char CurrentBufOverwrite[3]; // Input
337  int CursorPos; // Output
338  };
339  UserData user_data;
340  user_data.CursorPos = -1;
341  snprintf(user_data.CurrentBufOverwrite, 3, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
342  ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoHorizontalScroll | ImGuiInputTextFlags_CallbackAlways;
343  flags |= ImGuiInputTextFlags_AlwaysOverwrite; // was ImGuiInputTextFlags_AlwaysInsertMode
344  ImGui::SetNextItemWidth(s.GlyphWidth * 2);
345  if (ImGui::InputText("##data", DataInputBuf, IM_ARRAYSIZE(DataInputBuf), flags, UserData::Callback, &user_data))
346  data_write = data_next = true;
347  else if (!DataEditingTakeFocus && !ImGui::IsItemActive())
348  DataEditingAddr = data_editing_addr_next = (size_t)-1;
349  DataEditingTakeFocus = false;
350  if (user_data.CursorPos >= 2)
351  data_write = data_next = true;
352  if (data_editing_addr_next != (size_t)-1)
353  data_write = data_next = false;
354  unsigned int data_input_value = 0;
355  if (data_write && sscanf(DataInputBuf, "%X", &data_input_value) == 1)
356  {
357  if (WriteFn)
358  WriteFn(mem_data, addr, (ImU8)data_input_value);
359  else
360  mem_data[addr] = (ImU8)data_input_value;
361  }
362  ImGui::PopID();
363  }
364  else
365  {
366  // NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on.
367  ImU8 b = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
368 
369  if (OptShowHexII)
370  {
371  if ((b >= 32 && b < 128))
372  ImGui::Text(".%c ", b);
373  else if (b == 0xFF && OptGreyOutZeroes)
374  ImGui::TextDisabled("## ");
375  else if (b == 0x00)
376  ImGui::Text(" ");
377  else
378  ImGui::Text(format_byte_space, b);
379  }
380  else
381  {
382  if (b == 0 && OptGreyOutZeroes)
383  ImGui::TextDisabled("00 ");
384  else
385  ImGui::Text(format_byte_space, b);
386  }
387  if (!ReadOnly && ImGui::IsItemHovered() && ImGui::IsMouseClicked(0))
388  {
389  DataEditingTakeFocus = true;
390  data_editing_addr_next = addr;
391  }
392  }
393  }
394 
395  if (OptShowAscii)
396  {
397  // Draw ASCII values
398  ImGui::SameLine(s.PosAsciiStart);
399  ImVec2 pos = ImGui::GetCursorScreenPos();
400  addr = line_i * Cols;
401  ImGui::PushID(line_i);
402  if (ImGui::InvisibleButton("ascii", ImVec2(s.PosAsciiEnd - s.PosAsciiStart, s.LineHeight)))
403  {
404  DataEditingAddr = DataPreviewAddr = addr + (size_t)((ImGui::GetIO().MousePos.x - pos.x) / s.GlyphWidth);
405  DataEditingTakeFocus = true;
406  }
407  ImGui::PopID();
408  for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
409  {
410  if (addr == DataEditingAddr)
411  {
412  draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_FrameBg));
413  draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_TextSelectedBg));
414  }
415  unsigned char c = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
416  char display_c = (c < 32 || c >= 128) ? '.' : c;
417  draw_list->AddText(pos, (display_c == c) ? color_text : color_disabled, &display_c, &display_c + 1);
418  pos.x += s.GlyphWidth;
419  }
420  }
421  }
422  ImGui::PopStyleVar(2);
423  ImGui::EndChild();
424 
425  // Notify the main window of our ideal child content size (FIXME: we are missing an API to get the contents size from the child)
426  ImGui::SetCursorPosX(s.WindowWidth);
427  ImGui::Dummy(ImVec2(0.0f, 0.0f));
428 
429  if (data_next && DataEditingAddr + 1 < mem_size)
430  {
431  DataEditingAddr = DataPreviewAddr = DataEditingAddr + 1;
432  DataEditingTakeFocus = true;
433  }
434  else if (data_editing_addr_next != (size_t)-1)
435  {
436  DataEditingAddr = DataPreviewAddr = data_editing_addr_next;
437  DataEditingTakeFocus = true;
438  }
439 
440  const bool lock_show_data_preview = OptShowDataPreview;
441  if (OptShowOptions)
442  {
443  ImGui::Separator();
444  DrawOptionsLine(s, mem_data, mem_size, base_display_addr);
445  }
446 
447  if (lock_show_data_preview)
448  {
449  ImGui::Separator();
450  DrawPreviewLine(s, mem_data, mem_size, base_display_addr);
451  }
452  }
453 
454  void DrawOptionsLine(const Sizes& s, void* mem_data, size_t mem_size, size_t base_display_addr)
455  {
456  IM_UNUSED(mem_data);
457  ImGuiStyle& style = ImGui::GetStyle();
458  const char* format_range = OptUpperCaseHex ? "Range %0*" _PRISizeT "X..%0*" _PRISizeT "X" : "Range %0*" _PRISizeT "x..%0*" _PRISizeT "x";
459 
460  // Options menu
461  if (ImGui::Button("Options"))
462  ImGui::OpenPopup("context");
463  if (ImGui::BeginPopup("context"))
464  {
465  ImGui::SetNextItemWidth(s.GlyphWidth * 7 + style.FramePadding.x * 2.0f);
466  if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; if (Cols < 1) Cols = 1; }
467  ImGui::Checkbox("Show Data Preview", &OptShowDataPreview);
468  ImGui::Checkbox("Show HexII", &OptShowHexII);
469  if (ImGui::Checkbox("Show Ascii", &OptShowAscii)) { ContentsWidthChanged = true; }
470  ImGui::Checkbox("Grey out zeroes", &OptGreyOutZeroes);
471  ImGui::Checkbox("Uppercase Hex", &OptUpperCaseHex);
472 
473  ImGui::EndPopup();
474  }
475 
476  ImGui::SameLine();
477  ImGui::Text(format_range, s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1);
478  ImGui::SameLine();
479  ImGui::SetNextItemWidth((s.AddrDigitsCount + 1) * s.GlyphWidth + style.FramePadding.x * 2.0f);
480  if (ImGui::InputText("##addr", AddrInputBuf, IM_ARRAYSIZE(AddrInputBuf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue))
481  {
482  size_t goto_addr;
483  if (sscanf(AddrInputBuf, "%" _PRISizeT "X", &goto_addr) == 1)
484  {
485  GotoAddr = goto_addr - base_display_addr;
486  HighlightMin = HighlightMax = (size_t)-1;
487  }
488  }
489 
490  if (GotoAddr != (size_t)-1)
491  {
492  if (GotoAddr < mem_size)
493  {
494  ImGui::BeginChild("##scrolling");
495  ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + (GotoAddr / Cols) * ImGui::GetTextLineHeight());
496  ImGui::EndChild();
497  DataEditingAddr = DataPreviewAddr = GotoAddr;
498  DataEditingTakeFocus = true;
499  }
500  GotoAddr = (size_t)-1;
501  }
502  }
503 
504  void DrawPreviewLine(const Sizes& s, void* mem_data_void, size_t mem_size, size_t base_display_addr)
505  {
506  IM_UNUSED(base_display_addr);
507  ImU8* mem_data = (ImU8*)mem_data_void;
508  ImGuiStyle& style = ImGui::GetStyle();
509  ImGui::AlignTextToFramePadding();
510  ImGui::Text("Preview as:");
511  ImGui::SameLine();
512  ImGui::SetNextItemWidth((s.GlyphWidth * 10.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
513  if (ImGui::BeginCombo("##combo_type", DataTypeGetDesc(PreviewDataType), ImGuiComboFlags_HeightLargest))
514  {
515  for (int n = 0; n < ImGuiDataType_COUNT; n++)
516  if (ImGui::Selectable(DataTypeGetDesc((ImGuiDataType)n), PreviewDataType == n))
517  PreviewDataType = (ImGuiDataType)n;
518  ImGui::EndCombo();
519  }
520  ImGui::SameLine();
521  ImGui::SetNextItemWidth((s.GlyphWidth * 6.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
522  ImGui::Combo("##combo_endianness", &PreviewEndianness, "LE\0BE\0\0");
523 
524  char buf[128] = "";
525  float x = s.GlyphWidth * 6.0f;
526  bool has_value = DataPreviewAddr != (size_t)-1;
527  if (has_value)
528  DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Dec, buf, (size_t)IM_ARRAYSIZE(buf));
529  ImGui::Text("Dec"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
530  if (has_value)
531  DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Hex, buf, (size_t)IM_ARRAYSIZE(buf));
532  ImGui::Text("Hex"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
533  if (has_value)
534  DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Bin, buf, (size_t)IM_ARRAYSIZE(buf));
535  buf[IM_ARRAYSIZE(buf) - 1] = 0;
536  ImGui::Text("Bin"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
537  }
538 
539  // Utilities for Data Preview
540  const char* DataTypeGetDesc(ImGuiDataType data_type) const
541  {
542  const char* descs[] = { "Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64", "Float", "Double" };
543  IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
544  return descs[data_type];
545  }
546 
547  size_t DataTypeGetSize(ImGuiDataType data_type) const
548  {
549  const size_t sizes[] = { 1, 1, 2, 2, 4, 4, 8, 8, sizeof(float), sizeof(double) };
550  IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
551  return sizes[data_type];
552  }
553 
554  const char* DataFormatGetDesc(DataFormat data_format) const
555  {
556  const char* descs[] = { "Bin", "Dec", "Hex" };
557  IM_ASSERT(data_format >= 0 && data_format < DataFormat_COUNT);
558  return descs[data_format];
559  }
560 
561  bool IsBigEndian() const
562  {
563  uint16_t x = 1;
564  char c[2];
565  memcpy(c, &x, 2);
566  return c[0] != 0;
567  }
568 
569  static void* EndiannessCopyBigEndian(void* _dst, void* _src, size_t s, int is_little_endian)
570  {
571  if (is_little_endian)
572  {
573  uint8_t* dst = (uint8_t*)_dst;
574  uint8_t* src = (uint8_t*)_src + s - 1;
575  for (int i = 0, n = (int)s; i < n; ++i)
576  memcpy(dst++, src--, 1);
577  return _dst;
578  }
579  else
580  {
581  return memcpy(_dst, _src, s);
582  }
583  }
584 
585  static void* EndiannessCopyLittleEndian(void* _dst, void* _src, size_t s, int is_little_endian)
586  {
587  if (is_little_endian)
588  {
589  return memcpy(_dst, _src, s);
590  }
591  else
592  {
593  uint8_t* dst = (uint8_t*)_dst;
594  uint8_t* src = (uint8_t*)_src + s - 1;
595  for (int i = 0, n = (int)s; i < n; ++i)
596  memcpy(dst++, src--, 1);
597  return _dst;
598  }
599  }
600 
601  void* EndiannessCopy(void* dst, void* src, size_t size) const
602  {
603  static void* (*fp)(void*, void*, size_t, int) = NULL;
604  if (fp == NULL)
605  fp = IsBigEndian() ? EndiannessCopyBigEndian : EndiannessCopyLittleEndian;
606  return fp(dst, src, size, PreviewEndianness);
607  }
608 
609  const char* FormatBinary(const uint8_t* buf, int width) const
610  {
611  IM_ASSERT(width <= 64);
612  size_t out_n = 0;
613  static char out_buf[64 + 8 + 1];
614  int n = width / 8;
615  for (int j = n - 1; j >= 0; --j)
616  {
617  for (int i = 0; i < 8; ++i)
618  out_buf[out_n++] = (buf[j] & (1 << (7 - i))) ? '1' : '0';
619  out_buf[out_n++] = ' ';
620  }
621  IM_ASSERT(out_n < IM_ARRAYSIZE(out_buf));
622  out_buf[out_n] = 0;
623  return out_buf;
624  }
625 
626  // [Internal]
627  void DrawPreviewData(size_t addr, const ImU8* mem_data, size_t mem_size, ImGuiDataType data_type, DataFormat data_format, char* out_buf, size_t out_buf_size) const
628  {
629  uint8_t buf[8];
630  size_t elem_size = DataTypeGetSize(data_type);
631  size_t size = addr + elem_size > mem_size ? mem_size - addr : elem_size;
632  if (ReadFn)
633  for (int i = 0, n = (int)size; i < n; ++i)
634  buf[i] = ReadFn(mem_data, addr + i);
635  else
636  memcpy(buf, mem_data + addr, size);
637 
638  if (data_format == DataFormat_Bin)
639  {
640  uint8_t binbuf[8];
641  EndiannessCopy(binbuf, buf, size);
642  ImSnprintf(out_buf, out_buf_size, "%s", FormatBinary(binbuf, (int)size * 8));
643  return;
644  }
645 
646  out_buf[0] = 0;
647  switch (data_type)
648  {
649  case ImGuiDataType_S8:
650  {
651  int8_t int8d = 0;
652  EndiannessCopy(&int8d, buf, size);
653  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhd", int8d); return; }
654  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", int8d & 0xFF); return; }
655  break;
656  }
657  case ImGuiDataType_U8:
658  {
659  uint8_t uint8d = 0;
660  EndiannessCopy(&uint8d, buf, size);
661  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhu", uint8d); return; }
662  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", uint8d & 0XFF); return; }
663  break;
664  }
665  case ImGuiDataType_S16:
666  {
667  int16_t int16d = 0;
668  EndiannessCopy(&int16d, buf, size);
669  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hd", int16d); return; }
670  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", int16d & 0xFFFF); return; }
671  break;
672  }
673  case ImGuiDataType_U16:
674  {
675  uint16_t uint16d = 0;
676  EndiannessCopy(&uint16d, buf, size);
677  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hu", uint16d); return; }
678  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", uint16d & 0xFFFF); return; }
679  break;
680  }
681  case ImGuiDataType_S32:
682  {
683  int32_t int32d = 0;
684  EndiannessCopy(&int32d, buf, size);
685  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%d", int32d); return; }
686  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", int32d); return; }
687  break;
688  }
689  case ImGuiDataType_U32:
690  {
691  uint32_t uint32d = 0;
692  EndiannessCopy(&uint32d, buf, size);
693  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%u", uint32d); return; }
694  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", uint32d); return; }
695  break;
696  }
697  case ImGuiDataType_S64:
698  {
699  int64_t int64d = 0;
700  EndiannessCopy(&int64d, buf, size);
701  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%lld", (long long)int64d); return; }
702  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)int64d); return; }
703  break;
704  }
705  case ImGuiDataType_U64:
706  {
707  uint64_t uint64d = 0;
708  EndiannessCopy(&uint64d, buf, size);
709  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%llu", (long long)uint64d); return; }
710  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)uint64d); return; }
711  break;
712  }
713  case ImGuiDataType_Float:
714  {
715  float float32d = 0.0f;
716  EndiannessCopy(&float32d, buf, size);
717  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float32d); return; }
718  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float32d); return; }
719  break;
720  }
721  case ImGuiDataType_Double:
722  {
723  double float64d = 0.0;
724  EndiannessCopy(&float64d, buf, size);
725  if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float64d); return; }
726  if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float64d); return; }
727  break;
728  }
729  case ImGuiDataType_COUNT:
730  break;
731  } // Switch
732  IM_ASSERT(0); // Shouldn't reach
733  }
734 };
735 
736 #undef _PRISizeT
737 #undef ImSnprintf
738 
739 #ifdef _MSC_VER
740 #pragma warning (pop)
741 #endif
Definition: imgui.h:2774
Definition: imgui.h:3168
Definition: imgui.h:295
Definition: imgui_memory_editor.h:69
Definition: imgui_memory_editor.h:148
Definition: imgui.h:2545
Definition: imgui.h:2213