Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
61 changes: 61 additions & 0 deletions Flow.Launcher/Helper/HotKeyMapper.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using System;
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 +18,8 @@ internal static class HotKeyMapper

private static Settings _settings;
private static MainViewModel _mainViewModel;
private static Func<int, int, SpecialKeyState, bool> _winComboCallback;
private static string _winComboHotkeyStr;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated

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)
{
if (_winComboCallback != null)
{
App.API.RemoveGlobalKeyboardCallback(_winComboCallback);
_winComboCallback = null;
_winComboHotkeyStr = null;
}

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

_winComboCallback = (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 && !keyCurrentlyDown)
{
keyCurrentlyDown = true;
action?.Invoke(null, null);
return false;
}
if (isMatch && keyEvent == (int)KeyEvent.WM_KEYUP)
{
keyCurrentlyDown = false;
return false;
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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the hook emits WM_SYS* events while matcher currently filters on WM_KEY* only.
rg -nP --type=cs -C3 'WM_KEYDOWN|WM_KEYUP|WM_SYSKEYDOWN|WM_SYSKEYUP' \
  Flow.Launcher.Infrastructure/Hotkey/GlobalHotkey.cs \
  Flow.Launcher/Helper/HotKeyMapper.cs \
  Flow.Launcher/HotkeyControlDialog.xaml.cs

Repository: Flow-Launcher/Flow.Launcher

Length of output: 2731


🏁 Script executed:

# Get the complete HotKeyMapper method to understand the stuck key scenario
rg -n 'class\s|public\s+(bool|void).*\s+Hook|private.*keyCurrentlyDown' \
  Flow.Launcher/Helper/HotKeyMapper.cs -A 20 | head -100

Repository: Flow-Launcher/Flow.Launcher

Length of output: 858


🏁 Script executed:

# Check the full method context around lines 131-140
sed -n '100,150p' Flow.Launcher/Helper/HotKeyMapper.cs

Repository: Flow-Launcher/Flow.Launcher

Length of output: 1826


🏁 Script executed:

# Look for any other places where keyCurrentlyDown is accessed/reset
rg -n 'keyCurrentlyDown' Flow.Launcher/Helper/HotKeyMapper.cs

Repository: Flow-Launcher/Flow.Launcher

Length of output: 295


🏁 Script executed:

# Check if there are tests or other references that show expected behavior
rg -n 'WinComboCallback|SetWithGlobalCallback|keyCurrentlyDown' \
  Flow.Launcher/ -t cs --max-count=20

Repository: Flow-Launcher/Flow.Launcher

Length of output: 683


🏁 Script executed:

# Look for how KeyEvent enum is defined to understand WM_SYS variants
rg -n 'enum KeyEvent|WM_KEYDOWN|WM_SYSKEYDOWN' Flow.Launcher.Infrastructure/ -t cs -B 2 -A 10

Repository: Flow-Launcher/Flow.Launcher

Length of output: 1549


🏁 Script executed:

# Find and display the KeyEvent enum definition
rg -n 'enum KeyEvent' Flow.Launcher.Infrastructure/ -A 20

Repository: Flow-Launcher/Flow.Launcher

Length of output: 53


🏁 Script executed:

# Also check if there are any unit tests for the hotkey functionality
fd -e '.*Test.*\.cs$' | xargs rg -l 'HotKeyMapper|SetWithGlobalCallback' 2>/dev/null || echo "No hotkey tests found"

Repository: Flow-Launcher/Flow.Launcher

Length of output: 402


🏁 Script executed:

# Search more broadly for KeyEvent enum definition
rg -n 'enum KeyEvent' --type cs -i

Repository: Flow-Launcher/Flow.Launcher

Length of output: 132


🏁 Script executed:

# Check in common locations for enums
find . -name '*.cs' -type f | xargs grep -l 'enum KeyEvent' 2>/dev/null | head -5

Repository: Flow-Launcher/Flow.Launcher

Length of output: 106


🏁 Script executed:

# Look at the GlobalHotkey file more carefully to understand KeyEvent usage
sed -n '1,50p' Flow.Launcher.Infrastructure/Hotkey/GlobalHotkey.cs

Repository: Flow-Launcher/Flow.Launcher

Length of output: 1976


🏁 Script executed:

# Get the KeyEvent enum definition
cat Flow.Launcher.Plugin/KeyEvent.cs

Repository: Flow-Launcher/Flow.Launcher

Length of output: 928


🏁 Script executed:

# Verify the complete flow: check HotkeyControlDialog to see how it uses the matcher
cat -n Flow.Launcher/HotkeyControlDialog.xaml.cs | sed -n '50,80p'

Repository: Flow-Launcher/Flow.Launcher

Length of output: 1590


Include WM_SYS key events and fix stuck key latch in fallback matcher.*

The hook emits WM_SYSKEYDOWN/UP events (GlobalHotkey.cs) but the matcher only checks WM_KEYDOWN/UP. Additionally, if Win is released before the character key, keyCurrentlyDown cannot reset because isMatch becomes false (Win is no longer pressed), causing subsequent hotkey triggers to fail.

🔧 Suggested matcher fix
-            if (isMatch && keyEvent == (int)KeyEvent.WM_KEYDOWN && !keyCurrentlyDown)
+            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)
+            if (vkCode == expectedVkCode
+                && (keyEvent == (int)KeyEvent.WM_KEYUP || keyEvent == (int)KeyEvent.WM_SYSKEYUP))
             {
                 keyCurrentlyDown = false;
-                return false;
+                return isMatch ? false : true;
             }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (isMatch && keyEvent == (int)KeyEvent.WM_KEYDOWN && !keyCurrentlyDown)
{
keyCurrentlyDown = true;
action?.Invoke(null, null);
return false;
}
if (isMatch && keyEvent == (int)KeyEvent.WM_KEYUP)
{
keyCurrentlyDown = false;
return false;
if (isMatch
&& (keyEvent == (int)KeyEvent.WM_KEYDOWN || keyEvent == (int)KeyEvent.WM_SYSKEYDOWN)
&& !keyCurrentlyDown)
{
keyCurrentlyDown = true;
action?.Invoke(null, null);
return false;
}
if (vkCode == expectedVkCode
&& (keyEvent == (int)KeyEvent.WM_KEYUP || keyEvent == (int)KeyEvent.WM_SYSKEYUP))
{
keyCurrentlyDown = false;
return isMatch ? false : true;
}
🤖 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 131 - 140, The matcher
only checks KeyEvent.WM_KEYDOWN/WM_KEYUP and latches keyCurrentlyDown only when
isMatch is true, causing missed WM_SYS* events and a stuck latch if the modifier
(Win) is released first; update the conditional logic in HotKeyMapper.cs to
treat WM_SYSKEYDOWN and WM_SYSKEYUP the same as WM_KEYDOWN/WM_KEYUP (i.e.,
consider keyEvent == KeyEvent.WM_KEYDOWN || keyEvent == KeyEvent.WM_SYSKEYDOWN
for down and similarly for up), invoke action when isMatch and a down event
occurs, and also always clear keyCurrentlyDown on any up event (WM_KEYUP or
WM_SYSKEYUP) regardless of isMatch so the latch resets even when the modifier
was released earlier.

}
return true;
};

_winComboHotkeyStr = hotkey.ToString();
App.API.RegisterGlobalKeyboardCallback(_winComboCallback);
}

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

if (_winComboCallback != null && hotkeyStr == _winComboHotkeyStr)
{
App.API.RemoveGlobalKeyboardCallback(_winComboCallback);
_winComboCallback = null;
_winComboHotkeyStr = null;
return;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated

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
&& state.WinPressed
&& vkCode != VK_LWIN && vkCode != VK_RWIN)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
{
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
23 changes: 16 additions & 7 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,11 +664,13 @@ 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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
}

return continueHook;
}
Expand Down