MemoryEditor: port of imgui_club imgui_memory_editor v0.59 (buffer / ByteData / byte tables), tests, Roblox + LÖVE examples
This commit is contained in:
commit
10bd6c45d1
18 files changed
+1852
No files matched your search
@@ -0,0 +1,3 @@
|
||||
[submodule "tools/core"]
|
||||
path = tools/core
|
||||
url = https://git.bug.tools/bug/imgui-luau.git
|
||||
@@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2024 Omar Cornut
|
||||
Copyright (c) 2026 4DBug (Luau port)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,655 @@
|
||||
-- Memory Editor for imgui-luau. Port of imgui_club's imgui_memory_editor.h v0.59
|
||||
-- (https://github.com/ocornut/imgui_club @ b083116866e05e0d4bccb2c7f28d94a76ee4965e).
|
||||
-- Usage (same as C++):
|
||||
-- local MemoryEditor = require(path.MemoryEditor)(G) -- G = the table returned by the ImGui module
|
||||
-- local mem_edit = MemoryEditor.new() -- C++: static MemoryEditor mem_edit;
|
||||
-- mem_edit:DrawWindow("Memory Editor", data, size) -- or mem_edit:DrawContents(data, size)
|
||||
-- [Port] mem_data (C++ void*) is a Roblox `buffer`, a LÖVE `ByteData` (FFI pointer, or getString() read-only
|
||||
-- without FFI) or a table of bytes (index 1 = offset 0). mem_size defaults to the data's length.
|
||||
-- Offsets/addresses are 0-based like upstream; "none" (C++ (size_t)-1) is -1.
|
||||
-- Plain Lua 5.1 syntax so the same file loads on LÖVE (LuaJIT).
|
||||
return function(G)
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
local ImGuiCol, ImGuiKey, ImGuiCond = G.ImGuiCol, G.ImGuiKey, G.ImGuiCond
|
||||
local ImGuiWindowFlags, ImGuiChildFlags, ImGuiInputTextFlags = G.ImGuiWindowFlags, G.ImGuiChildFlags, G.ImGuiInputTextFlags
|
||||
local ImGuiStyleVar, ImGuiComboFlags, ImGuiHoveredFlags, ImGuiDataType = G.ImGuiStyleVar, G.ImGuiComboFlags, G.ImGuiHoveredFlags, G.ImGuiDataType
|
||||
local FLT_MIN, FLT_MAX, IM_COL32 = G.FLT_MIN, G.FLT_MAX, G.IM_COL32
|
||||
local bor, floor, format, char, byte = bit32.bor, math.floor, string.format, string.char, string.byte
|
||||
local NONE = -1
|
||||
|
||||
local MemoryEditor = {}
|
||||
MemoryEditor.__index = MemoryEditor
|
||||
MemoryEditor.DataFormat_Bin, MemoryEditor.DataFormat_Dec, MemoryEditor.DataFormat_Hex, MemoryEditor.DataFormat_COUNT = 0, 1, 2, 3
|
||||
|
||||
-- [Port] void* -> accessors. Returns read(off) -> byte, write(off, byte) or nil, length.
|
||||
local ffi
|
||||
do
|
||||
local ok, m = pcall(require, "ffi")
|
||||
if ok then ffi = m end
|
||||
end
|
||||
local function Access(mem)
|
||||
local t = type(mem)
|
||||
if t == "buffer" then -- Roblox/Luau
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
return function(off) return readu8(mem, off) end, function(off, d) writeu8(mem, off, d) end, buffer.len(mem)
|
||||
elseif t == "string" then
|
||||
return function(off) return byte(mem, off + 1) or 0 end, nil, #mem
|
||||
elseif (t == "userdata" or t == "table") and mem.getSize then -- LÖVE Data (ByteData, ImageData, ...)
|
||||
local n = mem:getSize()
|
||||
if ffi and mem.getFFIPointer then
|
||||
local p = ffi.cast("uint8_t*", mem:getFFIPointer())
|
||||
return function(off) return p[off] end, function(off, d) p[off] = d end, n
|
||||
end
|
||||
local s = mem:getString()
|
||||
return function(off) return byte(s, off + 1) or 0 end, nil, n
|
||||
elseif t == "table" then
|
||||
return function(off) return mem[off + 1] or 0 end, function(off, d) mem[off + 1] = d end, #mem
|
||||
end
|
||||
error("MemoryEditor: unsupported mem_data type " .. t)
|
||||
end
|
||||
MemoryEditor.Access = Access
|
||||
|
||||
function MemoryEditor.new()
|
||||
local self = setmetatable({}, MemoryEditor)
|
||||
-- Settings
|
||||
self.Open = true -- set to false when DrawWindow() was closed. ignore if not using DrawWindow().
|
||||
self.ReadOnly = false -- disable any editing.
|
||||
self.Cols = 16 -- number of columns to display.
|
||||
self.OptShowOptions = true -- display options button/context menu.
|
||||
self.OptShowDataPreview = false -- display a footer previewing the decimal/binary/hex/float representation of the selected bytes.
|
||||
self.OptShowHexII = false -- display values in HexII representation instead of regular hexadecimal.
|
||||
self.OptShowAscii = true -- display ASCII representation on the right side.
|
||||
self.OptGreyOutZeroes = true -- display null/zero bytes using the TextDisabled color.
|
||||
self.OptUpperCaseHex = true -- display hexadecimal values as "FF" instead of "ff".
|
||||
self.OptMidColsCount = 8 -- set to 0 to disable extra spacing between every mid-cols.
|
||||
self.OptAddrDigitsCount = 0 -- number of addr digits to display (default calculated based on maximum displayed addr).
|
||||
self.OptFooterExtraHeight = 0.0 -- space to reserve at the bottom of the widget to add custom widgets
|
||||
self.HighlightColor = IM_COL32(255, 255, 255, 50)
|
||||
-- Function handlers: ReadFn(mem, off, user_data) -> byte, WriteFn(mem, off, d, user_data),
|
||||
-- HighlightFn(mem, off, user_data) -> bool, BgColorFn(mem, off, user_data) -> ImU32
|
||||
self.ReadFn, self.WriteFn, self.HighlightFn, self.BgColorFn, self.UserData = nil, nil, nil, nil, nil
|
||||
-- Public read-only data
|
||||
self.MouseHovered = false
|
||||
self.MouseHoveredAddr = 0
|
||||
-- [Internal State]
|
||||
self.ContentsWidthChanged = false
|
||||
self.DataPreviewAddr, self.DataEditingAddr = NONE, NONE
|
||||
self.DataEditingTakeFocus = false
|
||||
self.DataInputBuf = ImGui.NewTextBuffer("", 32)
|
||||
self.AddrInputBuf = ImGui.NewTextBuffer("", 32)
|
||||
self.GotoAddr = NONE
|
||||
self.HighlightMin, self.HighlightMax = NONE, NONE
|
||||
self.PreviewEndianness = 0
|
||||
self.PreviewDataType = ImGuiDataType.S32
|
||||
return self
|
||||
end
|
||||
|
||||
function MemoryEditor:GotoAddrAndHighlight(addr_min, addr_max)
|
||||
self.GotoAddr = addr_min
|
||||
self.HighlightMin = addr_min
|
||||
self.HighlightMax = addr_max
|
||||
end
|
||||
|
||||
function MemoryEditor:CalcSizes(s, mem_size, base_display_addr)
|
||||
local style = ImGui.GetStyle()
|
||||
s.AddrDigitsCount = self.OptAddrDigitsCount
|
||||
if s.AddrDigitsCount == 0 then
|
||||
local n = base_display_addr + mem_size - 1
|
||||
while n > 0 do s.AddrDigitsCount = s.AddrDigitsCount + 1; n = floor(n / 16) end
|
||||
end
|
||||
s.LineHeight = ImGui.GetTextLineHeight()
|
||||
s.GlyphWidth = ImGui.CalcTextSize("F").x + 1 -- We assume the font is mono-space
|
||||
s.HexCellWidth = floor(s.GlyphWidth * 2.5) -- "FF " we include trailing space in the width to easily catch clicks everywhere
|
||||
s.SpacingBetweenMidCols = floor(s.HexCellWidth * 0.25) -- Every OptMidColsCount columns we add a bit of extra spacing
|
||||
s.OffsetHexMinX = (s.AddrDigitsCount + 2) * s.GlyphWidth
|
||||
s.OffsetHexMaxX = s.OffsetHexMinX + (s.HexCellWidth * self.Cols)
|
||||
s.OffsetAsciiMinX, s.OffsetAsciiMaxX = s.OffsetHexMaxX, s.OffsetHexMaxX
|
||||
if self.OptShowAscii then
|
||||
s.OffsetAsciiMinX = s.OffsetHexMaxX + s.GlyphWidth * 1
|
||||
if self.OptMidColsCount > 0 then
|
||||
s.OffsetAsciiMinX = s.OffsetAsciiMinX + floor((self.Cols + self.OptMidColsCount - 1) / self.OptMidColsCount) * s.SpacingBetweenMidCols
|
||||
end
|
||||
s.OffsetAsciiMaxX = s.OffsetAsciiMinX + self.Cols * s.GlyphWidth
|
||||
end
|
||||
s.WindowWidth = s.OffsetAsciiMaxX + style.ScrollbarSize + style.WindowPadding.x * 2 + s.GlyphWidth
|
||||
end
|
||||
|
||||
-- Standalone Memory Editor window
|
||||
function MemoryEditor:DrawWindow(title, mem_data, mem_size, base_display_addr)
|
||||
if mem_size == nil then mem_size = select(3, Access(mem_data)) end
|
||||
base_display_addr = base_display_addr or 0
|
||||
local s = {}
|
||||
self:CalcSizes(s, mem_size, base_display_addr)
|
||||
ImGui.SetNextWindowSize(ImVec2(s.WindowWidth, s.WindowWidth * 0.60), ImGuiCond.FirstUseEver)
|
||||
ImGui.SetNextWindowSizeConstraints(ImVec2(0.0, 0.0), ImVec2(s.WindowWidth, FLT_MAX))
|
||||
|
||||
local open, visible = ImGui.Begin(title, true, ImGuiWindowFlags.NoScrollbar)
|
||||
self.Open = open
|
||||
if visible then
|
||||
self:DrawContents(mem_data, mem_size, base_display_addr)
|
||||
if self.ContentsWidthChanged then
|
||||
self:CalcSizes(s, mem_size, base_display_addr)
|
||||
ImGui.SetWindowSize(ImVec2(s.WindowWidth, ImGui.GetWindowSize().y))
|
||||
end
|
||||
end
|
||||
ImGui.End()
|
||||
end
|
||||
|
||||
-- InputText callback for the byte being edited (upstream InputTextUserData::Callback)
|
||||
local function DataInputCallback(data)
|
||||
local user_data = data.UserData
|
||||
if not data:HasSelection() then
|
||||
user_data.CursorPos = data.CursorPos
|
||||
end
|
||||
if data.SelectionStart == 0 and data.SelectionEnd == data.BufTextLen then
|
||||
-- When not editing a byte, always refresh its InputText content pulled from underlying memory data
|
||||
data:DeleteChars(0, data.BufTextLen)
|
||||
data:InsertChars(0, user_data.CurrentBufOverwrite)
|
||||
data.SelectionStart = 0
|
||||
data.SelectionEnd = 2
|
||||
data.CursorPos = 0
|
||||
end
|
||||
return 0
|
||||
end
|
||||
local input_text_user_data = { CurrentBufOverwrite = "", CursorPos = -1 }
|
||||
|
||||
local function SetBuf(buf, str) -- snprintf into a NewTextBuffer
|
||||
for i = 1, #buf do buf[i] = byte(str, i) or 0 end
|
||||
buf[#buf] = 0
|
||||
end
|
||||
local function Hex(upper, digits, v) -- "%0*zX" / "%0*zx"
|
||||
return format(upper and "%0" .. math.max(digits, 1) .. "X" or "%0" .. math.max(digits, 1) .. "x", v)
|
||||
end
|
||||
MemoryEditor._Hex = Hex
|
||||
|
||||
-- Memory Editor contents only
|
||||
function MemoryEditor:DrawContents(mem_data, mem_size, base_display_addr)
|
||||
if self.Cols < 1 then self.Cols = 1 end
|
||||
local read, write, len = Access(mem_data)
|
||||
if mem_size == nil then mem_size = len end
|
||||
base_display_addr = base_display_addr or 0
|
||||
local ReadFn, WriteFn, HighlightFn, BgColorFn, UserData = self.ReadFn, self.WriteFn, self.HighlightFn, self.BgColorFn, self.UserData
|
||||
local function Read(addr)
|
||||
if ReadFn then return ReadFn(mem_data, addr, UserData) end
|
||||
return read(addr)
|
||||
end
|
||||
local Cols, OptMidColsCount = self.Cols, self.OptMidColsCount
|
||||
|
||||
local s = {}
|
||||
self:CalcSizes(s, mem_size, base_display_addr)
|
||||
local style = ImGui.GetStyle()
|
||||
|
||||
local contents_pos_start = ImGui.GetCursorScreenPos()
|
||||
|
||||
-- We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window.
|
||||
local height_separator = style.ItemSpacing.y
|
||||
local footer_height = self.OptFooterExtraHeight
|
||||
if self.OptShowOptions then
|
||||
footer_height = footer_height + height_separator + ImGui.GetFrameHeightWithSpacing() * 1
|
||||
end
|
||||
if self.OptShowDataPreview then
|
||||
footer_height = footer_height + height_separator + ImGui.GetFrameHeightWithSpacing() * 1 + ImGui.GetTextLineHeightWithSpacing() * 3
|
||||
end
|
||||
ImGui.BeginChild("##scrolling", ImVec2(-FLT_MIN, -footer_height), ImGuiChildFlags.None, bor(ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoNav))
|
||||
local draw_list = ImGui.GetWindowDrawList()
|
||||
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, ImVec2(0, 0))
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0))
|
||||
|
||||
-- We are not really using the clipper API correctly here, because we rely on visible_start_addr/visible_end_addr for our scrolling function.
|
||||
local avail_size = ImGui.GetContentRegionAvail()
|
||||
local line_total_count = floor((mem_size + Cols - 1) / Cols)
|
||||
local clipper = G.ImGuiListClipper()
|
||||
clipper:Begin(line_total_count, s.LineHeight)
|
||||
|
||||
local data_next = false
|
||||
|
||||
if self.DataEditingAddr >= mem_size then self.DataEditingAddr = NONE end
|
||||
if self.DataPreviewAddr >= mem_size then self.DataPreviewAddr = NONE end
|
||||
|
||||
local preview_data_type_size = self.OptShowDataPreview and self:DataTypeGetSize(self.PreviewDataType) or 0
|
||||
local DataPreviewAddr = self.DataPreviewAddr
|
||||
local preview_end = DataPreviewAddr ~= NONE and DataPreviewAddr + preview_data_type_size or NONE -- [Port] no size_t wrap
|
||||
|
||||
local data_editing_addr_next = NONE
|
||||
if self.DataEditingAddr ~= NONE then
|
||||
-- Move cursor but only apply on next frame so scrolling with be synchronized
|
||||
local a = self.DataEditingAddr
|
||||
if ImGui.IsKeyPressed(ImGuiKey.UpArrow) and a >= Cols then data_editing_addr_next = a - Cols
|
||||
elseif ImGui.IsKeyPressed(ImGuiKey.DownArrow) and a < mem_size - Cols then data_editing_addr_next = a + Cols
|
||||
elseif ImGui.IsKeyPressed(ImGuiKey.LeftArrow) and a > 0 then data_editing_addr_next = a - 1
|
||||
elseif ImGui.IsKeyPressed(ImGuiKey.RightArrow) and a < mem_size - 1 then data_editing_addr_next = a + 1
|
||||
end
|
||||
end
|
||||
|
||||
-- Draw vertical separator
|
||||
local window_pos = ImGui.GetWindowPos()
|
||||
if self.OptShowAscii then
|
||||
local x = window_pos.x + s.OffsetAsciiMinX - s.GlyphWidth
|
||||
draw_list:AddLine(ImVec2(x, window_pos.y), ImVec2(x, window_pos.y + 9999), ImGui.GetColorU32(ImGuiCol.Border))
|
||||
end
|
||||
|
||||
local color_text = ImGui.GetColorU32(ImGuiCol.Text)
|
||||
local color_disabled = self.OptGreyOutZeroes and ImGui.GetColorU32(ImGuiCol.TextDisabled) or color_text
|
||||
|
||||
local upper = self.OptUpperCaseHex
|
||||
local format_byte = upper and "%02X" or "%02x"
|
||||
local format_byte_space = upper and "%02X " or "%02x "
|
||||
|
||||
self.MouseHovered = false
|
||||
self.MouseHoveredAddr = 0
|
||||
|
||||
local HighlightMin, HighlightMax = self.HighlightMin, self.HighlightMax
|
||||
local function InPreview(a) return DataPreviewAddr ~= NONE and a >= DataPreviewAddr and a < preview_end end
|
||||
|
||||
while clipper:Step() do
|
||||
for line_i = clipper.DisplayStart, clipper.DisplayEnd - 1 do -- display only visible lines
|
||||
local addr = line_i * Cols
|
||||
ImGui.TextUnformatted(Hex(upper, s.AddrDigitsCount, base_display_addr + addr) .. ": ")
|
||||
|
||||
-- Draw Hexadecimal
|
||||
local n = 0
|
||||
while n < Cols and addr < mem_size do
|
||||
local byte_pos_x = s.OffsetHexMinX + s.HexCellWidth * n
|
||||
if OptMidColsCount > 0 then
|
||||
byte_pos_x = byte_pos_x + floor(n / OptMidColsCount) * s.SpacingBetweenMidCols
|
||||
end
|
||||
ImGui.SameLine(byte_pos_x)
|
||||
|
||||
-- Draw highlight or custom background color
|
||||
local is_highlight_from_user_range = (addr >= HighlightMin and addr < HighlightMax)
|
||||
local is_highlight_from_user_func = (HighlightFn ~= nil and HighlightFn(mem_data, addr, UserData)) and true or false
|
||||
local is_highlight_from_preview = InPreview(addr)
|
||||
|
||||
local bg_color = 0
|
||||
local is_next_byte_highlighted = false
|
||||
if is_highlight_from_user_range or is_highlight_from_user_func or is_highlight_from_preview then
|
||||
is_next_byte_highlighted = (addr + 1 < mem_size) and ((HighlightMax ~= NONE and addr + 1 < HighlightMax)
|
||||
or (HighlightFn ~= nil and HighlightFn(mem_data, addr + 1, UserData) and true) or InPreview(addr + 1)) or false
|
||||
bg_color = self.HighlightColor
|
||||
elseif BgColorFn ~= nil then
|
||||
is_next_byte_highlighted = (addr + 1 < mem_size) and (BgColorFn(mem_data, addr + 1, UserData) >= 0x1000000) -- & IM_COL32_A_MASK
|
||||
bg_color = BgColorFn(mem_data, addr, UserData)
|
||||
end
|
||||
if bg_color ~= 0 then
|
||||
local bg_width = s.GlyphWidth * 2
|
||||
if is_next_byte_highlighted or (n + 1 == Cols) then
|
||||
bg_width = s.HexCellWidth
|
||||
if OptMidColsCount > 0 and n > 0 and (n + 1) < Cols and ((n + 1) % OptMidColsCount) == 0 then
|
||||
bg_width = bg_width + s.SpacingBetweenMidCols
|
||||
end
|
||||
end
|
||||
local pos = ImGui.GetCursorScreenPos()
|
||||
draw_list:AddRectFilled(pos, ImVec2(pos.x + bg_width, pos.y + s.LineHeight), bg_color)
|
||||
end
|
||||
|
||||
if self.DataEditingAddr == addr then
|
||||
-- Display text input on current byte
|
||||
local data_write = false
|
||||
ImGui.PushID(addr)
|
||||
if self.DataEditingTakeFocus then
|
||||
ImGui.SetKeyboardFocusHere(0)
|
||||
SetBuf(self.AddrInputBuf, Hex(upper, s.AddrDigitsCount, base_display_addr + addr))
|
||||
SetBuf(self.DataInputBuf, format(format_byte, Read(addr)))
|
||||
end
|
||||
input_text_user_data.CursorPos = -1
|
||||
input_text_user_data.CurrentBufOverwrite = format(format_byte, Read(addr))
|
||||
local flags = bor(ImGuiInputTextFlags.CharsHexadecimal, ImGuiInputTextFlags.EnterReturnsTrue, ImGuiInputTextFlags.AutoSelectAll,
|
||||
ImGuiInputTextFlags.NoHorizontalScroll, ImGuiInputTextFlags.CallbackAlways)
|
||||
if self.ReadOnly then flags = bor(flags, ImGuiInputTextFlags.ReadOnly) end
|
||||
flags = bor(flags, ImGuiInputTextFlags.AlwaysOverwrite)
|
||||
ImGui.SetNextItemWidth(s.GlyphWidth * 2)
|
||||
if ImGui.InputText("##data", self.DataInputBuf, 32, flags, DataInputCallback, input_text_user_data) then
|
||||
data_write, data_next = true, true
|
||||
elseif not self.DataEditingTakeFocus and not ImGui.IsItemActive() then
|
||||
self.DataEditingAddr, data_editing_addr_next = NONE, NONE
|
||||
end
|
||||
self.DataEditingTakeFocus = false
|
||||
if input_text_user_data.CursorPos >= 2 then data_write, data_next = true, true end
|
||||
if data_editing_addr_next ~= NONE then data_write, data_next = false, false end
|
||||
local hex = ImGui.TextBufferToString(self.DataInputBuf):match("^%s*(%x+)") -- sscanf("%X")
|
||||
if not self.ReadOnly and data_write and hex then
|
||||
local data_input_value = tonumber(hex, 16) % 256
|
||||
if WriteFn then
|
||||
WriteFn(mem_data, addr, data_input_value, UserData)
|
||||
elseif write then
|
||||
write(addr, data_input_value)
|
||||
end
|
||||
end
|
||||
if ImGui.IsItemHovered() then
|
||||
self.MouseHovered = true
|
||||
self.MouseHoveredAddr = addr
|
||||
end
|
||||
ImGui.PopID()
|
||||
else
|
||||
-- NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on.
|
||||
local b = Read(addr)
|
||||
|
||||
if self.OptShowHexII then
|
||||
if b >= 32 and b < 128 then
|
||||
ImGui.TextUnformatted("." .. char(b) .. " ")
|
||||
elseif b == 0xFF and self.OptGreyOutZeroes then
|
||||
ImGui.TextDisabled("## ")
|
||||
elseif b == 0x00 then
|
||||
ImGui.TextUnformatted(" ")
|
||||
else
|
||||
ImGui.TextUnformatted(format(format_byte_space, b))
|
||||
end
|
||||
else
|
||||
if b == 0 and self.OptGreyOutZeroes then
|
||||
ImGui.TextDisabled("00 ")
|
||||
else
|
||||
ImGui.TextUnformatted(format(format_byte_space, b))
|
||||
end
|
||||
end
|
||||
if ImGui.IsItemHovered() then
|
||||
self.MouseHovered = true
|
||||
self.MouseHoveredAddr = addr
|
||||
if ImGui.IsMouseClicked(0) then
|
||||
self.DataEditingTakeFocus = true
|
||||
data_editing_addr_next = addr
|
||||
end
|
||||
end
|
||||
end
|
||||
n, addr = n + 1, addr + 1
|
||||
end
|
||||
|
||||
if self.OptShowAscii then
|
||||
-- Draw ASCII values
|
||||
ImGui.SameLine(s.OffsetAsciiMinX)
|
||||
local pos = ImGui.GetCursorScreenPos()
|
||||
addr = line_i * Cols
|
||||
|
||||
local mouse_off_x = ImGui.GetIO().MousePos.x - pos.x
|
||||
local mouse_addr = (mouse_off_x >= 0.0 and mouse_off_x < s.OffsetAsciiMaxX - s.OffsetAsciiMinX) and addr + floor(mouse_off_x / s.GlyphWidth) or NONE
|
||||
|
||||
ImGui.PushID(line_i)
|
||||
if ImGui.InvisibleButton("ascii", ImVec2(s.OffsetAsciiMaxX - s.OffsetAsciiMinX, s.LineHeight)) then
|
||||
self.DataEditingAddr, self.DataPreviewAddr = mouse_addr, mouse_addr
|
||||
self.DataEditingTakeFocus = true
|
||||
end
|
||||
if ImGui.IsItemHovered() then
|
||||
self.MouseHovered = true
|
||||
self.MouseHoveredAddr = mouse_addr
|
||||
end
|
||||
ImGui.PopID()
|
||||
n = 0
|
||||
while n < Cols and addr < mem_size do
|
||||
local pmax = ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight)
|
||||
if addr == self.DataEditingAddr then
|
||||
draw_list:AddRectFilled(pos, pmax, ImGui.GetColorU32(ImGuiCol.FrameBg))
|
||||
draw_list:AddRectFilled(pos, pmax, ImGui.GetColorU32(ImGuiCol.TextSelectedBg))
|
||||
elseif BgColorFn then
|
||||
draw_list:AddRectFilled(pos, pmax, BgColorFn(mem_data, addr, UserData))
|
||||
end
|
||||
local c = Read(addr)
|
||||
local printable = c >= 32 and c < 128
|
||||
draw_list:AddText(pos, printable and color_text or color_disabled, printable and char(c) or ".")
|
||||
pos = ImVec2(pos.x + s.GlyphWidth, pos.y)
|
||||
n, addr = n + 1, addr + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
ImGui.PopStyleVar(2)
|
||||
local child_width = ImGui.GetWindowSize().x
|
||||
ImGui.EndChild()
|
||||
|
||||
-- Notify the main window of our ideal child content size
|
||||
local backup_pos = ImGui.GetCursorScreenPos()
|
||||
ImGui.SetCursorPosX(s.WindowWidth)
|
||||
ImGui.Dummy(ImVec2(0.0, 0.0))
|
||||
ImGui.SetCursorScreenPos(backup_pos)
|
||||
|
||||
if data_next and self.DataEditingAddr + 1 < mem_size then
|
||||
self.DataEditingAddr = self.DataEditingAddr + 1
|
||||
self.DataPreviewAddr = self.DataEditingAddr
|
||||
self.DataEditingTakeFocus = true
|
||||
elseif data_editing_addr_next ~= NONE then
|
||||
self.DataEditingAddr, self.DataPreviewAddr = data_editing_addr_next, data_editing_addr_next
|
||||
self.DataEditingTakeFocus = true
|
||||
end
|
||||
|
||||
local lock_show_data_preview = self.OptShowDataPreview
|
||||
if self.OptShowOptions then
|
||||
ImGui.Separator()
|
||||
self:DrawOptionsLine(s, mem_data, mem_size, base_display_addr)
|
||||
end
|
||||
|
||||
if lock_show_data_preview then
|
||||
ImGui.Separator()
|
||||
self:DrawPreviewLine(s, mem_data, mem_size, base_display_addr)
|
||||
end
|
||||
|
||||
if self.GotoAddr ~= NONE then
|
||||
if self.GotoAddr >= 0 and self.GotoAddr < mem_size then
|
||||
ImGui.BeginChild("##scrolling")
|
||||
ImGui.SetScrollY(floor(self.GotoAddr / Cols) * ImGui.GetTextLineHeight() - avail_size.y * 0.5)
|
||||
ImGui.EndChild()
|
||||
self.DataEditingAddr, self.DataPreviewAddr = self.GotoAddr, self.GotoAddr
|
||||
self.DataEditingTakeFocus = true
|
||||
end
|
||||
self.GotoAddr = NONE
|
||||
end
|
||||
|
||||
local contents_pos_end = ImVec2(contents_pos_start.x + child_width, ImGui.GetCursorScreenPos().y)
|
||||
if self.OptShowOptions then
|
||||
if ImGui.IsMouseHoveringRect(contents_pos_start, contents_pos_end) then
|
||||
if ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) and ImGui.IsMouseReleased(1) then
|
||||
ImGui.OpenPopup("OptionsPopup")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if ImGui.BeginPopup("OptionsPopup") then
|
||||
local changed, _
|
||||
ImGui.SetNextItemWidth(s.GlyphWidth * 7 + style.FramePadding.x * 2.0)
|
||||
self.Cols, changed = ImGui.DragInt("##cols", self.Cols, 0.2, 4, 32, "%d cols")
|
||||
if changed then self.ContentsWidthChanged = true; if self.Cols < 1 then self.Cols = 1 end end
|
||||
_, self.OptShowDataPreview = ImGui.Checkbox("Show Data Preview", self.OptShowDataPreview)
|
||||
_, self.OptShowHexII = ImGui.Checkbox("Show HexII", self.OptShowHexII)
|
||||
changed, self.OptShowAscii = ImGui.Checkbox("Show Ascii", self.OptShowAscii)
|
||||
if changed then self.ContentsWidthChanged = true end
|
||||
_, self.OptGreyOutZeroes = ImGui.Checkbox("Grey out zeroes", self.OptGreyOutZeroes)
|
||||
_, self.OptUpperCaseHex = ImGui.Checkbox("Uppercase Hex", self.OptUpperCaseHex)
|
||||
ImGui.EndPopup()
|
||||
end
|
||||
end
|
||||
|
||||
function MemoryEditor:DrawOptionsLine(s, mem_data, mem_size, base_display_addr)
|
||||
local style = ImGui.GetStyle()
|
||||
local upper = self.OptUpperCaseHex
|
||||
|
||||
-- Options menu
|
||||
if ImGui.Button("Options") then
|
||||
ImGui.OpenPopup("OptionsPopup")
|
||||
end
|
||||
|
||||
ImGui.SameLine()
|
||||
ImGui.TextUnformatted("Range " .. Hex(upper, s.AddrDigitsCount, base_display_addr) .. ".." .. Hex(upper, s.AddrDigitsCount, base_display_addr + mem_size - 1))
|
||||
ImGui.SameLine()
|
||||
ImGui.SetNextItemWidth((s.AddrDigitsCount + 1) * s.GlyphWidth + style.FramePadding.x * 2.0)
|
||||
if ImGui.InputText("##addr", self.AddrInputBuf, 32, bor(ImGuiInputTextFlags.CharsHexadecimal, ImGuiInputTextFlags.EnterReturnsTrue)) then
|
||||
local hex = ImGui.TextBufferToString(self.AddrInputBuf):match("^%s*(%x+)")
|
||||
if hex then
|
||||
self.GotoAddr = tonumber(hex, 16) - base_display_addr
|
||||
self.HighlightMin, self.HighlightMax = NONE, NONE
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local supported_data_types = { "S8", "U8", "S16", "U16", "S32", "U32", "S64", "U64", "Float", "Double" }
|
||||
|
||||
function MemoryEditor:DrawPreviewLine(s, mem_data, mem_size, base_display_addr)
|
||||
local style = ImGui.GetStyle()
|
||||
ImGui.AlignTextToFramePadding()
|
||||
ImGui.TextUnformatted("Preview as:")
|
||||
ImGui.SameLine()
|
||||
ImGui.SetNextItemWidth((s.GlyphWidth * 10.0) + style.FramePadding.x * 2.0 + style.ItemInnerSpacing.x)
|
||||
|
||||
if ImGui.BeginCombo("##combo_type", self:DataTypeGetDesc(self.PreviewDataType), ImGuiComboFlags.HeightLargest) then
|
||||
for n = 1, #supported_data_types do
|
||||
local data_type = ImGuiDataType[supported_data_types[n]]
|
||||
if ImGui.Selectable(self:DataTypeGetDesc(data_type), self.PreviewDataType == data_type) then
|
||||
self.PreviewDataType = data_type
|
||||
end
|
||||
end
|
||||
ImGui.EndCombo()
|
||||
end
|
||||
ImGui.SameLine()
|
||||
ImGui.SetNextItemWidth((s.GlyphWidth * 6.0) + style.FramePadding.x * 2.0 + style.ItemInnerSpacing.x)
|
||||
self.PreviewEndianness = ImGui.Combo("##combo_endianness", self.PreviewEndianness, "LE\0BE\0\0")
|
||||
|
||||
local x = s.GlyphWidth * 6.0
|
||||
local has_value = self.DataPreviewAddr ~= NONE
|
||||
local buf = has_value and self:DrawPreviewData(self.DataPreviewAddr, mem_data, mem_size, self.PreviewDataType, MemoryEditor.DataFormat_Dec)
|
||||
ImGui.TextUnformatted("Dec"); ImGui.SameLine(x); ImGui.TextUnformatted(has_value and buf or "N/A")
|
||||
buf = has_value and self:DrawPreviewData(self.DataPreviewAddr, mem_data, mem_size, self.PreviewDataType, MemoryEditor.DataFormat_Hex)
|
||||
ImGui.TextUnformatted("Hex"); ImGui.SameLine(x); ImGui.TextUnformatted(has_value and buf or "N/A")
|
||||
buf = has_value and self:DrawPreviewData(self.DataPreviewAddr, mem_data, mem_size, self.PreviewDataType, MemoryEditor.DataFormat_Bin)
|
||||
ImGui.TextUnformatted("Bin"); ImGui.SameLine(x); ImGui.TextUnformatted(has_value and buf or "N/A")
|
||||
end
|
||||
|
||||
-- Utilities for Data Preview
|
||||
local descs = { "Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64", "Float", "Double" }
|
||||
local sizes = { 1, 1, 2, 2, 4, 4, 8, 8, 4, 8 }
|
||||
function MemoryEditor:DataTypeGetDesc(data_type) return assert(descs[data_type + 1]) end
|
||||
function MemoryEditor:DataTypeGetSize(data_type) return assert(sizes[data_type + 1]) end
|
||||
function MemoryEditor:DataFormatGetDesc(data_format) return assert(({ "Bin", "Dec", "Hex" })[data_format + 1]) end
|
||||
|
||||
-- [Port] bytes in little-endian value order (le[1] = least significant), 8 entries, zero padded
|
||||
local function FormatBinary(le, width)
|
||||
local out = {}
|
||||
for j = width / 8, 1, -1 do
|
||||
local b = le[j]
|
||||
for i = 7, 0, -1 do out[#out + 1] = (floor(b / 2 ^ i) % 2 == 1) and "1" or "0" end
|
||||
out[#out + 1] = " "
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local function UnsignedDec(le, n) -- exact decimal of an n-byte unsigned integer (Lua numbers stop at 2^53)
|
||||
local digits, bytes = {}, {}
|
||||
for i = 1, n do bytes[i] = le[i] end
|
||||
repeat
|
||||
local rem, nonzero = 0, false
|
||||
for i = n, 1, -1 do
|
||||
local cur = rem * 256 + bytes[i]
|
||||
bytes[i] = floor(cur / 10); rem = cur % 10
|
||||
if bytes[i] ~= 0 then nonzero = true end
|
||||
end
|
||||
table.insert(digits, 1, tostring(rem))
|
||||
until not nonzero
|
||||
return table.concat(digits)
|
||||
end
|
||||
|
||||
local function SignedDec(le, n)
|
||||
if le[n] < 128 then return UnsignedDec(le, n) end
|
||||
local neg, carry = {}, 1 -- two's complement magnitude
|
||||
for i = 1, n do
|
||||
local v = (255 - le[i]) + carry
|
||||
neg[i] = v % 256; carry = floor(v / 256)
|
||||
end
|
||||
return "-" .. UnsignedDec(neg, n)
|
||||
end
|
||||
|
||||
local function HexBytes(le, n)
|
||||
local t = {}
|
||||
for i = n, 1, -1 do t[#t + 1] = format("%02x", le[i]) end
|
||||
return table.concat(t)
|
||||
end
|
||||
|
||||
local function DecodeFloat(le, double) -- IEEE 754 from bytes, platform independent
|
||||
local sign, exp, mant, mbits, bias
|
||||
if double then
|
||||
sign = le[8] >= 128
|
||||
exp = (le[8] % 128) * 16 + floor(le[7] / 16)
|
||||
mant = (le[7] % 16) * 2 ^ 48 + le[6] * 2 ^ 40 + le[5] * 2 ^ 32 + le[4] * 2 ^ 24 + le[3] * 2 ^ 16 + le[2] * 2 ^ 8 + le[1]
|
||||
mbits, bias = 52, 1023
|
||||
else
|
||||
sign = le[4] >= 128
|
||||
exp = (le[4] % 128) * 2 + floor(le[3] / 128)
|
||||
mant = (le[3] % 128) * 65536 + le[2] * 256 + le[1]
|
||||
mbits, bias = 23, 127
|
||||
end
|
||||
local v
|
||||
if exp == bias * 2 + 1 then
|
||||
v = mant == 0 and math.huge or 0 / 0
|
||||
elseif exp == 0 then
|
||||
v = mant * 2 ^ (1 - bias - mbits)
|
||||
else
|
||||
v = (1 + mant / 2 ^ mbits) * 2 ^ (exp - bias)
|
||||
end
|
||||
return sign and -v or v, sign
|
||||
end
|
||||
|
||||
local function HexDigits52(f) -- 13 hex digits of a 52-bit fraction, trailing zeros trimmed
|
||||
local t = {}
|
||||
for i = 12, 0, -1 do t[#t + 1] = format("%x", floor(f / 16 ^ i) % 16) end
|
||||
return (table.concat(t):gsub("0+$", ""))
|
||||
end
|
||||
|
||||
local function FormatHexFloat(v, sign) -- C "%a" (glibc) of a double
|
||||
local s = sign and "-" or ""
|
||||
if v ~= v then return s .. "nan" end
|
||||
v = math.abs(v)
|
||||
if v == math.huge then return s .. "inf" end
|
||||
if v == 0 then return s .. "0x0p+0" end
|
||||
if v < 2 ^ -1022 then -- double subnormal
|
||||
local h = HexDigits52(v / 2 ^ -1074)
|
||||
return s .. "0x0" .. (h ~= "" and "." .. h or "") .. "p-1022"
|
||||
end
|
||||
local m, e = math.frexp(v) -- v = m * 2^e, m in [0.5, 1)
|
||||
local h = HexDigits52((m * 2 - 1) * 2 ^ 52)
|
||||
return s .. "0x1" .. (h ~= "" and "." .. h or "") .. format("p%+d", e - 1)
|
||||
end
|
||||
|
||||
-- [Internal] [Port] returns the string (C++ writes into out_buf)
|
||||
function MemoryEditor:DrawPreviewData(addr, mem_data, mem_size, data_type, data_format)
|
||||
local elem_size = self:DataTypeGetSize(data_type)
|
||||
local size = (addr + elem_size > mem_size) and mem_size - addr or elem_size
|
||||
local buf = {}
|
||||
if self.ReadFn then
|
||||
for i = 0, size - 1 do buf[i + 1] = self.ReadFn(mem_data, addr + i, self.UserData) end
|
||||
else
|
||||
local read = Access(mem_data)
|
||||
for i = 0, size - 1 do buf[i + 1] = read(addr + i) end
|
||||
end
|
||||
local le = {} -- EndiannessCopy: PreviewEndianness 0 = LE, 1 = BE
|
||||
for i = 1, 8 do
|
||||
if i > size then le[i] = 0
|
||||
elseif self.PreviewEndianness == 0 then le[i] = buf[i]
|
||||
else le[i] = buf[size - i + 1] end
|
||||
end
|
||||
|
||||
if data_format == MemoryEditor.DataFormat_Bin then
|
||||
return FormatBinary(le, size * 8)
|
||||
end
|
||||
|
||||
local DT, dec = ImGuiDataType, data_format == MemoryEditor.DataFormat_Dec
|
||||
if data_type == DT.S8 or data_type == DT.U8 then
|
||||
if dec then return data_type == DT.S8 and SignedDec(le, 1) or UnsignedDec(le, 1) end
|
||||
return "0x" .. HexBytes(le, 1)
|
||||
elseif data_type == DT.S16 or data_type == DT.U16 then
|
||||
if dec then return data_type == DT.S16 and SignedDec(le, 2) or UnsignedDec(le, 2) end
|
||||
return "0x" .. HexBytes(le, 2)
|
||||
elseif data_type == DT.S32 or data_type == DT.U32 then
|
||||
if dec then return data_type == DT.S32 and SignedDec(le, 4) or UnsignedDec(le, 4) end
|
||||
return "0x" .. HexBytes(le, 4)
|
||||
elseif data_type == DT.S64 or data_type == DT.U64 then
|
||||
if dec then return data_type == DT.S64 and SignedDec(le, 8) or UnsignedDec(le, 8) end
|
||||
return "0x" .. HexBytes(le, 8)
|
||||
elseif data_type == DT.Float or data_type == DT.Double then
|
||||
local v, sign = DecodeFloat(le, data_type == DT.Double)
|
||||
if dec then
|
||||
if v ~= v then return sign and "-nan" or "nan" end
|
||||
if v == math.huge then return "inf" elseif v == -math.huge then return "-inf" end
|
||||
return format("%f", v)
|
||||
end
|
||||
return FormatHexFloat(v, sign)
|
||||
end
|
||||
error("MemoryEditor: unsupported data type") -- Shouldn't reach
|
||||
end
|
||||
|
||||
return MemoryEditor
|
||||
end
|
||||
@@ -0,0 +1,49 @@
|
||||
# imgui-memory-editor-luau
|
||||
|
||||
Hex/memory editor widget for imgui-luau: view and edit a Roblox `buffer`, a LÖVE `ByteData` or a table of bytes.
|
||||
|
||||
Luau port of [imgui_memory_editor](https://github.com/ocornut/imgui_club) (imgui_club, v0.59) for [imgui-luau](https://git.bug.tools/bug/imgui-luau) ([GitHub](https://github.com/4DBug/imgui-luau)).
|
||||
Mirrors: [git.bug.tools](https://git.bug.tools/bug/imgui-memory-editor-luau) / [GitHub](https://github.com/4DBug/imgui-memory-editor-luau).
|
||||
|
||||
## Usage
|
||||
|
||||
```lua
|
||||
local G = require(ReplicatedStorage.ImGui)
|
||||
local MemoryEditor = require(ReplicatedStorage.MemoryEditor)(G)
|
||||
|
||||
local data = buffer.create(0x10000)
|
||||
local mem_edit = MemoryEditor.new() -- C++: static MemoryEditor mem_edit;
|
||||
|
||||
-- each frame:
|
||||
mem_edit:DrawWindow("Memory Editor", data) -- size defaults to the data's length
|
||||
-- or inside your own window:
|
||||
mem_edit:DrawContents(data, 0x100, 0x8000) -- mem_size, base_display_addr
|
||||
```
|
||||
|
||||
The API is upstream's: same fields (`Cols`, `ReadOnly`, `OptShowDataPreview`, `OptShowAscii`, `OptMidColsCount`,
|
||||
`HighlightColor`, `MouseHovered`, `MouseHoveredAddr`, ...), `GotoAddrAndHighlight(min, max)`, and the handlers
|
||||
`ReadFn(mem, off, user_data)`, `WriteFn(mem, off, d, user_data)`, `HighlightFn(mem, off, user_data)`,
|
||||
`BgColorFn(mem, off, user_data)` with `UserData`. Offsets and addresses are 0-based like upstream; "none" (C++ `(size_t)-1`) is `-1`.
|
||||
|
||||
`[Port]` differences:
|
||||
- `mem_data` (C++ `void*`) is any of: Roblox `buffer`; LÖVE `Data` (`ByteData`, `ImageData`, ...; writable through
|
||||
`getFFIPointer()`, read-only via `getString()` without FFI); a Lua table of bytes (index 1 = offset 0); a string (read-only).
|
||||
`mem_size` is optional and defaults to the data's length.
|
||||
- `DrawPreviewData` returns the string instead of writing into `out_buf`. 64-bit values are decoded exactly from the
|
||||
bytes (Lua numbers stop at 2^53); `%a` is formatted like glibc.
|
||||
|
||||
On LÖVE, load the file with `loadfile("MemoryEditor.lua")()(G)` (plain Lua 5.1 syntax). Examples:
|
||||
`examples/roblox/main.client.luau`, `examples/love` (`love examples/love`).
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
git clone --recursive https://git.bug.tools/bug/imgui-memory-editor-luau.git
|
||||
bash tools/test.sh # tests/t_*.luau in the core's Roblox mock, the Roblox example, and tests/love.lua under LuaJIT (nix-shell)
|
||||
```
|
||||
|
||||
Upstream source (pinned) is in `tools/upstream/`; port-specific comments are tagged `[Port]`.
|
||||
|
||||
## License
|
||||
|
||||
MIT, see LICENSE (upstream copyright kept).
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "imgui-memory-editor-luau",
|
||||
"tree": {
|
||||
"$className": "DataModel",
|
||||
"ReplicatedStorage": {
|
||||
"ImGui": { "$path": "tools/core/build/ImGuiTyped.luau", "Impl": { "$path": "tools/core/build/ImGui.luau" } },
|
||||
"MemoryEditor": { "$path": "MemoryEditor.lua" }
|
||||
},
|
||||
"StarterPlayer": { "StarterPlayerScripts": { "MemoryEditorExample": { "$path": "examples/roblox/main.client.luau" } } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
function love.conf(t)
|
||||
t.window.title = "Memory Editor - LÖVE example"
|
||||
t.window.width, t.window.height = 1280, 800
|
||||
t.window.resizable = true
|
||||
end
|
||||
@@ -0,0 +1,45 @@
|
||||
-- Memory editor over a LÖVE ByteData: love examples/love (uses tools/core/build/imgui_love.lua)
|
||||
local ROOT = love.filesystem.getSource() .. "/../../" -- repo root
|
||||
local f = assert(io.open(ROOT .. "tools/core/build/imgui_love.lua", "rb"), "missing tools/core: git submodule update --init")
|
||||
local G = assert(loadstring(f:read("*a"), "@imgui_love.lua"))(); f:close()
|
||||
local MemoryEditor = assert(loadfile(ROOT .. "MemoryEditor.lua"))()(G)
|
||||
local ImGui = G.ImGui
|
||||
|
||||
data = love.data.newByteData(0x400) -- global: tests/love.lua checks it
|
||||
local ptr = require("ffi").cast("uint8_t*", data:getFFIPointer())
|
||||
for i = 0x40, 0x3FF do ptr[i] = (i * 37) % 256 end
|
||||
local frame = 0
|
||||
|
||||
mem_edit = MemoryEditor.new()
|
||||
mem_edit.OptShowDataPreview = true
|
||||
|
||||
function love.load()
|
||||
ImGui.CreateContext()
|
||||
local io = ImGui.GetIO()
|
||||
io.IniFilename = nil
|
||||
G.ImGui_ImplLove.Init({ root = ROOT .. "tools/core/" })
|
||||
io.Fonts:AddFontDefault()
|
||||
end
|
||||
|
||||
function love.update(dt)
|
||||
frame = frame + 1
|
||||
ptr[0], ptr[1] = frame % 256, math.floor(frame / 256) % 256
|
||||
G.ImGui_ImplLove.NewFrame()
|
||||
ImGui.NewFrame()
|
||||
mem_edit:DrawWindow("Memory Editor", data) -- size defaults to data:getSize()
|
||||
ImGui.Render()
|
||||
end
|
||||
|
||||
function love.draw()
|
||||
love.graphics.clear(0.45, 0.55, 0.60, 1)
|
||||
G.ImGui_ImplLove.RenderDrawData(ImGui.GetDrawData())
|
||||
end
|
||||
|
||||
function love.mousemoved(x, y) G.ImGui_ImplLove.MouseMoved(x, y) end
|
||||
function love.mousepressed(x, y, b) G.ImGui_ImplLove.MousePressed(x, y, b) end
|
||||
function love.mousereleased(x, y, b) G.ImGui_ImplLove.MouseReleased(x, y, b) end
|
||||
function love.wheelmoved(x, y) G.ImGui_ImplLove.WheelMoved(x, y) end
|
||||
function love.keypressed(k) G.ImGui_ImplLove.KeyPressed(k) end
|
||||
function love.keyreleased(k) G.ImGui_ImplLove.KeyReleased(k) end
|
||||
function love.textinput(t) G.ImGui_ImplLove.TextInput(t) end
|
||||
function love.focus(f) G.ImGui_ImplLove.Focus(f) end
|
||||
@@ -0,0 +1,35 @@
|
||||
-- Memory editor over a Roblox buffer (live-updating counter at 0x00, a float at 0x10, a string at 0x20).
|
||||
local RS = game:GetService("ReplicatedStorage")
|
||||
local RunService = game:GetService("RunService")
|
||||
local G = require(RS:WaitForChild("ImGui"))
|
||||
local MemoryEditor = require(RS:WaitForChild("MemoryEditor"))(G)
|
||||
local ImGui = G.ImGui
|
||||
|
||||
local data = buffer.create(0x400)
|
||||
buffer.writef32(data, 0x10, math.pi)
|
||||
buffer.writestring(data, 0x20, "Hello from a Roblox buffer!")
|
||||
for i = 0x40, 0x3FF do buffer.writeu8(data, i, (i * 37) % 256) end
|
||||
|
||||
local mem_edit = MemoryEditor.new()
|
||||
mem_edit.OptShowDataPreview = true
|
||||
local mem_edit2 = MemoryEditor.new() -- DrawContents() inside your own window, highlighting even bytes
|
||||
mem_edit2.HighlightFn = function(mem, off) return buffer.readu8(mem, off) % 2 == 0 end
|
||||
|
||||
ImGui.CreateContext()
|
||||
G.ImGui_ImplRoblox.Init() -- defaults to LocalPlayer.PlayerGui
|
||||
local frame = 0
|
||||
RunService.RenderStepped:Connect(function()
|
||||
frame += 1
|
||||
buffer.writeu32(data, 0x00, frame)
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
ImGui.NewFrame()
|
||||
mem_edit:DrawWindow("Memory Editor", data) -- size defaults to buffer.len(data)
|
||||
local _, visible = ImGui.Begin("Memory Editor (DrawContents)") -- returns (open, visible)
|
||||
if visible then
|
||||
ImGui.Text("frame = %d (the u32 at 0x00)", frame)
|
||||
mem_edit2:DrawContents(data, 0x80, 0x1000) -- first 0x80 bytes, displayed from address 0x1000
|
||||
end
|
||||
ImGui.End()
|
||||
ImGui.Render()
|
||||
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
end)
|
||||
@@ -0,0 +1,22 @@
|
||||
-- LuaJIT: runs examples/love headless (core mock love) and types "AB" into byte 2 of the ByteData.
|
||||
local ex = "examples/love"
|
||||
dofile("tools/core/tools/test/love/mock_love.lua")
|
||||
love.filesystem.getSource = function() return ex end
|
||||
love.graphics.clear = function() end
|
||||
dofile(ex .. "/main.lua")
|
||||
love.load()
|
||||
local function step() love.timer.step(1 / 60); love.update(1 / 60); love.draw() end
|
||||
for i = 1, 5 do love.mousemoved(100 + i, 100); step() end
|
||||
mem_edit:GotoAddrAndHighlight(2, 3)
|
||||
for i = 1, 3 do step() end
|
||||
love.textinput("A"); step(); love.textinput("B"); step(); step()
|
||||
local ptr = require("ffi").cast("uint8_t*", data:getFFIPointer())
|
||||
assert(ptr[2] == 0xAB, "byte 2 not written: " .. ptr[2])
|
||||
assert(mem_edit.DataEditingAddr == 3, "editing did not advance")
|
||||
-- preview decoding under LuaJIT (ImGuiDataType: U64 = 7, Float = 8; formats: Dec = 1, Hex = 2)
|
||||
mem_edit.PreviewEndianness = 0
|
||||
local ff = { 255, 255, 255, 255, 255, 255, 255, 255 }
|
||||
assert(mem_edit:DrawPreviewData(0, ff, 8, 7, 1) == "18446744073709551615")
|
||||
assert(mem_edit:DrawPreviewData(0, { 0, 0, 0xC0, 0x3F }, 4, 8, 2) == "0x1.8p+0")
|
||||
assert(mem_edit:DrawPreviewData(0, { 0, 0, 0xC0, 0x3F }, 4, 8, 1) == "1.500000")
|
||||
print("OK")
|
||||
@@ -0,0 +1,61 @@
|
||||
-- Hex editing in a Roblox buffer: GotoAddrAndHighlight focuses byte 2, typing "AB" writes 0xAB and moves to byte 3;
|
||||
-- clicking a byte starts editing it; ReadOnly never writes; MouseHoveredAddr follows the mouse.
|
||||
local RS = game:GetService("ReplicatedStorage")
|
||||
local G = require(RS:WaitForChild("ImGui"))
|
||||
local MemoryEditor = require(RS:WaitForChild("MemoryEditor"))(G)
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
|
||||
ImGui.CreateContext()
|
||||
G.ImGui_ImplRoblox.Init()
|
||||
local io = ImGui.GetIO()
|
||||
|
||||
local mem = buffer.create(256)
|
||||
for i = 0, 255 do buffer.writeu8(mem, i, i) end
|
||||
local ed = MemoryEditor.new()
|
||||
ed.OptShowDataPreview = true
|
||||
local s = {}
|
||||
|
||||
local frame, done = 0, false
|
||||
local cellPos -- screen pos of byte 0x15 (line 1, col 5), found from the child window
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
if done then return end
|
||||
frame += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
io.DeltaTime = 1 / 60
|
||||
if frame == 3 then ed:GotoAddrAndHighlight(2, 3)
|
||||
elseif frame == 6 then io:AddInputCharacter(string.byte("A"))
|
||||
elseif frame == 7 then io:AddInputCharacter(string.byte("B"))
|
||||
elseif frame == 12 then io:AddMousePosEvent(cellPos.x + 2, cellPos.y + 2)
|
||||
elseif frame == 14 then io:AddMouseButtonEvent(0, true)
|
||||
elseif frame == 15 then io:AddMouseButtonEvent(0, false)
|
||||
elseif frame == 18 then ed.ReadOnly = true
|
||||
elseif frame == 20 then io:AddInputCharacter(string.byte("F"))
|
||||
elseif frame == 21 then io:AddInputCharacter(string.byte("F"))
|
||||
end
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(ImVec2(0, 0))
|
||||
ed:DrawWindow("Memory", mem)
|
||||
if frame == 11 then
|
||||
local w = ImGui.FindWindowByName("Memory")
|
||||
local child = w.DC.ChildWindows.Data[1]
|
||||
ed:CalcSizes(s, 256, 0)
|
||||
local x = child.Pos.x + s.OffsetHexMinX + s.HexCellWidth * 5
|
||||
cellPos = ImVec2(x, child.Pos.y + child.WindowPadding.y + s.LineHeight * 1)
|
||||
end
|
||||
ImGui.Render()
|
||||
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if frame == 10 then
|
||||
assert(buffer.readu8(mem, 2) == 0xAB, "byte 2 not written: " .. buffer.readu8(mem, 2))
|
||||
assert(buffer.readu8(mem, 3) == 3, "byte 3 changed")
|
||||
assert(ed.DataEditingAddr == 3, "editing did not advance: " .. ed.DataEditingAddr)
|
||||
assert(ed.DataPreviewAddr == 3)
|
||||
elseif frame == 13 then
|
||||
assert(ed.MouseHovered and ed.MouseHoveredAddr == 0x15, "hovered " .. tostring(ed.MouseHoveredAddr))
|
||||
elseif frame == 17 then
|
||||
assert(ed.DataEditingAddr == 0x15, "click did not start editing: " .. ed.DataEditingAddr)
|
||||
elseif frame == 26 then
|
||||
done = true
|
||||
assert(buffer.readu8(mem, 0x15) == 0x15, "ReadOnly wrote")
|
||||
print("OK")
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,7 @@
|
||||
local RS = game:GetService("ReplicatedStorage")
|
||||
local G = require(RS:WaitForChild("ImGui"))
|
||||
local MemoryEditor = require(RS:WaitForChild("MemoryEditor"))(G)
|
||||
assert(type(MemoryEditor.new) == "function")
|
||||
local ed = MemoryEditor.new()
|
||||
assert(ed.Cols == 16 and ed.Open and not ed.ReadOnly and ed.OptShowAscii and ed.PreviewDataType == G.ImGuiDataType.S32)
|
||||
print("OK")
|
||||
@@ -0,0 +1,47 @@
|
||||
-- DrawPreviewData: every data type x LE/BE x Dec/Hex/Bin, compared with C printf output.
|
||||
local RS = game:GetService("ReplicatedStorage")
|
||||
local G = require(RS:WaitForChild("ImGui"))
|
||||
local MemoryEditor = require(RS:WaitForChild("MemoryEditor"))(G)
|
||||
local DT = G.ImGuiDataType
|
||||
local ed = MemoryEditor.new()
|
||||
local BIN, DEC, HEX = MemoryEditor.DataFormat_Bin, MemoryEditor.DataFormat_Dec, MemoryEditor.DataFormat_Hex
|
||||
|
||||
local function check(bytes, dt, endian, fmt, want)
|
||||
ed.PreviewEndianness = endian
|
||||
local got = ed:DrawPreviewData(0, bytes, #bytes, dt, fmt)
|
||||
assert(got == want, ("type %d endian %d fmt %d: got %q want %q"):format(dt, endian, fmt, got, want))
|
||||
end
|
||||
check({ 0xFF }, DT.S8, 0, DEC, "-1")
|
||||
check({ 0xFF }, DT.U8, 0, DEC, "255")
|
||||
check({ 0xFF }, DT.S8, 0, HEX, "0xff")
|
||||
check({ 0x34, 0x12 }, DT.U16, 0, HEX, "0x1234")
|
||||
check({ 0x34, 0x12 }, DT.U16, 1, HEX, "0x3412")
|
||||
check({ 0x34, 0x12 }, DT.S16, 0, BIN, "00010010 00110100 ")
|
||||
check({ 0xFE, 0xFF, 0xFF, 0xFF }, DT.S32, 0, DEC, "-2")
|
||||
check({ 0xFE, 0xFF, 0xFF, 0xFF }, DT.U32, 0, DEC, "4294967294")
|
||||
check({ 0xFE, 0xFF, 0xFF, 0xFF }, DT.S32, 0, HEX, "0xfffffffe")
|
||||
check({ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, DT.U64, 0, DEC, "18446744073709551615")
|
||||
check({ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, DT.S64, 0, DEC, "-1")
|
||||
check({ 0, 0, 0, 0, 0, 0, 0, 0x80 }, DT.S64, 0, DEC, "-9223372036854775808")
|
||||
check({ 1, 2, 3, 4, 5, 6, 7, 8 }, DT.U64, 0, HEX, "0x0807060504030201")
|
||||
check({ 1, 2, 3, 4, 5, 6, 7, 8 }, DT.U64, 1, HEX, "0x0102030405060708")
|
||||
check({ 0, 0, 0xC0, 0x3F }, DT.Float, 0, DEC, "1.500000")
|
||||
check({ 0x3F, 0xC0, 0, 0 }, DT.Float, 1, DEC, "1.500000")
|
||||
check({ 0, 0, 0xC0, 0x3F }, DT.Float, 0, HEX, "0x1.8p+0")
|
||||
check({ 0, 0, 0x80, 0xBF }, DT.Float, 0, HEX, "-0x1p+0")
|
||||
check({ 0, 0, 0, 0 }, DT.Float, 0, HEX, "0x0p+0")
|
||||
check({ 1, 0, 0, 0 }, DT.Float, 0, HEX, "0x1p-149") -- float subnormal is a normal double
|
||||
check({ 0, 0, 0x80, 0x7F }, DT.Float, 0, DEC, "inf")
|
||||
check({ 0x18, 0x2D, 0x44, 0x54, 0xFB, 0x21, 0x09, 0x40 }, DT.Double, 0, DEC, "3.141593")
|
||||
check({ 0x18, 0x2D, 0x44, 0x54, 0xFB, 0x21, 0x09, 0x40 }, DT.Double, 0, HEX, "0x1.921fb54442d18p+1")
|
||||
check({ 1, 0, 0, 0, 0, 0, 0, 0 }, DT.Double, 0, HEX, "0x0.0000000000001p-1022")
|
||||
-- truncated at the end of memory: only the available bytes
|
||||
check({ 0x34, 0x12 }, DT.U32, 0, DEC, "4660")
|
||||
check({ 0x34, 0x12 }, DT.U32, 0, BIN, "00010010 00110100 ")
|
||||
-- buffer, string and ReadFn sources
|
||||
local b = buffer.create(4); buffer.writeu32(b, 0, 0xDEADBEEF)
|
||||
assert(ed:DrawPreviewData(0, b, 4, DT.U32, HEX) == "0xdeadbeef")
|
||||
assert(ed:DrawPreviewData(0, "\xEF\xBE\xAD\xDE", 4, DT.U32, HEX) == "0xdeadbeef")
|
||||
ed.ReadFn = function(mem, off) return mem[off + 1] + 1 end
|
||||
assert(ed:DrawPreviewData(0, { 0x10, 0x20 }, 2, DT.U16, HEX) == "0x2111")
|
||||
print("OK")
|
||||
Submodule
+1
Submodule tools/core added at e2d1cf5cf9.
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs every tests/t_*.luau against the core (tools/core submodule) in the Roblox mock, the Roblox example,
|
||||
# and (if nix-shell is available) the LÖVE checks under LuaJIT.
|
||||
cd "$(dirname "$0")/.."
|
||||
fail=0
|
||||
run() { python3 tools/core/tools/test/run.py --module MemoryEditor=MemoryEditor.lua --roblox "$@" 2>&1; }
|
||||
for t in tests/t_*.luau; do
|
||||
out=$(run --main "$t" --quiet)
|
||||
if echo "$out" | grep -q "^OK"; then echo "PASS $t"; else echo "FAIL $t"; echo "$out" | tail -20; fail=1; fi
|
||||
done
|
||||
# example LocalScript: 400 frames of random input (mock drives Stepped, not RenderStepped)
|
||||
ex=$(mktemp --suffix=.luau); sed 's/RenderStepped/Stepped/' examples/roblox/main.client.luau > "$ex"
|
||||
out=$(run --main "$ex")
|
||||
rm -f "$ex"
|
||||
if echo "$out" | grep -q "^avg frame"; then echo "PASS example"; else echo "FAIL example"; echo "$out" | tail -20; fail=1; fi
|
||||
if command -v nix-shell >/dev/null; then
|
||||
out=$(nix-shell -p luajit --run "luajit tests/love.lua" 2>&1)
|
||||
if echo "$out" | grep -q "^OK"; then echo "PASS love"; else echo "FAIL love"; echo "$out" | tail -20; fail=1; fi
|
||||
fi
|
||||
exit $fail
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2024 Omar Cornut
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1 @@
|
||||
https://github.com/ocornut/imgui_club @ b083116866e05e0d4bccb2c7f28d94a76ee4965e (imgui_memory_editor/imgui_memory_editor.h, v0.59)
|
||||
@@ -0,0 +1,836 @@
|
||||
// Mini memory editor for Dear ImGui (to embed in your game/tools)
|
||||
// Get latest version at http://www.github.com/ocornut/imgui_club
|
||||
// Licensed under The MIT License (MIT)
|
||||
|
||||
// Right-click anywhere to access the Options menu!
|
||||
// You can adjust the keyboard repeat delay/rate in ImGuiIO.
|
||||
// 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 calling this.
|
||||
//
|
||||
// Usage:
|
||||
// // Create a window and draw memory editor inside it:
|
||||
// static MemoryEditor mem_edit_1;
|
||||
// static char data[0x10000];
|
||||
// size_t data_size = 0x10000;
|
||||
// mem_edit_1.DrawWindow("Memory Editor", data, data_size);
|
||||
//
|
||||
// Usage:
|
||||
// // If you already have a window, use DrawContents() instead:
|
||||
// static MemoryEditor mem_edit_2;
|
||||
// ImGui::Begin("MyWindow")
|
||||
// mem_edit_2.DrawContents(this, sizeof(*this), (size_t)this);
|
||||
// ImGui::End();
|
||||
//
|
||||
// Changelog:
|
||||
// - v0.10: initial version
|
||||
// - v0.23 (2017/08/17): added to github. fixed right-arrow triggering a byte write.
|
||||
// - v0.24 (2018/06/02): changed DragInt("Rows" to use a %d data format (which is desirable since imgui 1.61).
|
||||
// - v0.25 (2018/07/11): fixed wording: all occurrences of "Rows" renamed to "Columns".
|
||||
// - v0.26 (2018/08/02): fixed clicking on hex region
|
||||
// - v0.30 (2018/08/02): added data preview for common data types
|
||||
// - v0.31 (2018/10/10): added OptUpperCaseHex option to select lower/upper casing display [@samhocevar]
|
||||
// - v0.32 (2018/10/10): changed signatures to use void* instead of unsigned char*
|
||||
// - v0.33 (2018/10/10): added OptShowOptions option to hide all the interactive option setting.
|
||||
// - v0.34 (2019/05/07): binary preview now applies endianness setting [@nicolasnoble]
|
||||
// - v0.35 (2020/01/29): using ImGuiDataType available since Dear ImGui 1.69.
|
||||
// - v0.36 (2020/05/05): minor tweaks, minor refactor.
|
||||
// - 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.
|
||||
// - v0.41 (2020/10/05): fix when using with keyboard/gamepad navigation enabled.
|
||||
// - v0.42 (2020/10/14): fix for . character in ASCII view always being greyed out.
|
||||
// - v0.43 (2021/03/12): added OptFooterExtraHeight to allow for custom drawing at the bottom of the editor [@leiradel]
|
||||
// - v0.44 (2021/03/12): use ImGuiInputTextFlags_AlwaysOverwrite in 1.82 + fix hardcoded width.
|
||||
// - v0.50 (2021/11/12): various fixes for recent dear imgui versions (fixed misuse of clipper, relying on SetKeyboardFocusHere() handling scrolling from 1.85). added default size.
|
||||
// - v0.51 (2024/02/22): fix for layout change in 1.89 when using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#34)
|
||||
// - v0.52 (2024/03/08): removed unnecessary GetKeyIndex() calls, they are a no-op since 1.87.
|
||||
// - v0.53 (2024/05/27): fixed right-click popup from not appearing when using DrawContents(). warning fixes. (#35)
|
||||
// - v0.54 (2024/07/29): allow ReadOnly mode to still select and preview data. (#46) [@DeltaGW2])
|
||||
// - v0.55 (2024/08/19): added BgColorFn to allow setting background colors independently from highlighted selection. (#27) [@StrikerX3]
|
||||
// added MouseHoveredAddr public readable field. (#47, #27) [@StrikerX3]
|
||||
// fixed a data preview crash with 1.91.0 WIP. fixed contiguous highlight color when using data preview.
|
||||
// *BREAKING* added UserData field passed to all optional function handlers: ReadFn, WriteFn, HighlightFn, BgColorFn. (#50) [@silverweed]
|
||||
// - v0.56 (2024/11/04): fixed MouseHovered, MouseHoveredAddr not being set when hovering a byte being edited. (#54)
|
||||
// - v0.57 (2025/03/26): fixed warnings. using ImGui's ImSXX/ImUXX types instead of e.g. int32_t/uint32_t. (#56)
|
||||
// - v0.58 (2025/03/31): fixed extraneous footer spacing (added in 0.51) breaking vertical auto-resize. (#53)
|
||||
// - v0.59 (2025/04/08): fixed GotoAddrAndHighlight() not working if OptShowOptions is disabled.
|
||||
//
|
||||
// TODO:
|
||||
// - This is generally old/crappy code, it should work but isn't very good.. to be rewritten some day.
|
||||
// - PageUp/PageDown are not supported because we use _NoNav. This is a good test scenario for working out idioms of how to mix natural nav and our own...
|
||||
// - Arrows are being sent to the InputText() about to disappear which for LeftArrow makes the text cursor appear at position 1 for one frame.
|
||||
// - Using InputText() is awkward and maybe overkill here, consider implementing something custom.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stdio.h> // sprintf, scanf
|
||||
#include <stdint.h> // uint8_t, etc.
|
||||
|
||||
#if defined(_MSC_VER) && !defined(snprintf)
|
||||
#define ImSnprintf _snprintf
|
||||
#else
|
||||
#define ImSnprintf snprintf
|
||||
#endif
|
||||
#if defined(_MSC_VER) && !defined(__clang__)
|
||||
#define _PRISizeT "I"
|
||||
#else
|
||||
#define _PRISizeT "z"
|
||||
#endif
|
||||
|
||||
#if defined(_MSC_VER) || defined(_UCRT)
|
||||
#pragma warning (push)
|
||||
#pragma warning (disable: 4996) // warning C4996: 'sprintf': This function or variable may be unsafe.
|
||||
#endif
|
||||
|
||||
struct MemoryEditor
|
||||
{
|
||||
enum DataFormat
|
||||
{
|
||||
DataFormat_Bin = 0,
|
||||
DataFormat_Dec = 1,
|
||||
DataFormat_Hex = 2,
|
||||
DataFormat_COUNT
|
||||
};
|
||||
|
||||
// Settings
|
||||
bool Open; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow().
|
||||
bool ReadOnly; // = false // disable any editing.
|
||||
int Cols; // = 16 // number of columns to display.
|
||||
bool OptShowOptions; // = true // display options button/context menu. when disabled, options will be locked unless you provide your own UI for them.
|
||||
bool OptShowDataPreview; // = false // display a footer previewing the decimal/binary/hex/float representation of the currently selected bytes.
|
||||
bool OptShowHexII; // = false // display values in HexII representation instead of regular hexadecimal: hide null/zero bytes, ascii values as ".X".
|
||||
bool OptShowAscii; // = true // display ASCII representation on the right side.
|
||||
bool OptGreyOutZeroes; // = true // display null/zero bytes using the TextDisabled color.
|
||||
bool OptUpperCaseHex; // = true // display hexadecimal values as "FF" instead of "ff".
|
||||
int OptMidColsCount; // = 8 // set to 0 to disable extra spacing between every mid-cols.
|
||||
int OptAddrDigitsCount; // = 0 // number of addr digits to display (default calculated based on maximum displayed addr).
|
||||
float OptFooterExtraHeight; // = 0 // space to reserve at the bottom of the widget to add custom widgets
|
||||
ImU32 HighlightColor; // // background color of highlighted bytes.
|
||||
|
||||
// Function handlers
|
||||
ImU8 (*ReadFn)(const ImU8* mem, size_t off, void* user_data); // = 0 // optional handler to read bytes.
|
||||
void (*WriteFn)(ImU8* mem, size_t off, ImU8 d, void* user_data); // = 0 // optional handler to write bytes.
|
||||
bool (*HighlightFn)(const ImU8* mem, size_t off, void* user_data); // = 0 // optional handler to return Highlight property (to support non-contiguous highlighting).
|
||||
ImU32 (*BgColorFn)(const ImU8* mem, size_t off, void* user_data); // = 0 // optional handler to return custom background color of individual bytes.
|
||||
void* UserData; // = NULL // user data forwarded to the function handlers
|
||||
|
||||
// Public read-only data
|
||||
bool MouseHovered; // set when mouse is hovering a value.
|
||||
size_t MouseHoveredAddr; // the address currently being hovered if MouseHovered is set.
|
||||
|
||||
// [Internal State]
|
||||
bool ContentsWidthChanged;
|
||||
size_t DataPreviewAddr;
|
||||
size_t DataEditingAddr;
|
||||
bool DataEditingTakeFocus;
|
||||
char DataInputBuf[32];
|
||||
char AddrInputBuf[32];
|
||||
size_t GotoAddr;
|
||||
size_t HighlightMin, HighlightMax;
|
||||
int PreviewEndianness;
|
||||
ImGuiDataType PreviewDataType;
|
||||
|
||||
MemoryEditor()
|
||||
{
|
||||
// Settings
|
||||
Open = true;
|
||||
ReadOnly = false;
|
||||
Cols = 16;
|
||||
OptShowOptions = true;
|
||||
OptShowDataPreview = false;
|
||||
OptShowHexII = false;
|
||||
OptShowAscii = true;
|
||||
OptGreyOutZeroes = true;
|
||||
OptUpperCaseHex = true;
|
||||
OptMidColsCount = 8;
|
||||
OptAddrDigitsCount = 0;
|
||||
OptFooterExtraHeight = 0.0f;
|
||||
HighlightColor = IM_COL32(255, 255, 255, 50);
|
||||
ReadFn = nullptr;
|
||||
WriteFn = nullptr;
|
||||
HighlightFn = nullptr;
|
||||
BgColorFn = nullptr;
|
||||
UserData = nullptr;
|
||||
|
||||
// State/Internals
|
||||
ContentsWidthChanged = false;
|
||||
DataPreviewAddr = DataEditingAddr = (size_t)-1;
|
||||
DataEditingTakeFocus = false;
|
||||
memset(DataInputBuf, 0, sizeof(DataInputBuf));
|
||||
memset(AddrInputBuf, 0, sizeof(AddrInputBuf));
|
||||
GotoAddr = (size_t)-1;
|
||||
MouseHovered = false;
|
||||
MouseHoveredAddr = 0;
|
||||
HighlightMin = HighlightMax = (size_t)-1;
|
||||
PreviewEndianness = 0;
|
||||
PreviewDataType = ImGuiDataType_S32;
|
||||
}
|
||||
|
||||
void GotoAddrAndHighlight(size_t addr_min, size_t addr_max)
|
||||
{
|
||||
GotoAddr = addr_min;
|
||||
HighlightMin = addr_min;
|
||||
HighlightMax = addr_max;
|
||||
}
|
||||
|
||||
struct Sizes
|
||||
{
|
||||
int AddrDigitsCount; // Number of digits required to represent maximum address.
|
||||
float LineHeight; // Height of each line (no spacing).
|
||||
float GlyphWidth; // Glyph width (assume mono-space).
|
||||
float HexCellWidth; // Width of a hex edit cell ~2.5f * GlypHWidth.
|
||||
float SpacingBetweenMidCols; // Spacing between each columns section (OptMidColsCount).
|
||||
float OffsetHexMinX;
|
||||
float OffsetHexMaxX;
|
||||
float OffsetAsciiMinX;
|
||||
float OffsetAsciiMaxX;
|
||||
float WindowWidth; // Ideal window width.
|
||||
|
||||
Sizes() { memset(this, 0, sizeof(*this)); }
|
||||
};
|
||||
|
||||
void CalcSizes(Sizes& s, size_t mem_size, size_t base_display_addr)
|
||||
{
|
||||
ImGuiStyle& style = ImGui::GetStyle();
|
||||
s.AddrDigitsCount = OptAddrDigitsCount;
|
||||
if (s.AddrDigitsCount == 0)
|
||||
for (size_t n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
|
||||
s.AddrDigitsCount++;
|
||||
s.LineHeight = ImGui::GetTextLineHeight();
|
||||
s.GlyphWidth = ImGui::CalcTextSize("F").x + 1; // We assume the font is mono-space
|
||||
s.HexCellWidth = (float)(int)(s.GlyphWidth * 2.5f); // "FF " we include trailing space in the width to easily catch clicks everywhere
|
||||
s.SpacingBetweenMidCols = (float)(int)(s.HexCellWidth * 0.25f); // Every OptMidColsCount columns we add a bit of extra spacing
|
||||
s.OffsetHexMinX = (s.AddrDigitsCount + 2) * s.GlyphWidth;
|
||||
s.OffsetHexMaxX = s.OffsetHexMinX + (s.HexCellWidth * Cols);
|
||||
s.OffsetAsciiMinX = s.OffsetAsciiMaxX = s.OffsetHexMaxX;
|
||||
if (OptShowAscii)
|
||||
{
|
||||
s.OffsetAsciiMinX = s.OffsetHexMaxX + s.GlyphWidth * 1;
|
||||
if (OptMidColsCount > 0)
|
||||
s.OffsetAsciiMinX += (float)((Cols + OptMidColsCount - 1) / OptMidColsCount) * s.SpacingBetweenMidCols;
|
||||
s.OffsetAsciiMaxX = s.OffsetAsciiMinX + Cols * s.GlyphWidth;
|
||||
}
|
||||
s.WindowWidth = s.OffsetAsciiMaxX + style.ScrollbarSize + style.WindowPadding.x * 2 + s.GlyphWidth;
|
||||
}
|
||||
|
||||
// Standalone Memory Editor window
|
||||
void DrawWindow(const char* title, void* mem_data, size_t mem_size, size_t base_display_addr = 0x0000)
|
||||
{
|
||||
Sizes s;
|
||||
CalcSizes(s, mem_size, base_display_addr);
|
||||
ImGui::SetNextWindowSize(ImVec2(s.WindowWidth, s.WindowWidth * 0.60f), ImGuiCond_FirstUseEver);
|
||||
ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, 0.0f), ImVec2(s.WindowWidth, FLT_MAX));
|
||||
|
||||
Open = true;
|
||||
if (ImGui::Begin(title, &Open, ImGuiWindowFlags_NoScrollbar))
|
||||
{
|
||||
DrawContents(mem_data, mem_size, base_display_addr);
|
||||
if (ContentsWidthChanged)
|
||||
{
|
||||
CalcSizes(s, mem_size, base_display_addr);
|
||||
ImGui::SetWindowSize(ImVec2(s.WindowWidth, ImGui::GetWindowSize().y));
|
||||
}
|
||||
}
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// Memory Editor contents only
|
||||
void DrawContents(void* mem_data_void, size_t mem_size, size_t base_display_addr = 0x0000)
|
||||
{
|
||||
if (Cols < 1)
|
||||
Cols = 1;
|
||||
|
||||
ImU8* mem_data = (ImU8*)mem_data_void;
|
||||
Sizes s;
|
||||
CalcSizes(s, mem_size, base_display_addr);
|
||||
ImGuiStyle& style = ImGui::GetStyle();
|
||||
|
||||
const ImVec2 contents_pos_start = ImGui::GetCursorScreenPos();
|
||||
|
||||
// We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window.
|
||||
// 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.
|
||||
const float height_separator = style.ItemSpacing.y;
|
||||
float footer_height = OptFooterExtraHeight;
|
||||
if (OptShowOptions)
|
||||
footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1;
|
||||
if (OptShowDataPreview)
|
||||
footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1 + ImGui::GetTextLineHeightWithSpacing() * 3;
|
||||
ImGui::BeginChild("##scrolling", ImVec2(-FLT_MIN, -footer_height), ImGuiChildFlags_None, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNav);
|
||||
ImDrawList* draw_list = ImGui::GetWindowDrawList();
|
||||
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
|
||||
|
||||
// We are not really using the clipper API correctly here, because we rely on visible_start_addr/visible_end_addr for our scrolling function.
|
||||
const ImVec2 avail_size = ImGui::GetContentRegionAvail();
|
||||
const int line_total_count = (int)((mem_size + Cols - 1) / Cols);
|
||||
ImGuiListClipper clipper;
|
||||
clipper.Begin(line_total_count, s.LineHeight);
|
||||
|
||||
bool data_next = false;
|
||||
|
||||
if (DataEditingAddr >= mem_size)
|
||||
DataEditingAddr = (size_t)-1;
|
||||
if (DataPreviewAddr >= mem_size)
|
||||
DataPreviewAddr = (size_t)-1;
|
||||
|
||||
size_t preview_data_type_size = OptShowDataPreview ? DataTypeGetSize(PreviewDataType) : 0;
|
||||
|
||||
size_t data_editing_addr_next = (size_t)-1;
|
||||
if (DataEditingAddr != (size_t)-1)
|
||||
{
|
||||
// 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)
|
||||
if (ImGui::IsKeyPressed(ImGuiKey_UpArrow) && (ptrdiff_t)DataEditingAddr >= (ptrdiff_t)Cols) { data_editing_addr_next = DataEditingAddr - Cols; }
|
||||
else if (ImGui::IsKeyPressed(ImGuiKey_DownArrow) && (ptrdiff_t)DataEditingAddr < (ptrdiff_t)mem_size - Cols){ data_editing_addr_next = DataEditingAddr + Cols; }
|
||||
else if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow) && (ptrdiff_t)DataEditingAddr > (ptrdiff_t)0) { data_editing_addr_next = DataEditingAddr - 1; }
|
||||
else if (ImGui::IsKeyPressed(ImGuiKey_RightArrow) && (ptrdiff_t)DataEditingAddr < (ptrdiff_t)mem_size - 1) { data_editing_addr_next = DataEditingAddr + 1; }
|
||||
}
|
||||
|
||||
// Draw vertical separator
|
||||
ImVec2 window_pos = ImGui::GetWindowPos();
|
||||
if (OptShowAscii)
|
||||
draw_list->AddLine(ImVec2(window_pos.x + s.OffsetAsciiMinX - s.GlyphWidth, window_pos.y), ImVec2(window_pos.x + s.OffsetAsciiMinX - s.GlyphWidth, window_pos.y + 9999), ImGui::GetColorU32(ImGuiCol_Border));
|
||||
|
||||
const ImU32 color_text = ImGui::GetColorU32(ImGuiCol_Text);
|
||||
const ImU32 color_disabled = OptGreyOutZeroes ? ImGui::GetColorU32(ImGuiCol_TextDisabled) : color_text;
|
||||
|
||||
const char* format_address = OptUpperCaseHex ? "%0*" _PRISizeT "X: " : "%0*" _PRISizeT "x: ";
|
||||
const char* format_data = OptUpperCaseHex ? "%0*" _PRISizeT "X" : "%0*" _PRISizeT "x";
|
||||
const char* format_byte = OptUpperCaseHex ? "%02X" : "%02x";
|
||||
const char* format_byte_space = OptUpperCaseHex ? "%02X " : "%02x ";
|
||||
|
||||
MouseHovered = false;
|
||||
MouseHoveredAddr = 0;
|
||||
|
||||
while (clipper.Step())
|
||||
for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible lines
|
||||
{
|
||||
size_t addr = (size_t)line_i * Cols;
|
||||
ImGui::Text(format_address, s.AddrDigitsCount, base_display_addr + addr);
|
||||
|
||||
// Draw Hexadecimal
|
||||
for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
|
||||
{
|
||||
float byte_pos_x = s.OffsetHexMinX + s.HexCellWidth * n;
|
||||
if (OptMidColsCount > 0)
|
||||
byte_pos_x += (float)(n / OptMidColsCount) * s.SpacingBetweenMidCols;
|
||||
ImGui::SameLine(byte_pos_x);
|
||||
|
||||
// Draw highlight or custom background color
|
||||
const bool is_highlight_from_user_range = (addr >= HighlightMin && addr < HighlightMax);
|
||||
const bool is_highlight_from_user_func = (HighlightFn && HighlightFn(mem_data, addr, UserData));
|
||||
const bool is_highlight_from_preview = (addr >= DataPreviewAddr && addr < DataPreviewAddr + preview_data_type_size);
|
||||
|
||||
ImU32 bg_color = 0;
|
||||
bool is_next_byte_highlighted = false;
|
||||
if (is_highlight_from_user_range || is_highlight_from_user_func || is_highlight_from_preview)
|
||||
{
|
||||
is_next_byte_highlighted = (addr + 1 < mem_size) && ((HighlightMax != (size_t)-1 && addr + 1 < HighlightMax) || (HighlightFn && HighlightFn(mem_data, addr + 1, UserData)) || (addr + 1 < DataPreviewAddr + preview_data_type_size));
|
||||
bg_color = HighlightColor;
|
||||
}
|
||||
else if (BgColorFn != nullptr)
|
||||
{
|
||||
is_next_byte_highlighted = (addr + 1 < mem_size) && ((BgColorFn(mem_data, addr + 1, UserData) & IM_COL32_A_MASK) != 0);
|
||||
bg_color = BgColorFn(mem_data, addr, UserData);
|
||||
}
|
||||
if (bg_color != 0)
|
||||
{
|
||||
float bg_width = s.GlyphWidth * 2;
|
||||
if (is_next_byte_highlighted || (n + 1 == Cols))
|
||||
{
|
||||
bg_width = s.HexCellWidth;
|
||||
if (OptMidColsCount > 0 && n > 0 && (n + 1) < Cols && ((n + 1) % OptMidColsCount) == 0)
|
||||
bg_width += s.SpacingBetweenMidCols;
|
||||
}
|
||||
ImVec2 pos = ImGui::GetCursorScreenPos();
|
||||
draw_list->AddRectFilled(pos, ImVec2(pos.x + bg_width, pos.y + s.LineHeight), bg_color);
|
||||
}
|
||||
|
||||
if (DataEditingAddr == addr)
|
||||
{
|
||||
// Display text input on current byte
|
||||
bool data_write = false;
|
||||
ImGui::PushID((void*)addr);
|
||||
if (DataEditingTakeFocus)
|
||||
{
|
||||
ImGui::SetKeyboardFocusHere(0);
|
||||
ImSnprintf(AddrInputBuf, 32, format_data, s.AddrDigitsCount, base_display_addr + addr);
|
||||
ImSnprintf(DataInputBuf, 32, format_byte, ReadFn ? ReadFn(mem_data, addr, UserData) : mem_data[addr]);
|
||||
}
|
||||
struct InputTextUserData
|
||||
{
|
||||
// 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.
|
||||
static int Callback(ImGuiInputTextCallbackData* data)
|
||||
{
|
||||
InputTextUserData* user_data = (InputTextUserData*)data->UserData;
|
||||
if (!data->HasSelection())
|
||||
user_data->CursorPos = data->CursorPos;
|
||||
#if IMGUI_VERSION_NUM < 19102
|
||||
if (data->Flags & ImGuiInputTextFlags_ReadOnly)
|
||||
return 0;
|
||||
#endif
|
||||
if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen)
|
||||
{
|
||||
// When not editing a byte, always refresh its InputText content pulled from underlying memory data
|
||||
// (this is a bit tricky, since InputText technically "owns" the master copy of the buffer we edit it in there)
|
||||
data->DeleteChars(0, data->BufTextLen);
|
||||
data->InsertChars(0, user_data->CurrentBufOverwrite);
|
||||
data->SelectionStart = 0;
|
||||
data->SelectionEnd = 2;
|
||||
data->CursorPos = 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
char CurrentBufOverwrite[3]; // Input
|
||||
int CursorPos; // Output
|
||||
};
|
||||
InputTextUserData input_text_user_data;
|
||||
input_text_user_data.CursorPos = -1;
|
||||
ImSnprintf(input_text_user_data.CurrentBufOverwrite, 3, format_byte, ReadFn ? ReadFn(mem_data, addr, UserData) : mem_data[addr]);
|
||||
ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoHorizontalScroll | ImGuiInputTextFlags_CallbackAlways;
|
||||
if (ReadOnly)
|
||||
flags |= ImGuiInputTextFlags_ReadOnly;
|
||||
flags |= ImGuiInputTextFlags_AlwaysOverwrite; // was ImGuiInputTextFlags_AlwaysInsertMode
|
||||
ImGui::SetNextItemWidth(s.GlyphWidth * 2);
|
||||
if (ImGui::InputText("##data", DataInputBuf, IM_ARRAYSIZE(DataInputBuf), flags, InputTextUserData::Callback, &input_text_user_data))
|
||||
data_write = data_next = true;
|
||||
else if (!DataEditingTakeFocus && !ImGui::IsItemActive())
|
||||
DataEditingAddr = data_editing_addr_next = (size_t)-1;
|
||||
DataEditingTakeFocus = false;
|
||||
if (input_text_user_data.CursorPos >= 2)
|
||||
data_write = data_next = true;
|
||||
if (data_editing_addr_next != (size_t)-1)
|
||||
data_write = data_next = false;
|
||||
unsigned int data_input_value = 0;
|
||||
if (!ReadOnly && data_write && sscanf(DataInputBuf, "%X", &data_input_value) == 1)
|
||||
{
|
||||
if (WriteFn)
|
||||
WriteFn(mem_data, addr, (ImU8)data_input_value, UserData);
|
||||
else
|
||||
mem_data[addr] = (ImU8)data_input_value;
|
||||
}
|
||||
if (ImGui::IsItemHovered())
|
||||
{
|
||||
MouseHovered = true;
|
||||
MouseHoveredAddr = addr;
|
||||
}
|
||||
ImGui::PopID();
|
||||
}
|
||||
else
|
||||
{
|
||||
// NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on.
|
||||
ImU8 b = ReadFn ? ReadFn(mem_data, addr, UserData) : mem_data[addr];
|
||||
|
||||
if (OptShowHexII)
|
||||
{
|
||||
if ((b >= 32 && b < 128))
|
||||
ImGui::Text(".%c ", b);
|
||||
else if (b == 0xFF && OptGreyOutZeroes)
|
||||
ImGui::TextDisabled("## ");
|
||||
else if (b == 0x00)
|
||||
ImGui::Text(" ");
|
||||
else
|
||||
ImGui::Text(format_byte_space, b);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (b == 0 && OptGreyOutZeroes)
|
||||
ImGui::TextDisabled("00 ");
|
||||
else
|
||||
ImGui::Text(format_byte_space, b);
|
||||
}
|
||||
if (ImGui::IsItemHovered())
|
||||
{
|
||||
MouseHovered = true;
|
||||
MouseHoveredAddr = addr;
|
||||
if (ImGui::IsMouseClicked(0))
|
||||
{
|
||||
DataEditingTakeFocus = true;
|
||||
data_editing_addr_next = addr;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (OptShowAscii)
|
||||
{
|
||||
// Draw ASCII values
|
||||
ImGui::SameLine(s.OffsetAsciiMinX);
|
||||
ImVec2 pos = ImGui::GetCursorScreenPos();
|
||||
addr = (size_t)line_i * Cols;
|
||||
|
||||
const float mouse_off_x = ImGui::GetIO().MousePos.x - pos.x;
|
||||
const size_t mouse_addr = (mouse_off_x >= 0.0f && mouse_off_x < s.OffsetAsciiMaxX - s.OffsetAsciiMinX) ? addr + (size_t)(mouse_off_x / s.GlyphWidth) : (size_t)-1;
|
||||
|
||||
ImGui::PushID(line_i);
|
||||
if (ImGui::InvisibleButton("ascii", ImVec2(s.OffsetAsciiMaxX - s.OffsetAsciiMinX, s.LineHeight)))
|
||||
{
|
||||
DataEditingAddr = DataPreviewAddr = mouse_addr;
|
||||
DataEditingTakeFocus = true;
|
||||
}
|
||||
if (ImGui::IsItemHovered())
|
||||
{
|
||||
MouseHovered = true;
|
||||
MouseHoveredAddr = mouse_addr;
|
||||
}
|
||||
ImGui::PopID();
|
||||
for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
|
||||
{
|
||||
if (addr == DataEditingAddr)
|
||||
{
|
||||
draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_FrameBg));
|
||||
draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_TextSelectedBg));
|
||||
}
|
||||
else if (BgColorFn)
|
||||
{
|
||||
draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), BgColorFn(mem_data, addr, UserData));
|
||||
}
|
||||
unsigned char c = ReadFn ? ReadFn(mem_data, addr, UserData) : mem_data[addr];
|
||||
char display_c = (c < 32 || c >= 128) ? '.' : c;
|
||||
draw_list->AddText(pos, (display_c == c) ? color_text : color_disabled, &display_c, &display_c + 1);
|
||||
pos.x += s.GlyphWidth;
|
||||
}
|
||||
}
|
||||
}
|
||||
ImGui::PopStyleVar(2);
|
||||
const float child_width = ImGui::GetWindowSize().x;
|
||||
ImGui::EndChild();
|
||||
|
||||
// Notify the main window of our ideal child content size (FIXME: we are missing an API to get the contents size from the child)
|
||||
ImVec2 backup_pos = ImGui::GetCursorScreenPos();
|
||||
ImGui::SetCursorPosX(s.WindowWidth);
|
||||
ImGui::Dummy(ImVec2(0.0f, 0.0f));
|
||||
ImGui::SetCursorScreenPos(backup_pos);
|
||||
|
||||
if (data_next && DataEditingAddr + 1 < mem_size)
|
||||
{
|
||||
DataEditingAddr = DataPreviewAddr = DataEditingAddr + 1;
|
||||
DataEditingTakeFocus = true;
|
||||
}
|
||||
else if (data_editing_addr_next != (size_t)-1)
|
||||
{
|
||||
DataEditingAddr = DataPreviewAddr = data_editing_addr_next;
|
||||
DataEditingTakeFocus = true;
|
||||
}
|
||||
|
||||
const bool lock_show_data_preview = OptShowDataPreview;
|
||||
if (OptShowOptions)
|
||||
{
|
||||
ImGui::Separator();
|
||||
DrawOptionsLine(s, mem_data, mem_size, base_display_addr);
|
||||
}
|
||||
|
||||
if (lock_show_data_preview)
|
||||
{
|
||||
ImGui::Separator();
|
||||
DrawPreviewLine(s, mem_data, mem_size, base_display_addr);
|
||||
}
|
||||
|
||||
if (GotoAddr != (size_t)-1)
|
||||
{
|
||||
if (GotoAddr < mem_size)
|
||||
{
|
||||
ImGui::BeginChild("##scrolling");
|
||||
ImGui::SetScrollY((GotoAddr / Cols) * ImGui::GetTextLineHeight() - avail_size.y * 0.5f);
|
||||
ImGui::EndChild();
|
||||
DataEditingAddr = DataPreviewAddr = GotoAddr;
|
||||
DataEditingTakeFocus = true;
|
||||
}
|
||||
GotoAddr = (size_t)-1;
|
||||
}
|
||||
|
||||
const ImVec2 contents_pos_end(contents_pos_start.x + child_width, ImGui::GetCursorScreenPos().y);
|
||||
//ImGui::GetForegroundDrawList()->AddRect(contents_pos_start, contents_pos_end, IM_COL32(255, 0, 0, 255));
|
||||
if (OptShowOptions)
|
||||
if (ImGui::IsMouseHoveringRect(contents_pos_start, contents_pos_end))
|
||||
if (ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) && ImGui::IsMouseReleased(ImGuiMouseButton_Right))
|
||||
ImGui::OpenPopup("OptionsPopup");
|
||||
|
||||
if (ImGui::BeginPopup("OptionsPopup"))
|
||||
{
|
||||
ImGui::SetNextItemWidth(s.GlyphWidth * 7 + style.FramePadding.x * 2.0f);
|
||||
if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; if (Cols < 1) Cols = 1; }
|
||||
ImGui::Checkbox("Show Data Preview", &OptShowDataPreview);
|
||||
ImGui::Checkbox("Show HexII", &OptShowHexII);
|
||||
if (ImGui::Checkbox("Show Ascii", &OptShowAscii)) { ContentsWidthChanged = true; }
|
||||
ImGui::Checkbox("Grey out zeroes", &OptGreyOutZeroes);
|
||||
ImGui::Checkbox("Uppercase Hex", &OptUpperCaseHex);
|
||||
|
||||
ImGui::EndPopup();
|
||||
}
|
||||
}
|
||||
|
||||
void DrawOptionsLine(const Sizes& s, void* mem_data, size_t mem_size, size_t base_display_addr)
|
||||
{
|
||||
IM_UNUSED(mem_data);
|
||||
ImGuiStyle& style = ImGui::GetStyle();
|
||||
const char* format_range = OptUpperCaseHex ? "Range %0*" _PRISizeT "X..%0*" _PRISizeT "X" : "Range %0*" _PRISizeT "x..%0*" _PRISizeT "x";
|
||||
|
||||
// Options menu
|
||||
if (ImGui::Button("Options"))
|
||||
ImGui::OpenPopup("OptionsPopup");
|
||||
|
||||
ImGui::SameLine();
|
||||
ImGui::Text(format_range, s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1);
|
||||
ImGui::SameLine();
|
||||
ImGui::SetNextItemWidth((s.AddrDigitsCount + 1) * s.GlyphWidth + style.FramePadding.x * 2.0f);
|
||||
if (ImGui::InputText("##addr", AddrInputBuf, IM_ARRAYSIZE(AddrInputBuf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue))
|
||||
{
|
||||
size_t goto_addr;
|
||||
if (sscanf(AddrInputBuf, "%" _PRISizeT "X", &goto_addr) == 1)
|
||||
{
|
||||
GotoAddr = goto_addr - base_display_addr;
|
||||
HighlightMin = HighlightMax = (size_t)-1;
|
||||
}
|
||||
}
|
||||
|
||||
//if (MouseHovered)
|
||||
//{
|
||||
// ImGui::SameLine();
|
||||
// ImGui::Text("Hovered: %p", MouseHoveredAddr);
|
||||
//}
|
||||
}
|
||||
|
||||
void DrawPreviewLine(const Sizes& s, void* mem_data_void, size_t mem_size, size_t base_display_addr)
|
||||
{
|
||||
IM_UNUSED(base_display_addr);
|
||||
ImU8* mem_data = (ImU8*)mem_data_void;
|
||||
ImGuiStyle& style = ImGui::GetStyle();
|
||||
ImGui::AlignTextToFramePadding();
|
||||
ImGui::Text("Preview as:");
|
||||
ImGui::SameLine();
|
||||
ImGui::SetNextItemWidth((s.GlyphWidth * 10.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
|
||||
|
||||
static const ImGuiDataType supported_data_types[] = { ImGuiDataType_S8, ImGuiDataType_U8, ImGuiDataType_S16, ImGuiDataType_U16, ImGuiDataType_S32, ImGuiDataType_U32, ImGuiDataType_S64, ImGuiDataType_U64, ImGuiDataType_Float, ImGuiDataType_Double };
|
||||
if (ImGui::BeginCombo("##combo_type", DataTypeGetDesc(PreviewDataType), ImGuiComboFlags_HeightLargest))
|
||||
{
|
||||
for (int n = 0; n < IM_ARRAYSIZE(supported_data_types); n++)
|
||||
{
|
||||
ImGuiDataType data_type = supported_data_types[n];
|
||||
if (ImGui::Selectable(DataTypeGetDesc(data_type), PreviewDataType == data_type))
|
||||
PreviewDataType = data_type;
|
||||
}
|
||||
ImGui::EndCombo();
|
||||
}
|
||||
ImGui::SameLine();
|
||||
ImGui::SetNextItemWidth((s.GlyphWidth * 6.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
|
||||
ImGui::Combo("##combo_endianness", &PreviewEndianness, "LE\0BE\0\0");
|
||||
|
||||
char buf[128] = "";
|
||||
float x = s.GlyphWidth * 6.0f;
|
||||
bool has_value = DataPreviewAddr != (size_t)-1;
|
||||
if (has_value)
|
||||
DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Dec, buf, (size_t)IM_ARRAYSIZE(buf));
|
||||
ImGui::Text("Dec"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
|
||||
if (has_value)
|
||||
DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Hex, buf, (size_t)IM_ARRAYSIZE(buf));
|
||||
ImGui::Text("Hex"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
|
||||
if (has_value)
|
||||
DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Bin, buf, (size_t)IM_ARRAYSIZE(buf));
|
||||
buf[IM_ARRAYSIZE(buf) - 1] = 0;
|
||||
ImGui::Text("Bin"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
|
||||
}
|
||||
|
||||
// Utilities for Data Preview (since we don't access imgui_internal.h)
|
||||
// FIXME: This technically depends on ImGuiDataType order.
|
||||
const char* DataTypeGetDesc(ImGuiDataType data_type) const
|
||||
{
|
||||
const char* descs[] = { "Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64", "Float", "Double" };
|
||||
IM_ASSERT(data_type >= 0 && data_type < IM_ARRAYSIZE(descs));
|
||||
return descs[data_type];
|
||||
}
|
||||
|
||||
size_t DataTypeGetSize(ImGuiDataType data_type) const
|
||||
{
|
||||
const size_t sizes[] = { 1, 1, 2, 2, 4, 4, 8, 8, sizeof(float), sizeof(double) };
|
||||
IM_ASSERT(data_type >= 0 && data_type < IM_ARRAYSIZE(sizes));
|
||||
return sizes[data_type];
|
||||
}
|
||||
|
||||
const char* DataFormatGetDesc(DataFormat data_format) const
|
||||
{
|
||||
const char* descs[] = { "Bin", "Dec", "Hex" };
|
||||
IM_ASSERT(data_format >= 0 && data_format < DataFormat_COUNT);
|
||||
return descs[data_format];
|
||||
}
|
||||
|
||||
bool IsBigEndian() const
|
||||
{
|
||||
ImU16 x = 1;
|
||||
char c[2];
|
||||
memcpy(c, &x, 2);
|
||||
return c[0] != 0;
|
||||
}
|
||||
|
||||
static void* EndiannessCopyBigEndian(void* _dst, void* _src, size_t s, int is_little_endian)
|
||||
{
|
||||
if (is_little_endian)
|
||||
{
|
||||
ImU8* dst = (ImU8*)_dst;
|
||||
ImU8* src = (ImU8*)_src + s - 1;
|
||||
for (int i = 0, n = (int)s; i < n; ++i)
|
||||
memcpy(dst++, src--, 1);
|
||||
return _dst;
|
||||
}
|
||||
else
|
||||
{
|
||||
return memcpy(_dst, _src, s);
|
||||
}
|
||||
}
|
||||
|
||||
static void* EndiannessCopyLittleEndian(void* _dst, void* _src, size_t s, int is_little_endian)
|
||||
{
|
||||
if (is_little_endian)
|
||||
{
|
||||
return memcpy(_dst, _src, s);
|
||||
}
|
||||
else
|
||||
{
|
||||
ImU8* dst = (ImU8*)_dst;
|
||||
ImU8* src = (ImU8*)_src + s - 1;
|
||||
for (int i = 0, n = (int)s; i < n; ++i)
|
||||
memcpy(dst++, src--, 1);
|
||||
return _dst;
|
||||
}
|
||||
}
|
||||
|
||||
void* EndiannessCopy(void* dst, void* src, size_t size) const
|
||||
{
|
||||
static void* (*fp)(void*, void*, size_t, int) = nullptr;
|
||||
if (fp == nullptr)
|
||||
fp = IsBigEndian() ? EndiannessCopyBigEndian : EndiannessCopyLittleEndian;
|
||||
return fp(dst, src, size, PreviewEndianness);
|
||||
}
|
||||
|
||||
const char* FormatBinary(const ImU8* buf, int width) const
|
||||
{
|
||||
IM_ASSERT(width <= 64);
|
||||
size_t out_n = 0;
|
||||
static char out_buf[64 + 8 + 1];
|
||||
int n = width / 8;
|
||||
for (int j = n - 1; j >= 0; --j)
|
||||
{
|
||||
for (int i = 0; i < 8; ++i)
|
||||
out_buf[out_n++] = (buf[j] & (1 << (7 - i))) ? '1' : '0';
|
||||
out_buf[out_n++] = ' ';
|
||||
}
|
||||
IM_ASSERT(out_n < IM_ARRAYSIZE(out_buf));
|
||||
out_buf[out_n] = 0;
|
||||
return out_buf;
|
||||
}
|
||||
|
||||
// [Internal]
|
||||
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
|
||||
{
|
||||
ImU8 buf[8];
|
||||
size_t elem_size = DataTypeGetSize(data_type);
|
||||
size_t size = addr + elem_size > mem_size ? mem_size - addr : elem_size;
|
||||
if (ReadFn)
|
||||
for (int i = 0, n = (int)size; i < n; ++i)
|
||||
buf[i] = ReadFn(mem_data, addr + i, UserData);
|
||||
else
|
||||
memcpy(buf, mem_data + addr, size);
|
||||
|
||||
if (data_format == DataFormat_Bin)
|
||||
{
|
||||
ImU8 binbuf[8];
|
||||
EndiannessCopy(binbuf, buf, size);
|
||||
ImSnprintf(out_buf, out_buf_size, "%s", FormatBinary(binbuf, (int)size * 8));
|
||||
return;
|
||||
}
|
||||
|
||||
out_buf[0] = 0;
|
||||
switch (data_type)
|
||||
{
|
||||
case ImGuiDataType_S8:
|
||||
{
|
||||
ImS8 data = 0;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhd", data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", data & 0xFF); return; }
|
||||
break;
|
||||
}
|
||||
case ImGuiDataType_U8:
|
||||
{
|
||||
ImU8 data = 0;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhu", data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", data & 0XFF); return; }
|
||||
break;
|
||||
}
|
||||
case ImGuiDataType_S16:
|
||||
{
|
||||
ImS16 data = 0;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hd", data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", data & 0xFFFF); return; }
|
||||
break;
|
||||
}
|
||||
case ImGuiDataType_U16:
|
||||
{
|
||||
ImU16 data = 0;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hu", data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", data & 0xFFFF); return; }
|
||||
break;
|
||||
}
|
||||
case ImGuiDataType_S32:
|
||||
{
|
||||
ImS32 data = 0;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%d", data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", data); return; }
|
||||
break;
|
||||
}
|
||||
case ImGuiDataType_U32:
|
||||
{
|
||||
ImU32 data = 0;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%u", data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", data); return; }
|
||||
break;
|
||||
}
|
||||
case ImGuiDataType_S64:
|
||||
{
|
||||
ImS64 data = 0;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%lld", (long long)data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)data); return; }
|
||||
break;
|
||||
}
|
||||
case ImGuiDataType_U64:
|
||||
{
|
||||
ImU64 data = 0;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%llu", (long long)data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)data); return; }
|
||||
break;
|
||||
}
|
||||
case ImGuiDataType_Float:
|
||||
{
|
||||
float data = 0.0f;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", data); return; }
|
||||
break;
|
||||
}
|
||||
case ImGuiDataType_Double:
|
||||
{
|
||||
double data = 0.0;
|
||||
EndiannessCopy(&data, buf, size);
|
||||
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", data); return; }
|
||||
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", data); return; }
|
||||
break;
|
||||
}
|
||||
default:
|
||||
case ImGuiDataType_COUNT:
|
||||
break;
|
||||
} // Switch
|
||||
IM_ASSERT(0); // Shouldn't reach
|
||||
}
|
||||
};
|
||||
|
||||
#undef _PRISizeT
|
||||
#undef ImSnprintf
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning (pop)
|
||||
#endif
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "4dbug/imgui-memory-editor-luau"
|
||||
version = "0.1.0"
|
||||
registry = "https://github.com/UpliftGames/wally-index"
|
||||
realm = "shared"
|
||||
license = "MIT"
|
||||
description = "Hex/memory editor (imgui_club imgui_memory_editor) for imgui-luau: Roblox buffers, LÖVE ByteData, byte tables."
|
||||
include = ["MemoryEditor.lua", "LICENSE", "README.md", "wally.toml", "default.project.json"]
|
||||
|
||||
[peer-dependencies]
|
||||
ImGui = "4dbug/imgui-luau@^0.4.1"
|
||||
Reference in new issue
Block a user