50#include <imgui_impl_opengl3.h>
51#include <imgui_impl_sdl2.h>
52#include <imgui_internal.h>
53#include <CustomFont.ii>
59using namespace std::literals;
61ImFont* ImGuiManager::addFont(
zstring_view filename,
int fontSize)
63 auto& io = ImGui::GetIO();
64 if (!filename.
empty()) {
69 auto fileSize = file.getSize();
70 auto ttfData = std::span(
71 static_cast<uint8_t*
>(ImGui::MemAlloc(fileSize)), fileSize);
74 static const std::array<ImWchar, 2*6 + 1>
ranges = {
90 return io.Fonts->AddFontFromMemoryTTF(
92 narrow<int>(ttfData.size()), narrow<float>(fontSize),
94 }
catch (MSXException& e) {
96 ". Reverted to builtin font");
99 return io.Fonts->AddFontDefault();
102void ImGuiManager::loadFont()
104 ImGuiIO& io = ImGui::GetIO();
110 static constexpr std::array<ImWchar, 3> icons_ranges = {ICON_MIN_IGFD, ICON_MAX_IGFD, 0};
111 ImFontConfig icons_config; icons_config.MergeMode =
true; icons_config.PixelSnapH =
true;
112 io.Fonts->AddFontFromMemoryCompressedBase85TTF(FONT_ICON_BUFFER_NAME_IGFD, 15.0f, &icons_config, icons_ranges.data());
120void ImGuiManager::reloadFont()
126 ImGuiIO& io = ImGui::GetIO();
134void ImGuiManager::initializeImGui()
137 IMGUI_CHECKVERSION();
138 ImGui::CreateContext();
139 ImGuiIO& io = ImGui::GetIO();
140 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard |
142 ImGuiConfigFlags_DockingEnable |
143 ImGuiConfigFlags_ViewportsEnable;
145 io.IniFilename = iniFilename.c_str();
150static void cleanupImGui()
152 ImGui::DestroyContext();
158 , fontPropFilename(reactor.getCommandController(),
"gui_font_default_filename",
"TTF font filename for the default GUI font",
"DejaVuSans.ttf.gz")
159 , fontMonoFilename(reactor.getCommandController(),
"gui_font_mono_filename",
"TTF font filename for the monospaced GUI font",
"DejaVuSansMono.ttf.gz")
160 , fontPropSize(reactor.getCommandController(),
"gui_font_default_size",
"size for the default GUI font", 13, 9, 72)
161 , fontMonoSize(reactor.getCommandController(),
"gui_font_mono_size",
"size for the monospaced GUI font", 13, 9, 72)
162 , windowPos{SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED}
165 parts.push_back(
this);
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);
177 breakPoints = std::make_unique<ImGuiBreakPoints>(*
this);
178 symbols = std::make_unique<ImGuiSymbols>(*
this);
179 watchExpr = std::make_unique<ImGuiWatchExpr>(*
this);
180 bitmap = std::make_unique<ImGuiBitmapViewer>(*
this);
181 character = std::make_unique<ImGuiCharacter>(*
this);
182 sprite = std::make_unique<ImGuiSpriteViewer>(*
this);
183 vdpRegs = std::make_unique<ImGuiVdpRegs>(*
this);
184 palette = std::make_unique<ImGuiPalette>(*
this);
185 osdIcons = std::make_unique<ImGuiOsdIcons>(*
this);
186 openFile = std::make_unique<ImGuiOpenFile>(*
this);
187 trainer = std::make_unique<ImGuiTrainer>(*
this);
188 cheatFinder = std::make_unique<ImGuiCheatFinder>(*
this);
190 soundChip = std::make_unique<ImGuiSoundChip>(*
this);
191 keyboard = std::make_unique<ImGuiKeyboard>(*
this);
192 console = std::make_unique<ImGuiConsole>(*
this);
193 messages = std::make_unique<ImGuiMessages>(*
this);
196 ImGuiSettingsHandler ini_handler;
197 ini_handler.TypeName =
"openmsx";
198 ini_handler.TypeHash =
ImHashStr(
"openmsx");
199 ini_handler.UserData =
this;
204 ini_handler.ReadInitFn = [](ImGuiContext*, ImGuiSettingsHandler* handler) {
206 static_cast<ImGuiManager*
>(handler->UserData)->iniReadInit();
208 ini_handler.ReadOpenFn = [](ImGuiContext*, ImGuiSettingsHandler* handler,
const char* name) ->
void* {
210 return static_cast<ImGuiManager*
>(handler->UserData)->iniReadOpen(name);
212 ini_handler.ReadLineFn = [](ImGuiContext*, ImGuiSettingsHandler* handler,
void* entry,
const char* line) {
214 static_cast<ImGuiManager*
>(handler->UserData)->loadLine(entry, line);
216 ini_handler.ApplyAllFn = [](ImGuiContext*, ImGuiSettingsHandler* handler) {
218 static_cast<ImGuiManager*
>(handler->UserData)->iniApplyAll();
220 ini_handler.WriteAllFn = [](ImGuiContext*, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf) {
222 static_cast<ImGuiManager*
>(handler->UserData)->iniWriteAll(*out_buf);
224 ImGui::AddSettingsHandler(&ini_handler);
261 assert(!
contains(toBeAddedParts, part));
262 toBeAddedParts.push_back(part);
267 if (
auto it1 =
ranges::find(parts, part); it1 != parts.end()) {
270 }
else if (
auto it2 =
ranges::find(toBeAddedParts, part); it2 != toBeAddedParts.end()) {
271 toBeAddedParts.erase(it2);
275void ImGuiManager::updateParts()
282 append(parts, toBeAddedParts);
283 toBeAddedParts.clear();
286void ImGuiManager::save(ImGuiTextBuffer& buf)
294void ImGuiManager::loadLine(std::string_view name,
zstring_view value)
299void ImGuiManager::loadEnd()
326 delayedActionQueue.push_back(std::move(action));
331 const std::function<
void(
const TclObject&)>& ok,
332 const std::function<
void(
const std::string&)>& error)
339 if (error) error(e.getMessage());
345 const std::function<
void(
const TclObject&)>& ok)
348 [
this](
const std::string& message) { this->
printError(message); });
356int ImGuiManager::signalEvent(
const Event& event)
358 if (
auto* evt = get_event_if<SdlEvent>(event)) {
359 const SDL_Event& sdlEvent = evt->getSdlEvent();
361 const ImGuiIO& io = ImGui::GetIO();
362 if ((io.WantCaptureMouse &&
363 sdlEvent.type ==
one_of(SDL_MOUSEMOTION, SDL_MOUSEWHEEL,
364 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP)) ||
365 (io.WantCaptureKeyboard &&
366 sdlEvent.type ==
one_of(SDL_KEYDOWN, SDL_KEYUP, SDL_TEXTINPUT))) {
373 for (
auto& action : delayedActionQueue) {
376 delayedActionQueue.clear();
380 const auto& fde = get_event<FileDropEvent>(event);
381 droppedFile = fde.getFileName();
382 handleDropped =
true;
395void ImGuiManager::update(
const Setting& )
noexcept
397 needReloadFont =
true;
401static std::vector<std::string> getDrives(MSXMotherBoard* motherBoard)
403 std::vector<std::string> result;
404 if (!motherBoard)
return result;
406 std::string driveName =
"diskX";
409 if (!(*drivesInUse)[i])
continue;
410 driveName[4] = char(
'a' + i);
411 result.push_back(driveName);
416static std::vector<std::string> getSlots(MSXMotherBoard* motherBoard)
418 std::vector<std::string> result;
419 if (!motherBoard)
return result;
421 const auto& slotManager = motherBoard->getSlotManager();
422 std::string cartName =
"cartX";
423 for (
auto slot :
xrange(CartridgeSlotManager::MAX_SLOTS)) {
424 if (!slotManager.slotExists(slot))
continue;
425 cartName[4] = char(
'a' + slot);
426 result.push_back(cartName);
434 ImGui::LoadIniSettingsFromDisk(
loadIniFile.c_str());
449 for (
auto* part : parts) {
450 part->paint(motherBoard);
457 for (
auto* part : parts) {
458 part->showMenu(motherBoard);
461 if (mainMenuBarUndocked) {
462 im::Window(
"openMSX main menu", &mainMenuBarUndocked, ImGuiWindowFlags_MenuBar, [&]{
464 if (ImGui::ArrowButton(
"re-dock-button", ImGuiDir_Down)) {
465 mainMenuBarUndocked =
false;
467 simpleToolTip(
"Dock the menu bar in the main openMSX window.");
472 bool active = ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) ||
473 ImGui::IsWindowFocused(ImGuiHoveredFlags_AnyWindow);
474 if (active != guiActive) {
481 auto target = active ? 1.0f : 0.0001f;
482 auto period = active ? 0.5f : 5.0f;
487 if (ImGui::ArrowButton(
"undock-button", ImGuiDir_Up)) {
488 mainMenuBarUndocked =
true;
490 simpleToolTip(
"Undock the menu bar from the main openMSX window.");
497 auto insert2 = [&](std::string_view displayName,
TclObject cmd) {
498 auto message =
strCat(
"Inserted ", droppedFile,
" in ", displayName);
500 insertedInfo = message;
501 openInsertedInfo =
true;
504 auto insert = [&](std::string_view displayName, std::string_view cmd) {
505 insert2(displayName,
makeTclList(cmd,
"insert", droppedFile));
508 handleDropped =
false;
509 insertedInfo.clear();
511 auto category =
execute(
makeTclList(
"openmsx_info",
"file_type_category", droppedFile))->getString();
516 auto error = [&](
auto&& ...message) {
519 auto cantHandle = [&](
auto&& ...message) {
520 error(
"Can't handle dropped file ", droppedFile,
": ", message...);
522 auto notPresent = [&](
const auto& mediaType) {
523 cantHandle(
"no ", mediaType,
" present.");
526 auto testMedia = [&](std::string_view displayName, std::string_view cmd) {
528 insert(displayName, cmd);
530 notPresent(displayName);
534 if (category ==
"disk") {
535 auto list = getDrives(motherBoard);
537 notPresent(
"disk drive");
538 }
else if (list.size() == 1) {
539 const auto& drive = list.front();
540 insert(
strCat(
"disk drive ",
char(drive.back() -
'a' +
'A')), drive);
542 selectList = std::move(list);
543 ImGui::OpenPopup(
"select-drive");
545 }
else if (category ==
"rom") {
546 auto list = getSlots(motherBoard);
548 notPresent(
"cartridge slot");
551 selectedMedia = list.front();
552 selectList = std::move(list);
558 selectedRomType = romInfo ? romInfo->
getRomType()
560 ImGui::OpenPopup(
"select-cart");
561 }
else if (category ==
"cassette") {
562 testMedia(
"casette port",
"cassetteplayer");
563 }
else if (category ==
"laserdisc") {
564 testMedia(
"laser disc player",
"laserdiscplayer");
565 }
else if (category ==
"savestate") {
567 }
else if (category ==
"replay") {
569 }
else if (category ==
"script") {
574 cantHandle(
"unknown file type");
579 auto n = std::min(3.5f, narrow<float>(selectList.size()));
580 auto height = n * ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().FramePadding.y;
581 im::ListBox(
"##select-media", {-FLT_MIN, height}, [&]{
582 for (
const auto& item : selectList) {
583 auto drive = item.back() -
'a';
584 auto display =
strCat(
char(
'A' + drive),
": ",
media->displayNameForDriveContent(drive,
true));
585 if (ImGui::Selectable(display.c_str())) {
586 insert(
strCat(
"disk drive ",
char(drive +
'A')), item);
587 ImGui::CloseCurrentPopup();
601 ImGui::TableSetupColumn(
"description", ImGuiTableColumnFlags_WidthFixed);
602 ImGui::TableSetupColumn(
"value", ImGuiTableColumnFlags_WidthStretch);
607 if (ImGui::TableNextColumn()) {
608 ImGui::AlignTextToFramePadding();
611 if (ImGui::TableNextColumn()) {
617 if (selectList.size() > 1) {
618 const auto& slotManager = motherBoard->getSlotManager();
620 auto n = std::min(3.5f, narrow<float>(selectList.size()));
621 auto height = n * ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().FramePadding.y;
622 im::ListBox(
"##select-media", {-FLT_MIN, height}, [&]{
623 for (
const auto& item : selectList) {
624 auto slot = item.back() -
'a';
627 " (", slotManager.getPsSsString(slot),
"): ",
628 media->displayNameForSlotContent(slotManager, slot,
true));
630 if (ImGui::Selectable(display.c_str(), item == selectedMedia)) {
631 selectedMedia = item;
637 ImGui::Checkbox(
"Reset MSX on inserting ROM", &
media->resetOnInsertRom);
639 if (ImGui::Button(
"Insert ROM")) {
640 auto cmd =
makeTclList(selectedMedia,
"insert", droppedFile);
644 insert2(
strCat(
"cartridge slot ",
char(selectedMedia.back() -
'a' +
'A')), cmd);
645 if (
media->resetOnInsertRom) {
648 ImGui::CloseCurrentPopup();
651 if (ImGui::Button(
"Cancel")) {
652 ImGui::CloseCurrentPopup();
655 if (openInsertedInfo) {
656 openInsertedInfo =
false;
657 insertedInfoTimeout = 3.0f;
658 ImGui::OpenPopup(
"inserted-info");
661 insertedInfoTimeout -= ImGui::GetIO().DeltaTime;
662 if (insertedInfoTimeout <= 0.0f || insertedInfo.empty()) {
663 ImGui::CloseCurrentPopup();
671void ImGuiManager::iniReadInit()
674 for (
auto* part : parts) {
681void* ImGuiManager::iniReadOpen(std::string_view name)
684 for (
auto* part : parts) {
685 if (part->iniName() == name)
return part;
690void ImGuiManager::loadLine(
void* entry,
const char* line_)
const
693 auto pos = line.
find(
'=');
695 std::string_view name = line.
substr(0, pos);
699 static_cast<ImGuiPartInterface*
>(entry)->loadLine(name, value);
702void ImGuiManager::iniApplyAll()
705 for (
auto* part : parts) {
710void ImGuiManager::iniWriteAll(ImGuiTextBuffer& buf)
713 for (
auto* part : parts) {
714 if (
auto name = part->iniName(); !name.empty()) {
715 buf.appendf(
"[openmsx][%s]\n", name.c_str());
void printError(std::string_view message)
void printWarning(std::string_view message)
void setWindowPosition(gl::ivec2 pos)
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=OTHER)
Registers a given object to receive certain events.
Priority
Priorities from high to low, higher priority listeners can block events for lower priority listeners.
std::string resolveCreate(std::string_view filename) const
Sha1Sum getSha1Sum(File &file)
Calculate sha1sum for the given File object.
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< 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
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< ImGuiCharacter > character
void unregisterPart(ImGuiPartInterface *part)
std::unique_ptr< ImGuiTools > tools
void executeDelayed(std::function< void()> action)
ImGuiManager(Reactor &reactor_, SettingsConfig &config_)
FilenameSetting fontMonoFilename
std::unique_ptr< ImGuiSymbols > symbols
int getInt() const noexcept
Contains the main loop of openMSX.
MSXMotherBoard * getMotherBoard() const
Interpreter & getInterpreter()
EventDistributor & getEventDistributor()
RomDatabase & getSoftwareDatabase()
static std::shared_ptr< DrivesInUse > getDrivesInUse(MSXMotherBoard &motherBoard)
const RomInfo * fetchRomInfo(const Sha1Sum &sha1sum) const
Lookup an entry in the database by sha1sum.
static std::string_view romTypeToName(RomType type)
RomType getRomType() const
void setShortcuts(Shortcuts &shortcuts_)
void detach(Observer< T > &observer)
void attach(Observer< T > &observer)
TclObject executeCommand(Interpreter &interp, bool compile=false)
Interpret this TclObject as a command and execute it.
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)
bool ImGui_ImplOpenGL3_CreateFontsTexture()
void ImGui_ImplOpenGL3_DestroyFontsTexture()
bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event *event)
void TextUnformatted(const std::string &str)
std::optional< Context > context
void Table(const char *str_id, int column, ImGuiTableFlags flags, const ImVec2 &outer_size, float inner_width, std::invocable<> auto next)
void MainMenuBar(std::invocable<> auto next)
void MenuBar(std::invocable<> auto next)
void Window(const char *name, bool *p_open, ImGuiWindowFlags flags, std::invocable<> auto next)
void StyleVar(ImGuiStyleVar idx, float val, std::invocable<> auto next)
void ListBox(const char *label, const ImVec2 &size, std::invocable<> auto next)
void TextWrapPos(float wrap_local_pos_x, std::invocable<> auto next)
void Popup(const char *str_id, ImGuiWindowFlags flags, std::invocable<> auto next)
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:
const FileContext & systemFileContext()
bool loadOnePersistent(std::string_view name, zstring_view value, C &c, const std::tuple< Elements... > &tup)
void simpleToolTip(std::string_view desc)
void savePersistent(ImGuiTextBuffer &buf, C &c, const std::tuple< Elements... > &tup)
EventType getType(const Event &event)
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
float calculateFade(float current, float target, float period)
TclObject makeTclList(Args &&... args)
auto remove(ForwardRange &&range, const T &value)
auto find(InputRange &&range, const T &value)
constexpr bool contains(ITER first, ITER last, const VAL &val)
Check if a range contains a given value, using linear search.
TemporaryString tmpStrCat(Ts &&... ts)
constexpr auto xrange(T e)