From d9a7f40eb416b94379463c7267c805b1bb28e0df Mon Sep 17 00:00:00 2001 From: Roman <40754203+BohdanQQ@users.noreply.github.com> Date: Sat, 14 Dec 2024 16:51:40 +0100 Subject: [PATCH] fix: Shortcuts not being disabled correctly when menu items are disabled (#1992) Fix crash on UNDO/REDO shortcut press when in "title screen" ### Problem description ImHex crashes when (by default CTRL + Z/Y) undo/redo is pressed when on "title"/"starting" screen (no file open, tested on Windows release build and Linux [WSL] from-source build). This is due to the shortcut's callback being called even if the `provider` is `nullptr`. (see `createEditMenu` function). Theoretically, this is prevented by the `enabledCallback` function passsed to `addMenuItem`. In this case, though, `addMenuItem` correctly propagates `enabledCallback` to menu item creation but does not pass `enabledCallback` to shortcut creation. Thus, when handling shortcuts, `enabledCallback` is not used at all and the shortcut's callback can be called in contradiction with its preconditions. (specified by `enabledCallback`) ### Implementation description The implementation wraps the callback in a check that decides whether the shortcut is enabled or not. (see changed files) ```c++ auto callbackIfEnabled = [enabledCallback, function]{ if (enabledCallback()) { function(); } }; ``` This function is then passed along instead of the `function` (shortcut's callback). Alternatively, we can check for `nullptr` in the callback directly. This would require modification of `createEditMenu`'s contents. (I did not choose this implementation because I do not think it addresses the root of the issue). ### Screenshots None ### Additional things I'm not sure how big of a deal it is but I am unsure whether I can capture (`[enabledCallback, function]`) by reference or not. --- lib/libimhex/source/api/content_registry.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/libimhex/source/api/content_registry.cpp b/lib/libimhex/source/api/content_registry.cpp index 867c2cc95..102009ac9 100644 --- a/lib/libimhex/source/api/content_registry.cpp +++ b/lib/libimhex/source/api/content_registry.cpp @@ -906,10 +906,11 @@ namespace hex { }); if (shortcut != Shortcut::None) { + auto callbackIfEnabled = [enabledCallback, function]{ if (enabledCallback()) { function(); } }; if (shortcut.isLocal() && view != nullptr) - ShortcutManager::addShortcut(view, shortcut, unlocalizedMainMenuNames.back(), function); + ShortcutManager::addShortcut(view, shortcut, unlocalizedMainMenuNames.back(), callbackIfEnabled); else - ShortcutManager::addGlobalShortcut(shortcut, unlocalizedMainMenuNames.back(), function); + ShortcutManager::addGlobalShortcut(shortcut, unlocalizedMainMenuNames.back(), callbackIfEnabled); } }