Path: blob/21.2-virgl/src/imgui/imgui_memory_editor.h
4558 views
// Mini memory editor for Dear ImGui (to embed in your game/tools)1// Animated GIF: https://twitter.com/ocornut/status/8942427043175301122// Get latest version at http://www.github.com/ocornut/imgui_club3//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! If you don't use the default font, use ImGui::PushFont()/PopFont() to switch to a mono-space font before caling this.7//8// Usage:9// static MemoryEditor mem_edit_1; // store your state somewhere10// 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())11//12// Usage:13// static MemoryEditor mem_edit_2;14// ImGui::Begin("MyWindow")15// mem_edit_2.DrawContents(this, sizeof(*this), (size_t)this);16// ImGui::End();17//18// Changelog:19// - v0.10: initial version20// - v0.11: always refresh active text input with the latest byte from source memory if it's not being edited.21// - v0.12: added OptMidRowsCount to allow extra spacing every XX rows.22// - v0.13: added optional ReadFn/WriteFn handlers to access memory via a function. various warning fixes for 64-bits.23// - v0.14: added GotoAddr member, added GotoAddrAndHighlight() and highlighting. fixed minor scrollbar glitch when resizing.24// - v0.15: added maximum window width. minor optimization.25// - v0.16: added OptGreyOutZeroes option. various sizing fixes when resizing using the "Rows" drag.26// - v0.17: added HighlightFn handler for optional non-contiguous highlighting.27// - v0.18: fixes for displaying 64-bits addresses, fixed mouse click gaps introduced in recent changes, cursor tracking scrolling fixes.28// - v0.19: fixed auto-focus of next byte leaving WantCaptureKeyboard=false for one frame. we now capture the keyboard during that transition.29// - v0.20: added options menu. added OptShowAscii checkbox. added optional HexII display. split Draw() in DrawWindow()/DrawContents(). fixing glyph width. refactoring/cleaning code.30// - v0.21: fixes for using DrawContents() in our own window. fixed HexII to actually be useful and not on the wrong side.31// - v0.22: clicking Ascii view select the byte in the Hex view. Ascii view highlight selection.32// - v0.23: fixed right-arrow triggering a byte write.33// - v0.24: changed DragInt("Rows" to use a %d data format (which is desirable since imgui 1.61).34// - v0.25: fixed wording: all occurrences of "Rows" renamed to "Columns".35// - v0.26: fixed clicking on hex region36// - v0.30: added data preview for common data types37// - v0.31: added OptUpperCaseHex option to select lower/upper casing display [@samhocevar]38// - v0.32: changed signatures to use void* instead of unsigned char*39// - v0.33: added OptShowOptions option to hide all the interactive option setting.40// - v0.34: binary preview now applies endianess setting [@nicolasnoble]41//42// Todo/Bugs:43// - Arrows are being sent to the InputText() about to disappear which for LeftArrow makes the text cursor appear at position 1 for one frame.44// - Using InputText() is awkward and maybe overkill here, consider implementing something custom.4546#pragma once47#include <stdio.h> // sprintf, scanf48#include <stdint.h> // uint8_t, etc.4950#ifdef _MSC_VER51#define _PRISizeT "I"52#define ImSnprintf _snprintf53#else54#define _PRISizeT "z"55#define ImSnprintf snprintf56#endif5758struct MemoryEditor59{60typedef unsigned char u8;6162enum DataType63{64DataType_S8,65DataType_U8,66DataType_S16,67DataType_U16,68DataType_S32,69DataType_U32,70DataType_S64,71DataType_U64,72DataType_Float,73DataType_Double,74DataType_COUNT75};7677enum DataFormat78{79DataFormat_Bin = 0,80DataFormat_Dec = 1,81DataFormat_Hex = 2,82DataFormat_COUNT83};8485// Settings86bool Open; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow().87bool ReadOnly; // = false // disable any editing.88int Cols; // = 16 // number of columns to display.89bool OptShowOptions; // = true // display options button/context menu. when disabled, options will be locked unless you provide your own UI for them.90bool OptShowDataPreview; // = false // display a footer previewing the decimal/binary/hex/float representation of the currently selected bytes.91bool OptShowHexII; // = false // display values in HexII representation instead of regular hexadecimal: hide null/zero bytes, ascii values as ".X".92bool OptShowAscii; // = true // display ASCII representation on the right side.93bool OptGreyOutZeroes; // = true // display null/zero bytes using the TextDisabled color.94bool OptUpperCaseHex; // = true // display hexadecimal values as "FF" instead of "ff".95int OptMidColsCount; // = 8 // set to 0 to disable extra spacing between every mid-cols.96int OptAddrDigitsCount; // = 0 // number of addr digits to display (default calculated based on maximum displayed addr).97ImU32 HighlightColor; // // background color of highlighted bytes.98u8 (*ReadFn)(const u8* data, size_t off); // = NULL // optional handler to read bytes.99void (*WriteFn)(u8* data, size_t off, u8 d); // = NULL // optional handler to write bytes.100bool (*HighlightFn)(const u8* data, size_t off);//NULL // optional handler to return Highlight property (to support non-contiguous highlighting).101102// [Internal State]103bool ContentsWidthChanged;104size_t DataPreviewAddr;105size_t DataEditingAddr;106bool DataEditingTakeFocus;107char DataInputBuf[32];108char AddrInputBuf[32];109size_t GotoAddr;110size_t HighlightMin, HighlightMax;111int PreviewEndianess;112DataType PreviewDataType;113114MemoryEditor()115{116// Settings117Open = true;118ReadOnly = false;119Cols = 16;120OptShowOptions = true;121OptShowDataPreview = false;122OptShowHexII = false;123OptShowAscii = true;124OptGreyOutZeroes = true;125OptUpperCaseHex = true;126OptMidColsCount = 8;127OptAddrDigitsCount = 0;128HighlightColor = IM_COL32(255, 255, 255, 50);129ReadFn = NULL;130WriteFn = NULL;131HighlightFn = NULL;132133// State/Internals134ContentsWidthChanged = false;135DataPreviewAddr = DataEditingAddr = (size_t)-1;136DataEditingTakeFocus = false;137memset(DataInputBuf, 0, sizeof(DataInputBuf));138memset(AddrInputBuf, 0, sizeof(AddrInputBuf));139GotoAddr = (size_t)-1;140HighlightMin = HighlightMax = (size_t)-1;141PreviewEndianess = 0;142PreviewDataType = DataType_S32;143}144145void GotoAddrAndHighlight(size_t addr_min, size_t addr_max)146{147GotoAddr = addr_min;148HighlightMin = addr_min;149HighlightMax = addr_max;150}151152struct Sizes153{154int AddrDigitsCount;155float LineHeight;156float GlyphWidth;157float HexCellWidth;158float SpacingBetweenMidCols;159float PosHexStart;160float PosHexEnd;161float PosAsciiStart;162float PosAsciiEnd;163float WindowWidth;164};165166void CalcSizes(Sizes& s, size_t mem_size, size_t base_display_addr)167{168ImGuiStyle& style = ImGui::GetStyle();169s.AddrDigitsCount = OptAddrDigitsCount;170if (s.AddrDigitsCount == 0)171for (size_t n = base_display_addr + mem_size - 1; n > 0; n >>= 4)172s.AddrDigitsCount++;173s.LineHeight = ImGui::GetTextLineHeight();174s.GlyphWidth = ImGui::CalcTextSize("F").x + 1; // We assume the font is mono-space175s.HexCellWidth = (float)(int)(s.GlyphWidth * 2.5f); // "FF " we include trailing space in the width to easily catch clicks everywhere176s.SpacingBetweenMidCols = (float)(int)(s.HexCellWidth * 0.25f); // Every OptMidColsCount columns we add a bit of extra spacing177s.PosHexStart = (s.AddrDigitsCount + 2) * s.GlyphWidth;178s.PosHexEnd = s.PosHexStart + (s.HexCellWidth * Cols);179s.PosAsciiStart = s.PosAsciiEnd = s.PosHexEnd;180if (OptShowAscii)181{182s.PosAsciiStart = s.PosHexEnd + s.GlyphWidth * 1;183if (OptMidColsCount > 0)184s.PosAsciiStart += (float)((Cols + OptMidColsCount - 1) / OptMidColsCount) * s.SpacingBetweenMidCols;185s.PosAsciiEnd = s.PosAsciiStart + Cols * s.GlyphWidth;186}187s.WindowWidth = s.PosAsciiEnd + style.ScrollbarSize + style.WindowPadding.x * 2 + s.GlyphWidth;188}189190// Standalone Memory Editor window191void DrawWindow(const char* title, void* mem_data, size_t mem_size, size_t base_display_addr = 0x0000)192{193Sizes s;194CalcSizes(s, mem_size, base_display_addr);195ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, 0.0f), ImVec2(s.WindowWidth, FLT_MAX));196197Open = true;198if (ImGui::Begin(title, &Open, ImGuiWindowFlags_NoScrollbar))199{200if (ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) && ImGui::IsMouseClicked(1))201ImGui::OpenPopup("context");202DrawContents(mem_data, mem_size, base_display_addr);203if (ContentsWidthChanged)204{205CalcSizes(s, mem_size, base_display_addr);206ImGui::SetWindowSize(ImVec2(s.WindowWidth, ImGui::GetWindowSize().y));207}208}209ImGui::End();210}211212// Memory Editor contents only213void DrawContents(void* mem_data_void_ptr, size_t mem_size, size_t base_display_addr = 0x0000)214{215u8* mem_data = (u8*)mem_data_void_ptr;216Sizes s;217CalcSizes(s, mem_size, base_display_addr);218ImGuiStyle& style = ImGui::GetStyle();219220// We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window.221// 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.222const float height_separator = style.ItemSpacing.y;223float footer_height = 0;224if (OptShowOptions)225footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1;226if (OptShowDataPreview)227footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1 + ImGui::GetTextLineHeightWithSpacing() * 3;228ImGui::BeginChild("##scrolling", ImVec2(0, -footer_height), false, ImGuiWindowFlags_NoMove);229ImDrawList* draw_list = ImGui::GetWindowDrawList();230231ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));232ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));233234const int line_total_count = (int)((mem_size + Cols - 1) / Cols);235ImGuiListClipper clipper(line_total_count, s.LineHeight);236const size_t visible_start_addr = clipper.DisplayStart * Cols;237const size_t visible_end_addr = clipper.DisplayEnd * Cols;238239bool data_next = false;240241if (ReadOnly || DataEditingAddr >= mem_size)242DataEditingAddr = (size_t)-1;243if (DataPreviewAddr >= mem_size)244DataPreviewAddr = (size_t)-1;245246size_t preview_data_type_size = OptShowDataPreview ? DataTypeGetSize(PreviewDataType) : 0;247248size_t data_editing_addr_backup = DataEditingAddr;249size_t data_editing_addr_next = (size_t)-1;250if (DataEditingAddr != (size_t)-1)251{252// 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)253if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_UpArrow)) && DataEditingAddr >= (size_t)Cols) { data_editing_addr_next = DataEditingAddr - Cols; DataEditingTakeFocus = true; }254else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_DownArrow)) && DataEditingAddr < mem_size - Cols) { data_editing_addr_next = DataEditingAddr + Cols; DataEditingTakeFocus = true; }255else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_LeftArrow)) && DataEditingAddr > 0) { data_editing_addr_next = DataEditingAddr - 1; DataEditingTakeFocus = true; }256else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_RightArrow)) && DataEditingAddr < mem_size - 1) { data_editing_addr_next = DataEditingAddr + 1; DataEditingTakeFocus = true; }257}258if (data_editing_addr_next != (size_t)-1 && (data_editing_addr_next / Cols) != (data_editing_addr_backup / Cols))259{260// Track cursor movements261const int scroll_offset = ((int)(data_editing_addr_next / Cols) - (int)(data_editing_addr_backup / Cols));262const 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);263if (scroll_desired)264ImGui::SetScrollY(ImGui::GetScrollY() + scroll_offset * s.LineHeight);265}266267// Draw vertical separator268ImVec2 window_pos = ImGui::GetWindowPos();269if (OptShowAscii)270draw_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));271272const ImU32 color_text = ImGui::GetColorU32(ImGuiCol_Text);273const ImU32 color_disabled = OptGreyOutZeroes ? ImGui::GetColorU32(ImGuiCol_TextDisabled) : color_text;274275const char* format_address = OptUpperCaseHex ? "%0*" _PRISizeT "X: " : "%0*" _PRISizeT "x: ";276const char* format_data = OptUpperCaseHex ? "%0*" _PRISizeT "X" : "%0*" _PRISizeT "x";277const char* format_range = OptUpperCaseHex ? "Range %0*" _PRISizeT "X..%0*" _PRISizeT "X" : "Range %0*" _PRISizeT "x..%0*" _PRISizeT "x";278const char* format_byte = OptUpperCaseHex ? "%02X" : "%02x";279const char* format_byte_space = OptUpperCaseHex ? "%02X " : "%02x ";280281for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible lines282{283size_t addr = (size_t)(line_i * Cols);284ImGui::Text(format_address, s.AddrDigitsCount, base_display_addr + addr);285286// Draw Hexadecimal287for (int n = 0; n < Cols && addr < mem_size; n++, addr++)288{289float byte_pos_x = s.PosHexStart + s.HexCellWidth * n;290if (OptMidColsCount > 0)291byte_pos_x += (float)(n / OptMidColsCount) * s.SpacingBetweenMidCols;292ImGui::SameLine(byte_pos_x);293294// Draw highlight295bool is_highlight_from_user_range = (addr >= HighlightMin && addr < HighlightMax);296bool is_highlight_from_user_func = (HighlightFn && HighlightFn(mem_data, addr));297bool is_highlight_from_preview = (addr >= DataPreviewAddr && addr < DataPreviewAddr + preview_data_type_size);298if (is_highlight_from_user_range || is_highlight_from_user_func || is_highlight_from_preview)299{300ImVec2 pos = ImGui::GetCursorScreenPos();301float highlight_width = s.GlyphWidth * 2;302bool is_next_byte_highlighted = (addr + 1 < mem_size) && ((HighlightMax != (size_t)-1 && addr + 1 < HighlightMax) || (HighlightFn && HighlightFn(mem_data, addr + 1)));303if (is_next_byte_highlighted || (n + 1 == Cols))304{305highlight_width = s.HexCellWidth;306if (OptMidColsCount > 0 && n > 0 && (n + 1) < Cols && ((n + 1) % OptMidColsCount) == 0)307highlight_width += s.SpacingBetweenMidCols;308}309draw_list->AddRectFilled(pos, ImVec2(pos.x + highlight_width, pos.y + s.LineHeight), HighlightColor);310}311312if (DataEditingAddr == addr)313{314// Display text input on current byte315bool data_write = false;316ImGui::PushID((void*)addr);317if (DataEditingTakeFocus)318{319ImGui::SetKeyboardFocusHere();320ImGui::CaptureKeyboardFromApp(true);321sprintf(AddrInputBuf, format_data, s.AddrDigitsCount, base_display_addr + addr);322sprintf(DataInputBuf, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);323}324ImGui::PushItemWidth(s.GlyphWidth * 2);325struct UserData326{327// 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.328static int Callback(ImGuiInputTextCallbackData* data)329{330UserData* user_data = (UserData*)data->UserData;331if (!data->HasSelection())332user_data->CursorPos = data->CursorPos;333if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen)334{335// 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)336data->DeleteChars(0, data->BufTextLen);337data->InsertChars(0, user_data->CurrentBufOverwrite);338data->SelectionStart = 0;339data->SelectionEnd = data->CursorPos = 2;340}341return 0;342}343char CurrentBufOverwrite[3]; // Input344int CursorPos; // Output345};346UserData user_data;347user_data.CursorPos = -1;348sprintf(user_data.CurrentBufOverwrite, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);349ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoHorizontalScroll | ImGuiInputTextFlags_AlwaysInsertMode | ImGuiInputTextFlags_CallbackAlways;350if (ImGui::InputText("##data", DataInputBuf, 32, flags, UserData::Callback, &user_data))351data_write = data_next = true;352else if (!DataEditingTakeFocus && !ImGui::IsItemActive())353DataEditingAddr = data_editing_addr_next = (size_t)-1;354DataEditingTakeFocus = false;355ImGui::PopItemWidth();356if (user_data.CursorPos >= 2)357data_write = data_next = true;358if (data_editing_addr_next != (size_t)-1)359data_write = data_next = false;360unsigned int data_input_value = 0;361if (data_write && sscanf(DataInputBuf, "%X", &data_input_value) == 1)362{363if (WriteFn)364WriteFn(mem_data, addr, (u8)data_input_value);365else366mem_data[addr] = (u8)data_input_value;367}368ImGui::PopID();369}370else371{372// NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on.373u8 b = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];374375if (OptShowHexII)376{377if ((b >= 32 && b < 128))378ImGui::Text(".%c ", b);379else if (b == 0xFF && OptGreyOutZeroes)380ImGui::TextDisabled("## ");381else if (b == 0x00)382ImGui::Text(" ");383else384ImGui::Text(format_byte_space, b);385}386else387{388if (b == 0 && OptGreyOutZeroes)389ImGui::TextDisabled("00 ");390else391ImGui::Text(format_byte_space, b);392}393if (!ReadOnly && ImGui::IsItemHovered() && ImGui::IsMouseClicked(0))394{395DataEditingTakeFocus = true;396data_editing_addr_next = addr;397}398}399}400401if (OptShowAscii)402{403// Draw ASCII values404ImGui::SameLine(s.PosAsciiStart);405ImVec2 pos = ImGui::GetCursorScreenPos();406addr = line_i * Cols;407ImGui::PushID(line_i);408if (ImGui::InvisibleButton("ascii", ImVec2(s.PosAsciiEnd - s.PosAsciiStart, s.LineHeight)))409{410DataEditingAddr = DataPreviewAddr = addr + (size_t)((ImGui::GetIO().MousePos.x - pos.x) / s.GlyphWidth);411DataEditingTakeFocus = true;412}413ImGui::PopID();414for (int n = 0; n < Cols && addr < mem_size; n++, addr++)415{416if (addr == DataEditingAddr)417{418draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_FrameBg));419draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_TextSelectedBg));420}421unsigned char c = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];422char display_c = (c < 32 || c >= 128) ? '.' : c;423draw_list->AddText(pos, (display_c == '.') ? color_disabled : color_text, &display_c, &display_c + 1);424pos.x += s.GlyphWidth;425}426}427}428clipper.End();429ImGui::PopStyleVar(2);430ImGui::EndChild();431432if (data_next && DataEditingAddr < mem_size)433{434DataEditingAddr = DataPreviewAddr = DataEditingAddr + 1;435DataEditingTakeFocus = true;436}437else if (data_editing_addr_next != (size_t)-1)438{439DataEditingAddr = DataPreviewAddr = data_editing_addr_next;440}441442bool next_show_data_preview = OptShowDataPreview;443if (OptShowOptions)444{445ImGui::Separator();446447// Options menu448449if (ImGui::Button("Options"))450ImGui::OpenPopup("context");451if (ImGui::BeginPopup("context"))452{453ImGui::PushItemWidth(56);454if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; }455ImGui::PopItemWidth();456ImGui::Checkbox("Show Data Preview", &next_show_data_preview);457ImGui::Checkbox("Show HexII", &OptShowHexII);458if (ImGui::Checkbox("Show Ascii", &OptShowAscii)) { ContentsWidthChanged = true; }459ImGui::Checkbox("Grey out zeroes", &OptGreyOutZeroes);460ImGui::Checkbox("Uppercase Hex", &OptUpperCaseHex);461462ImGui::EndPopup();463}464465ImGui::SameLine();466ImGui::Text(format_range, s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1);467ImGui::SameLine();468ImGui::PushItemWidth((s.AddrDigitsCount + 1) * s.GlyphWidth + style.FramePadding.x * 2.0f);469if (ImGui::InputText("##addr", AddrInputBuf, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue))470{471size_t goto_addr;472if (sscanf(AddrInputBuf, "%" _PRISizeT "X", &goto_addr) == 1)473{474GotoAddr = goto_addr - base_display_addr;475HighlightMin = HighlightMax = (size_t)-1;476}477}478ImGui::PopItemWidth();479480if (GotoAddr != (size_t)-1)481{482if (GotoAddr < mem_size)483{484ImGui::BeginChild("##scrolling");485ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + (GotoAddr / Cols) * ImGui::GetTextLineHeight());486ImGui::EndChild();487DataEditingAddr = DataPreviewAddr = GotoAddr;488DataEditingTakeFocus = true;489}490GotoAddr = (size_t)-1;491}492}493494if (OptShowDataPreview)495{496ImGui::Separator();497ImGui::AlignTextToFramePadding();498ImGui::Text("Preview as:");499ImGui::SameLine();500ImGui::PushItemWidth((s.GlyphWidth * 10.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);501if (ImGui::BeginCombo("##combo_type", DataTypeGetDesc(PreviewDataType), ImGuiComboFlags_HeightLargest))502{503for (int n = 0; n < DataType_COUNT; n++)504if (ImGui::Selectable(DataTypeGetDesc((DataType)n), PreviewDataType == n))505PreviewDataType = (DataType)n;506ImGui::EndCombo();507}508ImGui::PopItemWidth();509ImGui::SameLine();510ImGui::PushItemWidth((s.GlyphWidth * 6.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);511ImGui::Combo("##combo_endianess", &PreviewEndianess, "LE\0BE\0\0");512ImGui::PopItemWidth();513514char buf[128];515float x = s.GlyphWidth * 6.0f;516bool has_value = DataPreviewAddr != (size_t)-1;517if (has_value)518DisplayPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Dec, buf, (size_t)IM_ARRAYSIZE(buf));519ImGui::Text("Dec"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");520if (has_value)521DisplayPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Hex, buf, (size_t)IM_ARRAYSIZE(buf));522ImGui::Text("Hex"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");523if (has_value)524DisplayPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Bin, buf, (size_t)IM_ARRAYSIZE(buf));525ImGui::Text("Bin"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");526}527528OptShowDataPreview = next_show_data_preview;529530// Notify the main window of our ideal child content size (FIXME: we are missing an API to get the contents size from the child)531ImGui::SetCursorPosX(s.WindowWidth);532}533534// Utilities for Data Preview535const char* DataTypeGetDesc(DataType data_type) const536{537const char* descs[] = { "Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64", "Float", "Double" };538IM_ASSERT(data_type >= 0 && data_type < DataType_COUNT);539return descs[data_type];540}541542size_t DataTypeGetSize(DataType data_type) const543{544const size_t sizes[] = { 1, 1, 2, 2, 4, 4, 8, 8, 4, 8 };545IM_ASSERT(data_type >= 0 && data_type < DataType_COUNT);546return sizes[data_type];547}548549const char* DataFormatGetDesc(DataFormat data_format) const550{551const char* descs[] = { "Bin", "Dec", "Hex" };552IM_ASSERT(data_format >= 0 && data_format < DataFormat_COUNT);553return descs[data_format];554}555556bool IsBigEndian() const557{558uint16_t x = 1;559char c[2];560memcpy(c, &x, 2);561return c[0] != 0;562}563564static void* EndianessCopyBigEndian(void* _dst, void* _src, size_t s, int is_little_endian)565{566if (is_little_endian)567{568uint8_t* dst = (uint8_t*)_dst;569uint8_t* src = (uint8_t*)_src + s - 1;570for (int i = 0, n = (int)s; i < n; ++i)571memcpy(dst++, src--, 1);572return _dst;573}574else575{576return memcpy(_dst, _src, s);577}578}579580static void* EndianessCopyLittleEndian(void* _dst, void* _src, size_t s, int is_little_endian)581{582if (is_little_endian)583{584return memcpy(_dst, _src, s);585}586else587{588uint8_t* dst = (uint8_t*)_dst;589uint8_t* src = (uint8_t*)_src + s - 1;590for (int i = 0, n = (int)s; i < n; ++i)591memcpy(dst++, src--, 1);592return _dst;593}594}595596void* EndianessCopy(void *dst, void *src, size_t size) const597{598static void *(*fp)(void *, void *, size_t, int) = NULL;599if (fp == NULL)600fp = IsBigEndian() ? EndianessCopyBigEndian : EndianessCopyLittleEndian;601return fp(dst, src, size, PreviewEndianess);602}603604const char* FormatBinary(const uint8_t* buf, int width) const605{606IM_ASSERT(width <= 64);607size_t out_n = 0;608static char out_buf[64 + 8 + 1];609int n = width / 8;610for (int j = n - 1; j >= 0; --j)611{612for (int i = 0; i < 8; ++i)613out_buf[out_n++] = (buf[j] & (1 << (7 - i))) ? '1' : '0';614out_buf[out_n++] = ' ';615}616IM_ASSERT(out_n < IM_ARRAYSIZE(out_buf));617out_buf[out_n] = 0;618return out_buf;619}620621void 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) const622{623uint8_t buf[8];624size_t elem_size = DataTypeGetSize(data_type);625size_t size = addr + elem_size > mem_size ? mem_size - addr : elem_size;626if (ReadFn)627for (int i = 0, n = (int)size; i < n; ++i)628buf[i] = ReadFn(mem_data, addr + i);629else630memcpy(buf, mem_data + addr, size);631632if (data_format == DataFormat_Bin)633{634uint8_t binbuf[8];635EndianessCopy(binbuf, buf, size);636ImSnprintf(out_buf, out_buf_size, "%s", FormatBinary(binbuf, (int)size * 8));637return;638}639640out_buf[0] = 0;641switch (data_type)642{643case DataType_S8:644{645int8_t int8 = 0;646EndianessCopy(&int8, buf, size);647if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhd", int8); return; }648if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", int8 & 0xFF); return; }649break;650}651case DataType_U8:652{653uint8_t uint8 = 0;654EndianessCopy(&uint8, buf, size);655if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhu", uint8); return; }656if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", uint8 & 0XFF); return; }657break;658}659case DataType_S16:660{661int16_t int16 = 0;662EndianessCopy(&int16, buf, size);663if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hd", int16); return; }664if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", int16 & 0xFFFF); return; }665break;666}667case DataType_U16:668{669uint16_t uint16 = 0;670EndianessCopy(&uint16, buf, size);671if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hu", uint16); return; }672if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", uint16 & 0xFFFF); return; }673break;674}675case DataType_S32:676{677int32_t int32 = 0;678EndianessCopy(&int32, buf, size);679if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%d", int32); return; }680if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", int32); return; }681break;682}683case DataType_U32:684{685uint32_t uint32 = 0;686EndianessCopy(&uint32, buf, size);687if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%u", uint32); return; }688if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", uint32); return; }689break;690}691case DataType_S64:692{693int64_t int64 = 0;694EndianessCopy(&int64, buf, size);695if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%lld", (long long)int64); return; }696if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)int64); return; }697break;698}699case DataType_U64:700{701uint64_t uint64 = 0;702EndianessCopy(&uint64, buf, size);703if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%llu", (long long)uint64); return; }704if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)uint64); return; }705break;706}707case DataType_Float:708{709float float32 = 0.0f;710EndianessCopy(&float32, buf, size);711if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float32); return; }712if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float32); return; }713break;714}715case DataType_Double:716{717double float64 = 0.0;718EndianessCopy(&float64, buf, size);719if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float64); return; }720if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float64); return; }721break;722}723case DataType_COUNT:724break;725} // Switch726IM_ASSERT(0); // Shouldn't reach727}728};729730#undef _PRISizeT731#undef ImSnprintf732733734