Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Flow.Launcher/Flow.Launcher.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@
</ItemGroup>

<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
<Exec Command="taskkill /f /fi &quot;IMAGENAME eq Flow.Launcher.exe&quot;" />
<Exec Command="taskkill /f /fi &quot;IMAGENAME eq Flow.Launcher.exe&quot;" IgnoreExitCode="true" />
</Target>

<Target Name="RemoveDuplicateAnalyzers" BeforeTargets="CoreCompile">
Expand Down
60 changes: 60 additions & 0 deletions Flow.Launcher/Helper/HotKeyMapper.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using System;
using System.Collections.Generic;
using System.Windows.Input;
using ChefKeys;
using CommunityToolkit.Mvvm.DependencyInjection;
using Flow.Launcher.Infrastructure.Hotkey;
using Flow.Launcher.Infrastructure.DialogJump;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin;
using Flow.Launcher.ViewModel;
using NHotkey;
using NHotkey.Wpf;
Expand All @@ -16,6 +19,7 @@ internal static class HotKeyMapper

private static Settings _settings;
private static MainViewModel _mainViewModel;
private static readonly Dictionary<string, Func<int, int, SpecialKeyState, bool>> _winComboCallbacks = new();

internal static void Initialize()
{
Expand Down Expand Up @@ -82,6 +86,14 @@ internal static void SetHotkey(HotkeyModel hotkey, EventHandler<HotkeyEventArgs>
}
catch (Exception e)
{
if (hotkey.Win && hotkey.CharKey != Key.None)
{
App.API.LogDebug(ClassName,
$"|HotkeyMapper.SetHotkey|RegisterHotKey failed for {hotkeyStr} ({e.Message}); falling back to global keyboard callback.");
SetWithGlobalCallback(hotkey, action);
return;
}
Comment on lines +89 to +95
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Guard fallback registration failures to avoid uncaught exceptions.

If SetWithGlobalCallback fails (e.g., Line 146), that exception escapes from the catch block path and bypasses the normal error dialog flow for hotkey setup.

Suggested fix
             if (hotkey.Win && hotkey.CharKey != Key.None)
             {
-                App.API.LogDebug(ClassName,
-                    $"|HotkeyMapper.SetHotkey|RegisterHotKey failed for {hotkeyStr} ({e.Message}); falling back to global keyboard callback.");
-                SetWithGlobalCallback(hotkey, action);
-                return;
+                try
+                {
+                    App.API.LogDebug(ClassName,
+                        $"|HotkeyMapper.SetHotkey|RegisterHotKey failed for {hotkeyStr} ({e.Message}); falling back to global keyboard callback.");
+                    SetWithGlobalCallback(hotkey, action);
+                    return;
+                }
+                catch (Exception fallbackEx)
+                {
+                    App.API.LogError(ClassName,
+                        $"|HotkeyMapper.SetHotkey|Fallback registration failed for {hotkeyStr}: {fallbackEx.Message} \nStackTrace:{fallbackEx.StackTrace}");
+                    string errorMsg = Localize.registerHotkeyFailed(hotkeyStr);
+                    string errorMsgTitle = Localize.MessageBoxTitle();
+                    App.API.ShowMsgBox(errorMsg, errorMsgTitle);
+                    return;
+                }
             }

Also applies to: 146-147

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Flow.Launcher/Helper/HotKeyMapper.cs` around lines 89 - 95, The fallback call
to SetWithGlobalCallback in HotKeyMapper.SetHotkey can throw and currently
escapes the outer catch; wrap the fallback invocation in its own try/catch so
any exception is caught, logged via App.API.LogError/LogDebug with the hotkeyStr
and exception details, and then invoke the existing hotkey error handling/UI
path (same dialog or handler used in the outer catch) instead of letting the
exception propagate; apply the same guard around the other fallback site
referenced (lines calling SetWithGlobalCallback around 146-147) so all fallback
registrations are protected.


App.API.LogError(ClassName,
string.Format("|HotkeyMapper.SetHotkey|Error registering hotkey {2}: {0} \nStackTrace:{1}",
e.Message,
Expand All @@ -93,6 +105,47 @@ internal static void SetHotkey(HotkeyModel hotkey, EventHandler<HotkeyEventArgs>
}
}

private static void SetWithGlobalCallback(HotkeyModel hotkey, EventHandler<HotkeyEventArgs> action)
{
string hotkeyStr = hotkey.ToString();
if (_winComboCallbacks.TryGetValue(hotkeyStr, out var existing))
{
App.API.RemoveGlobalKeyboardCallback(existing);
_winComboCallbacks.Remove(hotkeyStr);
}

int expectedVkCode = KeyInterop.VirtualKeyFromKey(hotkey.CharKey);
bool needCtrl = hotkey.Ctrl;
bool needAlt = hotkey.Alt;
bool needShift = hotkey.Shift;
bool keyCurrentlyDown = false;

Func<int, int, SpecialKeyState, bool> callback = (keyEvent, vkCode, state) =>
{
bool isMatch = vkCode == expectedVkCode
&& state.WinPressed
&& state.CtrlPressed == needCtrl
&& state.AltPressed == needAlt
&& state.ShiftPressed == needShift;

if (isMatch && (keyEvent == (int)KeyEvent.WM_KEYDOWN || keyEvent == (int)KeyEvent.WM_SYSKEYDOWN) && !keyCurrentlyDown)
{
keyCurrentlyDown = true;
action?.Invoke(null, null);
return false;
}
if (isMatch && (keyEvent == (int)KeyEvent.WM_KEYUP || keyEvent == (int)KeyEvent.WM_SYSKEYUP))
{
keyCurrentlyDown = false;
return false;
}
return true;
};

_winComboCallbacks[hotkeyStr] = callback;
App.API.RegisterGlobalKeyboardCallback(callback);
}

internal static void RemoveHotkey(string hotkeyStr)
{
try
Expand All @@ -103,6 +156,13 @@ internal static void RemoveHotkey(string hotkeyStr)
return;
}

if (_winComboCallbacks.TryGetValue(hotkeyStr, out var callback))
{
App.API.RemoveGlobalKeyboardCallback(callback);
_winComboCallbacks.Remove(hotkeyStr);
return;
}

if (!string.IsNullOrEmpty(hotkeyStr))
HotkeyManager.Current.Remove(hotkeyStr);
}
Expand Down
5 changes: 3 additions & 2 deletions Flow.Launcher/HotkeyControl.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,10 @@ private void SetHotkey(HotkeyModel keyModel, bool triggerValidate = true)
{
bool hotkeyAvailable;
// TODO: This is a temporary way to enforce changing only the open flow hotkey to Win, and will be removed by PR #3157
if (keyModel.ToString() == "LWin" || keyModel.ToString() == "RWin")
if (keyModel.ToString() == "LWin" || keyModel.ToString() == "RWin"
|| (Type == HotkeyType.Hotkey && keyModel.Win && keyModel.CharKey != Key.None))
{
hotkeyAvailable = true;
hotkeyAvailable = keyModel.Validate(ValidateKeyGesture);
}
Comment on lines 280 to 285
Comment thread
coderabbitai[bot] marked this conversation as resolved.
else
{
Expand Down
57 changes: 52 additions & 5 deletions Flow.Launcher/HotkeyControlDialog.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ public enum EResultType
public string ResultValue { get; private set; } = string.Empty;
public static string EmptyHotkey => Localize.none();

private static bool isOpenFlowHotkey;
private bool isOpenFlowHotkey;
private Func<int, int, SpecialKeyState, bool>? _winComboInterceptor;

public HotkeyControlDialog(string hotkey, string defaultHotkey, string windowTitle = "")
{
Expand All @@ -52,11 +53,45 @@ public HotkeyControlDialog(string hotkey, string defaultHotkey, string windowTit

// TODO: This is a temporary way to enforce changing only the open flow hotkey to Win, and will be removed by PR #3157
isOpenFlowHotkey = _hotkeySettings.RegisteredHotkeys
.Any(x => x.DescriptionResourceKey == "flowlauncherHotkey"
.Any(x => x.DescriptionResourceKey == "flowlauncherHotkey"
&& x.Hotkey.ToString() == hotkey);

ChefKeysManager.StartMenuEnableBlocking = true;
ChefKeysManager.Start();

if (isOpenFlowHotkey)
{
_winComboInterceptor = (keyEvent, vkCode, state) =>
{
const int VK_LWIN = 0x5B;
const int VK_RWIN = 0x5C;
if ((keyEvent == (int)KeyEvent.WM_KEYDOWN || keyEvent == (int)KeyEvent.WM_SYSKEYDOWN)
&& state.WinPressed
&& vkCode != VK_LWIN && vkCode != VK_RWIN)
{
var key = KeyInterop.KeyFromVirtualKey(vkCode);
if (key is Key.None
or Key.LeftCtrl or Key.RightCtrl
or Key.LeftAlt or Key.RightAlt
or Key.LeftShift or Key.RightShift
or Key.LWin or Key.RWin)
{
return false;
}
_ = App.Current.Dispatcher.InvokeAsync(() =>
{
if (!IsLoaded) return;
var hotkeyModel = new HotkeyModel(state.AltPressed, state.ShiftPressed, state.WinPressed, state.CtrlPressed, key);
CurrentHotkey = hotkeyModel;
SetKeysToDisplay(CurrentHotkey);
});
return false;
}
return true;
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
App.API.RegisterGlobalKeyboardCallback(_winComboInterceptor);
this.Closed += (_, _) => UnregisterWinComboInterceptor();
}
Comment on lines +62 to +94
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

private void Reset(object sender, RoutedEventArgs routedEventArgs)
Expand All @@ -70,10 +105,20 @@ private void Delete(object sender, RoutedEventArgs routedEventArgs)
KeysToDisplay.Add(EmptyHotkey);
}

private void UnregisterWinComboInterceptor()
{
if (_winComboInterceptor != null)
{
App.API.RemoveGlobalKeyboardCallback(_winComboInterceptor);
_winComboInterceptor = null;
}
}

private void Cancel(object sender, RoutedEventArgs routedEventArgs)
{
ChefKeysManager.StartMenuEnableBlocking = false;
ChefKeysManager.Stop();
UnregisterWinComboInterceptor();

ResultType = EResultType.Cancel;
Hide();
Expand All @@ -83,6 +128,7 @@ private void Save(object sender, RoutedEventArgs routedEventArgs)
{
ChefKeysManager.StartMenuEnableBlocking = false;
ChefKeysManager.Stop();
UnregisterWinComboInterceptor();

if (KeysToDisplay.Count == 1 && KeysToDisplay[0] == EmptyHotkey)
{
Expand Down Expand Up @@ -182,10 +228,11 @@ private void SetKeysToDisplay(HotkeyModel? hotkey)
}
}

private static bool CheckHotkeyAvailability(HotkeyModel hotkey, bool validateKeyGesture)
private bool CheckHotkeyAvailability(HotkeyModel hotkey, bool validateKeyGesture)
{
if (isOpenFlowHotkey && (hotkey.ToString() == "LWin" || hotkey.ToString() == "RWin"))
return true;
if (isOpenFlowHotkey && (hotkey.ToString() == "LWin" || hotkey.ToString() == "RWin"
|| (hotkey.Win && hotkey.CharKey != Key.None)))
return hotkey.Validate(validateKeyGesture);

Comment on lines +233 to 236
return hotkey.Validate(validateKeyGesture) && HotKeyMapper.CheckAvailability(hotkey);
}
Expand Down
30 changes: 24 additions & 6 deletions Flow.Launcher/PublicAPIInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -538,12 +538,19 @@ public bool IsGameModeOn()
}

private readonly List<Func<int, int, SpecialKeyState, bool>> _globalKeyboardHandlers = new();
private readonly object _globalKeyboardHandlersLock = new();

public void RegisterGlobalKeyboardCallback(Func<int, int, SpecialKeyState, bool> callback) =>
_globalKeyboardHandlers.Add(callback);
public void RegisterGlobalKeyboardCallback(Func<int, int, SpecialKeyState, bool> callback)
{
lock (_globalKeyboardHandlersLock)
_globalKeyboardHandlers.Add(callback);
}

public void RemoveGlobalKeyboardCallback(Func<int, int, SpecialKeyState, bool> callback) =>
_globalKeyboardHandlers.Remove(callback);
public void RemoveGlobalKeyboardCallback(Func<int, int, SpecialKeyState, bool> callback)
{
lock (_globalKeyboardHandlersLock)
_globalKeyboardHandlers.Remove(callback);
}

public void ReQuery(bool reselect = true) => _mainVM.ReQuery(reselect);

Expand Down Expand Up @@ -657,10 +664,21 @@ public event ActualApplicationThemeChangedEventHandler ActualApplicationThemeCha

private bool KListener_hookedKeyboardCallback(KeyEvent keyevent, int vkcode, SpecialKeyState state)
{
Func<int, int, SpecialKeyState, bool>[] snapshot;
lock (_globalKeyboardHandlersLock)
snapshot = _globalKeyboardHandlers.ToArray();

var continueHook = true;
foreach (var x in _globalKeyboardHandlers)
foreach (var x in snapshot)
{
continueHook &= x((int)keyevent, vkcode, state);
try
{
continueHook &= x((int)keyevent, vkcode, state);
}
catch (Exception e)
{
LogException(ClassName, "Global keyboard callback failed", e);
}
}

return continueHook;
Expand Down