Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

feat: focus follows cursor (#245)

blam458fcd9e84cc
diff --git a/GlazeWM.Bootstrapper/Resources/sample-config.yaml b/GlazeWM.Bootstrapper/Resources/sample-config.yaml
index 1e002488..d4e2adba 100644
--- a/GlazeWM.Bootstrapper/Resources/sample-config.yaml
+++ b/GlazeWM.Bootstrapper/Resources/sample-config.yaml
@@ -3,6 +3,7 @@ gaps:
outer_gap: 20
general:
+ focus_follows_cursor: false
# Whether to show floating windows as always on top.
show_floating_on_top: false
floating_window_move_amount: "5%"
diff --git a/GlazeWM.Bootstrapper/Startup.cs b/GlazeWM.Bootstrapper/Startup.cs
index 21d2787d..e0935d55 100644
--- a/GlazeWM.Bootstrapper/Startup.cs
+++ b/GlazeWM.Bootstrapper/Startup.cs
@@ -4,7 +4,10 @@ using System.Reactive.Linq;
using System.Windows.Forms;
using GlazeWM.Bar;
using GlazeWM.Domain.Common.Commands;
+using GlazeWM.Domain.Containers.Commands;
+using GlazeWM.Domain.UserConfigs;
using GlazeWM.Domain.UserConfigs.Commands;
+using GlazeWM.Domain.Windows;
using GlazeWM.Domain.Windows.Commands;
using GlazeWM.Infrastructure.Bussing;
using GlazeWM.Infrastructure.Common.Commands;
@@ -20,6 +23,8 @@ namespace GlazeWM.Bootstrapper
private readonly Bus _bus;
private readonly KeybindingService _keybindingService;
private readonly WindowEventService _windowEventService;
+ private readonly WindowService _windowService;
+ private readonly UserConfigService _userConfigService;
private SystemTrayIcon _systemTrayIcon { get; set; }
@@ -27,12 +32,16 @@ namespace GlazeWM.Bootstrapper
BarService barService,
Bus bus,
KeybindingService keybindingService,
- WindowEventService windowEventService)
+ WindowEventService windowEventService,
+ UserConfigService userConfigService,
+ WindowService windowService)
{
_barService = barService;
_bus = bus;
_keybindingService = keybindingService;
_windowEventService = windowEventService;
+ _windowService = windowService;
+ _userConfigService = userConfigService;
}
public void Run()
@@ -77,6 +86,14 @@ namespace GlazeWM.Bootstrapper
_systemTrayIcon = new SystemTrayIcon(systemTrayIconConfig);
_systemTrayIcon.Show();
+ // Hook mouse event for focus follows cursor.
+ if (_userConfigService.GeneralConfig.FocusFollowsCursor)
+ MouseEvents.MouseMoves.Sample(TimeSpan.FromMilliseconds(50)).Subscribe((@event) =>
+ {
+ _bus.InvokeAsync(new FocusContainerUnderCursorCommand(@event.Point));
+ });
+
Application.Run();
}
catch (Exception exception)
diff --git a/GlazeWM.Domain/Containers/CommandHandlers/FocusContainerUnderCursorHandler.cs b/GlazeWM.Domain/Containers/CommandHandlers/FocusContainerUnderCursorHandler.cs
new file mode 100644
index 00000000..6a377c14
--- /dev/null
+++ b/GlazeWM.Domain/Containers/CommandHandlers/FocusContainerUnderCursorHandler.cs
@@ -0,0 +1,74 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using GlazeWM.Domain.Containers.Commands;
+using GlazeWM.Domain.Windows;
+using GlazeWM.Infrastructure.Bussing;
+using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;
+
+namespace GlazeWM.Domain.Containers.CommandHandlers
+{
+ internal sealed class FocusContainerUnderCursorHandler : ICommandHandler<FocusContainerUnderCursorCommand>
+ {
+ private readonly Bus _bus;
+ private readonly ContainerService _containerService;
+ private List<IntPtr> _focusedWindows = new();
+ private readonly WindowService _windowService;
+ public FocusContainerUnderCursorHandler(Bus bus, ContainerService containerService, WindowService windowService)
+ {
+ _bus = bus;
+ _containerService = containerService;
+ _windowService = windowService;
+ }
+
+ public CommandResponse Handle(FocusContainerUnderCursorCommand command)
+ {
+ // Returns window underneath cursor. This could be a child window or parent.
+ var windowHandle = WindowFromPoint(command.TargetPoint);
+
+ // If the mouse is hovering over the currently focused main window or one of it's children, do nothing.
+ if (_focusedWindows.Contains(windowHandle))
+ return CommandResponse.Ok;
+
+ // If the FocusedWindows list didn't contain the window, this might be a new window being focused.
+ var newFocusedWindowsList = new List<IntPtr>
+ {
+ windowHandle
+ };
+
+ // Check if the window is the main window or a child window.
+ var parentWindow = GetParent(windowHandle);
+
+ // Walk the window up each parent window until you have the main window.
+ while (parentWindow != IntPtr.Zero)
+ {
+ windowHandle = parentWindow;
+ newFocusedWindowsList.Add(windowHandle);
+ parentWindow = GetParent(windowHandle);
+ }
+
+ // Determine if the same window or a new window is being hovered
+ if (_focusedWindows.Contains(newFocusedWindowsList.Last()))
+ {
+ _focusedWindows = _focusedWindows.Union(newFocusedWindowsList).ToList();
+ }
+ else
+ {
+ _focusedWindows = newFocusedWindowsList;
+ var foundWindow = _windowService
+ .GetWindows()
+ .FirstOrDefault(window => window.Handle == windowHandle);
+
+ if (foundWindow is not null)
+ {
+ // Focus the new window
+ SetForegroundWindow(foundWindow.Handle);
+ SetFocus(foundWindow.Handle);
+ }
+ }
+
+ return CommandResponse.Ok;
+ }
+ }
+}
diff --git a/GlazeWM.Domain/Containers/Commands/FocusContainerUnderCursorCommand.cs b/GlazeWM.Domain/Containers/Commands/FocusContainerUnderCursorCommand.cs
new file mode 100644
index 00000000..104ca4cf
--- /dev/null
+++ b/GlazeWM.Domain/Containers/Commands/FocusContainerUnderCursorCommand.cs
@@ -0,0 +1,14 @@
+using GlazeWM.Infrastructure.Bussing;
+using GlazeWM.Infrastructure.WindowsApi;
+
+namespace GlazeWM.Domain.Containers.Commands
+{
+ public class FocusContainerUnderCursorCommand : Command
+ {
+ public Point TargetPoint { get; }
+ public FocusContainerUnderCursorCommand(Point targetPoint)
+ {
+ TargetPoint = targetPoint;
+ }
+ }
+}
diff --git a/GlazeWM.Domain/DependencyInjection.cs b/GlazeWM.Domain/DependencyInjection.cs
index 4fbe6613..3fc68a5b 100644
--- a/GlazeWM.Domain/DependencyInjection.cs
+++ b/GlazeWM.Domain/DependencyInjection.cs
@@ -79,6 +79,7 @@ namespace GlazeWM.Domain
services.AddSingleton<ICommandHandler<FocusWorkspaceCommand>, FocusWorkspaceHandler>();
services.AddSingleton<ICommandHandler<FocusWorkspaceRecentCommand>, FocusWorkspaceRecentHandler>();
services.AddSingleton<ICommandHandler<FocusWorkspaceSequenceCommand>, FocusWorkspaceSequenceHandler>();
+ services.AddSingleton<ICommandHandler<FocusContainerUnderCursorCommand>, FocusContainerUnderCursorHandler>();
services.AddSingleton<ICommandHandler<MoveWindowToWorkspaceCommand>, MoveWindowToWorkspaceHandler>();
services.AddSingleton<ICommandHandler<UpdateWorkspacesFromConfigCommand>, UpdateWorkspacesFromConfigHandler>();
services.AddSingleton<ICommandHandler<MoveWorkspaceInDirectionCommand>, MoveWorkspaceInDirectionHandler>();
diff --git a/GlazeWM.Domain/UserConfigs/GeneralConfig.cs b/GlazeWM.Domain/UserConfigs/GeneralConfig.cs
index bc27dd00..5e752711 100644
--- a/GlazeWM.Domain/UserConfigs/GeneralConfig.cs
+++ b/GlazeWM.Domain/UserConfigs/GeneralConfig.cs
@@ -12,6 +12,9 @@ namespace GlazeWM.Domain.UserConfigs
/// </summary>
public bool CursorFollowsFocus { get; set; }
/// <summary>
+ /// Focus the window directly under the cursor at all times
+ /// </summary>
+ public bool FocusFollowsCursor { get; set; }
/// Amount by which to move floating windows
/// </summary>
public string FloatingWindowMoveAmount { get; set; } = "5%";
diff --git a/GlazeWM.Infrastructure/WindowsApi/MouseEvents.cs b/GlazeWM.Infrastructure/WindowsApi/MouseEvents.cs
new file mode 100644
index 00000000..481d378f
--- /dev/null
+++ b/GlazeWM.Infrastructure/WindowsApi/MouseEvents.cs
@@ -0,0 +1,77 @@
+using System;
+using System.Diagnostics;
+using System.Reactive.Disposables;
+using System.Reactive.Linq;
+using System.Reactive.Subjects;
+using System.Runtime.InteropServices;
+using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;
+
+namespace GlazeWM.Infrastructure.WindowsApi
+{
+ public static class MouseEvents
+ {
+ public static IObservable<MouseMoveEvent> MouseMoves
+ {
+ get
+ {
+ var mouseEvents = new Subject<MouseMoveEvent>();
+
+ var isMouseDown = false;
+ var hookProc = new HookProc((nCode, wParam, lParam) =>
+ {
+ var details = (LowLevelMouseInputEventDetails)Marshal.PtrToStructure(
+ lParam,
+ typeof(LowLevelMouseInputEventDetails)
+ );
+
+ // Check if mouse click is being held.
+ switch ((WMessages)wParam)
+ {
+ case WMessages.WM_LBUTTONUP:
+ isMouseDown = false;
+ break;
+ case WMessages.WM_LBUTTONDOWN:
+ isMouseDown = true;
+ break;
+ }
+
+ var filteredEvent = new MouseMoveEvent(details.pt, isMouseDown, details.TimeStamp);
+
+ mouseEvents.OnNext(filteredEvent);
+
+ return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
+ });
+
+ var hookId = CreateHook(hookProc);
+
+ return Observable.Create<MouseMoveEvent>(observer =>
+ {
+ var subscription = mouseEvents.Subscribe(
+ mouseEvent => observer.OnNext(mouseEvent)
+ );
+
+ return Disposable.Create(() =>
+ {
+ // Unregister mouse hook on observable completion.
+ subscription.Dispose();
+ UnhookWindowsHookEx(hookId);
+ GC.KeepAlive(hookProc);
+ });
+ });
+ }
+ }
+
+ /// <summary>
+ /// Create a low-level mouse hook.
+ /// </summary>
+ private static IntPtr CreateHook(HookProc proc)
+ {
+ return SetWindowsHookEx(
+ HookType.MouseLowLevel,
+ proc,
+ Process.GetCurrentProcess().MainModule.BaseAddress,
+ 0
+ );
+ }
+ }
+}
diff --git a/GlazeWM.Infrastructure/WindowsApi/MouseMoveEvent.cs b/GlazeWM.Infrastructure/WindowsApi/MouseMoveEvent.cs
new file mode 100644
index 00000000..060f0ec0
--- /dev/null
+++ b/GlazeWM.Infrastructure/WindowsApi/MouseMoveEvent.cs
@@ -0,0 +1,91 @@
+using System;
+using System.Runtime.InteropServices;
+using GlazeWM.Infrastructure.Bussing;
+using GlazeWM.Infrastructure.WindowsApi;
+
+public class MouseMoveEvent : Event
+{
+ /// <summary>
+ /// (X,Y) location of mouse with 0,0 being the top-left corner of the main monitor
+ /// </summary>
+ public Point Point { get; }
+
+ /// <summary>
+ /// Whether left-click is currently pressed.
+ /// </summary>
+ public bool IsMouseDown { get; }
+
+ /// <summary>
+ /// The time stamp for this message, equivalent to what `GetMessageTime` would
+ /// return.
+ /// </summary>
+ public int TimeStamp { get; }
+
+ public MouseMoveEvent(Point point, bool isMouseDown, int timeStamp)
+ {
+ Point = point;
+ IsMouseDown = isMouseDown;
+ TimeStamp = timeStamp;
+ }
+}
+
+
+public enum WMessages
+{
+ WM_MOUSEMOVE = 0x0200,
+ WM_LBUTTONDOWN = 0x201,
+ WM_LBUTTONUP = 0x202,
+ WM_RBUTTONDOWN = 0x0204,
+ WM_RBUTTONUP = 0x0205,
+ WM_KEYDOWN = 0x100,
+ WM_KEYUP = 0x101,
+ WH_KEYBOARD_LL = 13,
+ WH_MOUSE_LL = 14,
+}
+[StructLayout(LayoutKind.Sequential)]
+public struct LowLevelMouseInputEvent
+{
+ /// <summary>
+ /// Mouse event details.
+ /// </summary>
+ public LowLevelMouseInputEventDetails lParam;
+
+ /// <summary>
+ /// Determines how to process the event.
+ /// </summary>
+ public int nCode;
+
+ /// <summary>
+ /// Identify type of event.
+ /// </summary>
+ public WMessages wParam;
+}
+
+[StructLayout(LayoutKind.Sequential)]
+public struct LowLevelMouseInputEventDetails
+{
+ /// <summary>
+ /// (X,Y) location of mouse with 0,0 being the top-left corner of the main monitor
+ /// </summary>
+ public Point pt;
+
+ /// <summary>
+ /// Mouse data.
+ /// </summary>
+ public int mouseData;
+
+ /// <summary>
+ /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
+ /// </summary>
+ public int Flags;
+
+ /// <summary>
+ /// The time stamp for this message, equivalent to what GetMessageTime would return for this message.
+ /// </summary>
+ public int TimeStamp;
+
+ /// <summary>
+ /// Additional information associated with the message.
+ /// </summary>
+ public IntPtr dwExtraInfo;
+}
diff --git a/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.cs b/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.cs
index 0263a439..092121b4 100644
--- a/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.cs
+++ b/GlazeWM.Infrastructure/WindowsApi/WindowsApiService.cs
@@ -228,6 +228,12 @@ namespace GlazeWM.Infrastructure.WindowsApi
[DllImport("user32.dll")]
public static extern bool SetFocus(IntPtr hWnd);
+ [DllImport("user32.dll")]
+ public static extern IntPtr WindowFromPoint(Point Point);
+
+ [DllImport("user32.dll")]
+ public static extern IntPtr GetParent(IntPtr hWnd);
+
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int x, int y);
@@ -361,6 +367,9 @@ namespace GlazeWM.Infrastructure.WindowsApi
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx([Optional] IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
+ [DllImport("user32.dll")]
+ public static extern bool UnhookWindowsHookEx(IntPtr hhk);
+
[DllImport("user32.dll")]
public static extern int GetKeyboardState(byte[] pbKeyState);