imgui_memory_editor.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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. //
  42. // Todo/Bugs:
  43. // - This is generally old code, it should work but please don't use this as reference!
  44. // - Arrows are being sent to the InputText() about to disappear which for LeftArrow makes the text cursor appear at position 1 for one frame.
  45. // - Using InputText() is awkward and maybe overkill here, consider implementing something custom.
  46. #pragma once
  47. #include <stdio.h> // sprintf, scanf
  48. #include <stdint.h> // uint8_t, etc.
  49. #ifdef _MSC_VER
  50. #define _PRISizeT "I"
  51. #define ImSnprintf _snprintf
  52. #else
  53. #define _PRISizeT "z"
  54. #define ImSnprintf snprintf
  55. #endif
  56. #ifdef _MSC_VER
  57. #pragma warning (push)
  58. #pragma warning (disable: 4996) // warning C4996: 'sprintf': This function or variable may be unsafe.
  59. #endif
  60. struct MemoryEditor
  61. {
  62. enum DataFormat
  63. {
  64. DataFormat_Bin = 0,
  65. DataFormat_Dec = 1,
  66. DataFormat_Hex = 2,
  67. DataFormat_COUNT
  68. };
  69. // Settings
  70. bool Open; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow().
  71. bool ReadOnly; // = false // disable any editing.
  72. int Cols; // = 16 // number of columns to display.
  73. bool OptShowOptions; // = true // display options button/context menu. when disabled, options will be locked unless you provide your own UI for them.
  74. bool OptShowDataPreview; // = false // display a footer previewing the decimal/binary/hex/float representation of the currently selected bytes.
  75. bool OptShowHexII; // = false // display values in HexII representation instead of regular hexadecimal: hide null/zero bytes, ascii values as ".X".
  76. bool OptShowAscii; // = true // display ASCII representation on the right side.
  77. bool OptGreyOutZeroes; // = true // display null/zero bytes using the TextDisabled color.
  78. bool OptUpperCaseHex; // = true // display hexadecimal values as "FF" instead of "ff".
  79. int OptMidColsCount; // = 8 // set to 0 to disable extra spacing between every mid-cols.
  80. int OptAddrDigitsCount; // = 0 // number of addr digits to display (default calculated based on maximum displayed addr).
  81. float OptFooterExtraHeight; // = 0 // space to reserve at the bottom of the widget to add custom widgets
  82. ImU32 HighlightColor; // // background color of highlighted bytes.
  83. ImU8 (*ReadFn)(const ImU8* data, size_t off); // = 0 // optional handler to read bytes.
  84. void (*WriteFn)(ImU8* data, size_t off, ImU8 d); // = 0 // optional handler to write bytes.
  85. bool (*HighlightFn)(const ImU8* data, size_t off);//= 0 // optional handler to return Highlight property (to support non-contiguous highlighting).
  86. // [Internal State]
  87. bool ContentsWidthChanged;
  88. size_t DataPreviewAddr;
  89. size_t DataEditingAddr;
  90. bool DataEditingTakeFocus;
  91. char DataInputBuf[32];
  92. char AddrInputBuf[32];
  93. size_t GotoAddr;
  94. size_t HighlightMin, HighlightMax;
  95. int PreviewEndianess;
  96. ImGuiDataType PreviewDataType;
  97. MemoryEditor()
  98. {
  99. // Settings
  100. Open = true;
  101. ReadOnly = false;
  102. Cols = 16;
  103. OptShowOptions = true;
  104. OptShowDataPreview = false;
  105. OptShowHexII = false;
  106. OptShowAscii = true;
  107. OptGreyOutZeroes = true;
  108. OptUpperCaseHex = true;
  109. OptMidColsCount = 8;
  110. OptAddrDigitsCount = 0;
  111. OptFooterExtraHeight = 0.0f;
  112. HighlightColor = IM_COL32(255, 255, 255, 50);
  113. ReadFn = NULL;
  114. WriteFn = NULL;
  115. HighlightFn = NULL;
  116. // State/Internals
  117. ContentsWidthChanged = false;
  118. DataPreviewAddr = DataEditingAddr = (size_t)-1;
  119. DataEditingTakeFocus = false;
  120. memset(DataInputBuf, 0, sizeof(DataInputBuf));
  121. memset(AddrInputBuf, 0, sizeof(AddrInputBuf));
  122. GotoAddr = (size_t)-1;
  123. HighlightMin = HighlightMax = (size_t)-1;
  124. PreviewEndianess = 0;
  125. PreviewDataType = ImGuiDataType_S32;
  126. }
  127. void GotoAddrAndHighlight(size_t addr_min, size_t addr_max)
  128. {
  129. GotoAddr = addr_min;
  130. HighlightMin = addr_min;
  131. HighlightMax = addr_max;
  132. }
  133. struct Sizes
  134. {
  135. int AddrDigitsCount;
  136. float LineHeight;
  137. float GlyphWidth;
  138. float HexCellWidth;
  139. float SpacingBetweenMidCols;
  140. float PosHexStart;
  141. float PosHexEnd;
  142. float PosAsciiStart;
  143. float PosAsciiEnd;
  144. float WindowWidth;
  145. Sizes() { memset(this, 0, sizeof(*this)); }
  146. };
  147. void CalcSizes(Sizes& s, size_t mem_size, size_t base_display_addr)
  148. {
  149. ImGuiStyle& style = ImGui::GetStyle();
  150. s.AddrDigitsCount = OptAddrDigitsCount;
  151. if (s.AddrDigitsCount == 0)
  152. for (size_t n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
  153. s.AddrDigitsCount++;
  154. s.LineHeight = ImGui::GetTextLineHeight();
  155. s.GlyphWidth = ImGui::CalcTextSize("F").x + 1; // We assume the font is mono-space
  156. s.HexCellWidth = (float)(int)(s.GlyphWidth * 2.5f); // "FF " we include trailing space in the width to easily catch clicks everywhere
  157. s.SpacingBetweenMidCols = (float)(int)(s.HexCellWidth * 0.25f); // Every OptMidColsCount columns we add a bit of extra spacing
  158. s.PosHexStart = (s.AddrDigitsCount + 2) * s.GlyphWidth;
  159. s.PosHexEnd = s.PosHexStart + (s.HexCellWidth * Cols);
  160. s.PosAsciiStart = s.PosAsciiEnd = s.PosHexEnd;
  161. if (OptShowAscii)
  162. {
  163. s.PosAsciiStart = s.PosHexEnd + s.GlyphWidth * 1;
  164. if (OptMidColsCount > 0)
  165. s.PosAsciiStart += (float)((Cols + OptMidColsCount - 1) / OptMidColsCount) * s.SpacingBetweenMidCols;
  166. s.PosAsciiEnd = s.PosAsciiStart + Cols * s.GlyphWidth;
  167. }
  168. s.WindowWidth = s.PosAsciiEnd + style.ScrollbarSize + style.WindowPadding.x * 2 + s.GlyphWidth;
  169. }
  170. // Standalone Memory Editor window
  171. void DrawWindow(const char* title, void* mem_data, size_t mem_size, size_t base_display_addr = 0x0000)
  172. {
  173. Sizes s;
  174. CalcSizes(s, mem_size, base_display_addr);
  175. ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, 0.0f), ImVec2(s.WindowWidth, FLT_MAX));
  176. Open = true;
  177. if (ImGui::Begin(title, &Open, ImGuiWindowFlags_NoScrollbar))
  178. {
  179. if (ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) && ImGui::IsMouseReleased(ImGuiMouseButton_Right))
  180. ImGui::OpenPopup("context");
  181. DrawContents(mem_data, mem_size, base_display_addr);
  182. if (ContentsWidthChanged)
  183. {
  184. CalcSizes(s, mem_size, base_display_addr);
  185. ImGui::SetWindowSize(ImVec2(s.WindowWidth, ImGui::GetWindowSize().y));
  186. }
  187. }
  188. ImGui::End();
  189. }
  190. // Memory Editor contents only
  191. void DrawContents(void* mem_data_void, size_t mem_size, size_t base_display_addr = 0x0000)
  192. {
  193. if (Cols < 1)
  194. Cols = 1;
  195. ImU8* mem_data = (ImU8*)mem_data_void;
  196. Sizes s;
  197. CalcSizes(s, mem_size, base_display_addr);
  198. ImGuiStyle& style = ImGui::GetStyle();
  199. // We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window.
  200. // 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.
  201. const float height_separator = style.ItemSpacing.y;
  202. float footer_height = OptFooterExtraHeight;
  203. if (OptShowOptions)
  204. footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1;
  205. if (OptShowDataPreview)
  206. footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1 + ImGui::GetTextLineHeightWithSpacing() * 3;
  207. ImGui::BeginChild("##scrolling", ImVec2(0, -footer_height), false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNav);
  208. ImDrawList* draw_list = ImGui::GetWindowDrawList();
  209. ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
  210. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
  211. // We are not really using the clipper API correctly here, because we rely on visible_start_addr/visible_end_addr for our scrolling function.
  212. const int line_total_count = (int)((mem_size + Cols - 1) / Cols);
  213. ImGuiListClipper clipper;
  214. clipper.Begin(line_total_count, s.LineHeight);
  215. clipper.Step();
  216. const size_t visible_start_addr = clipper.DisplayStart * Cols;
  217. const size_t visible_end_addr = clipper.DisplayEnd * Cols;
  218. bool data_next = false;
  219. if (ReadOnly || DataEditingAddr >= mem_size)
  220. DataEditingAddr = (size_t)-1;
  221. if (DataPreviewAddr >= mem_size)
  222. DataPreviewAddr = (size_t)-1;
  223. size_t preview_data_type_size = OptShowDataPreview ? DataTypeGetSize(PreviewDataType) : 0;
  224. size_t data_editing_addr_backup = DataEditingAddr;
  225. size_t data_editing_addr_next = (size_t)-1;
  226. if (DataEditingAddr != (size_t)-1)
  227. {
  228. // 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)
  229. if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_UpArrow)) && DataEditingAddr >= (size_t)Cols) { data_editing_addr_next = DataEditingAddr - Cols; DataEditingTakeFocus = true; }
  230. else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_DownArrow)) && DataEditingAddr < mem_size - Cols) { data_editing_addr_next = DataEditingAddr + Cols; DataEditingTakeFocus = true; }
  231. else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_LeftArrow)) && DataEditingAddr > 0) { data_editing_addr_next = DataEditingAddr - 1; DataEditingTakeFocus = true; }
  232. else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_RightArrow)) && DataEditingAddr < mem_size - 1) { data_editing_addr_next = DataEditingAddr + 1; DataEditingTakeFocus = true; }
  233. }
  234. if (data_editing_addr_next != (size_t)-1 && (data_editing_addr_next / Cols) != (data_editing_addr_backup / Cols))
  235. {
  236. // Track cursor movements
  237. const int scroll_offset = ((int)(data_editing_addr_next / Cols) - (int)(data_editing_addr_backup / Cols));
  238. 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);
  239. if (scroll_desired)
  240. ImGui::SetScrollY(ImGui::GetScrollY() + scroll_offset * s.LineHeight);
  241. }
  242. // Draw vertical separator
  243. ImVec2 window_pos = ImGui::GetWindowPos();
  244. if (OptShowAscii)
  245. 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));
  246. const ImU32 color_text = ImGui::GetColorU32(ImGuiCol_Text);
  247. const ImU32 color_disabled = OptGreyOutZeroes ? ImGui::GetColorU32(ImGuiCol_TextDisabled) : color_text;
  248. const char* format_address = OptUpperCaseHex ? "%0*" _PRISizeT "X: " : "%0*" _PRISizeT "x: ";
  249. const char* format_data = OptUpperCaseHex ? "%0*" _PRISizeT "X" : "%0*" _PRISizeT "x";
  250. const char* format_byte = OptUpperCaseHex ? "%02X" : "%02x";
  251. const char* format_byte_space = OptUpperCaseHex ? "%02X " : "%02x ";
  252. for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible lines
  253. {
  254. size_t addr = (size_t)(line_i * Cols);
  255. ImGui::Text(format_address, s.AddrDigitsCount, base_display_addr + addr);
  256. // Draw Hexadecimal
  257. for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
  258. {
  259. float byte_pos_x = s.PosHexStart + s.HexCellWidth * n;
  260. if (OptMidColsCount > 0)
  261. byte_pos_x += (float)(n / OptMidColsCount) * s.SpacingBetweenMidCols;
  262. ImGui::SameLine(byte_pos_x);
  263. // Draw highlight
  264. bool is_highlight_from_user_range = (addr >= HighlightMin && addr < HighlightMax);
  265. bool is_highlight_from_user_func = (HighlightFn && HighlightFn(mem_data, addr));
  266. bool is_highlight_from_preview = (addr >= DataPreviewAddr && addr < DataPreviewAddr + preview_data_type_size);
  267. if (is_highlight_from_user_range || is_highlight_from_user_func || is_highlight_from_preview)
  268. {
  269. ImVec2 pos = ImGui::GetCursorScreenPos();
  270. float highlight_width = s.GlyphWidth * 2;
  271. bool is_next_byte_highlighted = (addr + 1 < mem_size) && ((HighlightMax != (size_t)-1 && addr + 1 < HighlightMax) || (HighlightFn && HighlightFn(mem_data, addr + 1)));
  272. if (is_next_byte_highlighted || (n + 1 == Cols))
  273. {
  274. highlight_width = s.HexCellWidth;
  275. if (OptMidColsCount > 0 && n > 0 && (n + 1) < Cols && ((n + 1) % OptMidColsCount) == 0)
  276. highlight_width += s.SpacingBetweenMidCols;
  277. }
  278. draw_list->AddRectFilled(pos, ImVec2(pos.x + highlight_width, pos.y + s.LineHeight), HighlightColor);
  279. }
  280. if (DataEditingAddr == addr)
  281. {
  282. // Display text input on current byte
  283. bool data_write = false;
  284. ImGui::PushID((void*)addr);
  285. if (DataEditingTakeFocus)
  286. {
  287. ImGui::SetKeyboardFocusHere();
  288. ImGui::CaptureKeyboardFromApp(true);
  289. sprintf(AddrInputBuf, format_data, s.AddrDigitsCount, base_display_addr + addr);
  290. sprintf(DataInputBuf, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
  291. }
  292. struct UserData
  293. {
  294. // 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.
  295. static int Callback(ImGuiInputTextCallbackData* data)
  296. {
  297. UserData* user_data = (UserData*)data->UserData;
  298. if (!data->HasSelection())
  299. user_data->CursorPos = data->CursorPos;
  300. if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen)
  301. {
  302. // 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)
  303. data->DeleteChars(0, data->BufTextLen);
  304. data->InsertChars(0, user_data->CurrentBufOverwrite);
  305. data->SelectionStart = 0;
  306. data->SelectionEnd = 2;
  307. data->CursorPos = 0;
  308. }
  309. return 0;
  310. }
  311. char CurrentBufOverwrite[3]; // Input
  312. int CursorPos; // Output
  313. };
  314. UserData user_data;
  315. user_data.CursorPos = -1;
  316. sprintf(user_data.CurrentBufOverwrite, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
  317. ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoHorizontalScroll | ImGuiInputTextFlags_CallbackAlways;
  318. #if IMGUI_VERSION_NUM >= 18104
  319. flags |= ImGuiInputTextFlags_AlwaysOverwrite;
  320. #else
  321. flags |= ImGuiInputTextFlags_AlwaysInsertMode;
  322. #endif
  323. ImGui::SetNextItemWidth(s.GlyphWidth * 2);
  324. if (ImGui::InputText("##data", DataInputBuf, IM_ARRAYSIZE(DataInputBuf), flags, UserData::Callback, &user_data))
  325. data_write = data_next = true;
  326. else if (!DataEditingTakeFocus && !ImGui::IsItemActive())
  327. DataEditingAddr = data_editing_addr_next = (size_t)-1;
  328. DataEditingTakeFocus = false;
  329. if (user_data.CursorPos >= 2)
  330. data_write = data_next = true;
  331. if (data_editing_addr_next != (size_t)-1)
  332. data_write = data_next = false;
  333. unsigned int data_input_value = 0;
  334. if (data_write && sscanf(DataInputBuf, "%X", &data_input_value) == 1)
  335. {
  336. if (WriteFn)
  337. WriteFn(mem_data, addr, (ImU8)data_input_value);
  338. else
  339. mem_data[addr] = (ImU8)data_input_value;
  340. }
  341. ImGui::PopID();
  342. }
  343. else
  344. {
  345. // NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on.
  346. ImU8 b = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
  347. if (OptShowHexII)
  348. {
  349. if ((b >= 32 && b < 128))
  350. ImGui::Text(".%c ", b);
  351. else if (b == 0xFF && OptGreyOutZeroes)
  352. ImGui::TextDisabled("## ");
  353. else if (b == 0x00)
  354. ImGui::Text(" ");
  355. else
  356. ImGui::Text(format_byte_space, b);
  357. }
  358. else
  359. {
  360. if (b == 0 && OptGreyOutZeroes)
  361. ImGui::TextDisabled("00 ");
  362. else
  363. ImGui::Text(format_byte_space, b);
  364. }
  365. if (!ReadOnly && ImGui::IsItemHovered() && ImGui::IsMouseClicked(0))
  366. {
  367. DataEditingTakeFocus = true;
  368. data_editing_addr_next = addr;
  369. }
  370. }
  371. }
  372. if (OptShowAscii)
  373. {
  374. // Draw ASCII values
  375. ImGui::SameLine(s.PosAsciiStart);
  376. ImVec2 pos = ImGui::GetCursorScreenPos();
  377. addr = line_i * Cols;
  378. ImGui::PushID(line_i);
  379. if (ImGui::InvisibleButton("ascii", ImVec2(s.PosAsciiEnd - s.PosAsciiStart, s.LineHeight)))
  380. {
  381. DataEditingAddr = DataPreviewAddr = addr + (size_t)((ImGui::GetIO().MousePos.x - pos.x) / s.GlyphWidth);
  382. DataEditingTakeFocus = true;
  383. }
  384. ImGui::PopID();
  385. for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
  386. {
  387. if (addr == DataEditingAddr)
  388. {
  389. draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_FrameBg));
  390. draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_TextSelectedBg));
  391. }
  392. unsigned char c = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
  393. char display_c = (c < 32 || c >= 128) ? '.' : c;
  394. draw_list->AddText(pos, (display_c == c) ? color_text : color_disabled, &display_c, &display_c + 1);
  395. pos.x += s.GlyphWidth;
  396. }
  397. }
  398. }
  399. IM_ASSERT(clipper.Step() == false);
  400. clipper.End();
  401. ImGui::PopStyleVar(2);
  402. ImGui::EndChild();
  403. // Notify the main window of our ideal child content size (FIXME: we are missing an API to get the contents size from the child)
  404. ImGui::SetCursorPosX(s.WindowWidth);
  405. if (data_next && DataEditingAddr < mem_size)
  406. {
  407. DataEditingAddr = DataPreviewAddr = DataEditingAddr + 1;
  408. DataEditingTakeFocus = true;
  409. }
  410. else if (data_editing_addr_next != (size_t)-1)
  411. {
  412. DataEditingAddr = DataPreviewAddr = data_editing_addr_next;
  413. }
  414. const bool lock_show_data_preview = OptShowDataPreview;
  415. if (OptShowOptions)
  416. {
  417. ImGui::Separator();
  418. DrawOptionsLine(s, mem_data, mem_size, base_display_addr);
  419. }
  420. if (lock_show_data_preview)
  421. {
  422. ImGui::Separator();
  423. DrawPreviewLine(s, mem_data, mem_size, base_display_addr);
  424. }
  425. }
  426. void DrawOptionsLine(const Sizes& s, void* mem_data, size_t mem_size, size_t base_display_addr)
  427. {
  428. IM_UNUSED(mem_data);
  429. ImGuiStyle& style = ImGui::GetStyle();
  430. const char* format_range = OptUpperCaseHex ? "Range %0*" _PRISizeT "X..%0*" _PRISizeT "X" : "Range %0*" _PRISizeT "x..%0*" _PRISizeT "x";
  431. // Options menu
  432. if (ImGui::Button("Options"))
  433. ImGui::OpenPopup("context");
  434. if (ImGui::BeginPopup("context"))
  435. {
  436. ImGui::SetNextItemWidth(s.GlyphWidth * 7 + style.FramePadding.x * 2.0f);
  437. if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; if (Cols < 1) Cols = 1; }
  438. ImGui::Checkbox("Show Data Preview", &OptShowDataPreview);
  439. ImGui::Checkbox("Show HexII", &OptShowHexII);
  440. if (ImGui::Checkbox("Show Ascii", &OptShowAscii)) { ContentsWidthChanged = true; }
  441. ImGui::Checkbox("Grey out zeroes", &OptGreyOutZeroes);
  442. ImGui::Checkbox("Uppercase Hex", &OptUpperCaseHex);
  443. ImGui::EndPopup();
  444. }
  445. ImGui::SameLine();
  446. ImGui::Text(format_range, s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1);
  447. ImGui::SameLine();
  448. ImGui::SetNextItemWidth((s.AddrDigitsCount + 1) * s.GlyphWidth + style.FramePadding.x * 2.0f);
  449. if (ImGui::InputText("##addr", AddrInputBuf, IM_ARRAYSIZE(AddrInputBuf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue))
  450. {
  451. size_t goto_addr;
  452. if (sscanf(AddrInputBuf, "%" _PRISizeT "X", &goto_addr) == 1)
  453. {
  454. GotoAddr = goto_addr - base_display_addr;
  455. HighlightMin = HighlightMax = (size_t)-1;
  456. }
  457. }
  458. if (GotoAddr != (size_t)-1)
  459. {
  460. if (GotoAddr < mem_size)
  461. {
  462. ImGui::BeginChild("##scrolling");
  463. ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + (GotoAddr / Cols) * ImGui::GetTextLineHeight());
  464. ImGui::EndChild();
  465. DataEditingAddr = DataPreviewAddr = GotoAddr;
  466. DataEditingTakeFocus = true;
  467. }
  468. GotoAddr = (size_t)-1;
  469. }
  470. }
  471. void DrawPreviewLine(const Sizes& s, void* mem_data_void, size_t mem_size, size_t base_display_addr)
  472. {
  473. IM_UNUSED(base_display_addr);
  474. ImU8* mem_data = (ImU8*)mem_data_void;
  475. ImGuiStyle& style = ImGui::GetStyle();
  476. ImGui::AlignTextToFramePadding();
  477. ImGui::Text("Preview as:");
  478. ImGui::SameLine();
  479. ImGui::SetNextItemWidth((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 < ImGuiDataType_COUNT; n++)
  483. if (ImGui::Selectable(DataTypeGetDesc((ImGuiDataType)n), PreviewDataType == n))
  484. PreviewDataType = (ImGuiDataType)n;
  485. ImGui::EndCombo();
  486. }
  487. ImGui::SameLine();
  488. ImGui::SetNextItemWidth((s.GlyphWidth * 6.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
  489. ImGui::Combo("##combo_endianess", &PreviewEndianess, "LE\0BE\0\0");
  490. char buf[128] = "";
  491. float x = s.GlyphWidth * 6.0f;
  492. bool has_value = DataPreviewAddr != (size_t)-1;
  493. if (has_value)
  494. DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Dec, buf, (size_t)IM_ARRAYSIZE(buf));
  495. ImGui::Text("Dec"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
  496. if (has_value)
  497. DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Hex, buf, (size_t)IM_ARRAYSIZE(buf));
  498. ImGui::Text("Hex"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
  499. if (has_value)
  500. DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Bin, buf, (size_t)IM_ARRAYSIZE(buf));
  501. buf[IM_ARRAYSIZE(buf) - 1] = 0;
  502. ImGui::Text("Bin"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
  503. }
  504. // Utilities for Data Preview
  505. const char* DataTypeGetDesc(ImGuiDataType data_type) const
  506. {
  507. const char* descs[] = { "Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64", "Float", "Double" };
  508. IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
  509. return descs[data_type];
  510. }
  511. size_t DataTypeGetSize(ImGuiDataType data_type) const
  512. {
  513. const size_t sizes[] = { 1, 1, 2, 2, 4, 4, 8, 8, sizeof(float), sizeof(double) };
  514. IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
  515. return sizes[data_type];
  516. }
  517. const char* DataFormatGetDesc(DataFormat data_format) const
  518. {
  519. const char* descs[] = { "Bin", "Dec", "Hex" };
  520. IM_ASSERT(data_format >= 0 && data_format < DataFormat_COUNT);
  521. return descs[data_format];
  522. }
  523. bool IsBigEndian() const
  524. {
  525. uint16_t x = 1;
  526. char c[2];
  527. memcpy(c, &x, 2);
  528. return c[0] != 0;
  529. }
  530. static void* EndianessCopyBigEndian(void* _dst, void* _src, size_t s, int is_little_endian)
  531. {
  532. if (is_little_endian)
  533. {
  534. uint8_t* dst = (uint8_t*)_dst;
  535. uint8_t* src = (uint8_t*)_src + s - 1;
  536. for (int i = 0, n = (int)s; i < n; ++i)
  537. memcpy(dst++, src--, 1);
  538. return _dst;
  539. }
  540. else
  541. {
  542. return memcpy(_dst, _src, s);
  543. }
  544. }
  545. static void* EndianessCopyLittleEndian(void* _dst, void* _src, size_t s, int is_little_endian)
  546. {
  547. if (is_little_endian)
  548. {
  549. return memcpy(_dst, _src, s);
  550. }
  551. else
  552. {
  553. uint8_t* dst = (uint8_t*)_dst;
  554. uint8_t* src = (uint8_t*)_src + s - 1;
  555. for (int i = 0, n = (int)s; i < n; ++i)
  556. memcpy(dst++, src--, 1);
  557. return _dst;
  558. }
  559. }
  560. void* EndianessCopy(void* dst, void* src, size_t size) const
  561. {
  562. static void* (*fp)(void*, void*, size_t, int) = NULL;
  563. if (fp == NULL)
  564. fp = IsBigEndian() ? EndianessCopyBigEndian : EndianessCopyLittleEndian;
  565. return fp(dst, src, size, PreviewEndianess);
  566. }
  567. const char* FormatBinary(const uint8_t* buf, int width) const
  568. {
  569. IM_ASSERT(width <= 64);
  570. size_t out_n = 0;
  571. static char out_buf[64 + 8 + 1];
  572. int n = width / 8;
  573. for (int j = n - 1; j >= 0; --j)
  574. {
  575. for (int i = 0; i < 8; ++i)
  576. out_buf[out_n++] = (buf[j] & (1 << (7 - i))) ? '1' : '0';
  577. out_buf[out_n++] = ' ';
  578. }
  579. IM_ASSERT(out_n < IM_ARRAYSIZE(out_buf));
  580. out_buf[out_n] = 0;
  581. return out_buf;
  582. }
  583. // [Internal]
  584. 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
  585. {
  586. uint8_t buf[8];
  587. size_t elem_size = DataTypeGetSize(data_type);
  588. size_t size = addr + elem_size > mem_size ? mem_size - addr : elem_size;
  589. if (ReadFn)
  590. for (int i = 0, n = (int)size; i < n; ++i)
  591. buf[i] = ReadFn(mem_data, addr + i);
  592. else
  593. memcpy(buf, mem_data + addr, size);
  594. if (data_format == DataFormat_Bin)
  595. {
  596. uint8_t binbuf[8];
  597. EndianessCopy(binbuf, buf, size);
  598. ImSnprintf(out_buf, out_buf_size, "%s", FormatBinary(binbuf, (int)size * 8));
  599. return;
  600. }
  601. out_buf[0] = 0;
  602. switch (data_type)
  603. {
  604. case ImGuiDataType_S8:
  605. {
  606. int8_t int8 = 0;
  607. EndianessCopy(&int8, buf, size);
  608. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhd", int8); return; }
  609. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", int8 & 0xFF); return; }
  610. break;
  611. }
  612. case ImGuiDataType_U8:
  613. {
  614. uint8_t uint8 = 0;
  615. EndianessCopy(&uint8, buf, size);
  616. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhu", uint8); return; }
  617. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", uint8 & 0XFF); return; }
  618. break;
  619. }
  620. case ImGuiDataType_S16:
  621. {
  622. int16_t int16 = 0;
  623. EndianessCopy(&int16, buf, size);
  624. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hd", int16); return; }
  625. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", int16 & 0xFFFF); return; }
  626. break;
  627. }
  628. case ImGuiDataType_U16:
  629. {
  630. uint16_t uint16 = 0;
  631. EndianessCopy(&uint16, buf, size);
  632. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hu", uint16); return; }
  633. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", uint16 & 0xFFFF); return; }
  634. break;
  635. }
  636. case ImGuiDataType_S32:
  637. {
  638. int32_t int32 = 0;
  639. EndianessCopy(&int32, buf, size);
  640. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%d", int32); return; }
  641. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", int32); return; }
  642. break;
  643. }
  644. case ImGuiDataType_U32:
  645. {
  646. uint32_t uint32 = 0;
  647. EndianessCopy(&uint32, buf, size);
  648. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%u", uint32); return; }
  649. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", uint32); return; }
  650. break;
  651. }
  652. case ImGuiDataType_S64:
  653. {
  654. int64_t int64 = 0;
  655. EndianessCopy(&int64, buf, size);
  656. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%lld", (long long)int64); return; }
  657. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)int64); return; }
  658. break;
  659. }
  660. case ImGuiDataType_U64:
  661. {
  662. uint64_t uint64 = 0;
  663. EndianessCopy(&uint64, buf, size);
  664. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%llu", (long long)uint64); return; }
  665. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)uint64); return; }
  666. break;
  667. }
  668. case ImGuiDataType_Float:
  669. {
  670. float float32 = 0.0f;
  671. EndianessCopy(&float32, buf, size);
  672. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float32); return; }
  673. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float32); return; }
  674. break;
  675. }
  676. case ImGuiDataType_Double:
  677. {
  678. double float64 = 0.0;
  679. EndianessCopy(&float64, buf, size);
  680. if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float64); return; }
  681. if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float64); return; }
  682. break;
  683. }
  684. case ImGuiDataType_COUNT:
  685. break;
  686. } // Switch
  687. IM_ASSERT(0); // Shouldn't reach
  688. }
  689. };
  690. #undef _PRISizeT
  691. #undef ImSnprintf
  692. #ifdef _MSC_VER
  693. #pragma warning (pop)
  694. #endif