openMSX
ImGuiManager.cc
Go to the documentation of this file.
1#include "ImGuiManager.hh"
2
3#include "ImGuiBreakPoints.hh"
4#include "ImGuiCheatFinder.hh"
5#include "ImGuiConnector.hh"
6#include "ImGuiConsole.hh"
7#include "ImGuiCpp.hh"
8#include "ImGuiDebugger.hh"
10#include "ImGuiHelp.hh"
11#include "ImGuiKeyboard.hh"
12#include "ImGuiMachine.hh"
13#include "ImGuiMedia.hh"
14#include "ImGuiMessages.hh"
15#include "ImGuiOpenFile.hh"
16#include "ImGuiOsdIcons.hh"
17#include "ImGuiPalette.hh"
18#include "ImGuiReverseBar.hh"
19#include "ImGuiSCCViewer.hh"
20#include "ImGuiSettings.hh"
21#include "ImGuiSoundChip.hh"
22#include "ImGuiSymbols.hh"
23#include "ImGuiTools.hh"
24#include "ImGuiTrainer.hh"
25#include "ImGuiUtils.hh"
26#include "ImGuiVdpRegs.hh"
27#include "ImGuiWatchExpr.hh"
28#include "ImGuiWaveViewer.hh"
29
31#include "CommandException.hh"
32#include "Display.hh"
33#include "Event.hh"
34#include "EventDistributor.hh"
35#include "FileContext.hh"
36#include "FileOperations.hh"
37#include "FilePool.hh"
38#include "HardwareConfig.hh"
39#include "Keyboard.hh"
40#include "Reactor.hh"
41#include "RealDrive.hh"
42#include "RomDatabase.hh"
43#include "RomInfo.hh"
44#include "SettingsConfig.hh"
45#include "VDP.hh"
46
47#include "stl.hh"
48#include "strCat.hh"
49
50#include <imgui.h>
51#include <imgui_impl_opengl3.h>
52#include <imgui_impl_sdl2.h>
53#include <imgui_internal.h>
54#include <CustomFont.ii> // icons for ImGuiFileDialog
55
56#include <SDL.h>
57
58namespace openmsx {
59
60using namespace std::literals;
61
62ImFont* ImGuiManager::addFont(zstring_view filename, int fontSize)
63{
64 auto& io = ImGui::GetIO();
65 if (!filename.empty()) {
66 try {
67 const auto& context = systemFileContext();
68
69 File file(context.resolve(FileOperations::join("skins", filename)));
70 auto fileSize = file.getSize();
71 auto ttfData = std::span(
72 static_cast<uint8_t*>(ImGui::MemAlloc(fileSize)), fileSize);
73 file.read(ttfData);
74
75 static const std::array<ImWchar, 2*6 + 1> ranges = {
76 0x0020, 0x00FF, // Basic Latin + Latin Supplement
77 0x0370, 0x03FF, // Greek and Coptic
78 0x0400, 0x052F, // Cyrillic + Cyrillic Supplement
79 //0x0E00, 0x0E7F, // Thai
80 //0x2000, 0x206F, // General Punctuation
81 //0x2DE0, 0x2DFF, // Cyrillic Extended-A
82 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
83 0x3131, 0x3163, // Korean alphabets
84 0x31F0, 0x31FF, // Katakana Phonetic Extensions
85 //0x4e00, 0x9FAF, // CJK Ideograms
86 //0xA640, 0xA69F, // Cyrillic Extended-B
87 //0xAC00, 0xD7A3, // Korean characters
88 //0xFF00, 0xFFEF, // Half-width characters
89 0
90 };
91 return io.Fonts->AddFontFromMemoryTTF(
92 ttfData.data(), // transfer ownership of 'ttfData' buffer
93 narrow<int>(ttfData.size()), narrow<float>(fontSize),
94 nullptr, ranges.data());
95 } catch (MSXException& e) {
96 getCliComm().printWarning("Couldn't load font: ", filename, ": ", e.getMessage(),
97 ". Reverted to builtin font");
98 }
99 }
100 return io.Fonts->AddFontDefault(); // embedded "ProggyClean.ttf", size 13
101}
102
103void ImGuiManager::loadFont()
104{
105 ImGuiIO& io = ImGui::GetIO();
106
107 assert(fontProp == nullptr);
109
111 static constexpr std::array<ImWchar, 3> icons_ranges = {ICON_MIN_IGFD, ICON_MAX_IGFD, 0};
112 ImFontConfig icons_config; icons_config.MergeMode = true; icons_config.PixelSnapH = true;
113 io.Fonts->AddFontFromMemoryCompressedBase85TTF(FONT_ICON_BUFFER_NAME_IGFD, 15.0f, &icons_config, icons_ranges.data());
114 // load debugger icons, also only in default font
116
117 assert(fontMono == nullptr);
119}
120
121void ImGuiManager::reloadFont()
122{
123 fontProp = fontMono = nullptr;
124
126
127 ImGuiIO& io = ImGui::GetIO();
128 io.Fonts->Clear();
129 loadFont();
130 io.Fonts->Build();
131
133}
134
135void ImGuiManager::initializeImGui()
136{
137 // Setup Dear ImGui context
138 IMGUI_CHECKVERSION();
139 ImGui::CreateContext();
140 ImGuiIO& io = ImGui::GetIO();
141 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard |
142 //ImGuiConfigFlags_NavEnableGamepad | // TODO revisit this later
143 ImGuiConfigFlags_DockingEnable |
144 ImGuiConfigFlags_ViewportsEnable;
145 static auto iniFilename = systemFileContext().resolveCreate("imgui.ini");
146 io.IniFilename = iniFilename.c_str();
147
148 loadFont();
149}
150
151static void cleanupImGui()
152{
153 ImGui::DestroyContext();
154}
155
156
158 : reactor(reactor_)
159 , fontPropFilename(reactor.getCommandController(), "gui_font_default_filename", "TTF font filename for the default GUI font", "DejaVuSans.ttf.gz")
160 , fontMonoFilename(reactor.getCommandController(), "gui_font_mono_filename", "TTF font filename for the monospaced GUI font", "DejaVuSansMono.ttf.gz")
161 , fontPropSize(reactor.getCommandController(), "gui_font_default_size", "size for the default GUI font", 13, 9, 72)
162 , fontMonoSize(reactor.getCommandController(), "gui_font_mono_size", "size for the monospaced GUI font", 13, 9, 72)
163 , windowPos{SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED}
164{
165 parts.push_back(this);
166
167 // In order that they appear in the menubar
168 machine = std::make_unique<ImGuiMachine>(*this);
169 media = std::make_unique<ImGuiMedia>(*this);
170 connector = std::make_unique<ImGuiConnector>(*this);
171 reverseBar = std::make_unique<ImGuiReverseBar>(*this);
172 tools = std::make_unique<ImGuiTools>(*this);
173 settings = std::make_unique<ImGuiSettings>(*this);
174 debugger = std::make_unique<ImGuiDebugger>(*this);
175 help = std::make_unique<ImGuiHelp>(*this);
176
177 breakPoints = std::make_unique<ImGuiBreakPoints>(*this);
178 symbols = std::make_unique<ImGuiSymbols>(*this);
179 watchExpr = std::make_unique<ImGuiWatchExpr>(*this);
180 vdpRegs = std::make_unique<ImGuiVdpRegs>(*this);
181 palette = std::make_unique<ImGuiPalette>(*this);
182 osdIcons = std::make_unique<ImGuiOsdIcons>(*this);
183 openFile = std::make_unique<ImGuiOpenFile>(*this);
184 trainer = std::make_unique<ImGuiTrainer>(*this);
185 cheatFinder = std::make_unique<ImGuiCheatFinder>(*this);
186 sccViewer = std::make_unique<ImGuiSCCViewer>(*this);
187 waveViewer = std::make_unique<ImGuiWaveViewer>(*this);
188 diskManipulator = std::make_unique<ImGuiDiskManipulator>(*this);
189 soundChip = std::make_unique<ImGuiSoundChip>(*this);
190 keyboard = std::make_unique<ImGuiKeyboard>(*this);
191 console = std::make_unique<ImGuiConsole>(*this);
192 messages = std::make_unique<ImGuiMessages>(*this);
193 initializeImGui();
194
195 ImGuiSettingsHandler ini_handler;
196 ini_handler.TypeName = "openmsx";
197 ini_handler.TypeHash = ImHashStr("openmsx");
198 ini_handler.UserData = this;
199 //ini_handler.ClearAllFn = [](ImGuiContext*, ImGuiSettingsHandler* handler) { // optional
200 // // Clear all settings data
201 // static_cast<ImGuiManager*>(handler->UserData)->iniClearAll();
202 //};
203 ini_handler.ReadInitFn = [](ImGuiContext*, ImGuiSettingsHandler* handler) { // optional
204 // Read: Called before reading (in registration order)
205 static_cast<ImGuiManager*>(handler->UserData)->iniReadInit();
206 };
207 ini_handler.ReadOpenFn = [](ImGuiContext*, ImGuiSettingsHandler* handler, const char* name) -> void* { // required
208 // Read: Called when entering into a new ini entry e.g. "[Window][Name]"
209 return static_cast<ImGuiManager*>(handler->UserData)->iniReadOpen(name);
210 };
211 ini_handler.ReadLineFn = [](ImGuiContext*, ImGuiSettingsHandler* handler, void* entry, const char* line) { // required
212 // Read: Called for every line of text within an ini entry
213 static_cast<ImGuiManager*>(handler->UserData)->loadLine(entry, line);
214 };
215 ini_handler.ApplyAllFn = [](ImGuiContext*, ImGuiSettingsHandler* handler) { // optional
216 // Read: Called after reading (in registration order)
217 static_cast<ImGuiManager*>(handler->UserData)->iniApplyAll();
218 };
219 ini_handler.WriteAllFn = [](ImGuiContext*, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf) { // required
220 // Write: Output every entries into 'out_buf'
221 static_cast<ImGuiManager*>(handler->UserData)->iniWriteAll(*out_buf);
222 };
223 ImGui::AddSettingsHandler(&ini_handler);
224
225 auto& eventDistributor = reactor.getEventDistributor();
226 using enum EventType;
230 eventDistributor.registerEventListener(type, *this, EventDistributor::Priority::IMGUI);
231 }
232
235 fontPropSize.attach(*this);
236 fontMonoSize.attach(*this);
237}
238
240{
241 fontMonoSize.detach(*this);
242 fontPropSize.detach(*this);
245
246 auto& eventDistributor = reactor.getEventDistributor();
247 using enum EventType;
251 eventDistributor.unregisterEventListener(type, *this);
252 }
253
254 cleanupImGui();
255}
256
258{
259 assert(!contains(parts, part));
260 assert(!contains(toBeAddedParts, part));
261 toBeAddedParts.push_back(part);
262}
263
265{
266 if (auto it1 = ranges::find(parts, part); it1 != parts.end()) {
267 *it1 = nullptr;
268 removeParts = true; // filter nullptr later
269 } else if (auto it2 = ranges::find(toBeAddedParts, part); it2 != toBeAddedParts.end()) {
270 toBeAddedParts.erase(it2); // fine to remove now
271 }
272}
273
274void ImGuiManager::updateParts()
275{
276 if (removeParts) {
277 removeParts = false;
278 parts.erase(ranges::remove(parts, nullptr), parts.end());
279 }
280
281 append(parts, toBeAddedParts);
282 toBeAddedParts.clear();
283}
284
285void ImGuiManager::save(ImGuiTextBuffer& buf)
286{
287 // We cannot query "reactor.getDisplay().getWindowPosition()" here
288 // because display may already be destroyed. Instead Display pushes
289 // window position to here
290 savePersistent(buf, *this, persistentElements);
291}
292
293void ImGuiManager::loadLine(std::string_view name, zstring_view value)
294{
295 loadOnePersistent(name, value, *this, persistentElements);
296}
297
298static gl::ivec2 ensureVisible(gl::ivec2 windowPos, gl::ivec2 windowSize)
299{
300 auto windowTL = windowPos;
301 auto windowBR = windowTL + windowSize;
302 auto overlaps = [&](const ImGuiPlatformMonitor& monitor) {
303 auto monitorTL = trunc(gl::vec2(monitor.MainPos));
304 auto monitorBR = monitorTL + trunc(gl::vec2(monitor.MainSize));
305 return windowTL.x < monitorBR.x &&
306 windowBR.x > monitorTL.x &&
307 windowTL.y < monitorBR.y &&
308 windowBR.y > monitorTL.y;
309 };
310
311 if (const auto& monitors = ImGui::GetPlatformIO().Monitors;
312 !monitors.empty() && ranges::none_of(monitors, overlaps)) {
313 // window isn't visible in any of the monitors
314 // -> place centered on primary monitor
315 return gl::ivec2(SDL_WINDOWPOS_CENTERED);
316 }
317 return windowPos; // current placement is fine
318}
319
320void ImGuiManager::loadEnd()
321{
322 auto& display = reactor.getDisplay();
323 windowPos = ensureVisible(windowPos, display.getWindowSize());
324 display.setWindowPosition(windowPos);
325}
326
328{
329 return reactor.getInterpreter();
330}
331
333{
334 return reactor.getCliComm();
335}
336
337std::optional<TclObject> ImGuiManager::execute(TclObject command)
338{
339 try {
340 return command.executeCommand(getInterpreter());
341 } catch (CommandException&) {
342 // ignore
343 return {};
344 }
345}
346
347void ImGuiManager::executeDelayed(std::function<void()> action)
348{
349 delayedActionQueue.push_back(std::move(action));
351}
352
354 const std::function<void(const TclObject&)>& ok,
355 const std::function<void(const std::string&)>& error)
356{
357 executeDelayed([this, command, ok, error]() mutable {
358 try {
359 auto result = command.executeCommand(getInterpreter());
360 if (ok) ok(result);
361 } catch (CommandException& e) {
362 if (error) error(e.getMessage());
363 }
364 });
365}
366
368 const std::function<void(const TclObject&)>& ok)
369{
370 executeDelayed(std::move(command), ok,
371 [this](const std::string& message) { this->printError(message); });
372}
373
374void ImGuiManager::printError(std::string_view message)
375{
376 getCliComm().printError(message);
377}
378
379bool ImGuiManager::signalEvent(const Event& event)
380{
381 if (auto* evt = get_event_if<SdlEvent>(event)) {
382 const ImGuiIO& io = ImGui::GetIO();
383 if (!io.BackendPlatformUserData) {
384 // ImGui backend not (yet) initialized (e.g. after 'set renderer none')
385 return false;
386 }
387 const SDL_Event& sdlEvent = evt->getSdlEvent();
389 if ((io.WantCaptureMouse &&
390 sdlEvent.type == one_of(SDL_MOUSEMOTION, SDL_MOUSEWHEEL,
391 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP)) ||
392 (io.WantCaptureKeyboard &&
393 sdlEvent.type == one_of(SDL_KEYDOWN, SDL_KEYUP, SDL_TEXTINPUT))) {
394 return true; // block event for lower priority listeners
395 }
396 } else {
397 switch (getType(event)) {
399 for (auto& action : delayedActionQueue) {
400 std::invoke(action);
401 }
402 delayedActionQueue.clear();
403 break;
404 }
406 const auto& fde = get_event<FileDropEvent>(event);
407 droppedFile = fde.getFileName();
408 handleDropped = true;
409 break;
410 }
412 // Triggers when a new machine gets activated, e.g.:
413 // * after a 'step_back' (or any click in the reverse bar).
414 // * after a machine instance switch
415 // (For now) this triggers the same behavior as BREAK: scroll debugger to PC
416 [[fallthrough]];
417 case EventType::BREAK:
418 debugger->signalBreak();
419 break;
420 default:
422 }
423 }
424 return false;
425}
426
427void ImGuiManager::update(const Setting& /*setting*/) noexcept
428{
429 needReloadFont = true;
430}
431
432// TODO share code with ImGuiMedia
433static std::vector<std::string> getDrives(MSXMotherBoard* motherBoard)
434{
435 std::vector<std::string> result;
436 if (!motherBoard) return result;
437
438 std::string driveName = "diskX";
439 auto drivesInUse = RealDrive::getDrivesInUse(*motherBoard);
440 for (auto i : xrange(RealDrive::MAX_DRIVES)) {
441 if (!(*drivesInUse)[i]) continue;
442 driveName[4] = char('a' + i);
443 result.push_back(driveName);
444 }
445 return result;
446}
447
448static std::vector<std::string> getSlots(MSXMotherBoard* motherBoard)
449{
450 std::vector<std::string> result;
451 if (!motherBoard) return result;
452
453 const auto& slotManager = motherBoard->getSlotManager();
454 std::string cartName = "cartX";
455 for (auto slot : xrange(CartridgeSlotManager::MAX_SLOTS)) {
456 if (!slotManager.slotExists(slot)) continue;
457 cartName[4] = char('a' + slot);
458 result.push_back(cartName);
459 }
460 return result;
461}
462
464{
465 if (!loadIniFile.empty()) {
466 ImGui::LoadIniSettingsFromDisk(loadIniFile.c_str());
467 loadIniFile.clear();
468 }
469 if (needReloadFont) {
470 needReloadFont = false;
471 reloadFont();
472 }
473}
474
475static bool hoverMenuBar()
476{
477 const auto* viewport = ImGui::GetMainViewport();
478 gl::vec2 topLeft = viewport->Pos;
479 gl::vec2 bottomRight = topLeft + gl::vec2(viewport->Size.x, ImGui::GetFrameHeight());
480 gl::vec2 mouse = ImGui::GetMousePos();
481 return mouse.x >= topLeft.x && mouse.x <= bottomRight.x &&
482 mouse.y >= topLeft.y && mouse.y <= bottomRight.y;
483}
484
486{
487 // Apply added/removed parts. Avoids iterating over a changing vector.
488 updateParts();
489
490 auto* motherBoard = reactor.getMotherBoard();
491 if (motherBoard) {
492 if (auto* keyb = motherBoard->getKeyboard()) {
493 auto time = motherBoard->getCurrentTime();
494 keyb->setFocus(!ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow), time);
495 }
496 }
497
498 for (auto* part : parts) {
499 part->paint(motherBoard);
500 }
502 openFile->doPaint();
503 }
504
505 auto drawMenu = [&]{
506 for (auto* part : parts) {
507 part->showMenu(motherBoard);
508 }
509 };
510 if (mainMenuBarUndocked) {
511 im::Window("openMSX main menu", &mainMenuBarUndocked, ImGuiWindowFlags_MenuBar, [&]{
512 im::MenuBar([&]{
513 if (ImGui::ArrowButton("re-dock-button", ImGuiDir_Down)) {
514 mainMenuBarUndocked = false;
515 }
516 simpleToolTip("Dock the menu bar in the main openMSX window.");
517 drawMenu();
518 });
519 });
520 } else {
521 bool active = ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) ||
522 ImGui::IsWindowFocused(ImGuiHoveredFlags_AnyWindow) ||
523 hoverMenuBar();
524 if (active != guiActive) {
525 guiActive = active;
526 auto& eventDistributor = reactor.getEventDistributor();
527 eventDistributor.distributeEvent(ImGuiActiveEvent(active));
528 }
529 menuAlpha = [&] {
530 if (!menuFade) return 1.0f;
531 auto target = active ? 1.0f : 0.0f;
532 auto period = active ? 0.5f : 5.0f;
533 return calculateFade(menuAlpha, target, period);
534 }();
535 im::StyleVar(ImGuiStyleVar_Alpha, menuAlpha, [&]{
536 im::MainMenuBar([&]{
537 if (ImGui::ArrowButton("undock-button", ImGuiDir_Up)) {
538 mainMenuBarUndocked = true;
539 }
540 simpleToolTip("Undock the menu bar from the main openMSX window.");
541 drawMenu();
542 });
543 });
544 }
545
546 if (statusBarVisible) drawStatusBar(motherBoard);
547
548 // drag and drop (move this to ImGuiMedia ?)
549 auto insert2 = [&](std::string_view displayName, const TclObject& cmd) {
550 auto message = strCat("Inserted ", droppedFile, " in ", displayName);
551 executeDelayed(cmd, [this, message, cmd](const TclObject&){
552 insertedInfo = message;
553 openInsertedInfo = true;
554 media->addRecent(cmd);
555 });
556 };
557 auto insert = [&](std::string_view displayName, std::string_view cmd) {
558 insert2(displayName, makeTclList(cmd, "insert", droppedFile));
559 };
560 if (handleDropped) {
561 handleDropped = false;
562 insertedInfo.clear();
563
564 auto category = execute(makeTclList("openmsx_info", "file_type_category", droppedFile))->getString();
565 if (category == "unknown" && FileOperations::isDirectory(droppedFile)) {
566 category = "disk";
567 }
568
569 auto error = [&](auto&& ...message) {
570 executeDelayed(makeTclList("error", strCat(message...)));
571 };
572 auto cantHandle = [&](auto&& ...message) {
573 error("Can't handle dropped file ", droppedFile, ": ", message...);
574 };
575 auto notPresent = [&](const auto& mediaType) {
576 cantHandle("no ", mediaType, " present.");
577 };
578
579 auto testMedia = [&](std::string_view displayName, std::string_view cmd) {
580 if (auto cmdResult = execute(TclObject(cmd))) {
581 insert(displayName, cmd);
582 } else {
583 notPresent(displayName);
584 }
585 };
586
587 if (category == "disk") {
588 auto list = getDrives(motherBoard);
589 if (list.empty()) {
590 notPresent("disk drive");
591 } else if (list.size() == 1) {
592 const auto& drive = list.front();
593 insert(strCat("disk drive ", char(drive.back() - 'a' + 'A')), drive);
594 } else {
595 selectList = std::move(list);
596 ImGui::OpenPopup("select-drive");
597 }
598 } else if (category == "rom") {
599 auto list = getSlots(motherBoard);
600 if (list.empty()) {
601 notPresent("cartridge slot");
602 return;
603 }
604 selectedMedia = list.front();
605 selectList = std::move(list);
606 if (auto sha1 = reactor.getFilePool().getSha1Sum(droppedFile)) {
607 romInfo = reactor.getSoftwareDatabase().fetchRomInfo(*sha1);
608 } else {
609 romInfo = nullptr;
610 }
611 selectedRomType = romInfo ? romInfo->getRomType()
612 : RomType::UNKNOWN; // auto-detect
613 ImGui::OpenPopup("select-cart");
614 } else if (category == "cassette") {
615 testMedia("casette port", "cassetteplayer");
616 } else if (category == "laserdisc") {
617 testMedia("laser disc player", "laserdiscplayer");
618 } else if (category == "savestate") {
619 executeDelayed(makeTclList("loadstate", droppedFile));
620 } else if (category == "replay") {
621 executeDelayed(makeTclList("reverse", "loadreplay", droppedFile));
622 } else if (category == "script") {
623 executeDelayed(makeTclList("source", droppedFile));
624 } else if (FileOperations::getExtension(droppedFile) == ".txt") {
625 executeDelayed(makeTclList("type_from_file", droppedFile));
626 } else {
627 cantHandle("unknown file type");
628 }
629 }
630 im::Popup("select-drive", [&]{
631 ImGui::TextUnformatted(tmpStrCat("Select disk drive for ", droppedFile));
632 auto n = std::min(3.5f, narrow<float>(selectList.size()));
633 auto height = n * ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().FramePadding.y;
634 im::ListBox("##select-media", {-FLT_MIN, height}, [&]{
635 for (const auto& item : selectList) {
636 auto drive = item.back() - 'a';
637 auto display = strCat(char('A' + drive), ": ", media->displayNameForDriveContent(drive, true));
638 if (ImGui::Selectable(display.c_str())) {
639 insert(strCat("disk drive ", char(drive + 'A')), item);
640 ImGui::CloseCurrentPopup();
641 }
642 }
643 });
644 });
645 im::Popup("select-cart", [&]{
646 ImGui::TextUnformatted(strCat("Filename: ", droppedFile));
647 ImGui::Separator();
648
649 if (!romInfo) {
650 ImGui::TextUnformatted("ROM not present in software database"sv);
651 }
652 im::Table("##extension-info", 2, [&]{
653 const char* buf = reactor.getSoftwareDatabase().getBufferStart();
654 ImGui::TableSetupColumn("description", ImGuiTableColumnFlags_WidthFixed);
655 ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthStretch);
656
657 if (romInfo) {
658 ImGuiMedia::printDatabase(*romInfo, buf);
659 }
660 if (ImGui::TableNextColumn()) {
661 ImGui::AlignTextToFramePadding();
662 ImGui::TextUnformatted("Mapper"sv);
663 }
664 if (ImGui::TableNextColumn()) {
665 ImGuiMedia::selectMapperType("##mapper-type", selectedRomType);
666 }
667 });
668 ImGui::Separator();
669
670 if (selectList.size() > 1) {
671 const auto& slotManager = motherBoard->getSlotManager();
672 ImGui::TextUnformatted("Select cartridge slot"sv);
673 auto n = std::min(3.5f, narrow<float>(selectList.size()));
674 auto height = n * ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().FramePadding.y;
675 im::ListBox("##select-media", {-FLT_MIN, height}, [&]{
676 for (const auto& item : selectList) {
677 auto slot = item.back() - 'a';
678 auto display = strCat(
679 char('A' + slot),
680 " (", slotManager.getPsSsString(slot), "): ",
681 media->displayNameForSlotContent(slotManager, slot, true));
682
683 if (ImGui::Selectable(display.c_str(), item == selectedMedia)) {
684 selectedMedia = item;
685 }
686 }
687 });
688 }
689
690 ImGui::Checkbox("Reset MSX on inserting ROM", &media->resetOnInsertRom);
691
692 if (ImGui::Button("Insert ROM")) {
693 auto cmd = makeTclList(selectedMedia, "insert", droppedFile);
694 if (selectedRomType != RomType::UNKNOWN) {
695 cmd.addListElement("-romtype", RomInfo::romTypeToName(selectedRomType));
696 }
697 insert2(strCat("cartridge slot ", char(selectedMedia.back() - 'a' + 'A')), cmd);
698 if (media->resetOnInsertRom) {
699 executeDelayed(TclObject("reset"));
700 }
701 ImGui::CloseCurrentPopup();
702 }
703 ImGui::SameLine();
704 if (ImGui::Button("Cancel")) {
705 ImGui::CloseCurrentPopup();
706 }
707 });
708 if (openInsertedInfo) {
709 openInsertedInfo = false;
710 insertedInfoTimeout = 3.0f;
711 ImGui::OpenPopup("inserted-info");
712 }
713 im::Popup("inserted-info", [&]{
714 insertedInfoTimeout -= ImGui::GetIO().DeltaTime;
715 if (insertedInfoTimeout <= 0.0f || insertedInfo.empty()) {
716 ImGui::CloseCurrentPopup();
717 }
718 im::TextWrapPos(ImGui::GetFontSize() * 35.0f, [&]{
719 ImGui::TextUnformatted(insertedInfo);
720 });
721 });
722}
723
724void ImGuiManager::drawStatusBar(MSXMotherBoard* motherBoard)
725{
726 if (ImGui::BeginViewportSideBar("##MainStatusBar", nullptr, ImGuiDir_Down, ImGui::GetFrameHeight(),
727 ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar)) {
728 im::MenuBar([&]{
729 auto frameTime = ImGui::GetIO().DeltaTime;
730
731 // limit updating to at most 10Hz
732 fpsDrawTimeOut -= frameTime;
733 if (fpsDrawTimeOut < 0.0f) {
734 fpsDrawTimeOut = 0.1f;
735 fps = reactor.getDisplay().getFps();
736 }
737 std::stringstream ssFps;
738 ssFps << std::fixed << std::setprecision(1) << fps << " fps";
739 ImGui::RightAlignText(ssFps.str(), "999.9 fps");
740 simpleToolTip("refresh rate");
741 ImGui::Separator();
742
743 auto [modeStr, extendedStr_] = [&] { // TODO: remove duplication with VDP debugger code
744 if (!motherBoard) return std::pair{"-", ""};
745 const auto* vdp = dynamic_cast<const VDP*>(motherBoard->findDevice("VDP"));
746 if (!vdp) return std::pair{"-", ""};
747
748 auto mode = vdp->getDisplayMode();
749 auto base = mode.getBase();
750 if (base == DisplayMode::TEXT1) return std::pair{"0 (40)", "TEXT 1"};
751 if (base == DisplayMode::TEXT2) return std::pair{"0 (80)", "TEXT 2"};
752 if (base == DisplayMode::GRAPHIC1) return std::pair{"1", "GRAPHIC 1"};
753 if (base == DisplayMode::GRAPHIC2) return std::pair{"2", "GRAPHIC 2"};
754 if (base == DisplayMode::GRAPHIC3) return std::pair{"4", "GRAPHIC 3"};
755 if (base == DisplayMode::MULTICOLOR) return std::pair{"3", "MULTICOLOR"};
756 if (base == DisplayMode::GRAPHIC4) return std::pair{"5", "GRAPHIC 4"};
757 if (base == DisplayMode::GRAPHIC5) return std::pair{"6", "GRAPHIC 5"};
758 if (base == DisplayMode::GRAPHIC6) return std::pair{"7", "GRAPHIC 6"};
759 if (base != DisplayMode::GRAPHIC7) return std::pair{"?", ""};
760 return (mode.getByte() & DisplayMode::YJK)
761 ? (mode.getByte() & DisplayMode::YAE) ? std::pair{"11", "GRAPHIC 7 (YJK/YAE mode)"} : std::pair{"12", "GRAPHIC 7 (YJK mode)"}
762 : std::pair{"8", "GRAPHIC 7"};
763 }();
764 auto extendedStr = extendedStr_; // pre-clang-16 workaround
765 ImGui::RightAlignText(modeStr, "0 (80)");
766 simpleToolTip([&]{
767 std::string result = "screen mode as used in MSX-BASIC";
768 if (extendedStr[0]) {
769 strAppend(result, ", corresponds to VDP mode ", extendedStr);
770 }
771 return result;
772 });
773 ImGui::Separator();
774
775 auto timeStr = motherBoard
776 ? formatTime((motherBoard->getCurrentTime() - EmuTime::zero()).toDouble())
777 : formatTime(std::nullopt);
779 simpleToolTip("time since MSX power on");
780 ImGui::Separator();
781
782 if (motherBoard) {
783 // limit updating to at most 1Hz
784 speedDrawTimeOut -= frameTime;
785 if (speedDrawTimeOut < 0.0f) {
786 auto realTimePassed = 1.0f - speedDrawTimeOut;
787 speedDrawTimeOut = 1.0f;
788
789 auto boardTime = motherBoard->getCurrentTime();
790 auto boardTimePassed = (boardTime < prevBoardTime)
791 ? 0.0 // due to reverse for instance
792 : (boardTime - prevBoardTime).toDouble();
793 prevBoardTime = boardTime;
794
795 speed = 100.0f * float(boardTimePassed) / realTimePassed;
796 }
797 } else {
798 speed = 0.0f;
799 prevBoardTime = EmuTime::zero();
800 }
801 ImGui::RightAlignText(strCat(std::round(speed), '%'), "10000%");
802 simpleToolTip("emulation speed");
803 ImGui::Separator();
804
805 if (motherBoard) {
806 if (const HardwareConfig* machineConfig = motherBoard->getMachineConfig()) {
807 if (const auto* info = machineConfig->getConfig().findChild("info")) {
808 auto manuf = info->getChildData("manufacturer", "?");
809 auto code = info->getChildData("code", "?");
810 ImGui::StrCat(manuf, ' ', code);
811 simpleToolTip([&]{
812 auto type = info->getChildData("type", "");
813 auto desc = info->getChildData("description", "");
814 return strCat((type.empty() ? "" : strCat("Machine type: ", type, '\n')), desc);
815 });
816 }
817 }
818 }
819 ImGui::Separator();
820
821 if (auto result = execute(TclObject("guess_title"))) {
822 ImGui::TextUnformatted(result->getString());
823 simpleToolTip("the (probably) currently running software");
824 }
825
826 });
827 }
828 ImGui::End();
829}
830
831void ImGuiManager::iniReadInit()
832{
833 updateParts();
834 for (auto* part : parts) {
835 if (part) { // loadStart() could call unregisterPart()
836 part->loadStart();
837 }
838 }
839}
840
841void* ImGuiManager::iniReadOpen(std::string_view name)
842{
843 updateParts();
844 for (auto* part : parts) {
845 if (part->iniName() == name) return part;
846 }
847 return nullptr;
848}
849
850void ImGuiManager::loadLine(void* entry, const char* line_) const
851{
852 zstring_view line = line_;
853 auto pos = line.find('=');
854 if (pos == zstring_view::npos) return;
855 std::string_view name = line.substr(0, pos);
856 zstring_view value = line.substr(pos + 1);
857
858 assert(entry);
859 static_cast<ImGuiPartInterface*>(entry)->loadLine(name, value);
860}
861
862void ImGuiManager::iniApplyAll()
863{
864 updateParts();
865 for (auto* part : parts) {
866 part->loadEnd();
867 }
868}
869
870void ImGuiManager::iniWriteAll(ImGuiTextBuffer& buf)
871{
872 updateParts();
873 for (auto* part : parts) {
874 if (auto name = part->iniName(); !name.empty()) {
875 buf.appendf("[openmsx][%s]\n", name.c_str());
876 part->save(buf);
877 buf.append("\n");
878 }
879 }
880}
881
882} // namespace openmsx
void printError(std::string_view message)
Definition CliComm.cc:17
void printWarning(std::string_view message)
Definition CliComm.cc:12
static constexpr uint8_t GRAPHIC3
static constexpr uint8_t MULTICOLOR
static constexpr uint8_t GRAPHIC4
static constexpr uint8_t GRAPHIC5
static constexpr uint8_t GRAPHIC1
static constexpr uint8_t GRAPHIC7
static constexpr uint8_t TEXT2
static constexpr byte YAE
Encoding of YAE flag.
static constexpr uint8_t GRAPHIC6
static constexpr byte YJK
Encoding of YJK flag.
static constexpr uint8_t GRAPHIC2
static constexpr uint8_t TEXT1
float getFps() const
Definition Display.cc:252
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
void distributeEvent(Event &&event)
Schedule the given event for delivery.
void registerEventListener(EventType type, EventListener &listener, Priority priority=Priority::OTHER)
Registers a given object to receive certain events.
std::string resolveCreate(std::string_view filename) const
Sha1Sum getSha1Sum(File &file)
Calculate sha1sum for the given File object.
Definition FilePool.cc:58
zstring_view getString() const noexcept
std::unique_ptr< ImGuiMachine > machine
void registerPart(ImGuiPartInterface *part)
std::unique_ptr< ImGuiBreakPoints > breakPoints
void printError(std::string_view message)
std::unique_ptr< ImGuiVdpRegs > vdpRegs
std::unique_ptr< ImGuiCheatFinder > cheatFinder
std::unique_ptr< ImGuiTrainer > trainer
std::unique_ptr< ImGuiDiskManipulator > diskManipulator
IntegerSetting fontMonoSize
std::unique_ptr< ImGuiWatchExpr > watchExpr
std::unique_ptr< ImGuiPalette > palette
std::unique_ptr< ImGuiWaveViewer > waveViewer
std::unique_ptr< ImGuiConnector > connector
std::optional< TclObject > execute(TclObject command)
std::unique_ptr< ImGuiKeyboard > keyboard
std::unique_ptr< ImGuiHelp > help
IntegerSetting fontPropSize
Interpreter & getInterpreter()
std::unique_ptr< ImGuiConsole > console
std::unique_ptr< ImGuiSoundChip > soundChip
ImGuiManager(Reactor &reactor_)
std::unique_ptr< ImGuiReverseBar > reverseBar
std::unique_ptr< ImGuiMedia > media
std::unique_ptr< ImGuiMessages > messages
std::unique_ptr< ImGuiOpenFile > openFile
std::unique_ptr< ImGuiOsdIcons > osdIcons
FilenameSetting fontPropFilename
std::unique_ptr< ImGuiSettings > settings
std::unique_ptr< ImGuiDebugger > debugger
std::unique_ptr< ImGuiSCCViewer > sccViewer
void unregisterPart(ImGuiPartInterface *part)
std::unique_ptr< ImGuiTools > tools
void executeDelayed(std::function< void()> action)
FilenameSetting fontMonoFilename
std::unique_ptr< ImGuiSymbols > symbols
static void printDatabase(const RomInfo &romInfo, const char *buf)
static bool selectMapperType(const char *label, RomType &item)
int getInt() const noexcept
EmuTime::param getCurrentTime() const
Convenience method: This is the same as getScheduler().getCurrentTime().
const HardwareConfig * getMachineConfig() const
MSXDevice * findDevice(std::string_view name)
Find a MSXDevice by name.
Contains the main loop of openMSX.
Definition Reactor.hh:75
MSXMotherBoard * getMotherBoard() const
Definition Reactor.cc:409
Display & getDisplay()
Definition Reactor.hh:93
CliComm & getCliComm()
Definition Reactor.cc:323
Interpreter & getInterpreter()
Definition Reactor.cc:328
EventDistributor & getEventDistributor()
Definition Reactor.hh:89
RomDatabase & getSoftwareDatabase()
Definition Reactor.cc:315
FilePool & getFilePool()
Definition Reactor.hh:98
static std::shared_ptr< DrivesInUse > getDrivesInUse(MSXMotherBoard &motherBoard)
Definition RealDrive.cc:21
const RomInfo * fetchRomInfo(const Sha1Sum &sha1sum) const
Lookup an entry in the database by sha1sum.
static zstring_view romTypeToName(RomType type)
Definition RomInfo.cc:191
RomType getRomType() const
Definition RomInfo.hh:62
void detach(Observer< T > &observer)
Definition Subject.hh:60
void attach(Observer< T > &observer)
Definition Subject.hh:54
TclObject executeCommand(Interpreter &interp, bool compile=false)
Interpret this TclObject as a command and execute it.
Definition TclObject.cc:248
Like std::string_view, but with the extra guarantee that it refers to a zero-terminated string.
static constexpr auto npos
constexpr auto find(char c, size_type pos=0) const
constexpr zstring_view substr(size_type pos) const
constexpr auto empty() const
ImGuiID ImHashStr(const char *data_p, size_t data_size, ImGuiID seed)
Definition imgui.cc:2267
bool ImGui_ImplOpenGL3_CreateFontsTexture()
void ImGui_ImplOpenGL3_DestroyFontsTexture()
bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event *event)
void StrCat(Ts &&...ts)
Definition ImGuiUtils.hh:45
void TextUnformatted(const std::string &str)
Definition ImGuiUtils.hh:26
void RightAlignText(std::string_view text, std::string_view maxWidthText)
Definition ImGuiUtils.hh:51
constexpr double e
Definition Math.hh:21
vecN< 2, int > ivec2
Definition gl_vec.hh:385
constexpr vecN< N, int > trunc(const vecN< N, T > &x)
Definition gl_vec.hh:540
vecN< 2, float > vec2
Definition gl_vec.hh:382
std::optional< Context > context
Definition GLContext.cc:10
void Table(const char *str_id, int column, ImGuiTableFlags flags, const ImVec2 &outer_size, float inner_width, std::invocable<> auto next)
Definition ImGuiCpp.hh:455
void MainMenuBar(std::invocable<> auto next)
Definition ImGuiCpp.hh:350
void MenuBar(std::invocable<> auto next)
Definition ImGuiCpp.hh:341
void Window(const char *name, bool *p_open, ImGuiWindowFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:63
void StyleVar(ImGuiStyleVar idx, float val, std::invocable<> auto next)
Definition ImGuiCpp.hh:190
void ListBox(const char *label, const ImVec2 &size, std::invocable<> auto next)
Definition ImGuiCpp.hh:328
void TextWrapPos(float wrap_local_pos_x, std::invocable<> auto next)
Definition ImGuiCpp.hh:212
void Popup(const char *str_id, ImGuiWindowFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:391
string_view getExtension(string_view path)
Returns the extension portion of a path.
bool isDirectory(const Stat &st)
string join(string_view part1, string_view part2)
Join two paths.
This file implemented 3 utility functions:
Definition Autofire.cc:11
const FileContext & systemFileContext()
EventType
Definition Event.hh:454
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:79
void savePersistent(ImGuiTextBuffer &buf, C &c, const std::tuple< Elements... > &tup)
EventType getType(const Event &event)
Definition Event.hh:517
std::variant< KeyUpEvent, KeyDownEvent, MouseMotionEvent, MouseButtonUpEvent, MouseButtonDownEvent, MouseWheelEvent, JoystickAxisMotionEvent, JoystickHatEvent, JoystickButtonUpEvent, JoystickButtonDownEvent, OsdControlReleaseEvent, OsdControlPressEvent, WindowEvent, TextEvent, FileDropEvent, QuitEvent, FinishFrameEvent, CliCommandEvent, GroupEvent, BootEvent, FrameDrawnEvent, BreakEvent, SwitchRendererEvent, TakeReverseSnapshotEvent, AfterTimedEvent, MachineLoadedEvent, MachineActivatedEvent, MachineDeactivatedEvent, MidiInReaderEvent, MidiInWindowsEvent, MidiInCoreMidiEvent, MidiInCoreMidiVirtualEvent, MidiInALSAEvent, Rs232TesterEvent, Rs232NetEvent, ImGuiDelayedActionEvent, ImGuiActiveEvent > Event
Definition Event.hh:445
std::string formatTime(std::optional< double > time)
float calculateFade(float current, float target, float period)
TclObject makeTclList(Args &&... args)
Definition TclObject.hh:293
auto remove(ForwardRange &&range, const T &value)
Definition ranges.hh:291
constexpr bool none_of(InputRange &&range, UnaryPredicate pred)
Definition ranges.hh:212
auto find(InputRange &&range, const T &value)
Definition ranges.hh:162
STL namespace.
constexpr bool contains(ITER first, ITER last, const VAL &val)
Check if a range contains a given value, using linear search.
Definition stl.hh:35
std::string strCat()
Definition strCat.hh:703
TemporaryString tmpStrCat(Ts &&... ts)
Definition strCat.hh:742
void strAppend(std::string &result, Ts &&...ts)
Definition strCat.hh:752
#define UNREACHABLE
constexpr auto xrange(T e)
Definition xrange.hh:132