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