openMSX
DebuggableEditor.cc
Go to the documentation of this file.
1#include "DebuggableEditor.hh"
2
3#include "ImGuiCpp.hh"
4#include "ImGuiManager.hh"
5#include "ImGuiSettings.hh"
6#include "ImGuiUtils.hh"
7#include "Shortcuts.hh"
8
9#include "CommandException.hh"
10#include "Debuggable.hh"
11#include "Debugger.hh"
12#include "Interpreter.hh"
13#include "MSXMotherBoard.hh"
14#include "SymbolManager.hh"
15#include "TclObject.hh"
16
17#include "enumerate.hh"
18#include "narrow.hh"
19#include "unreachable.hh"
20
21#include "imgui_stdlib.h"
22
23#include <algorithm>
24#include <array>
25#include <bit>
26#include <cassert>
27#include <cstdint>
28#include <cstdio>
29#include <span>
30
31namespace openmsx {
32
33using namespace std::literals;
34
35static constexpr int MidColsCount = 8; // extra spacing between every mid-cols.
36static constexpr auto HighlightColor = IM_COL32(255, 255, 255, 50); // background color of highlighted bytes.
37
38DebuggableEditor::DebuggableEditor(ImGuiManager& manager_, std::string debuggableName_, size_t index)
39 : ImGuiPart(manager_)
40 , symbolManager(manager.getReactor().getSymbolManager())
41 , title(std::move(debuggableName_))
42{
43 debuggableNameSize = title.size();
44 if (index) {
45 strAppend(title, " (", index + 1, ')');
46 }
47}
48
49void DebuggableEditor::save(ImGuiTextBuffer& buf)
50{
51 savePersistent(buf, *this, persistentElements);
52}
53
54void DebuggableEditor::loadLine(std::string_view name, zstring_view value)
55{
56 loadOnePersistent(name, value, *this, persistentElements);
57 parseSearchString(searchString);
58}
59
61{
62 updateAddr = true;
63}
64
65DebuggableEditor::Sizes DebuggableEditor::calcSizes(unsigned memSize) const
66{
67 Sizes s;
68 const auto& style = ImGui::GetStyle();
69
70 s.addrDigitsCount = 0;
71 for (unsigned n = memSize - 1; n > 0; n >>= 4) {
72 ++s.addrDigitsCount;
73 }
74
75 s.lineHeight = ImGui::GetTextLineHeight();
76 s.glyphWidth = ImGui::CalcTextSize("F").x + 1; // We assume the font is mono-space
77 s.hexCellWidth = truncf(s.glyphWidth * 2.5f); // "FF " we include trailing space in the width to easily catch clicks everywhere
78 s.spacingBetweenMidCols = truncf(s.hexCellWidth * 0.25f); // Every 'MidColsCount' columns we add a bit of extra spacing
79 s.posHexStart = float(s.addrDigitsCount + 2) * s.glyphWidth;
80 auto posHexEnd = s.posHexStart + (s.hexCellWidth * float(columns));
81 s.posAsciiStart = s.posAsciiEnd = posHexEnd;
82 if (showAscii) {
83 int numMacroColumns = (columns + MidColsCount - 1) / MidColsCount;
84 s.posAsciiStart = posHexEnd + s.glyphWidth + float(numMacroColumns) * s.spacingBetweenMidCols;
85 s.posAsciiEnd = s.posAsciiStart + float(columns) * s.glyphWidth;
86 }
87 s.windowWidth = s.posAsciiEnd + style.ScrollbarSize + style.WindowPadding.x * 2 + s.glyphWidth;
88 return s;
89}
90
92{
93 if (!open || !motherBoard) return;
94 auto& debugger = motherBoard->getDebugger();
95 auto* debuggable = debugger.findDebuggable(getDebuggableName());
96 if (!debuggable) return;
97
99
100 unsigned memSize = debuggable->getSize();
101 columns = std::min(columns, narrow<int>(memSize));
102 auto s = calcSizes(memSize);
103 ImGui::SetNextWindowSize(ImVec2(s.windowWidth, s.windowWidth * 0.60f), ImGuiCond_FirstUseEver);
104
105 im::Window(title.c_str(), &open, ImGuiWindowFlags_NoScrollbar, [&]{
106 if (ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) &&
107 ImGui::IsMouseReleased(ImGuiMouseButton_Right)) {
108 ImGui::OpenPopup("context");
109 }
110 drawContents(s, *debuggable, memSize);
111 });
112}
113
114[[nodiscard]] static unsigned DataTypeGetSize(ImGuiDataType dataType)
115{
116 std::array<unsigned, ImGuiDataType_COUNT - 2> sizes = { 1, 1, 2, 2, 4, 4, 8, 8 };
117 assert(dataType >= 0 && dataType < (ImGuiDataType_COUNT - 2));
118 return sizes[dataType];
119}
120
121[[nodiscard]] static std::optional<int> parseHexDigit(char c)
122{
123 if ('0' <= c && c <= '9') return c - '0';
124 if ('a' <= c && c <= 'f') return c - 'a' + 10;
125 if ('A' <= c && c <= 'F') return c - 'A' + 10;
126 return std::nullopt;
127}
128
129[[nodiscard]] static std::optional<uint8_t> parseDataValue(std::string_view str)
130{
131 if (str.size() == 1) {
132 return parseHexDigit(str[0]);
133 } else if (str.size() == 2) {
134 if (auto digit0 = parseHexDigit(str[0])) {
135 if (auto digit1 = parseHexDigit(str[1])) {
136 return 16 * *digit0 + *digit1;
137 }
138 }
139 }
140 return std::nullopt;
141}
142
143struct ParseAddrResult { // TODO c++23 std::expected might be a good fit here
144 std::string error;
145 unsigned addr = 0;
146};
147[[nodiscard]] static ParseAddrResult parseAddressExpr(
148 std::string_view str, const SymbolManager& symbolManager, Interpreter& interp)
149{
151 if (str.empty()) return r;
152
153 // TODO linear search, probably OK for now, but can be improved if it turns out to be a problem
154 // Note: limited to 16-bit, but larger values trigger an errors and are then handled below, so that's fine
155 if (auto addr = symbolManager.parseSymbolOrValue(str)) {
156 r.addr = *addr;
157 return r;
158 }
159
160 try {
161 r.addr = TclObject(str).eval(interp).getInt(interp);
162 } catch (CommandException& e) {
163 r.error = e.getMessage();
164 }
165 return r;
166}
167
168[[nodiscard]] static std::string formatData(uint8_t val)
169{
170 return strCat(hex_string<2, HexCase::upper>(val));
171}
172
173[[nodiscard]] static char formatAsciiData(uint8_t val)
174{
175 return (val < 32 || val >= 128) ? '.' : char(val);
176}
177
178[[nodiscard]] std::string DebuggableEditor::formatAddr(const Sizes& s, unsigned addr) const
179{
180 return strCat(hex_string<HexCase::upper>(Digits{size_t(s.addrDigitsCount)}, addr));
181}
182void DebuggableEditor::setStrings(const Sizes& s, Debuggable& debuggable)
183{
184 addrStr = strCat("0x", formatAddr(s, currentAddr));
185 auto b = debuggable.read(currentAddr);
186 if (dataEditingActive == HEX ) dataInput = formatData(b);
187 if (dataEditingActive == ASCII) dataInput = std::string(1, formatAsciiData(b));
188}
189bool DebuggableEditor::setAddr(const Sizes& s, Debuggable& debuggable, unsigned memSize, unsigned addr)
190{
191 addr = std::min(addr, memSize - 1);
192 if (currentAddr == addr) return false;
193 currentAddr = addr;
194 setStrings(s, debuggable);
195 return true;
196}
197void DebuggableEditor::scrollAddr(const Sizes& s, Debuggable& debuggable, unsigned memSize, unsigned addr)
198{
199 if (setAddr(s, debuggable, memSize, addr)) {
200 im::Child("##scrolling", [&]{
201 int row = narrow<int>(currentAddr) / columns;
202 ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + float(row) * ImGui::GetTextLineHeight());
203 });
204 }
205}
206
207void DebuggableEditor::drawContents(const Sizes& s, Debuggable& debuggable, unsigned memSize)
208{
209 const auto& style = ImGui::GetStyle();
210 if (updateAddr) {
211 updateAddr = false;
212 auto addr = currentAddr;
213 ++currentAddr; // any change
214 scrollAddr(s, debuggable, memSize, addr);
215 } else {
216 // still clip addr (for the unlikely case that 'memSize' got smaller)
217 setAddr(s, debuggable, memSize, currentAddr);
218 }
219
220 float footerHeight = 0.0f;
221 if (showAddress) {
222 footerHeight += style.ItemSpacing.y + ImGui::GetFrameHeightWithSpacing();
223 }
224 if (showSearch) {
225 footerHeight += style.ItemSpacing.y + 2 * ImGui::GetFrameHeightWithSpacing();
226 }
227 if (showDataPreview) {
228 footerHeight += style.ItemSpacing.y + ImGui::GetFrameHeightWithSpacing() + 3 * ImGui::GetTextLineHeightWithSpacing();
229 }
230 // We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window.
231 // 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.
232 int cFlags = ImGuiWindowFlags_NoMove;
233 // note: with ImGuiWindowFlags_NoNav it happens occasionally that (rapid) cursor-input is passed to the underlying MSX window
234 // without ImGuiWindowFlags_NoNav PgUp/PgDown work, but they are ALSO interpreted as openMSX hotkeys,
235 // though other windows have the same problem.
236 //flags |= ImGuiWindowFlags_NoNav;
237 cFlags |= ImGuiWindowFlags_HorizontalScrollbar;
238 ImGui::BeginChild("##scrolling", ImVec2(0, -footerHeight), ImGuiChildFlags_None, cFlags);
239 ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
240 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
241
242 std::optional<unsigned> nextAddr;
243 // 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)
244 if (addrMode == CURSOR) {
245 const auto& shortcuts = manager.getShortcuts();
246 if ((int(currentAddr) >= columns) &&
247 shortcuts.checkShortcut({.keyChord = ImGuiKey_UpArrow, .repeat = true})) {
248 nextAddr = currentAddr - columns;
249 }
250 if ((int(currentAddr) < int(memSize - columns)) &&
251 shortcuts.checkShortcut({.keyChord = ImGuiKey_DownArrow, .repeat = true})) {
252 nextAddr = currentAddr + columns;
253 }
254 if ((int(currentAddr) > 0) &&
255 shortcuts.checkShortcut({.keyChord = ImGuiKey_LeftArrow, .repeat = true})) {
256 nextAddr = currentAddr - 1;
257 }
258 if ((int(currentAddr) < int(memSize - 1)) &&
259 shortcuts.checkShortcut({.keyChord = ImGuiKey_RightArrow, .repeat = true})) {
260 nextAddr = currentAddr + 1;
261 }
262 }
263
264 // Draw vertical separator
265 auto* drawList = ImGui::GetWindowDrawList();
266 ImVec2 windowPos = ImGui::GetWindowPos();
267 if (showAscii) {
268 drawList->AddLine(ImVec2(windowPos.x + s.posAsciiStart - s.glyphWidth, windowPos.y),
269 ImVec2(windowPos.x + s.posAsciiStart - s.glyphWidth, windowPos.y + 9999),
270 ImGui::GetColorU32(ImGuiCol_Border));
271 }
272
273 auto handleInput = [&](unsigned addr, int width, auto formatData, auto parseData, int extraFlags = 0) {
274 // Display text input on current byte
275 if (dataEditingTakeFocus) {
276 ImGui::SetKeyboardFocusHere();
277 setStrings(s, debuggable);
278 }
279 struct UserData {
280 // TODO: 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.
281 static int Callback(ImGuiInputTextCallbackData* data) {
282 auto* userData = static_cast<UserData*>(data->UserData);
283 if (!data->HasSelection()) {
284 userData->cursorPos = data->CursorPos;
285 }
286 if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen) {
287 // When not editing a byte, always refresh its InputText content pulled from underlying memory data
288 // (this is a bit tricky, since InputText technically "owns" the master copy of the buffer we edit it in there)
289 data->DeleteChars(0, data->BufTextLen);
290 userData->format(data);
291 //data->InsertChars(0, ...);
292 //data->SelectionEnd = width;
293 data->SelectionStart = 0;
294 data->CursorPos = 0;
295 }
296 return 0;
297 }
298 std::function<void(ImGuiInputTextCallbackData* data)> format;
299 int cursorPos = -1; // Output
300 };
301 UserData userData;
302 userData.format = formatData;
303 ImGuiInputTextFlags flags = ImGuiInputTextFlags_EnterReturnsTrue
304 | ImGuiInputTextFlags_AutoSelectAll
305 | ImGuiInputTextFlags_NoHorizontalScroll
306 | ImGuiInputTextFlags_CallbackAlways
307 | ImGuiInputTextFlags_AlwaysOverwrite
308 | extraFlags;
309 ImGui::SetNextItemWidth(s.glyphWidth * float(width));
310 bool dataWrite = false;
311 im::ID(int(addr), [&]{
312 if (ImGui::InputText("##data", &dataInput, flags, UserData::Callback, &userData)) {
313 dataWrite = true;
314 } else if (!ImGui::IsItemActive()) {
315 setStrings(s, debuggable);
316 }
317 });
318 dataEditingTakeFocus = false;
319 dataWrite |= userData.cursorPos >= width;
320 if (nextAddr) dataWrite = false;
321 if (dataWrite) {
322 if (auto value = parseData(dataInput)) {
323 debuggable.write(addr, *value);
324 assert(!nextAddr);
325 nextAddr = currentAddr + 1;
326 }
327 }
328 };
329
330 const auto totalLineCount = int((memSize + columns - 1) / columns);
331 im::ListClipper(totalLineCount, -1, s.lineHeight, [&](int line) {
332 auto addr = unsigned(line) * columns;
333 ImGui::StrCat(formatAddr(s, addr), ':');
334
335 auto previewDataTypeSize = DataTypeGetSize(previewDataType);
336 auto inside = [](unsigned a, unsigned start, unsigned size) {
337 return (start <= a) && (a < (start + size));
338 };
339 auto highLightDataPreview = [&](unsigned a) {
340 return inside(a, currentAddr, previewDataTypeSize);
341 };
342 auto highLightSearch = [&](unsigned a) {
343 if (!searchPattern) return false;
344 auto len = narrow<unsigned>(searchPattern->size());
345 if (searchHighlight == static_cast<int>(SearchHighlight::SINGLE)) {
346 if (searchResult) {
347 return inside(a, *searchResult, len);
348 }
349 } else if (searchHighlight == static_cast<int>(SearchHighlight::ALL)) {
350 int start = std::max(0, int(a - len + 1));
351 for (unsigned i = start; i <= a; ++i) {
352 if (match(debuggable, memSize, i)) return true;
353 }
354 }
355 return false;
356 };
357 auto highLight = [&](unsigned a) {
358 return highLightDataPreview(a) || highLightSearch(a);
359 };
360
361 // Draw Hexadecimal
362 for (int n = 0; n < columns && addr < memSize; ++n, ++addr) {
363 int macroColumn = n / MidColsCount;
364 float bytePosX = s.posHexStart + float(n) * s.hexCellWidth
365 + float(macroColumn) * s.spacingBetweenMidCols;
366 ImGui::SameLine(bytePosX);
367
368 // Draw highlight
369 if (highLight(addr)) {
370 ImVec2 pos = ImGui::GetCursorScreenPos();
371 float highlightWidth = s.glyphWidth * 2;
372 if (highLight(addr + 1)) {
373 highlightWidth = s.hexCellWidth;
374 if (n > 0 && (n + 1) < columns && ((n + 1) % MidColsCount) == 0) {
375 highlightWidth += s.spacingBetweenMidCols;
376 }
377 }
378 drawList->AddRectFilled(pos, ImVec2(pos.x + highlightWidth, pos.y + s.lineHeight), HighlightColor);
379 }
380
381 if (currentAddr == addr && (dataEditingActive == HEX)) {
382 handleInput(addr, 2,
383 [&](ImGuiInputTextCallbackData* data) { // format
384 auto valStr = formatData(debuggable.read(addr));
385 data->InsertChars(0, valStr.data(), valStr.data() + valStr.size());
386 data->SelectionEnd = 2;
387 },
388 [&](std::string_view data) { // parse
389 return parseDataValue(data);
390 },
391 ImGuiInputTextFlags_CharsHexadecimal);
392 } else {
393 uint8_t b = debuggable.read(addr);
394 im::StyleColor(b == 0 && greyOutZeroes, ImGuiCol_Text, getColor(imColor::TEXT_DISABLED), [&]{
395 ImGui::StrCat(formatData(b), ' ');
396 });
397 if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0)) {
398 dataEditingActive = HEX;
399 dataEditingTakeFocus = true;
400 nextAddr = addr;
401 }
402 }
403 }
404
405 if (showAscii) {
406 // Draw ASCII values
407 ImGui::SameLine(s.posAsciiStart);
408 gl::vec2 pos = ImGui::GetCursorPos();
409 gl::vec2 scrnPos = ImGui::GetCursorScreenPos();
410 addr = unsigned(line) * columns;
411
412 im::ID(line, [&]{
413 // handle via a single full-width button, this ensures we don't miss
414 // clicks because they fall in between two chars
415 if (ImGui::InvisibleButton("ascii", ImVec2(s.posAsciiEnd - s.posAsciiStart, s.lineHeight))) {
416 dataEditingActive = ASCII;
417 dataEditingTakeFocus = true;
418 nextAddr = addr + unsigned((ImGui::GetIO().MousePos.x - scrnPos.x) / s.glyphWidth);
419 }
420 });
421
422 for (int n = 0; n < columns && addr < memSize; ++n, ++addr) {
423 if (highLight(addr)) {
424 auto start = scrnPos + gl::vec2(float(n) * s.glyphWidth, 0.0f);
425 drawList->AddRectFilled(start, start + gl::vec2(s.glyphWidth, s.lineHeight), ImGui::GetColorU32(HighlightColor));
426 }
427
428 ImGui::SetCursorPos(pos);
429 if (currentAddr == addr && (dataEditingActive == ASCII)) {
430 handleInput(addr, 1,
431 [&](ImGuiInputTextCallbackData* data) { // format
432 char valChar = formatAsciiData(debuggable.read(addr));
433 data->InsertChars(0, &valChar, &valChar + 1);
434 data->SelectionEnd = 1;
435 },
436 [&](std::string_view data) -> std::optional<uint8_t> { // parse
437 if (data.empty()) return {};
438 uint8_t b = data[0];
439 if (b < 32 || b >= 128) return {};
440 return b;
441 });
442 } else {
443 uint8_t c = debuggable.read(addr);
444 char display = formatAsciiData(c);
445 im::StyleColor(display != char(c), ImGuiCol_Text, getColor(imColor::TEXT_DISABLED), [&]{
446 ImGui::TextUnformatted(&display, &display + 1);
447 });
448 }
449 pos.x += s.glyphWidth;
450 }
451 }
452 });
453 ImGui::PopStyleVar(2);
454 ImGui::EndChild();
455
456 if (nextAddr) {
457 setAddr(s, debuggable, memSize, *nextAddr);
458 dataEditingTakeFocus = true;
459 addrMode = CURSOR;
460 }
461
462 if (showAddress) {
463 ImGui::Separator();
464 ImGui::AlignTextToFramePadding();
465 ImGui::TextUnformatted("Address");
466 ImGui::SameLine();
467 ImGui::SetNextItemWidth(2.0f * style.FramePadding.x + ImGui::CalcTextSize("Expression").x + ImGui::GetFrameHeight());
468 if (ImGui::Combo("##mode", &addrMode, "Cursor\0Expression\0Link BC\0Link DE\0Link HL\0")) {
469 dataEditingTakeFocus = true;
470 if (addrMode >=2) {
471 static constexpr std::array linkExpr = {
472 "[reg bc]", "[reg de]", "[reg hl]"
473 };
474 addrExpr = linkExpr[addrMode - 2];
475 addrMode = EXPRESSION;
476 }
477 }
478 ImGui::SameLine();
479
480 std::string* as = addrMode == CURSOR ? &addrStr : &addrExpr;
481 auto r = parseAddressExpr(*as, symbolManager, manager.getInterpreter());
482 im::StyleColor(!r.error.empty(), ImGuiCol_Text, getColor(imColor::ERROR), [&] {
483 if (addrMode == EXPRESSION && r.error.empty()) {
484 scrollAddr(s, debuggable, memSize, r.addr);
485 }
486 if (manager.getShortcuts().checkShortcut(Shortcuts::ID::HEX_GOTO_ADDR)) {
487 ImGui::SetKeyboardFocusHere();
488 }
489 ImGui::SetNextItemWidth(15.0f * ImGui::GetFontSize());
490 if (ImGui::InputText("##addr", as, ImGuiInputTextFlags_EnterReturnsTrue)) {
491 auto r2 = parseAddressExpr(addrStr, symbolManager, manager.getInterpreter());
492 if (r2.error.empty()) {
493 scrollAddr(s, debuggable, memSize, r2.addr);
494 dataEditingTakeFocus = true;
495 }
496 }
497 simpleToolTip([&]{
498 return r.error.empty() ? strCat("0x", formatAddr(s, r.addr))
499 : r.error;
500 });
501 });
502 im::Font(manager.fontProp, [&]{
503 HelpMarker("Address-mode:\n"
504 " Cursor: view the cursor position\n"
505 " Expression: continuously re-evaluate an expression and view that address\n"
506 "\n"
507 "Addresses can be entered as:\n"
508 " Decimal or hexadecimal values (e.g. 0x1234)\n"
509 " A calculation like 0x1234 + 7*22\n"
510 " The name of a label (e.g. CHPUT)\n"
511 " A Tcl expression (e.g. [reg hl] to follow the content of register HL)\n"
512 "\n"
513 "Right-click to configure this view.");
514 });
515 }
516 if (showSearch) {
517 ImGui::Separator();
518 drawSearch(s, debuggable, memSize);
519 }
520 if (showDataPreview) {
521 ImGui::Separator();
522 drawPreviewLine(s, debuggable, memSize);
523 }
524
525 im::Popup("context", [&]{
526 ImGui::SetNextItemWidth(7.5f * s.glyphWidth + 2.0f * style.FramePadding.x);
527 if (ImGui::InputInt("Columns", &columns, 1, 0)) {
528 columns = std::clamp(columns, 1, MAX_COLUMNS);
529 }
530 ImGui::Checkbox("Show Address bar", &showAddress);
531 ImGui::Checkbox("Show Search pane", &showSearch);
532 ImGui::Checkbox("Show Data Preview", &showDataPreview);
533 ImGui::Checkbox("Show Ascii", &showAscii);
534 ImGui::Checkbox("Grey out zeroes", &greyOutZeroes);
535 });
536 im::Popup("NotFound", [&]{
537 ImGui::TextUnformatted("Not found");
538 });
539}
540
541[[nodiscard]] static const char* DataTypeGetDesc(ImGuiDataType dataType)
542{
543 std::array<const char*, ImGuiDataType_COUNT - 2> desc = {
544 "Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64"
545 };
546 assert(dataType >= 0 && dataType < (ImGuiDataType_COUNT - 2));
547 return desc[dataType];
548}
549
550template<typename T>
551[[nodiscard]] static T read(std::span<const uint8_t> buf)
552{
553 assert(buf.size() >= sizeof(T));
554 T t = 0;
555 memcpy(&t, buf.data(), sizeof(T));
556 return t;
557}
558
559static void formatDec(std::span<const uint8_t> buf, ImGuiDataType dataType)
560{
561 switch (dataType) {
562 case ImGuiDataType_S8:
563 ImGui::StrCat(read<int8_t>(buf));
564 break;
565 case ImGuiDataType_U8:
566 ImGui::StrCat(read<uint8_t>(buf));
567 break;
568 case ImGuiDataType_S16:
569 ImGui::StrCat(read<int16_t>(buf));
570 break;
571 case ImGuiDataType_U16:
572 ImGui::StrCat(read<uint16_t>(buf));
573 break;
574 case ImGuiDataType_S32:
575 ImGui::StrCat(read<int32_t>(buf));
576 break;
577 case ImGuiDataType_U32:
578 ImGui::StrCat(read<uint32_t>(buf));
579 break;
580 case ImGuiDataType_S64:
581 ImGui::StrCat(read<int64_t>(buf));
582 break;
583 case ImGuiDataType_U64:
584 ImGui::StrCat(read<uint64_t>(buf));
585 break;
586 default:
588 }
589}
590
591static void formatHex(std::span<const uint8_t> buf, ImGuiDataType data_type)
592{
593 switch (data_type) {
594 case ImGuiDataType_S8:
595 case ImGuiDataType_U8:
596 ImGui::StrCat(hex_string<2>(read<uint8_t>(buf)));
597 break;
598 case ImGuiDataType_S16:
599 case ImGuiDataType_U16:
600 ImGui::StrCat(hex_string<4>(read<uint16_t>(buf)));
601 break;
602 case ImGuiDataType_S32:
603 case ImGuiDataType_U32:
604 ImGui::StrCat(hex_string<8>(read<uint32_t>(buf)));
605 break;
606 case ImGuiDataType_S64:
607 case ImGuiDataType_U64:
608 ImGui::StrCat(hex_string<16>(read<uint64_t>(buf)));
609 break;
610 default:
612 }
613}
614
615static void formatBin(std::span<const uint8_t> buf)
616{
617 for (int i = int(buf.size()) - 1; i >= 0; --i) {
618 ImGui::StrCat(bin_string<8>(buf[i]));
619 if (i != 0) ImGui::SameLine();
620 }
621}
622
623void DebuggableEditor::parseSearchString(std::string_view str)
624{
625 searchPattern.reset();
626 searchResult.reset();
627 std::vector<uint8_t> result;
628
629 if (searchType == static_cast<int>(SearchType::ASCII)) {
630 const auto* begin = std::bit_cast<const uint8_t*>(str.data());
631 const auto* end = begin + str.size();
632 result.assign(begin, end);
633 } else {
634 assert(searchType == static_cast<int>(SearchType::HEX));
635 std::optional<int> partial;
636 for (char c : str) {
637 if (c == ' ') continue; // ignore space characters
638 auto digit = parseHexDigit(c);
639 if (!digit) return; // error: invalid hex digit
640 if (partial) {
641 result.push_back(narrow<uint8_t>(16 * *partial + *digit));
642 partial.reset();
643 } else {
644 partial = *digit;
645 }
646 }
647 if (partial) return; // error: odd number of hex digits
648 }
649
650 searchPattern = std::move(result);
651}
652
653void DebuggableEditor::drawSearch(const Sizes& s, Debuggable& debuggable, unsigned memSize)
654{
655 const auto& style = ImGui::GetStyle();
656
657 bool doSearch = false;
658 auto buttonSize = ImGui::CalcTextSize("Search").x + 2.0f * style.FramePadding.x;
659 ImGui::SetNextItemWidth(-(buttonSize + style.WindowPadding.x));
660 im::StyleColor(!searchPattern, ImGuiCol_Text, getColor(imColor::ERROR), [&] {
661 auto callback = [](ImGuiInputTextCallbackData* data) {
662 if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit) {
663 auto& self = *static_cast<DebuggableEditor*>(data->UserData);
664 self.parseSearchString(std::string_view(data->Buf, data->BufTextLen));
665 }
666 return 0;
667 };
668 ImGuiInputTextFlags flags = ImGuiInputTextFlags_EnterReturnsTrue
669 | ImGuiInputTextFlags_CallbackEdit;
670 if (ImGui::InputText("##search_string", &searchString, flags, callback, this)) {
671 doSearch = true; // pressed enter
672 }
673 });
674 ImGui::SameLine();
675 im::Disabled(!searchPattern, [&]{
676 doSearch |= ImGui::Button("Search");
677 });
678 if (!searchPattern) {
679 simpleToolTip("Must be an even number of hex digits, optionally separated by spaces");
680 }
681 if (searchPattern && doSearch) {
682 search(s, debuggable, memSize);
683 }
684
685 auto arrowSize = ImGui::GetFrameHeight();
686 auto extra = arrowSize + 2.0f * style.FramePadding.x;
687 ImGui::AlignTextToFramePadding();
689 ImGui::SameLine();
690 ImGui::SetNextItemWidth(ImGui::CalcTextSize("Ascii").x + extra);
691 if (ImGui::Combo("##search_type", &searchType, "Hex\0Ascii\0\0")) {
692 parseSearchString(searchString);
693 }
694
695 ImGui::SameLine(0.0f, 2 * ImGui::GetFontSize());
696 ImGui::TextUnformatted("Direction");
697 ImGui::SameLine();
698 ImGui::SetNextItemWidth(ImGui::CalcTextSize("Backwards").x + extra);
699 ImGui::Combo("##search_direction", &searchDirection, "Forwards\0Backwards\0\0");
700
701 ImGui::SameLine(0.0f, 2 * ImGui::GetFontSize());
702 ImGui::TextUnformatted("Highlight");
703 ImGui::SameLine();
704 ImGui::SetNextItemWidth(ImGui::CalcTextSize("Single").x + extra);
705 ImGui::Combo("##search_highlight", &searchHighlight, "None\0Single\0All\0\0");
706}
707
708bool DebuggableEditor::match(Debuggable& debuggable, unsigned memSize, unsigned addr)
709{
710 assert(searchPattern);
711 if ((addr + searchPattern->size()) > memSize) return false;
712 for (auto [i, c] : enumerate(*searchPattern)) {
713 if (debuggable.read(narrow<unsigned>(addr + i)) != c) return false;
714 }
715 return true;
716}
717
718void DebuggableEditor::search(const Sizes& s, Debuggable& debuggable, unsigned memSize)
719{
720 std::optional<unsigned> found;
721 auto test = [&](unsigned addr) {
722 if (match(debuggable, memSize, addr)) {
723 found = addr;
724 return true;
725 }
726 return false;
727 };
728 if (searchDirection == static_cast<int>(SearchDirection::FWD)) {
729 for (unsigned addr = currentAddr + 1; addr < memSize; ++addr) {
730 if (test(addr)) break;
731 }
732 if (!found) {
733 for (unsigned addr = 0; addr <= currentAddr; ++addr) {
734 if (test(addr)) break;
735 }
736 }
737 } else {
738 for (int addr = currentAddr - 1; addr > 0; --addr) {
739 if (test(unsigned(addr))) break;
740 }
741 if (!found) {
742 for (int addr = memSize - 1; addr >= int(currentAddr); --addr) {
743 if (test(unsigned(addr))) break;
744 }
745 }
746 }
747 if (found) {
748 searchResult = *found;
749 scrollAddr(s, debuggable, memSize, *found);
750 dataEditingTakeFocus = true;
751 addrMode = CURSOR;
752 } else {
753 searchResult.reset();
754 ImGui::OpenPopup("NotFound");
755 }
756}
757
758void DebuggableEditor::drawPreviewLine(const Sizes& s, Debuggable& debuggable, unsigned memSize)
759{
760 const auto& style = ImGui::GetStyle();
761 ImGui::AlignTextToFramePadding();
762 ImGui::TextUnformatted("Preview as:"sv);
763 ImGui::SameLine();
764 ImGui::SetNextItemWidth((s.glyphWidth * 10.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
765 if (ImGui::BeginCombo("##combo_type", DataTypeGetDesc(previewDataType), ImGuiComboFlags_HeightLargest)) {
766 for (ImGuiDataType n = 0; n < (ImGuiDataType_COUNT - 2); ++n) {
767 if (ImGui::Selectable(DataTypeGetDesc(n), previewDataType == n)) {
768 previewDataType = n;
769 }
770 }
771 ImGui::EndCombo();
772 }
773 ImGui::SameLine();
774 ImGui::SetNextItemWidth((s.glyphWidth * 6.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
775 ImGui::Combo("##combo_endianess", &previewEndianess, "LE\0BE\0\0");
776
777 std::array<uint8_t, 8> dataBuf = {};
778 auto elemSize = DataTypeGetSize(previewDataType);
779 for (auto i : xrange(elemSize)) {
780 auto addr = currentAddr + i;
781 dataBuf[i] = (addr < memSize) ? debuggable.read(addr) : 0;
782 }
783
784 static constexpr bool nativeIsLittle = std::endian::native == std::endian::little;
785 if (bool previewIsLittle = previewEndianess == LE;
786 nativeIsLittle != previewIsLittle) {
787 std::reverse(dataBuf.begin(), dataBuf.begin() + elemSize);
788 }
789
790 ImGui::TextUnformatted("Dec "sv);
791 ImGui::SameLine();
792 formatDec(dataBuf, previewDataType);
793
794 ImGui::TextUnformatted("Hex "sv);
795 ImGui::SameLine();
796 formatHex(dataBuf, previewDataType);
797
798 ImGui::TextUnformatted("Bin "sv);
799 ImGui::SameLine();
800 formatBin(subspan(dataBuf, 0, elemSize));
801}
802
803} // namespace openmsx
void test(const IterableBitSet< N > &s, std::initializer_list< size_t > list)
TclObject t
void paint(MSXMotherBoard *motherBoard) override
DebuggableEditor(ImGuiManager &manager_, std::string debuggableName, size_t index)
std::string_view getDebuggableName() const
void loadLine(std::string_view name, zstring_view value) override
void save(ImGuiTextBuffer &buf) override
Debuggable * findDebuggable(std::string_view name)
Definition Debugger.cc:64
ImGuiManager & manager
Definition ImGuiPart.hh:30
std::optional< uint16_t > parseSymbolOrValue(std::string_view s) const
Like std::string_view, but with the extra guarantee that it refers to a zero-terminated string.
constexpr auto enumerate(Iterable &&iterable)
Heavily inspired by Nathan Reed's blog post: Python-Like enumerate() In C++17 http://reedbeta....
Definition enumerate.hh:28
void StrCat(Ts &&...ts)
Definition ImGuiUtils.hh:43
auto CalcTextSize(std::string_view str)
Definition ImGuiUtils.hh:37
void TextUnformatted(const std::string &str)
Definition ImGuiUtils.hh:24
constexpr double e
Definition Math.hh:21
vecN< 2, float > vec2
Definition gl_vec.hh:178
void Window(const char *name, bool *p_open, ImGuiWindowFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:63
void ID(const char *str_id, std::invocable<> auto next)
Definition ImGuiCpp.hh:244
void StyleColor(bool active, Args &&...args)
Definition ImGuiCpp.hh:175
void Child(const char *str_id, const ImVec2 &size, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:110
void Disabled(bool b, std::invocable<> auto next)
Definition ImGuiCpp.hh:510
void Font(ImFont *font, std::invocable<> auto next)
Definition ImGuiCpp.hh:131
void ListClipper(size_t count, int forceIndex, float lineHeight, std::invocable< int > auto next)
Definition ImGuiCpp.hh:542
void Popup(const char *str_id, ImGuiWindowFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:395
void format(SectorAccessibleDisk &disk, MSXBootSectorType bootType)
Format the given disk (= a single partition).
This file implemented 3 utility functions:
Definition Autofire.cc:11
bool loadOnePersistent(std::string_view name, zstring_view value, C &c, const std::tuple< Elements... > &tup)
void simpleToolTip(std::string_view desc)
Definition ImGuiUtils.hh:66
void savePersistent(ImGuiTextBuffer &buf, C &c, const std::tuple< Elements... > &tup)
std::optional< bool > match(const BooleanInput &binding, const Event &event, function_ref< int(JoystickId)> getJoyDeadZone)
ImU32 getColor(imColor col)
STL namespace.
constexpr auto subspan(Range &&range, size_t offset, size_t count=std::dynamic_extent)
Definition ranges.hh:473
std::string strCat()
Definition strCat.hh:703
void strAppend(std::string &result, Ts &&...ts)
Definition strCat.hh:752
#define UNREACHABLE
constexpr auto xrange(T e)
Definition xrange.hh:132
constexpr auto begin(const zstring_view &x)
constexpr auto end(const zstring_view &x)