cscg22-gearboy

CSCG 2022 Challenge 'Gearboy'
git clone https://git.sinitax.com/sinitax/cscg22-gearboy
Log | Files | Refs | sfeed.txt

imgui_memory_editor.h (36109B)


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