diff --git a/AGENTS.md b/AGENTS.md index f6c4aec..7774122 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,7 +29,7 @@ Single test / focused run: hotkeys, reload flow, and Command Overlay) or run targeted helper tools in `tools/`. - Focused validation (pick relevant items): - Launch `harken.ahk` with a clean config and verify: super hotkeys, window cycling, overlay. - - If virtual desktops touched: test `super+alt+h/l`, mapped desktop hotkeys, and tray indicator. + - If virtual desktops touched: test `super+j/k`, `super+shift+j/k`, mapped desktop hotkeys, and tray indicator. ## Code Style Guidelines diff --git a/CHANGELOG.md b/CHANGELOG.md index ddca95d..ac2d3f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,21 +12,38 @@ All notable changes to this project are documented here. This changelog is human - Virtual desktop scroll navigation and move-window scroll support (`super+scroll` & `super+alt+shift+scroll`). - Optional desktop switch curtain to mask brief background flashes. - Project now uses CHANGELOG.md +- Optional `modes.carousel` mode with niri-like horizontal focus/move behavior scoped to current virtual desktop and active monitor. +- Carousel mode desktop move follow toggle (`super+f`) and native overview shortcut (`super+o`). +- Carousel mode width controls (`super+-` / `super+=`) and auto-maintained trailing empty desktop support. +- Persistent carousel status bar with desktop count, active desktop highlight, and current strip window titles. +- `[[virtual_desktop.N]]` desktop mappings now support `super+` goto and `super+alt+` no-follow window expel. ### Changed -- Double-super now opens native Task View; move mode is entered from command mode, and h/j/k/l navigate Task View. +- Default non-carousel hotkeys now follow a niri-like layout: `super+h/l` focus, `super+j/k` desktop navigation, `super+ctrl+h/j/k/l` window movement, and `super+shift+j/k` window-to-desktop moves. +- Centered resize moved to `super+alt+arrows`; monitor focus/move now uses `super+u/i` and `super+shift+u/i`. +- Legacy `super+alt+h/l` and `super+alt+shift+h/l` virtual desktop defaults are disabled, while config support remains. +- Double-super overview is now disabled by default and can be restored with `window.super_double_tap_action = "overview"`. +- Move mode is entered from command mode, and h/j/k/l navigate Task View. - Super+scroll switches virtual desktops (replacing the prior super+alt+scroll combo). - Config flow favors `config_watch` instead of a dedicated reload section. - Example config updates (apps list and focus border thickness). - App matching now uses cached window metadata and PID-based lookups for off-desktop windows, with focus diagnostics logging. - README adds a comparison section with similar tools. - Config validation favors warnings over hard errors where possible. +- Window manager grid movement hotkeys yield to carousel mode when active. +- Carousel mode now auto-relayouts after external focus changes (Task View selection and app focus hotkeys). +- Carousel tile width adjustments now persist per app executable across restarts. +- Carousel strip order now restores best-effort per desktop+monitor scope using app executable order. +- Non-carousel desktop switching can now skip the post-switch wait for faster focus changes, and trailing empty desktop management now creates and prunes desktops to keep exactly one empty desktop at the end. +- Status bar enablement is now controlled globally from `virtual_desktop.status_bar`, with optional visibility in non-carousel mode. ### Fixed +- Mapped desktop hotkeys now use true super-combo registration so `super+1/2/3/4/5` works with CapsLock/F24 super keys. - Window walker rendering issues when the resolution changes. - Window cycling now includes more than two tiles reliably. - Grid snapping edge cases. - EnumWindows callback signature. +- UI Automation no longer sets the Windows screen-reader flag, avoiding PowerShell PSReadLine warnings. ## [0.2.1] - 2026-02-07 ### Added diff --git a/README.md b/README.md index a2e4a59..1db4c49 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Harken allows a keyboard-centered workflow on Windows: a single super modifier, -Launch-or-focus a program with `super + [letter]`, or directionally change window focus with `alt + h/l/j/k` (left, right, down, up) and `alt + [` / `alt + ]` for back/forward in a stack. +Launch-or-focus a program with `super + [letter]`, or directionally change window focus with `super + h/l` (left/right) and `super + [` / `super + ]` for back/forward in a stack. ![Alt text](docs/assets/focus.gif) Cycle centered window widths with `super + spacebar`. @@ -49,15 +49,17 @@ Cycle centered window widths with `super + spacebar`. Maximizes/restores with `super + m`. ![Alt text](docs/assets/maximize.gif) -Move a window with `super + h/j/k/l`. +Move a window with `super + ctrl + h/j/k/l`. ![Alt text](docs/assets/move.gif) -Freely move a window with double tap super + h/j/k/l +Freely move a window from command mode, then use h/j/k/l. ![Alt text](docs/assets/free-move.gif) -Resize edges with `super + shift + h/j/k/l`. +Resize edges with `super + arrows`. ![Alt text](docs/assets/resize.gif) +Resize from the center with `super + alt + arrows`. + Show the [Command Overlay](#command-overlay) when the super key is held. Disable through command mode. ![Alt text](docs/assets/command_overlay.png) @@ -69,14 +71,13 @@ Other - `super + c` cycle through windows of the same app - `super + shift + c` cycle through windows of the same app on the current desktop - `super + .` screen search (click hints) -- `super + alt + h/l` switch to previous/next virtual desktop -- `super + alt + shift + h/l` move the active window to previous/next desktop (follow) +- `super + j/k` switch to next/previous virtual desktop +- `super + shift + j/k` move the active window to next/previous desktop (follow) - `super + w` open Window Selector (fuzzy find open windows) -- `alt + h/l` move window focus left/right -- `alt + j/k` move window focus down/up (non-stacked) -- `alt + [` / `alt + ]` move window focus forward/back through stacked windows -- `super + alt + h/l` to move between desktops -- `super + shift + alt + h/l` send current tile to adjacent desktop +- `super + h/l` move window focus left/right +- `super + [` / `super + ]` move window focus forward/back through stacked windows +- `super + u/i` focus previous/next monitor +- `super + shift + u/i` move the active window to previous/next monitor Enter Command Mode with `super + ;`. - `r` to reload program/config @@ -152,9 +153,39 @@ Add `debug = true` under `match.process_tree` to log process tree details to | `super + m` | Maximize/un-maximize | | `alt + q` | Close window | | `super + Left/Right/Up/Down` | Resize window and snap to grids | -| `super + shift + h/j/k/l` | Resize centered | -| `super + ctrl + h/j/k/l` | Move window | -| `super` (double tap) | Toggle move mode | +| `super + alt + Left/Right/Up/Down` | Resize centered | +| `super + ctrl + h/j/k/l` | Move/snap window | +| `super + u/i` | Focus previous/next monitor | +| `super + shift + u/i` | Move window to previous/next monitor | +| `super + o` | Open native Task View overview | +| `window.super_double_tap_action = "overview"` | Optionally make double-super open native Task View overview | + +When `modes.active = "carousel"` and `modes.carousel.enabled = true`, these key behaviors change: + +| Shortcut | Action | +| --- | --- | +| `super + h/l` | Carousel focus left/right (current desktop + active monitor) | +| `super + shift + h/l` | Move carousel order left/right | +| `super + j/k` | Next/previous virtual desktop | +| `super + shift + j/k` | Move focused window to next/previous desktop | +| `super + space` | Center active tile on demand | +| `super + - / =` | Decrease/increase focused tile width | +| `super + o` | Open native Task View overview | +| `super + f` | Toggle desktop move follow behavior | + +Carousel mode also maintains one trailing empty virtual desktop when +`modes.carousel.ensure_empty_desktop = true`. + +The desktop status bar is globally enabled through `virtual_desktop.status_bar.enabled`. +Set `virtual_desktop.status_bar.show_in_non_carousel = true` to show it outside carousel mode too. +Carousel mode adds the current desktop's window strip using the appearance settings under +`modes.carousel.status_bar` such as `window_display`. +Status bar design inspiration: EngineeringMechanicsB's AHKVirtualDesktop project. + +Carousel mode also does best-effort persistence for per-app tile width and strip order. +Order restore is keyed by `desktop:monitor` scope and app executable name, so it cannot +distinguish multiple windows from the same executable across restarts, and restore quality +can degrade when desktop indices or monitor numbering change. #### Window management (Move mode) @@ -163,27 +194,30 @@ Add `debug = true` under `match.process_tree` to log process tree details to | `h/j/k/l` | Move window | | `Esc` or `super` | Exit move mode | -#### Focus navigation (Alt) +#### Focus navigation | Shortcut | Action | | --- | --- | -| `alt + h/l` | Focus left/right | -| `alt + j/k` | Focus down/up | -| `alt + [` / `alt + ]` | Cycle stacked (prev/next) | +| `super + h/l` | Focus left/right | +| `super + [` / `super + ]` | Cycle stacked (prev/next) | #### Virtual desktops | Shortcut | Action | | --- | --- | -| `super + alt + h/l` | Previous/next desktop | +| `super + j/k` | Next/previous desktop | | `super + WheelUp/WheelDown` | Previous/next desktop (when `virtual_desktop.scroll_switch = true`) | -| `super + alt + shift + h/l` | Move window to previous/next desktop (follow) | +| `super + shift + j/k` | Move window to next/previous desktop (follow) | | `super + alt + shift + WheelUp/WheelDown` | Move window to previous/next desktop (when `virtual_desktop.scroll_switch = true`) | -| `super + alt + ` | Go to mapped desktop (`[[virtual_desktop.]]`) | +| `super + ` | Go to mapped desktop (`[[virtual_desktop.]]`) | +| `super + alt + ` | Expel window to mapped desktop without following | | `super + alt + shift + ` | Move window to mapped desktop (follow) | +| `virtual_desktop.fast_switch_non_carousel` | Skip the post-switch wait in non-carousel mode for faster desktop focus changes | +| `virtual_desktop.ensure_trailing_empty` | Keep exactly one trailing empty virtual desktop by creating and pruning as needed | | `virtual_desktop.auto_assign` | Move newly created windows that match `apps[]` with `desktop` set | | `virtual_desktop.debug_focus` | Log cross-desktop focus attempts to `%APPDATA%\harken\vd.focus.debug.log` | | `virtual_desktop.switch_curtain` | Dim overlay during desktop switches to reduce flicker | +| `virtual_desktop.status_bar` | Global desktop status bar enablement; `show_in_non_carousel` extends it beyond carousel mode | #### Apps (defaults) @@ -282,7 +316,7 @@ GlazeWM is another popular tiling window manager for Windows operating systems. | --- | --- | --- | --- | --- | | Primary interaction model | Keyboard-first hotkeys and commands | Zone-based snapping (mouse + keyboard) | Dynamic tiling WM | Dynamic tiling WM | | Launch-or-focus app hotkeys | Yes (configurable per app) | No (outside scope) | Possible via external tooling/scripts | Possible via external tooling/scripts | -| Directional focus movement | Yes (`alt + h/j/k/l`) | No | Yes | Yes | +| Directional focus movement | Yes (`super + h/l`) | No | Yes | Yes | | Stack/window cycling | Yes (`super + [` / `super + ]`, app cycling) | Mostly | Yes (tiling containers/workspaces) | Yes (tiling containers/workspaces) | | Virtual desktop hotkeys | Yes (native desktop integration) | Indirect (PowerToys + Windows shortcuts) | Yes | Yes | | Freeform floating adjustments | Yes (move mode + resize controls) | Primarily zone snapping | Primarily tiling; floating is secondary | Primarily tiling; floating is secondary | diff --git a/config/config.example.toml b/config/config.example.toml index d7af86b..bf86879 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -126,6 +126,8 @@ send_keys = "^{Tab}" resize_step = 20 move_step = 20 super_double_tap_ms = 300 +# "overview" opens native Task View; "" disables double-super. +super_double_tap_action = "" # Cycle app windows across all desktops. cycle_app_windows_hotkey = "+c" @@ -189,6 +191,8 @@ bottom = 5 enabled = true switch_on_focus = true ensure_count = 0 +ensure_trailing_empty = true +fast_switch_non_carousel = true cycle_prefer_current = true # Optional mouse wheel switching (super+wheel). @@ -201,12 +205,17 @@ enabled = true opacity = 204 color = "#202020" -# Hotkey fields here use AHK syntax without super (super is implied). -# Modifiers are applied by Harken (alt or alt+shift) for desktop actions. -prev_hotkey = "h" -next_hotkey = "l" -move_prev_hotkey = "h" -move_next_hotkey = "l" +[virtual_desktop.status_bar] +enabled = true +# Show the desktop bar outside carousel mode too. +show_in_non_carousel = false + +# Legacy super+alt desktop hotkeys are supported but disabled by default. +# The default workspace model uses super+j/k and super+shift+j/k instead. +prev_hotkey = "" +next_hotkey = "" +move_prev_hotkey = "" +move_next_hotkey = "" # Debug logs write to %APPDATA%\harken when enabled. debug_cycle = false @@ -220,12 +229,23 @@ tray_format = "{current}/{total}" # auto_assign = false # auto_assign_interval_ms = 500 +# Mapped desktop hotkeys use super+ for goto, super+alt+ +# for quick no-follow moves, and super+alt+shift+ to move and follow. [[virtual_desktop.1]] hotkey = "1" [[virtual_desktop.2]] hotkey = "2" +[[virtual_desktop.3]] +hotkey = "3" + +[[virtual_desktop.4]] +hotkey = "4" + +[[virtual_desktop.5]] +hotkey = "5" + # ------------------------------------------------------------- # Directional focus # ------------------------------------------------------------- @@ -242,6 +262,74 @@ perpendicular_overlap_min = 0.2 cross_monitor = false debug_enabled = false +# ------------------------------------------------------------- +# Modes (optional) +# ------------------------------------------------------------- + +[modes] +# "carousel" enables niri-like horizontal focus/move behavior. +# Use "" to keep the default grid-oriented movement keys. +active = "" + +[modes.carousel] +enabled = false +# niri-like default: do not auto-center on every focus change. +# Use super+space to center the active tile on demand. +auto_snap_center_on_focus = false +center_width_ratio = 0.5 +side_width_ratio = 0.25 +width_step = 0.05 +gap_px = 12 +wrap_enabled = false +include_minimized = false +excluded_apps = ["PowerToys.PowerLauncher.exe"] +# offscreen | stack_peek +overflow_policy = "offscreen" +# Keep tile sizes stable when focus changes. +resize_on_focus = false +# Skip tiny move/resize diffs to reduce jitter. +layout_epsilon_px = 8 +# Keep focused tile away from hard viewport edges while scrolling. +scroll_reveal_margin_px = 80 +ensure_empty_desktop = true +# Experimental: use native Windows API to reorder desktop indices. +native_desktop_reorder = false +# super+shift+j/k move-to-desktop follows focus when true. +desktop_move_follows_focus = true +focus_left_hotkey = "h" +focus_right_hotkey = "l" +move_left_hotkey = "+h" +move_right_hotkey = "+l" +desktop_prev_hotkey = "k" +desktop_next_hotkey = "j" +desktop_move_prev_hotkey = "+k" +desktop_move_next_hotkey = "+j" +desktop_reorder_up_hotkey = "^+k" +desktop_reorder_down_hotkey = "^+j" +overview_hotkey = "o" +center_hotkey = "Space" +width_decrease_hotkey = "-" +width_increase_hotkey = "=" +toggle_follow_hotkey = "f" +debug_enabled = false + +[modes.carousel.status_bar] +# top | bottom +position = "top" +height_px = 34 +# Reserve extra pixels so carousel tiles do not sit under the bar. +reserve_gap_px = 4 +# 0-255 +opacity = 220 +background_color = "#181818" +text_color = "#CCCCCC" +active_color = "#A020F0" +font_size = 10 +# Max title characters per window in strip preview. +title_max_len = 26 +# title | icon +window_display = "icon" + # ------------------------------------------------------------- # Focus border # ------------------------------------------------------------- diff --git a/harken.ahk b/harken.ahk index a32bdae..815ecc4 100644 --- a/harken.ahk +++ b/harken.ahk @@ -9,6 +9,8 @@ #Include src/lib/virtual_desktop.ahk #Include src/lib/focus_or_run.ahk #Include src/lib/command_toast.ahk +; Avoid advertising harken as a screen reader; PowerShell disables PSReadLine when this flag is set. +IUIAutomationActivateScreenReader := 0 #Include src/lib/UIA.ahk #Include src/lib/screen_search.ahk #Include src/lib/window_inspector.ahk @@ -39,7 +41,7 @@ super_keys := Config["super_key"] if !(super_keys is Array) super_keys := [super_keys] -RegisterSuperKeyHotkey("~", "", (*) => OnSuperKeyDown()) +RegisterSuperKeyDownHotkeys() if HasSuperKey("CapsLock") SetCapsLockState "AlwaysOff" @@ -64,16 +66,21 @@ SetWinDelay(-1) #Include src/lib/window_manager.ahk #Include src/lib/directional_focus.ahk +#Include src/lib/carousel_mode.ahk +#Include src/lib/carousel_status_bar.ahk #Include src/lib/focus_border.ahk #Include src/lib/window_walker.ahk #Include src/hotkeys/global_hotkey.ahk #Include src/hotkeys/apps.ahk #Include src/hotkeys/window.ahk +#Include src/hotkeys/carousel.ahk #Include src/hotkeys/directional_focus.ahk #Include src/hotkeys/window_walker.ahk #Include src/hotkeys/screen_search.ahk #Include src/hotkeys/unbound.ahk +SetTimer((*) => InitCarouselStatusBar(), -200) + DefaultConfig() { return Map( "config_version", 1, @@ -96,6 +103,7 @@ DefaultConfig() { "resize_step", 20, "move_step", 20, "super_double_tap_ms", 300, + "super_double_tap_action", "", "move_mode", Map( "enable", true, "cancel_key", "Esc" @@ -144,6 +152,8 @@ DefaultConfig() { "enabled", true, "switch_on_focus", true, "ensure_count", 0, + "ensure_trailing_empty", true, + "fast_switch_non_carousel", true, "cycle_prefer_current", true, "scroll_switch", false, "switch_curtain", Map( @@ -151,10 +161,14 @@ DefaultConfig() { "opacity", 204, "color", "#202020" ), - "prev_hotkey", "h", - "next_hotkey", "l", - "move_prev_hotkey", "h", - "move_next_hotkey", "l", + "status_bar", Map( + "enabled", true, + "show_in_non_carousel", false + ), + "prev_hotkey", "", + "next_hotkey", "", + "move_prev_hotkey", "", + "move_next_hotkey", "", "desktop_hotkeys", [], "goto_hotkeys", [], "move_hotkeys", [], @@ -177,6 +191,56 @@ DefaultConfig() { "cross_monitor", false, "debug_enabled", false ), + "modes", Map( + "active", "", + "carousel", Map( + "enabled", false, + "auto_snap_center_on_focus", false, + "center_width_ratio", 0.5, + "side_width_ratio", 0.25, + "width_step", 0.05, + "gap_px", 12, + "wrap_enabled", false, + "include_minimized", false, + "excluded_apps", [], + "overflow_policy", "offscreen", + "resize_on_focus", false, + "layout_epsilon_px", 8, + "scroll_reveal_margin_px", 80, + "ensure_empty_desktop", true, + "native_desktop_reorder", false, + "desktop_move_follows_focus", true, + "focus_left_hotkey", "h", + "focus_right_hotkey", "l", + "move_left_hotkey", "+h", + "move_right_hotkey", "+l", + "desktop_prev_hotkey", "k", + "desktop_next_hotkey", "j", + "desktop_move_prev_hotkey", "+k", + "desktop_move_next_hotkey", "+j", + "desktop_reorder_up_hotkey", "^+k", + "desktop_reorder_down_hotkey", "^+j", + "overview_hotkey", "o", + "center_hotkey", "Space", + "width_decrease_hotkey", "-", + "width_increase_hotkey", "=", + "toggle_follow_hotkey", "f", + "status_bar", Map( + "enabled", true, + "position", "top", + "height_px", 34, + "reserve_gap_px", 4, + "opacity", 220, + "background_color", "#181818", + "text_color", "#CCCCCC", + "active_color", "#A020F0", + "font_size", 10, + "title_max_len", 26, + "window_display", "icon" + ), + "debug_enabled", false + ) + ), "focus_border", Map( "enabled", true, "border_color", "#357EC7", @@ -471,6 +535,15 @@ RegisterSuperKeyHotkey(prefix, suffix, callback) { Hotkey(prefix key suffix, callback) } +RegisterSuperKeyDownHotkeys() { + global super_keys + for _, key in super_keys { + ; F24 is often used as a hardware-level Super key and should not leak to focused apps. + prefix := StrLower(key) = "f24" ? "*" : "~" + Hotkey(prefix key, (*) => OnSuperKeyDown()) + } +} + RegisterSuperComboHotkey(hotkey_name, callback) { global super_keys for _, key in super_keys diff --git a/src/hotkeys/carousel.ahk b/src/hotkeys/carousel.ahk new file mode 100644 index 0000000..86a908c --- /dev/null +++ b/src/hotkeys/carousel.ahk @@ -0,0 +1,36 @@ +; Carousel mode hotkeys. +global Config + +if CarouselModeEnabled() { + carousel := Config["modes"]["carousel"] + + RegisterSuperComboHotkey(carousel["focus_left_hotkey"], (*) => CarouselHandleHorizontalKey("left")) + RegisterSuperComboHotkey(carousel["focus_right_hotkey"], (*) => CarouselHandleHorizontalKey("right")) + RegisterSuperComboHotkey(carousel["desktop_prev_hotkey"], (*) => CarouselHandleDesktopKey(-1)) + RegisterSuperComboHotkey(carousel["desktop_next_hotkey"], (*) => CarouselHandleDesktopKey(1)) + RegisterSuperComboHotkey(carousel["center_hotkey"], (*) => CarouselRelayout("center")) + RegisterSuperComboHotkey(carousel["width_decrease_hotkey"], (*) => CarouselAdjustCenterWidth(-1)) + RegisterSuperComboHotkey(carousel["width_increase_hotkey"], (*) => CarouselAdjustCenterWidth(1)) + RegisterSuperComboHotkey(carousel["overview_hotkey"], CarouselOpenOverview) + if (carousel["toggle_follow_hotkey"] != "") + RegisterSuperComboHotkey(carousel["toggle_follow_hotkey"], (*) => ToggleCarouselDesktopMoveFollow()) + + ; Snap windows into carousel layout shortly after startup/reload. + SetTimer((*) => CarouselRelayout("startup"), -150) + SetTimer(CarouselFocusWatcherTick, 250) + SetTimer((*) => EnsureCarouselTrailingEmptyDesktop(), -600) +} + +CarouselHandleHorizontalKey(direction) { + if !CarouselModeEnabled() || Window.IsMoveMode() + return + if IsAltPressed() + return + if GetKeyState("Ctrl", "P") + return + if GetKeyState("Shift", "P") { + CarouselMove(direction) + return + } + CarouselFocus(direction) +} diff --git a/src/hotkeys/directional_focus.ahk b/src/hotkeys/directional_focus.ahk index 52763dc..b6361d8 100644 --- a/src/hotkeys/directional_focus.ahk +++ b/src/hotkeys/directional_focus.ahk @@ -2,14 +2,13 @@ global Config if Config.Has("directional_focus") && Config["directional_focus"]["enabled"] { - HotIf (*) => !IsSuperKeyPressed() - Hotkey("!h", (*) => DirectionalFocus("left")) - Hotkey("!l", (*) => DirectionalFocus("right")) - Hotkey("!j", (*) => DirectionalFocus("down")) - Hotkey("!k", (*) => DirectionalFocus("up")) - Hotkey("![", (*) => DirectionalFocusStacked("prev")) - Hotkey("!]", (*) => DirectionalFocusStacked("next")) - Hotkey("!+d", (*) => ToggleDirectionalFocusDebug()) - Hotkey("!+s", (*) => SetLastStackedFromActive()) + HotIf (*) => IsSuperKeyPressed() && !IsAltPressed() && !GetKeyState("Ctrl", "P") && !GetKeyState("Shift", "P") + Hotkey("h", (*) => DirectionalFocus("left")) + Hotkey("l", (*) => DirectionalFocus("right")) + Hotkey("[", (*) => DirectionalFocusStacked("prev")) + Hotkey("]", (*) => DirectionalFocusStacked("next")) + HotIf (*) => IsSuperKeyPressed() && !IsAltPressed() && GetKeyState("Ctrl", "P") && GetKeyState("Shift", "P") + Hotkey("^+d", (*) => ToggleDirectionalFocusDebug()) + Hotkey("^+s", (*) => SetLastStackedFromActive()) HotIf } diff --git a/src/hotkeys/unbound.ahk b/src/hotkeys/unbound.ahk index 8d945cd..bd32bbc 100644 --- a/src/hotkeys/unbound.ahk +++ b/src/hotkeys/unbound.ahk @@ -17,6 +17,25 @@ RegisterUnboundHotkeys() { AddUsedKey(used_keys, "o") AddUsedKey(used_keys, "n") + if CarouselModeEnabled() { + carousel := Config["modes"]["carousel"] + AddUsedKey(used_keys, carousel["focus_left_hotkey"]) + AddUsedKey(used_keys, carousel["focus_right_hotkey"]) + AddUsedKey(used_keys, carousel["move_left_hotkey"]) + AddUsedKey(used_keys, carousel["move_right_hotkey"]) + AddUsedKey(used_keys, carousel["desktop_prev_hotkey"]) + AddUsedKey(used_keys, carousel["desktop_next_hotkey"]) + AddUsedKey(used_keys, carousel["desktop_move_prev_hotkey"]) + AddUsedKey(used_keys, carousel["desktop_move_next_hotkey"]) + AddUsedKey(used_keys, carousel["desktop_reorder_up_hotkey"]) + AddUsedKey(used_keys, carousel["desktop_reorder_down_hotkey"]) + AddUsedKey(used_keys, carousel["overview_hotkey"]) + AddUsedKey(used_keys, carousel["center_hotkey"]) + AddUsedKey(used_keys, carousel["width_decrease_hotkey"]) + AddUsedKey(used_keys, carousel["width_increase_hotkey"]) + AddUsedKey(used_keys, carousel["toggle_follow_hotkey"]) + } + if Config.Has("screen_search") && Config["screen_search"]["enabled"] AddUsedKey(used_keys, Config["screen_search"]["hotkey"]) diff --git a/src/hotkeys/window.ahk b/src/hotkeys/window.ahk index 414808f..5cda636 100644 --- a/src/hotkeys/window.ahk +++ b/src/hotkeys/window.ahk @@ -3,6 +3,7 @@ global Config resize_step := Config["window"]["resize_step"] move_step := Config["window"]["move_step"] super_double_tap_ms := Config["window"]["super_double_tap_ms"] +super_double_tap_action := Config["window"].Has("super_double_tap_action") ? Config["window"]["super_double_tap_action"] : "" move_mode_enabled := Config["window"]["move_mode"]["enable"] move_mode_cancel_key := Config["window"]["move_mode"]["cancel_key"] ; Window hotkeys (resize/move/cycle) and virtual desktop bindings. @@ -70,9 +71,6 @@ ResizeActiveWindowCentered(delta_w, delta_h) { if !hwnd || Window.IsException("ahk_id " hwnd) return - if IsAltPressed() || AltPressedSoon() - return - if (WinGetMinMax("ahk_id " hwnd) = 1) WinRestore "ahk_id " hwnd @@ -452,6 +450,35 @@ RegisterDesktopHotkey(kind, hotkey_name, desktop_num, callback) { )) } +RegisterMappedDesktopHotkey(hotkey_name, desktop_num) { + if (hotkey_name = "") + return + RegisterSuperComboHotkey(hotkey_name, (*) => HandleMappedDesktopHotkey(hotkey_name, desktop_num)) +} + +HandleMappedDesktopHotkey(hotkey_name, desktop_num) { + alt_pressed := IsAltPressed() + shift_pressed := GetKeyState("Shift", "P") + + if (alt_pressed && shift_pressed) { + LogVirtualDesktopAction("move_absolute hotkey=" hotkey_name " desktop=" desktop_num " current=" GetCurrentDesktopNumFresh()) + MoveWindowToDesktopNumber(desktop_num) + return + } + + if (alt_pressed) { + LogVirtualDesktopAction("move_absolute_no_follow hotkey=" hotkey_name " desktop=" desktop_num " current=" GetCurrentDesktopNumFresh()) + MoveWindowToDesktopNumberNoFollow(desktop_num) + return + } + + if (shift_pressed) + return + + LogVirtualDesktopAction("goto_absolute_super hotkey=" hotkey_name " desktop=" desktop_num " current=" GetCurrentDesktopNumFresh()) + GoToDesktopNumber(desktop_num) +} + GetCycleDebugDir() { appdata := EnvGet("APPDATA") if appdata @@ -507,7 +534,7 @@ BuildCycleWindowList(exe, win_list) { } HandleSuperTap() { - global last_super_tap, super_double_tap_ms + global last_super_tap, super_double_tap_ms, super_double_tap_action if Window.IsMoveMode() { Window.SetMoveMode(false) @@ -516,8 +543,8 @@ HandleSuperTap() { } if (A_TickCount - last_super_tap <= super_double_tap_ms) { - ; Use native overview instead of move mode (heuristic detects Task View state). - Send("#{Tab}") + if (super_double_tap_action = "overview") + Send("#{Tab}") UpdateCommandToastVisibility() last_super_tap := 0 return @@ -797,15 +824,15 @@ GoToRelativeDesktop(delta) { return target := VD.modulusResolveDesktopNum(current + delta) LogVirtualDesktopAction("goto_relative current=" current " delta=" delta " target=" target) - RefreshVirtualDesktopState() curtain_visible := BeginDesktopSwitchCurtain() try { VD.goToDesktopNum(target) - VD.WaitDesktopSwitched(target) + WaitRelativeDesktopSwitch(target) } finally { EndDesktopSwitchCurtain(curtain_visible) } - RefreshVirtualDesktopState() + ScheduleEnsureVirtualDesktopTrailingEmpty() + try ScheduleCarouselStatusBarUpdate(80) } GoToDesktopNumber(desktop_num) { @@ -814,16 +841,25 @@ GoToDesktopNumber(desktop_num) { if (desktop_num <= 0) return LogVirtualDesktopAction("goto_absolute target=" desktop_num " current=" GetCurrentDesktopNumFresh()) - RefreshVirtualDesktopState() - GetCurrentDesktopNumFresh() curtain_visible := BeginDesktopSwitchCurtain() try { + EnsureDesktopExists(desktop_num) VD.goToDesktopNum(desktop_num) - VD.WaitDesktopSwitched(desktop_num) + WaitRelativeDesktopSwitch(desktop_num) } finally { EndDesktopSwitchCurtain(curtain_visible) } - RefreshVirtualDesktopState() + ScheduleEnsureVirtualDesktopTrailingEmpty() + try ScheduleCarouselStatusBarUpdate(80) +} + +WaitRelativeDesktopSwitch(target) { + if VirtualDesktopFastSwitchNonCarousel() { + ; Keep the new bindings responsive but do not return before VD state catches up. + VD.WaitDesktopSwitched(target, 250, 0) + return + } + VD.WaitDesktopSwitched(target) } MoveWindowToRelativeDesktop(delta) { @@ -845,7 +881,8 @@ MoveWindowToRelativeDesktop(delta) { } finally { EndDesktopSwitchCurtain(curtain_visible) } - RefreshVirtualDesktopState() + ScheduleEnsureVirtualDesktopTrailingEmpty() + try ScheduleCarouselStatusBarUpdate(80) } MoveWindowToDesktopNumber(desktop_num) { @@ -854,33 +891,60 @@ MoveWindowToDesktopNumber(desktop_num) { if (desktop_num <= 0) return LogVirtualDesktopAction("move_absolute target=" desktop_num " current=" GetCurrentDesktopNumFresh()) - RefreshVirtualDesktopState() - GetCurrentDesktopNumFresh() curtain_visible := BeginDesktopSwitchCurtain() try { + EnsureDesktopExists(desktop_num) VD.MoveWindowToDesktopNum("A", desktop_num, true) VD.WaitDesktopSwitched(desktop_num) } finally { EndDesktopSwitchCurtain(curtain_visible) } + ScheduleEnsureVirtualDesktopTrailingEmpty() + try ScheduleCarouselStatusBarUpdate(80) +} + +MoveWindowToDesktopNumberNoFollow(desktop_num) { + if !VirtualDesktopEnabled() + return + if (desktop_num <= 0) + return + LogVirtualDesktopAction("move_absolute_no_follow target=" desktop_num " current=" GetCurrentDesktopNumFresh()) + try { + EnsureDesktopExists(desktop_num) + VD.MoveWindowToDesktopNum("A", desktop_num, false) + } + ScheduleEnsureVirtualDesktopTrailingEmpty() + try ScheduleCarouselStatusBarUpdate(80) +} + +EnsureDesktopExists(desktop_num) { + if !VirtualDesktopEnabled() + return false + if (desktop_num <= 0) + return false RefreshVirtualDesktopState() + count := VD.getCount() + if (count >= desktop_num) + return false + VD.createUntil(desktop_num) + RefreshVirtualDesktopState() + return true } HotIf (*) => IsSuperKeyPressed() && !IsAltPressed() -Hotkey(center_cycle_hotkey, CenterWidthCycle) Hotkey("Left", (*) => ResizeActiveWindow(-resize_step, 0)) Hotkey("Right", (*) => ResizeActiveWindow(resize_step, 0)) Hotkey("Up", (*) => ResizeActiveWindow(0, -resize_step)) Hotkey("Down", (*) => ResizeActiveWindow(0, resize_step)) -Hotkey("+h", (*) => ResizeActiveWindowCentered(-resize_step, 0)) -Hotkey("+l", (*) => ResizeActiveWindowCentered(resize_step, 0)) -Hotkey("+j", (*) => ResizeActiveWindowCentered(0, -resize_step)) -Hotkey("+k", (*) => ResizeActiveWindowCentered(0, resize_step)) -Hotkey("^h", (*) => MoveActiveWindow(-move_step, 0)) -Hotkey("^l", (*) => MoveActiveWindow(move_step, 0)) -Hotkey("^j", (*) => MoveActiveWindow(0, move_step)) -Hotkey("^k", (*) => MoveActiveWindow(0, -move_step)) -HotIf IsSuperKeyPressed +if !CarouselModeEnabled() { + Hotkey(center_cycle_hotkey, CenterWidthCycle) +} +HotIf (*) => IsSuperKeyPressed() && IsAltPressed() && !GetKeyState("Ctrl", "P") && !GetKeyState("Shift", "P") +Hotkey("*Left", (*) => ResizeActiveWindowCentered(-resize_step, 0)) +Hotkey("*Right", (*) => ResizeActiveWindowCentered(resize_step, 0)) +Hotkey("*Up", (*) => ResizeActiveWindowCentered(0, -resize_step)) +Hotkey("*Down", (*) => ResizeActiveWindowCentered(0, resize_step)) +HotIf (*) => IsSuperKeyPressed() && !IsAltPressed() Hotkey("m", ToggleMaximize) Hotkey(cycle_app_windows_hotkey, CycleAppWindows) if (cycle_app_windows_current_hotkey != "") @@ -890,6 +954,35 @@ if (minimize_others_hotkey != "") Hotkey(minimize_others_hotkey, MinimizeOtherWindows) HotIf +if (vd_desktop_hotkeys is Array && vd_desktop_hotkeys.Length > 0) { + LogVirtualDesktopHotkeys("desktop_hotkeys_count=" vd_desktop_hotkeys.Length) + for _, entry in vd_desktop_hotkeys { + if !(entry is Map) + continue + if !entry.Has("hotkey") || !entry.Has("desktop") + continue + hotkey_name := entry["hotkey"] + desktop_num := entry["desktop"] + key_copy := hotkey_name + num_copy := desktop_num + RegisterMappedDesktopHotkey(key_copy, num_copy) + LogVirtualDesktopHotkeys("map desktop hotkey=" key_copy " desktop=" num_copy) + } +} + +HotIf (*) => IsSuperKeyPressed() && !IsAltPressed() && !GetKeyState("Ctrl", "P") && !GetKeyState("Shift", "P") +Hotkey("j", (*) => GoToRelativeDesktop(1)) +Hotkey("k", (*) => GoToRelativeDesktop(-1)) +Hotkey("u", (*) => FocusRelativeMonitor(-1)) +Hotkey("i", (*) => FocusRelativeMonitor(1)) +Hotkey("o", (*) => Send("#{Tab}")) +HotIf + +HotIf (*) => IsSuperKeyPressed() && !IsAltPressed() && !GetKeyState("Ctrl", "P") && GetKeyState("Shift", "P") +Hotkey("j", (*) => MoveWindowToRelativeDesktop(1)) +Hotkey("k", (*) => MoveWindowToRelativeDesktop(-1)) +HotIf + Hotkey("!q", CloseWindow) HotIf (*) => IsSuperKeyPressed() && IsAltPressed() && !GetKeyState("Shift", "P") @@ -919,24 +1012,6 @@ for _, entry in vd_goto_hotkeys { } LogVirtualDesktopHotkeys("map goto hotkey=" key_copy " desktop=" num_copy) } -if (vd_desktop_hotkeys is Array && vd_desktop_hotkeys.Length > 0) { - LogVirtualDesktopHotkeys("desktop_hotkeys_count=" vd_desktop_hotkeys.Length) - for _, entry in vd_desktop_hotkeys { - if !(entry is Map) - continue - if !entry.Has("hotkey") || !entry.Has("desktop") - continue - hotkey_name := NormalizeAltHotkey(entry["hotkey"]) - desktop_num := entry["desktop"] - key_copy := hotkey_name - num_copy := desktop_num - if (key_copy != "") { - callback := GoToDesktopNumber.Bind(num_copy) - RegisterDesktopHotkey("goto_absolute", key_copy, num_copy, callback) - } - LogVirtualDesktopHotkeys("map goto hotkey=" key_copy " desktop=" num_copy) - } -} HotIf HotIf (*) => IsSuperKeyPressed() && !GetKeyState("Shift", "P") @@ -990,24 +1065,6 @@ for _, entry in vd_move_hotkeys { } LogVirtualDesktopHotkeys("map move hotkey=" key_copy " desktop=" num_copy) } -if (vd_desktop_hotkeys is Array && vd_desktop_hotkeys.Length > 0) { - LogVirtualDesktopHotkeys("desktop_hotkeys_count=" vd_desktop_hotkeys.Length) - for _, entry in vd_desktop_hotkeys { - if !(entry is Map) - continue - if !entry.Has("hotkey") || !entry.Has("desktop") - continue - hotkey_name := NormalizeAltHotkey(entry["hotkey"], true) - desktop_num := entry["desktop"] - key_copy := hotkey_name - num_copy := desktop_num - if (key_copy != "") { - callback := MoveWindowToDesktopNumber.Bind(num_copy) - RegisterDesktopHotkey("move_absolute", key_copy, num_copy, callback) - } - LogVirtualDesktopHotkeys("map move hotkey=" key_copy " desktop=" num_copy) - } -} HotIf Hotkey("!-", MinimizeWindow) @@ -1127,3 +1184,53 @@ ActivateMostRecentWindow(exclude_hwnd := 0) { return } } + +FocusRelativeMonitor(delta) { + if (MonitorGetCount() < 2) + return + + active_hwnd := WinExist("A") + active_monitor := active_hwnd ? Screen.FromWindow("ahk_id " active_hwnd) : MonitorGetPrimary() + target_monitor := ResolveRelativeMonitor(active_monitor, delta) + if (target_monitor = active_monitor) + return + + for _, hwnd in WinGetList() { + if !IsFocusableMonitorWindow(hwnd) + continue + if (Screen.FromWindow("ahk_id " hwnd) != target_monitor) + continue + WinActivate "ahk_id " hwnd + return + } +} + +ResolveRelativeMonitor(current_monitor, delta) { + count := MonitorGetCount() + if (count <= 1) + return current_monitor + if (current_monitor <= 0 || current_monitor > count) + current_monitor := MonitorGetPrimary() + + target := current_monitor + delta + if (target < 1) + target := count + if (target > count) + target := 1 + return target +} + +IsFocusableMonitorWindow(hwnd) { + if !hwnd + return false + if Window.IsException("ahk_id " hwnd) + return false + if (WinGetMinMax("ahk_id " hwnd) = -1) + return false + ex_style := WinGetExStyle("ahk_id " hwnd) + if (ex_style & 0x80) || (ex_style & 0x8000000) + return false + if !(WinGetStyle("ahk_id " hwnd) & 0x10000000) + return false + return true +} diff --git a/src/lib/VD.ahk b/src/lib/VD.ahk index 4db1a12..3b68ad6 100644 --- a/src/lib/VD.ahk +++ b/src/lib/VD.ahk @@ -46,6 +46,7 @@ class VD { idx_GetDesktops:7, idx_SwitchDesktop:9, idx_CreateDesktop:10, + idx_MoveDesktop:-1, idx_RemoveDesktop:11, idx_FindDesktop:12, ; get/set @@ -73,6 +74,7 @@ class VD { idx_GetDesktops:7, idx_SwitchDesktop:9, idx_CreateDesktop:10, + idx_MoveDesktop:-1, idx_RemoveDesktop:11, idx_FindDesktop:12, ; get/set @@ -100,6 +102,7 @@ class VD { idx_GetDesktops:7, idx_SwitchDesktop:9, idx_CreateDesktop:10, + idx_MoveDesktop:-1, idx_RemoveDesktop:12, idx_FindDesktop:13, ; get/set @@ -127,6 +130,7 @@ class VD { idx_GetDesktops:8, idx_SwitchDesktop:10, idx_CreateDesktop:11, + idx_MoveDesktop:12, idx_RemoveDesktop:13, idx_FindDesktop:14, ; get/set @@ -154,6 +158,7 @@ class VD { idx_GetDesktops:7, idx_SwitchDesktop:9, idx_CreateDesktop:10, + idx_MoveDesktop:-1, idx_RemoveDesktop:12, idx_FindDesktop:13, ; get/set @@ -181,6 +186,7 @@ class VD { idx_GetDesktops:7, idx_SwitchDesktop:9, idx_CreateDesktop:10, + idx_MoveDesktop:11, idx_RemoveDesktop:12, idx_FindDesktop:13, ; get/set @@ -208,6 +214,7 @@ class VD { idx_GetDesktops:7, idx_SwitchDesktop:9, idx_CreateDesktop:11, + idx_MoveDesktop:12, idx_RemoveDesktop:13, idx_FindDesktop:14, ; get/set @@ -664,6 +671,21 @@ class VD { VD.IVirtualDesktopManagerInternal.SwitchDesktop(IVirtualDesktop_ofNewDesktop) } } + static moveDesktop(desktopNum, targetDesktopNum) { + if !VD.version.HasOwnProp("idx_MoveDesktop") || (VD.version.idx_MoveDesktop <= 0) + return false + VD.IVirtualDesktopListChanged() + count := VD.IVirtualDesktopList.Length + if (desktopNum < 1 || desktopNum > count) + return false + if (targetDesktopNum < 1 || targetDesktopNum > count) + return false + if (desktopNum = targetDesktopNum) + return true + VD.IVirtualDesktopManagerInternal.MoveDesktop(VD.IVirtualDesktopList[desktopNum], targetDesktopNum - 1) + VD.IVirtualDesktopListChanged() + return true + } static removeDesktop(desktopNum := VD.currentDesktopNum, fallback_desktopNum := -1) { if (VD.IVirtualDesktopList.Length == 1) { return ;can't delete last @@ -877,6 +899,11 @@ class VD { ComCall(this.version.idx_CreateDesktop, this.IVirtualDesktopManagerInternal, "Ptr*", &IVirtualDesktop_created := 0) return IVirtualDesktop_created } + MoveDesktop(IVirtualDesktop, zero_based_index) { + if !this.version.HasOwnProp("idx_MoveDesktop") || (this.version.idx_MoveDesktop <= 0) + throw Error("MoveDesktop is unavailable for this Windows build") + ComCall(this.version.idx_MoveDesktop, this.IVirtualDesktopManagerInternal, "Ptr", IVirtualDesktop, "Int", zero_based_index) + } RemoveDesktop(IVirtualDesktop, IVirtualDesktop_fallback) { ComCall(this.version.idx_RemoveDesktop, this.IVirtualDesktopManagerInternal, "Ptr", IVirtualDesktop, "Ptr", IVirtualDesktop_fallback) } @@ -1027,8 +1054,13 @@ class VD { VD.IVirtualDesktopListChanged() ; called after CurrentVirtualDesktopChanged } _common_CurrentVirtualDesktopChanged(IVirtualDesktop_old, IVirtualDesktop_new) { - desktopNum_old := VD.IVirtualDesktopMap[IVirtualDesktop_old] - VD.currentDesktopNum := VD.IVirtualDesktopMap[IVirtualDesktop_new] + desktopNum_old := VD.IVirtualDesktopMap.Has(IVirtualDesktop_old) ? VD.IVirtualDesktopMap[IVirtualDesktop_old] : 0 + desktopNum_new := VD.IVirtualDesktopMap.Has(IVirtualDesktop_new) ? VD.IVirtualDesktopMap[IVirtualDesktop_new] : 0 + if (desktopNum_new <= 0) { + VD.IVirtualDesktopListChanged() + desktopNum_new := VD.IVirtualDesktopMap.Has(IVirtualDesktop_new) ? VD.IVirtualDesktopMap[IVirtualDesktop_new] : VD.currentDesktopNum + } + VD.currentDesktopNum := desktopNum_new if (VD.WinActivate_callback) { VD.WinActivate_callback.Call() } diff --git a/src/lib/carousel_mode.ahk b/src/lib/carousel_mode.ahk new file mode 100644 index 0000000..b3491bb --- /dev/null +++ b/src/lib/carousel_mode.ahk @@ -0,0 +1,810 @@ +; Carousel mode helpers (niri-like horizontal focus/workflow per desktop+monitor). +global Config, AppState +global carousel_order_by_scope := Map() +global carousel_tile_width_ratio := Map() +global carousel_viewport_x_by_scope := Map() +global carousel_last_active_hwnd := 0 +global carousel_last_scope_key := "" +global carousel_last_active_by_scope := Map() +global carousel_last_relayout_tick := 0 +global carousel_ensure_empty_pending := false +global carousel_status_bar_update_pending := false + +IsCarouselModeActive() { + if !Config.Has("modes") || !(Config["modes"] is Map) + return false + if !Config["modes"].Has("active") + return false + return Config["modes"]["active"] = "carousel" +} + +CarouselModeEnabled() { + if !IsCarouselModeActive() + return false + if !Config["modes"].Has("carousel") || !(Config["modes"]["carousel"] is Map) + return false + return Config["modes"]["carousel"]["enabled"] +} + +CarouselDesktopMoveFollowsFocus() { + if !CarouselModeEnabled() + return true + return Config["modes"]["carousel"]["desktop_move_follows_focus"] +} + +ToggleCarouselDesktopMoveFollow() { + if !CarouselModeEnabled() + return + current := CarouselDesktopMoveFollowsFocus() + Config["modes"]["carousel"]["desktop_move_follows_focus"] := !current + LogCarouselDebug("toggle_follow enabled=" (!current)) + UpdateCommandToastVisibility() + CarouselStatusBarUpdate() +} + +CarouselOpenOverview(*) { + Send("#{Tab}") +} + +CarouselAdjustCenterWidth(delta) { + if !CarouselModeEnabled() + return + carousel := Config["modes"]["carousel"] + step := carousel["width_step"] + active_hwnd := WinGetID("A") + if !active_hwnd + return + center_ratio := GetTileCenterWidthRatio(active_hwnd) + delta * step + center_ratio := Min(0.9, Max(0.2, center_ratio)) + carousel_tile_width_ratio[active_hwnd] := center_ratio + PersistCarouselWidthPreference(active_hwnd, center_ratio) + LogCarouselDebug("width_adjust hwnd=" Format("0x{:X}", active_hwnd) " center=" Round(center_ratio, 3)) + CarouselRelayout("resize") +} + +CarouselFocus(direction) { + if !CarouselModeEnabled() + return + if (direction != "left" && direction != "right") + return + + state := BuildCarouselState() + if (state["windows"].Length < 2) + return + + active_hwnd := state["active_hwnd"] + current_index := CarouselIndexOf(state["windows"], active_hwnd) + if (current_index = 0) + current_index := 1 + + wrap := Config["modes"]["carousel"]["wrap_enabled"] + target_index := current_index + if (direction = "left") { + if (current_index <= 1) + target_index := wrap ? state["windows"].Length : 1 + else + target_index := current_index - 1 + } else { + if (current_index >= state["windows"].Length) + target_index := wrap ? 1 : state["windows"].Length + else + target_index := current_index + 1 + } + + target_hwnd := state["windows"][target_index] + if (target_hwnd = active_hwnd && !wrap) + return + + activated_hwnd := ActivateCarouselWindow(target_hwnd) + if activated_hwnd + state["active_hwnd"] := activated_hwnd + else + state["active_hwnd"] := target_hwnd + ; Always advance the carousel viewport on explicit carousel focus moves. + ; auto_snap_center_on_focus only controls passive/external focus changes. + CarouselRelayout("focus", state) +} + +CarouselMove(direction) { + if !CarouselModeEnabled() + return + if (direction != "left" && direction != "right") + return + + state := BuildCarouselState() + windows := state["windows"] + if (windows.Length < 2) + return + + active_hwnd := state["active_hwnd"] + current_index := CarouselIndexOf(windows, active_hwnd) + if (current_index = 0) + return + + wrap := Config["modes"]["carousel"]["wrap_enabled"] + target_index := current_index + if (direction = "left") { + if (current_index <= 1) + target_index := wrap ? windows.Length : 1 + else + target_index := current_index - 1 + } else { + if (current_index >= windows.Length) + target_index := wrap ? 1 : windows.Length + else + target_index := current_index + 1 + } + if (target_index = current_index) + return + + moving_hwnd := windows[current_index] + windows.RemoveAt(current_index) + windows.InsertAt(target_index, moving_hwnd) + SetCarouselScopeOrder(state["scope_key"], windows) + PersistCarouselScopeOrder(state["scope_key"], windows) + ActivateCarouselWindow(active_hwnd) + CarouselRelayout("move", state) +} + +CarouselRelayout(reason := "general", state := "") { + if !CarouselModeEnabled() + return + + if !(state is Map) + state := BuildCarouselState() + windows := state["windows"] + if (windows.Length = 0) + return + + active_hwnd := state["active_hwnd"] + active_index := CarouselIndexOf(windows, active_hwnd) + if (active_index = 0) + active_index := 1 + + metrics := GetCarouselMonitorMetrics(state["monitor_num"]) + if (metrics["w"] <= 0 || metrics["h"] <= 0) + return + + gap_px := Config["modes"]["carousel"]["gap_px"] + scope_key := state["scope_key"] + + col_x := [] + col_w := [] + cursor_x := 0 + for _, hwnd in windows { + width_px := GetTileWidthPx(hwnd, metrics["w"], gap_px) + col_x.Push(cursor_x) + col_w.Push(width_px) + cursor_x += width_px + gap_px + } + total_strip_width := Max(0, cursor_x - gap_px) + + active_start := col_x[active_index] + active_width := col_w[active_index] + active_end := active_start + active_width + viewport_x := carousel_viewport_x_by_scope.Has(scope_key) ? carousel_viewport_x_by_scope[scope_key] : 0 + reveal_margin := Config["modes"]["carousel"]["scroll_reveal_margin_px"] + max_margin := Max(0, Round((metrics["w"] - active_width) / 2)) + reveal_margin := Min(reveal_margin, max_margin) + + is_manual_center := (reason = "center" || reason = "manual") + if is_manual_center { + viewport_x := active_start - Round((metrics["w"] - active_width) / 2) + } else { + left_limit := viewport_x + reveal_margin + right_limit := viewport_x + metrics["w"] - reveal_margin + if (active_start < left_limit) + viewport_x := active_start - reveal_margin + else if (active_end > right_limit) + viewport_x := active_end + reveal_margin - metrics["w"] + } + + min_viewport := 0 + max_viewport := Max(0, total_strip_width - metrics["w"]) + if is_manual_center { + ; Allow edge tiles to truly center, even if that reveals blank margin. + center_slack := Max(0, Round((metrics["w"] - active_width) / 2)) + min_viewport -= center_slack + max_viewport += center_slack + } + viewport_x := Min(max_viewport, Max(min_viewport, viewport_x)) + carousel_viewport_x_by_scope[scope_key] := viewport_x + + resize_for_this_layout := ShouldResizeForRelayout(reason) + + for i, hwnd in windows { + if !WindowExistsAcrossDesktops(hwnd) + continue + if (WinGetMinMax("ahk_id " hwnd) = 1) + WinRestore("ahk_id " hwnd) + + target_x := 0 + target_y := metrics["y"] + target_w := col_w[i] + target_h := metrics["h"] + target_x := metrics["x"] + col_x[i] - viewport_x + + ; Even when resize-on-focus is disabled, the active tile should still + ; restore to its own stored focus width when revisited. + allow_resize := resize_for_this_layout || (i = active_index) + MoveWindowIfNeeded(hwnd, target_x, target_y, target_w, target_h, allow_resize) + } + + global carousel_last_relayout_tick + carousel_last_relayout_tick := A_TickCount + ScheduleCarouselStatusBarUpdate() +} + +ActivateCarouselWindow(hwnd) { + if !hwnd + return 0 + if !WindowExistsAcrossDesktops(hwnd) + return 0 + ; Carousel windows are already filtered to current desktop/monitor. + ; Prefer direct activation to avoid extra virtual desktop API calls. + try { + WinActivate "ahk_id " hwnd + return WinGetID("A") + } catch { + return ActivateWindowAcrossDesktops(hwnd) + } +} + +ScheduleCarouselStatusBarUpdate(delay_ms := 40) { + global carousel_status_bar_update_pending + if carousel_status_bar_update_pending + return + carousel_status_bar_update_pending := true + SetTimer(CarouselStatusBarUpdateDeferredTick, -delay_ms) +} + +CarouselStatusBarUpdateDeferredTick(*) { + global carousel_status_bar_update_pending + try CarouselStatusBarUpdate() + carousel_status_bar_update_pending := false +} + +CarouselSwitchDesktop(delta) { + if !CarouselModeEnabled() + return + ; Prevent plain desktop-switch handler from firing on shift-modified + ; combos such as super+shift+j/k (which are reserved for moving tiles). + if GetKeyState("Shift", "P") + return + GoToRelativeDesktopFast(delta) + ScheduleEnsureCarouselTrailingEmptyDesktop() + ScheduleCarouselStatusBarUpdate(80) +} + +CarouselHandleDesktopKey(delta) { + if !CarouselModeEnabled() || Window.IsMoveMode() + return + if GetKeyState("Ctrl", "P") && GetKeyState("Shift", "P") { + if Config["modes"]["carousel"]["native_desktop_reorder"] + CarouselMoveCurrentDesktop(delta) + return + } + if GetKeyState("Shift", "P") { + CarouselMoveWindowDesktop(delta) + return + } + CarouselSwitchDesktop(delta) +} + +CarouselMoveWindowDesktop(delta) { + if !CarouselModeEnabled() + return + MoveWindowToRelativeDesktopWithFollow(delta, CarouselDesktopMoveFollowsFocus()) + ScheduleCarouselStatusBarUpdate(80) +} + +CarouselMoveCurrentDesktop(delta) { + if !CarouselModeEnabled() || !VirtualDesktopEnabled() + return + if !Config["modes"]["carousel"]["native_desktop_reorder"] + return + current := GetCurrentDesktopNumFresh() + if (current <= 0) + current := VD.getCurrentDesktopNum() + if (current <= 0) + return + count := VD.getCount() + if (count <= 1) + return + target := current + delta + if (target < 1) + target := 1 + if (target > count) + target := count + if (target = current) + return + try { + moved := VD.moveDesktop(current, target) + if moved + LogCarouselDebug("desktop_reorder current=" current " target=" target) + } catch as err { + LogCarouselDebug("desktop_reorder_failed current=" current " target=" target " err=" err.Message) + } + RefreshVirtualDesktopState() + ScheduleCarouselStatusBarUpdate() +} + +MoveWindowToRelativeDesktopWithFollow(delta, follow_desktop := true) { + if !VirtualDesktopEnabled() + return + moving_hwnd := WinGetID("A") + if !moving_hwnd + return + source_monitor := Screen.FromWindow("ahk_id " moving_hwnd) + if (source_monitor <= 0) + source_monitor := MonitorGetPrimary() + + RefreshVirtualDesktopState() + current := GetCurrentDesktopNumFresh() + if (current <= 0) + current := VD.getCurrentDesktopNum() + if (current <= 0) + return + target := VD.modulusResolveDesktopNum(current + delta) + LogVirtualDesktopAction("move_relative current=" current " delta=" delta " target=" target " follow=" follow_desktop) + RefreshVirtualDesktopState() + if follow_desktop { + VD.MoveWindowToDesktopNum("A", target, true) + } else { + VD.MoveWindowToDesktopNum("A", target, false) + } + + IntegrateMovedWindowIntoDestinationScope(moving_hwnd, target, source_monitor) + + RefreshVirtualDesktopState() + ScheduleEnsureCarouselTrailingEmptyDesktop() + ScheduleCarouselStatusBarUpdate() +} + +IntegrateMovedWindowIntoDestinationScope(moving_hwnd, target_desktop_num, monitor_num) { + if !moving_hwnd + return + if (target_desktop_num <= 0 || monitor_num <= 0) + return + + scope_key := target_desktop_num ":" monitor_num + discovered := GetCarouselWindows(monitor_num, target_desktop_num) + + active_hwnd := 0 + if carousel_last_active_by_scope.Has(scope_key) + active_hwnd := carousel_last_active_by_scope[scope_key] + + ordered := BuildScopeOrder(scope_key, discovered, active_hwnd) + moving_index := CarouselIndexOf(ordered, moving_hwnd) + if (moving_index > 0) + ordered.RemoveAt(moving_index) + + anchor_index := CarouselIndexOf(ordered, active_hwnd) + if (anchor_index > 0) + ordered.InsertAt(anchor_index + 1, moving_hwnd) + else + ordered.Push(moving_hwnd) + + SetCarouselScopeOrder(scope_key, ordered) + carousel_last_active_by_scope[scope_key] := moving_hwnd +} + +GoToRelativeDesktopFast(delta) { + if !VirtualDesktopEnabled() + return + current := GetCurrentDesktopNumFresh() + if (current <= 0) + current := VD.getCurrentDesktopNum() + if (current <= 0) + return + target := VD.modulusResolveDesktopNum(current + delta) + LogVirtualDesktopAction("goto_relative_fast current=" current " delta=" delta " target=" target) + try VD.goToDesktopNum(target) +} + +CarouselFocusWatcherTick(*) { + global carousel_last_active_hwnd, carousel_last_scope_key, carousel_last_relayout_tick + if !CarouselModeEnabled() + return + hwnd := 0 + try hwnd := WinGetID("A") + if !hwnd + return + if Window.IsException("ahk_id " hwnd) + return + + monitor_num := Screen.FromWindow("ahk_id " hwnd) + desktop_num := VirtualDesktopEnabled() ? GetCurrentDesktopNumFresh() : 0 + scope_key := desktop_num ":" monitor_num + changed := (hwnd != carousel_last_active_hwnd) || (scope_key != carousel_last_scope_key) + if (changed && IsOverviewActive()) { + carousel_last_active_hwnd := hwnd + carousel_last_scope_key := scope_key + ScheduleCarouselStatusBarUpdate() + return + } + ; Snap viewport to externally focused windows (Task View selection, + ; app hotkeys, mouse focus, etc.) without forcing auto-centering. + if changed { + if (A_TickCount - carousel_last_relayout_tick > 250) + CarouselRelayout("focus") + } + carousel_last_active_hwnd := hwnd + carousel_last_scope_key := scope_key + carousel_last_active_by_scope[scope_key] := hwnd + if changed + ScheduleCarouselStatusBarUpdate() +} + +EnsureCarouselTrailingEmptyDesktop() { + if !CarouselModeEnabled() || !VirtualDesktopEnabled() + return + if !Config["modes"]["carousel"]["ensure_empty_desktop"] + return + EnsureVirtualDesktopTrailingEmpty(true) +} + +ScheduleEnsureCarouselTrailingEmptyDesktop(delay_ms := 700) { + global carousel_ensure_empty_pending + if carousel_ensure_empty_pending + return + carousel_ensure_empty_pending := true + SetTimer(CarouselEnsureEmptyDesktopDeferredTick, -delay_ms) +} + +CarouselEnsureEmptyDesktopDeferredTick(*) { + global carousel_ensure_empty_pending + try EnsureCarouselTrailingEmptyDesktop() + carousel_ensure_empty_pending := false +} + +GetTileCenterWidthRatio(hwnd) { + default_ratio := Config["modes"]["carousel"]["center_width_ratio"] + if !hwnd + return default_ratio + if carousel_tile_width_ratio.Has(hwnd) && WindowExistsAcrossDesktops(hwnd) + return carousel_tile_width_ratio[hwnd] + if carousel_tile_width_ratio.Has(hwnd) && !WindowExistsAcrossDesktops(hwnd) + carousel_tile_width_ratio.Delete(hwnd) + + persisted_ratio := GetPersistedCarouselWidthRatio(hwnd) + if (persisted_ratio != "") { + carousel_tile_width_ratio[hwnd] := persisted_ratio + return persisted_ratio + } + + return default_ratio +} + +GetPersistedCarouselWidthRatio(hwnd) { + global AppState + if !(AppState is Map) + return "" + if !AppState.Has("carousel_tile_width_ratio_by_exe") + return "" + + ratio_by_exe := AppState["carousel_tile_width_ratio_by_exe"] + if !(ratio_by_exe is Map) + return "" + + app_key := GetCarouselPersistentWidthKey(hwnd) + if (app_key = "") || !ratio_by_exe.Has(app_key) + return "" + + persisted_ratio := ratio_by_exe[app_key] + if !IsNumber(persisted_ratio) + return "" + + persisted_ratio := Min(0.9, Max(0.2, persisted_ratio)) + LogCarouselDebug("width_restore key=" app_key " center=" Round(persisted_ratio, 3)) + return persisted_ratio +} + +PersistCarouselWidthPreference(hwnd, center_ratio) { + global AppState + app_key := GetCarouselPersistentWidthKey(hwnd) + if (app_key = "") + return + + if !(AppState is Map) + AppState := Map() + if !AppState.Has("carousel_tile_width_ratio_by_exe") || !(AppState["carousel_tile_width_ratio_by_exe"] is Map) + AppState["carousel_tile_width_ratio_by_exe"] := Map() + + ratio_by_exe := AppState["carousel_tile_width_ratio_by_exe"] + ratio_by_exe[app_key] := center_ratio + SaveState(AppState) + LogCarouselDebug("width_persist key=" app_key " center=" Round(center_ratio, 3)) +} + +GetCarouselPersistentWidthKey(hwnd) { + return GetCarouselPersistentAppKey(hwnd) +} + +GetCarouselPersistentAppKey(hwnd) { + if !hwnd + return "" + process_name := "" + try process_name := StrLower(WinGetProcessName("ahk_id " hwnd)) + if !process_name + return "" + return process_name +} + +GetTileWidthPx(hwnd, monitor_width, gap_px := 0) { + ratio := GetTileCenterWidthRatio(hwnd) + ; Account for one inter-tile gap so two default 50% tiles can sit flush + ; within the viewport without slight overflow-induced extra panning. + available_width := Max(120, monitor_width - gap_px) + width_px := Round(available_width * ratio) + width_px := Min(Max(120, width_px), monitor_width) + return width_px +} + +ShouldResizeForRelayout(reason) { + if (reason = "resize" || reason = "move" || reason = "startup" || reason = "manual") + return true + return Config["modes"]["carousel"]["resize_on_focus"] +} + +MoveWindowIfNeeded(hwnd, target_x, target_y, target_w, target_h, allow_resize := true) { + epsilon := Config["modes"]["carousel"]["layout_epsilon_px"] + x := 0 + y := 0 + w := 0 + h := 0 + try WinGetPosEx(&x, &y, &w, &h, "ahk_id " hwnd) + catch + return + + move_needed := (Abs(x - target_x) > epsilon) || (Abs(y - target_y) > epsilon) + size_needed := (Abs(w - target_w) > epsilon) || (Abs(h - target_h) > epsilon) + if !move_needed && (!allow_resize || !size_needed) + return + + if allow_resize + WinMoveEx(target_x, target_y, target_w, target_h, "ahk_id " hwnd) + else + WinMoveEx(target_x, target_y,,, "ahk_id " hwnd) +} + +BuildCarouselState() { + active_hwnd := WinGetID("A") + if !active_hwnd + return Map("windows", [], "active_hwnd", 0, "monitor_num", 0, "scope_key", "") + + monitor_num := Screen.FromWindow("ahk_id " active_hwnd) + desktop_num := VirtualDesktopEnabled() ? GetCurrentDesktopNumFresh() : 0 + scope_key := desktop_num ":" monitor_num + discovered := GetCarouselWindows(monitor_num, desktop_num) + windows := BuildScopeOrder(scope_key, discovered, active_hwnd) + return Map( + "windows", windows, + "active_hwnd", active_hwnd, + "monitor_num", monitor_num, + "scope_key", scope_key + ) +} + +GetCarouselWindows(monitor_num, desktop_num := 0) { + include_minimized := Config["modes"]["carousel"]["include_minimized"] + excluded_apps := Config["modes"]["carousel"]["excluded_apps"] + windows := [] + bak_detect_hidden_windows := A_DetectHiddenWindows + A_DetectHiddenWindows := true + list := WinGetList() + A_DetectHiddenWindows := bak_detect_hidden_windows + for _, hwnd in list { + if !WindowExistsAcrossDesktops(hwnd) + continue + if Window.IsException("ahk_id " hwnd) + continue + minmax := 0 + try minmax := WinGetMinMax("ahk_id " hwnd) + catch + continue + if !include_minimized && (minmax = -1) + continue + ex_style := 0 + try ex_style := WinGetExStyle("ahk_id " hwnd) + catch + continue + if (ex_style & 0x80) || (ex_style & 0x8000000) + continue + style := 0 + try style := WinGetStyle("ahk_id " hwnd) + catch + continue + if !include_minimized && !(style & 0x10000000) + continue + if (Screen.FromWindow("ahk_id " hwnd) != monitor_num) + continue + if (VirtualDesktopEnabled() && desktop_num > 0) { + hwnd_desktop := GetWindowDesktopNum(hwnd) + if (hwnd_desktop > 0 && hwnd_desktop != desktop_num) + continue + } + process_name := "" + try process_name := StrLower(WinGetProcessName("ahk_id " hwnd)) + if CarouselExcludedProcess(process_name, excluded_apps) + continue + windows.Push(hwnd) + } + return windows +} + +CarouselExcludedProcess(process_name, excluded_apps) { + if !process_name + return false + for _, excluded in excluded_apps { + if (StrLower(excluded) = process_name) + return true + } + return false +} + +BuildScopeOrder(scope_key, discovered, active_hwnd) { + existing := [] + used_persisted_order := false + if carousel_order_by_scope.Has(scope_key) + existing := carousel_order_by_scope[scope_key] + else { + persisted_order := BuildPersistedScopeOrder(scope_key, discovered) + used_persisted_order := (persisted_order.Length > 0) + if used_persisted_order + existing := persisted_order + } + ordered := [] + seen := Map() + + for _, hwnd in existing { + if !WindowExistsAcrossDesktops(hwnd) + continue + if CarouselIndexOf(discovered, hwnd) = 0 + continue + ordered.Push(hwnd) + seen[hwnd] := true + } + + for _, hwnd in discovered { + if !seen.Has(hwnd) { + ordered.Push(hwnd) + seen[hwnd] := true + } + } + + if !used_persisted_order && (active_hwnd && CarouselIndexOf(ordered, active_hwnd) = 0 && CarouselIndexOf(discovered, active_hwnd) > 0) + ordered.InsertAt(1, active_hwnd) + + SetCarouselScopeOrder(scope_key, ordered) + PersistCarouselScopeOrder(scope_key, ordered) + return ordered +} + +BuildPersistedScopeOrder(scope_key, discovered) { + ordered := [] + seen := Map() + persisted_keys := GetPersistedCarouselScopeOrderKeys(scope_key) + if (persisted_keys.Length = 0) + return ordered + + ; Best-effort restore maps persisted app order to current live windows. + ; Duplicate app windows are consumed in discovery order. + for _, app_key in persisted_keys { + if !app_key + continue + for _, hwnd in discovered { + if seen.Has(hwnd) + continue + if (GetCarouselPersistentAppKey(hwnd) != app_key) + continue + ordered.Push(hwnd) + seen[hwnd] := true + break + } + } + + if (ordered.Length > 0) + LogCarouselDebug("order_restore scope=" scope_key " matched=" ordered.Length " discovered=" discovered.Length) + return ordered +} + +GetPersistedCarouselScopeOrderKeys(scope_key) { + global AppState + if !(AppState is Map) + return [] + if !AppState.Has("carousel_order_by_scope") + return [] + + by_scope := AppState["carousel_order_by_scope"] + if !(by_scope is Map) + return [] + if !by_scope.Has(scope_key) + return [] + + persisted_keys := by_scope[scope_key] + if !(persisted_keys is Array) + return [] + return persisted_keys +} + +PersistCarouselScopeOrder(scope_key, windows) { + global AppState + if !(windows is Array) + return + + keys := [] + for _, hwnd in windows { + app_key := GetCarouselPersistentAppKey(hwnd) + if app_key + keys.Push(app_key) + } + if (keys.Length = 0) + return + + if !(AppState is Map) + AppState := Map() + if !AppState.Has("carousel_order_by_scope") || !(AppState["carousel_order_by_scope"] is Map) + AppState["carousel_order_by_scope"] := Map() + + by_scope := AppState["carousel_order_by_scope"] + if by_scope.Has(scope_key) && (by_scope[scope_key] is Array) && CarouselStringArraysEqual(by_scope[scope_key], keys) + return + + by_scope[scope_key] := keys + SaveState(AppState) + LogCarouselDebug("order_persist scope=" scope_key " windows=" windows.Length) +} + +CarouselStringArraysEqual(a, b) { + if !(a is Array) || !(b is Array) + return false + if (a.Length != b.Length) + return false + for i, value in a { + if (value != b[i]) + return false + } + return true +} + +SetCarouselScopeOrder(scope_key, windows) { + copy := [] + for _, hwnd in windows + copy.Push(hwnd) + carousel_order_by_scope[scope_key] := copy +} + +GetCarouselMonitorMetrics(monitor_num) { + MonitorGetWorkArea(monitor_num, &left, &top, &right, &bottom) + left += Screen.left_margin + top += Screen.top_margin + top += CarouselStatusBarReservedTopPx(monitor_num) + right -= Screen.right_margin + bottom -= Screen.bottom_margin + width := right - left + height := bottom - top + return Map("x", left, "y", top, "w", width, "h", height) +} + +CarouselIndexOf(list, hwnd) { + for i, id in list { + if (id = hwnd) + return i + } + return 0 +} + +LogCarouselDebug(message) { + if !CarouselModeEnabled() + return + if !Config["modes"]["carousel"]["debug_enabled"] + return + + appdata := EnvGet("APPDATA") + if !appdata + return + log_path := appdata "\\harken\\carousel.debug.log" + DirCreate(appdata "\\harken") + FileAppend("[" A_Now "] " message "`n", log_path) +} diff --git a/src/lib/carousel_status_bar.ahk b/src/lib/carousel_status_bar.ahk new file mode 100644 index 0000000..71bfc4e --- /dev/null +++ b/src/lib/carousel_status_bar.ahk @@ -0,0 +1,426 @@ +global Config + +global carousel_status_bar_gui := "" +global carousel_status_bar_visible := false +global carousel_status_bar_monitor := 0 +global carousel_status_bar_desktop_ctrls := [] +global carousel_status_bar_window_ctrls := [] +global carousel_status_bar_last_key := "" +global carousel_status_bar_last_layout_key := "" +global carousel_status_bar_vd_listener_registered := false +global carousel_status_bar_icon_path_cache := Map() + +InitCarouselStatusBar() { + if !VirtualDesktopStatusBarVisibleInCurrentMode() { + DestroyCarouselStatusBar() + return + } + EnsureCarouselStatusBarListener() + CarouselStatusBarUpdate() +} + +EnsureCarouselStatusBarListener() { + global carousel_status_bar_vd_listener_registered + if carousel_status_bar_vd_listener_registered + return + if !VirtualDesktopEnabled() + return + VD.ListenersCurrentVirtualDesktopChanged[CarouselStatusBarDesktopChanged] := true + carousel_status_bar_vd_listener_registered := true +} + +CarouselStatusBarDesktopChanged(*) { + CarouselStatusBarUpdate() +} + +CarouselStatusBarConfigEnabled() { + return VirtualDesktopStatusBarEnabled() +} + +GetCarouselStatusBarSettings() { + if Config.Has("modes") && (Config["modes"] is Map) && Config["modes"].Has("carousel") { + carousel := Config["modes"]["carousel"] + if (carousel is Map && carousel.Has("status_bar") && (carousel["status_bar"] is Map)) + return carousel["status_bar"] + } + return Map( + "enabled", true, + "position", "top", + "height_px", 34, + "reserve_gap_px", 4, + "opacity", 220, + "background_color", "#181818", + "text_color", "#CCCCCC", + "active_color", "#A020F0", + "font_size", 10, + "title_max_len", 26, + "window_display", "icon" + ) +} + +CarouselStatusBarReservedTopPx(*) { + if !CarouselModeEnabled() || !VirtualDesktopStatusBarVisibleInCurrentMode() + return 0 + settings := GetCarouselStatusBarSettings() + if (settings["position"] != "top") + return 0 + return settings["height_px"] + settings["reserve_gap_px"] +} + +CarouselStatusBarUpdate(*) { + global carousel_status_bar_gui, carousel_status_bar_visible, carousel_status_bar_last_key, carousel_status_bar_last_layout_key + if !VirtualDesktopStatusBarVisibleInCurrentMode() { + DestroyCarouselStatusBar() + return + } + + settings := GetCarouselStatusBarSettings() + model := BuildCarouselStatusBarModel(settings) + if !(model is Map) + return + + view_key := model["key"] + layout_key := model["layout_key"] + if !carousel_status_bar_gui { + CreateCarouselStatusBarGui(model, settings) + } else if (carousel_status_bar_last_layout_key != layout_key) { + RebuildCarouselStatusBarGui(model, settings) + } else { + UpdateCarouselStatusBarContent(model) + } + + ShowCarouselStatusBarGui(settings) + carousel_status_bar_last_key := view_key + carousel_status_bar_last_layout_key := layout_key + carousel_status_bar_visible := true +} + +BuildCarouselStatusBarModel(settings) { + desktop_total := VirtualDesktopEnabled() ? VD.getCount() : 1 + if (desktop_total <= 0) + desktop_total := 1 + + active_desktop := VirtualDesktopEnabled() ? GetCurrentDesktopNumFresh() : 1 + if (active_desktop <= 0) + active_desktop := 1 + + desktop_cells := [] + Loop desktop_total { + desktop_num := A_Index + desktop_cells.Push(Map( + "num", desktop_num, + "active", desktop_num = active_desktop + )) + } + + show_windows := CarouselModeEnabled() + windows := [] + active_hwnd := 0 + if show_windows { + state := BuildCarouselState() + windows := state["windows"] + active_hwnd := state["active_hwnd"] + } + window_display := CarouselStatusBarWindowDisplay(settings) + + window_cells := [] + for _, hwnd in windows { + if !WindowExistsAcrossDesktops(hwnd) + continue + title := "" + exe := "" + try title := WinGetTitle("ahk_id " hwnd) + try exe := WinGetProcessName("ahk_id " hwnd) + if (title = "") { + if (exe != "") + title := RegExReplace(exe, "(?i)\.exe$", "") + else + title := "(untitled)" + } + icon_path := GetCarouselStatusBarIconPath(hwnd) + title := CarouselStatusBarTruncate(title, settings["title_max_len"]) + window_cells.Push(Map( + "hwnd", hwnd, + "title", title, + "icon_path", icon_path, + "active", hwnd = active_hwnd + )) + } + + key := active_desktop "/" desktop_total "|show_windows=" (show_windows ? 1 : 0) "|" + for _, d in desktop_cells + key .= d["active"] ? ("[" d["num"] "]") : d["num"] + key .= "|" + for _, w in window_cells { + if (window_display = "icon") + key .= (w["active"] ? "*" : "") w["hwnd"] ":" w["icon_path"] "|" + else + key .= (w["active"] ? "*" : "") w["hwnd"] ":" w["title"] "|" + } + + layout_key := "d:" desktop_cells.Length "|w:" window_cells.Length "|show_windows=" (show_windows ? 1 : 0) + + model := Map( + "desktop_total", desktop_total, + "active_desktop", active_desktop, + "desktop_cells", desktop_cells, + "window_cells", window_cells, + "show_windows", show_windows, + "layout_key", layout_key, + "key", key + ) + return model +} + +CarouselStatusBarTruncate(text, max_len) { + if (max_len <= 0) + return "" + if (StrLen(text) <= max_len) + return text + if (max_len <= 3) + return SubStr(text, 1, max_len) + return SubStr(text, 1, max_len - 3) "..." +} + +CarouselStatusBarWindowDisplay(settings) { + mode := "title" + if settings.Has("window_display") + mode := StrLower(settings["window_display"]) + if (mode != "title" && mode != "icon") + mode := "title" + return mode +} + +GetCarouselStatusBarIconPath(hwnd) { + global carousel_status_bar_icon_path_cache + if !hwnd + return "shell32.dll" + if carousel_status_bar_icon_path_cache.Has(hwnd) { + cached := carousel_status_bar_icon_path_cache[hwnd] + if (cached != "" && FileExist(cached)) + return cached + } + + path := "" + try path := WinGetProcessPath("ahk_id " hwnd) + if (path != "" && FileExist(path)) { + carousel_status_bar_icon_path_cache[hwnd] := path + return path + } + + carousel_status_bar_icon_path_cache[hwnd] := "shell32.dll" + return "shell32.dll" +} + +CreateCarouselStatusBarGui(model, settings) { + global carousel_status_bar_gui + carousel_status_bar_gui := Gui("+AlwaysOnTop -Caption +ToolWindow +Border", "harken Carousel Status") + carousel_status_bar_gui.MarginX := 10 + carousel_status_bar_gui.MarginY := 6 + carousel_status_bar_gui.BackColor := NormalizeHexColor(settings["background_color"], "181818") + RebuildCarouselStatusBarGui(model, settings) +} + +RebuildCarouselStatusBarGui(model, settings) { + global carousel_status_bar_gui, carousel_status_bar_desktop_ctrls, carousel_status_bar_window_ctrls + if carousel_status_bar_gui + carousel_status_bar_gui.Destroy() + carousel_status_bar_gui := "" + carousel_status_bar_desktop_ctrls := [] + carousel_status_bar_window_ctrls := [] + + carousel_status_bar_gui := Gui("+AlwaysOnTop -Caption +ToolWindow +Border", "harken Carousel Status") + carousel_status_bar_gui.MarginX := 10 + carousel_status_bar_gui.MarginY := 6 + carousel_status_bar_gui.BackColor := NormalizeHexColor(settings["background_color"], "181818") + + BuildCarouselStatusBarControls(model, settings) +} + +BuildCarouselStatusBarControls(model, settings) { + global carousel_status_bar_gui, carousel_status_bar_desktop_ctrls, carousel_status_bar_window_ctrls + + font_size := settings["font_size"] + text_color := NormalizeHexColor(settings["text_color"], "CCCCCC") + active_color := NormalizeHexColor(settings["active_color"], "A020F0") + + carousel_status_bar_gui.SetFont("s" font_size " w600 c" text_color, "Segoe UI") + desktop_label := carousel_status_bar_gui.AddText("xm ym", "Desktops:") + carousel_status_bar_desktop_ctrls.Push(desktop_label) + + max_desktop_digits := StrLen("" model["desktop_total"]) + if (max_desktop_digits < 1) + max_desktop_digits := 1 + ; Keep each desktop token wide enough for bracketed active state, e.g. [12]. + desktop_token_chars := max_desktop_digits + 2 + desktop_token_w := Round(font_size * desktop_token_chars * 0.7) + 10 + if (desktop_token_w < 20) + desktop_token_w := 20 + + is_first_desktop := true + for _, cell in model["desktop_cells"] { + token := cell["active"] ? ("[" cell["num"] "]") : cell["num"] + color := cell["active"] ? active_color : text_color + weight := cell["active"] ? "w700" : "w500" + opts := is_first_desktop ? "x+8 yp w" desktop_token_w " Center" : "x+4 yp w" desktop_token_w " Center" + carousel_status_bar_gui.SetFont("s" font_size " " weight " c" color, "Segoe UI") + desktop_token_ctrl := carousel_status_bar_gui.AddText(opts, token) + carousel_status_bar_desktop_ctrls.Push(desktop_token_ctrl) + is_first_desktop := false + } + + if !model["show_windows"] + return + + carousel_status_bar_gui.SetFont("s" font_size " c" text_color, "Segoe UI") + windows_prefix := carousel_status_bar_gui.AddText("x+14 yp", "|") + carousel_status_bar_window_ctrls.Push(windows_prefix) + + window_display := CarouselStatusBarWindowDisplay(settings) + win_cells := model["window_cells"] + if (win_cells.Length = 0) { + empty_ctrl := carousel_status_bar_gui.AddText("x+8 yp", "(no windows)") + carousel_status_bar_window_ctrls.Push(empty_ctrl) + return + } + + if (window_display = "icon") { + windows_prefix.GetPos(&prefix_x, &prefix_y, &prefix_w, &prefix_h) + icon_size := 16 + icon_y := prefix_y - 1 + underline_y := icon_y + icon_size + 1 + x_cursor := prefix_x + prefix_w + 8 + for _, cell in win_cells { + icon_opts := "x" x_cursor " y" icon_y " w" icon_size " h" icon_size " Icon1" + icon_ctrl := carousel_status_bar_gui.AddPicture(icon_opts, cell["icon_path"]) + + underline_color := cell["active"] ? active_color : text_color + underline_token := cell["active"] ? "*" : " " + carousel_status_bar_gui.SetFont("s8 w700 c" underline_color, "Segoe UI") + underline_ctrl := carousel_status_bar_gui.AddText("x" x_cursor " y" underline_y " w" icon_size " Center", underline_token) + + carousel_status_bar_window_ctrls.Push(Map( + "underline", underline_ctrl, + "icon", icon_ctrl, + "mode", "icon" + )) + x_cursor += icon_size + 10 + } + return + } + + is_first := true + for _, cell in win_cells { + color := cell["active"] ? active_color : text_color + weight := "w500" + token := " " cell["title"] " " + opts := is_first ? "x+8 yp" : "x+10 yp" + carousel_status_bar_gui.SetFont("s" font_size " " weight " c" color, "Segoe UI") + ctrl := carousel_status_bar_gui.AddText(opts " +Border", token) + carousel_status_bar_window_ctrls.Push(ctrl) + is_first := false + } +} + +UpdateCarouselStatusBarContent(model) { + global carousel_status_bar_desktop_ctrls, carousel_status_bar_window_ctrls + + settings := GetCarouselStatusBarSettings() + text_color := NormalizeHexColor(settings["text_color"], "CCCCCC") + active_color := NormalizeHexColor(settings["active_color"], "A020F0") + font_size := settings["font_size"] + + desktop_cells := model["desktop_cells"] + for i, cell in desktop_cells { + ctrl_index := i + 1 + if (ctrl_index > carousel_status_bar_desktop_ctrls.Length) + continue + ctrl := carousel_status_bar_desktop_ctrls[ctrl_index] + token := cell["active"] ? ("[" cell["num"] "]") : cell["num"] + color := cell["active"] ? active_color : text_color + weight := cell["active"] ? "w700" : "w500" + ctrl.SetFont("s" font_size " " weight " c" color, "Segoe UI") + ctrl.Text := token + } + + win_cells := model["window_cells"] + if !model["show_windows"] + return + window_display := CarouselStatusBarWindowDisplay(settings) + + if (window_display = "icon") { + for i, cell in win_cells { + ctrl_index := i + 1 + if (ctrl_index > carousel_status_bar_window_ctrls.Length) + continue + entry := carousel_status_bar_window_ctrls[ctrl_index] + if !(entry is Map) + continue + underline_color := cell["active"] ? active_color : text_color + underline_token := cell["active"] ? "*" : " " + underline_ctrl := entry["underline"] + underline_ctrl.SetFont("s8 w700 c" underline_color, "Segoe UI") + underline_ctrl.Text := underline_token + + icon_ctrl := entry["icon"] + try icon_ctrl.Value := "*Icon1 " cell["icon_path"] + } + return + } + + for i, cell in win_cells { + ctrl_index := i + 1 + if (ctrl_index > carousel_status_bar_window_ctrls.Length) + continue + ctrl := carousel_status_bar_window_ctrls[ctrl_index] + if (ctrl is Map) + continue + color := cell["active"] ? active_color : text_color + weight := "w500" + ctrl.SetFont("s" font_size " " weight " c" color, "Segoe UI") + ctrl.Text := " " cell["title"] " " + } +} + +ShowCarouselStatusBarGui(settings) { + global carousel_status_bar_gui, carousel_status_bar_monitor + if !carousel_status_bar_gui + return + + opacity := settings["opacity"] + opacity := Max(0, Min(255, Round(opacity))) + if (opacity < 255) + WinSetTransparent(opacity, carousel_status_bar_gui) + + mon := MonitorGetPrimary() + try { + hwnd := WinGetID("A") + if hwnd + mon := Screen.FromWindow("ahk_id " hwnd) + } + carousel_status_bar_monitor := mon + + MonitorGetWorkArea(mon, &left, &top, &right, &bottom) + width := right - left + height := settings["height_px"] + if (height < 24) + height := 24 + + pos := settings["position"] + y := (pos = "bottom") ? (bottom - height) : top + carousel_status_bar_gui.Show("NoActivate x" left " y" y " w" width " h" height) +} + +DestroyCarouselStatusBar() { + global carousel_status_bar_gui, carousel_status_bar_visible, carousel_status_bar_last_key, carousel_status_bar_last_layout_key + global carousel_status_bar_desktop_ctrls, carousel_status_bar_window_ctrls + if carousel_status_bar_gui { + carousel_status_bar_gui.Destroy() + carousel_status_bar_gui := "" + } + carousel_status_bar_desktop_ctrls := [] + carousel_status_bar_window_ctrls := [] + carousel_status_bar_last_key := "" + carousel_status_bar_last_layout_key := "" + carousel_status_bar_visible := false +} diff --git a/src/lib/command_toast.ahk b/src/lib/command_toast.ahk index c0b0c41..fd3c0b4 100644 --- a/src/lib/command_toast.ahk +++ b/src/lib/command_toast.ahk @@ -369,10 +369,30 @@ BuildCommandToastRows(key_width := 16) { rows := [] rows.Push(Map("key", "Window", "desc", "")) rows.Push(Map("key", "super+arrows", "desc", "resize")) - rows.Push(Map("key", "super+shift+h/j/k/l", "desc", "resize center")) - rows.Push(Map("key", "super+ctrl+h/j/k/l", "desc", "move")) + rows.Push(Map("key", "super+alt+arrows", "desc", "resize center")) + if CarouselModeEnabled() { + rows.Push(Map("key", "super+h/l", "desc", "carousel focus")) + rows.Push(Map("key", "super+shift+h/l", "desc", "carousel move")) + rows.Push(Map("key", "super+j/k", "desc", "desktop next/prev")) + rows.Push(Map("key", "super+shift+j/k", "desc", "move desktop (follow toggle)")) + rows.Push(Map("key", "super+space", "desc", "center active tile")) + if Config["modes"]["carousel"]["native_desktop_reorder"] + rows.Push(Map("key", "super+ctrl+shift+j/k", "desc", "reorder current desktop")) + rows.Push(Map("key", "super+- / =", "desc", "current tile width -/+")) + rows.Push(Map("key", "super+f", "desc", "toggle desktop move follow")) + } else { + rows.Push(Map("key", "super+h/l", "desc", "focus left/right")) + rows.Push(Map("key", "super+[ / ]", "desc", "cycle stacked")) + rows.Push(Map("key", "super+j/k", "desc", "desktop next/prev")) + rows.Push(Map("key", "super+shift+j/k", "desc", "move desktop")) + rows.Push(Map("key", "super+u/i", "desc", "focus monitor prev/next")) + rows.Push(Map("key", "super+shift+u/i", "desc", "move monitor prev/next")) + } + rows.Push(Map("key", "super+ctrl+h/j/k/l", "desc", "move/snap")) rows.Push(Map("key", "super+m", "desc", "maximize")) - rows.Push(Map("key", "double-super", "desc", "native overview")) + if Config["window"].Has("super_double_tap_action") && Config["window"]["super_double_tap_action"] = "overview" + rows.Push(Map("key", "double-super", "desc", "native overview")) + rows.Push(Map("key", "super+o", "desc", "native overview")) rows.Push(Map("key", "overview h/j/k/l", "desc", "navigate")) rows.Push(Map("key", "alt+-", "desc", "minimize")) rows.Push(Map("key", "alt+q", "desc", "close")) @@ -385,11 +405,6 @@ BuildCommandToastRows(key_width := 16) { if Config.Has("screen_search") && Config["screen_search"]["enabled"] { rows.Push(Map("key", "super+" Config["screen_search"]["hotkey"], "desc", "screen search")) } - if Config.Has("directional_focus") && Config["directional_focus"]["enabled"] { - rows.Push(Map("key", "alt+h/l", "desc", "focus left/right")) - rows.Push(Map("key", "alt+j/k", "desc", "focus down/up")) - rows.Push(Map("key", "alt+[ / ]", "desc", "cycle stacked")) - } rows.Push(Map("key", "", "desc", "")) rows.Push(Map("key", "Global Hotkeys", "desc", "")) for _, hotkey_config in Config["global_hotkeys"] { diff --git a/src/lib/config_loader.ahk b/src/lib/config_loader.ahk index aecf6e3..9a4b6c9 100644 --- a/src/lib/config_loader.ahk +++ b/src/lib/config_loader.ahk @@ -25,6 +25,7 @@ LoadConfig(config_path, default_config := Map()) { ValidateSuperKeys(config, errors) ValidateApps(config, errors) ValidateVirtualDesktopHotkeys(config, errors) + ValidateModes(config, errors) return Map( "config", config, @@ -83,6 +84,7 @@ ConfigSchema() { "resize_step", "number", "move_step", "number", "super_double_tap_ms", "number", + "super_double_tap_action", OptionalSpec("string"), "move_mode", Map( "enable", "bool", "cancel_key", "string" @@ -127,6 +129,8 @@ ConfigSchema() { "enabled", "bool", "switch_on_focus", "bool", "ensure_count", "number", + "ensure_trailing_empty", "bool", + "fast_switch_non_carousel", "bool", "cycle_prefer_current", "bool", "scroll_switch", "bool", "switch_curtain", Map( @@ -134,6 +138,10 @@ ConfigSchema() { "opacity", "number", "color", "string" ), + "status_bar", Map( + "enabled", "bool", + "show_in_non_carousel", "bool" + ), "prev_hotkey", "string", "next_hotkey", "string", "move_prev_hotkey", "string", @@ -174,6 +182,56 @@ ConfigSchema() { "cross_monitor", "bool", "debug_enabled", "bool" ), + "modes", Map( + "active", "string", + "carousel", Map( + "enabled", "bool", + "auto_snap_center_on_focus", "bool", + "center_width_ratio", "number", + "side_width_ratio", "number", + "width_step", "number", + "gap_px", "number", + "wrap_enabled", "bool", + "include_minimized", "bool", + "excluded_apps", ["string"], + "overflow_policy", "string", + "resize_on_focus", "bool", + "layout_epsilon_px", "number", + "scroll_reveal_margin_px", "number", + "ensure_empty_desktop", "bool", + "native_desktop_reorder", "bool", + "desktop_move_follows_focus", "bool", + "focus_left_hotkey", "string", + "focus_right_hotkey", "string", + "move_left_hotkey", "string", + "move_right_hotkey", "string", + "desktop_prev_hotkey", "string", + "desktop_next_hotkey", "string", + "desktop_move_prev_hotkey", "string", + "desktop_move_next_hotkey", "string", + "desktop_reorder_up_hotkey", "string", + "desktop_reorder_down_hotkey", "string", + "overview_hotkey", "string", + "center_hotkey", "string", + "width_decrease_hotkey", "string", + "width_increase_hotkey", "string", + "toggle_follow_hotkey", "string", + "status_bar", Map( + "enabled", "bool", + "position", "string", + "height_px", "number", + "reserve_gap_px", "number", + "opacity", "number", + "background_color", "string", + "text_color", "string", + "active_color", "string", + "font_size", "number", + "title_max_len", "number", + "window_display", "string" + ), + "debug_enabled", "bool" + ) + ), "focus_border", Map( "enabled", "bool", "border_color", "string", @@ -388,6 +446,36 @@ ValidateVirtualDesktopHotkeys(config, errors) { } } +ValidateModes(config, errors) { + if !config.Has("modes") || !(config["modes"] is Map) + return + if !config["modes"].Has("carousel") || !(config["modes"]["carousel"] is Map) + return + + carousel := config["modes"]["carousel"] + center_ratio := carousel.Has("center_width_ratio") ? carousel["center_width_ratio"] : 0.5 + side_ratio := carousel.Has("side_width_ratio") ? carousel["side_width_ratio"] : 0.25 + if (center_ratio <= 0 || center_ratio >= 1) + errors.Push("config.modes.carousel.center_width_ratio must be between 0 and 1") + if (side_ratio <= 0 || side_ratio >= 1) + errors.Push("config.modes.carousel.side_width_ratio must be between 0 and 1") + width_step := carousel.Has("width_step") ? carousel["width_step"] : 0.05 + if (width_step <= 0 || width_step >= 1) + errors.Push("config.modes.carousel.width_step must be between 0 and 1") + if carousel.Has("gap_px") && carousel["gap_px"] < 0 + errors.Push("config.modes.carousel.gap_px must be >= 0") + if carousel.Has("layout_epsilon_px") && carousel["layout_epsilon_px"] < 0 + errors.Push("config.modes.carousel.layout_epsilon_px must be >= 0") + if carousel.Has("scroll_reveal_margin_px") && carousel["scroll_reveal_margin_px"] < 0 + errors.Push("config.modes.carousel.scroll_reveal_margin_px must be >= 0") + + if carousel.Has("overflow_policy") { + policy := carousel["overflow_policy"] + if (policy != "offscreen" && policy != "stack_peek") + errors.Push("config.modes.carousel.overflow_policy must be offscreen or stack_peek") + } +} + ValidateNode(value, spec, path, errors, warnings) { if (spec is Map) { if spec.Has("__optional__") { diff --git a/src/lib/virtual_desktop.ahk b/src/lib/virtual_desktop.ahk index 6f4e1a9..3b802bb 100644 --- a/src/lib/virtual_desktop.ahk +++ b/src/lib/virtual_desktop.ahk @@ -173,11 +173,174 @@ InitVirtualDesktop() { ensure_count := Config["virtual_desktop"]["ensure_count"] if (ensure_count > 0) VD.createUntil(ensure_count) + SetTimer((*) => EnsureVirtualDesktopTrailingEmpty(), -500) InitVirtualDesktopTrayIndicator() InitVirtualDesktopAutoAssign() EnsureFocusDebugLogInit() } +VirtualDesktopFastSwitchNonCarousel() { + global Config + if !VirtualDesktopEnabled() + return false + if !Config["virtual_desktop"].Has("fast_switch_non_carousel") + return false + return Config["virtual_desktop"]["fast_switch_non_carousel"] +} + +VirtualDesktopTrailingEmptyEnabled() { + global Config + if !VirtualDesktopEnabled() + return false + if !Config["virtual_desktop"].Has("ensure_trailing_empty") + return false + return Config["virtual_desktop"]["ensure_trailing_empty"] +} + +VirtualDesktopStatusBarEnabled() { + global Config + if !VirtualDesktopEnabled() + return false + if Config["virtual_desktop"].Has("status_bar") { + status_bar := Config["virtual_desktop"]["status_bar"] + if (status_bar is Map && status_bar.Has("enabled")) + return status_bar["enabled"] + } + + ; Preserve existing user configs until they migrate to the global setting. + if Config.Has("modes") && (Config["modes"] is Map) && Config["modes"].Has("carousel") { + carousel := Config["modes"]["carousel"] + if (carousel is Map && carousel.Has("status_bar")) { + settings := carousel["status_bar"] + if (settings is Map && settings.Has("enabled")) + return settings["enabled"] + } + } + return false +} + +VirtualDesktopStatusBarShowInNonCarousel() { + global Config + if !VirtualDesktopEnabled() + return false + if !Config["virtual_desktop"].Has("status_bar") + return false + status_bar := Config["virtual_desktop"]["status_bar"] + if !(status_bar is Map) || !status_bar.Has("show_in_non_carousel") + return false + return status_bar["show_in_non_carousel"] +} + +VirtualDesktopStatusBarVisibleInCurrentMode() { + if !VirtualDesktopStatusBarEnabled() + return false + return CarouselModeEnabled() || VirtualDesktopStatusBarShowInNonCarousel() +} + +global vd_trailing_empty_pending := false +global vd_trailing_empty_signature := "" +global vd_trailing_empty_stable_count := 0 + +ScheduleEnsureVirtualDesktopTrailingEmpty(delay_ms := 700) { + global vd_trailing_empty_pending + if vd_trailing_empty_pending + return + vd_trailing_empty_pending := true + SetTimer(VirtualDesktopEnsureTrailingEmptyDeferredTick, -delay_ms) +} + +VirtualDesktopEnsureTrailingEmptyDeferredTick(*) { + global vd_trailing_empty_pending + try EnsureVirtualDesktopTrailingEmpty() + vd_trailing_empty_pending := false +} + +EnsureVirtualDesktopTrailingEmpty(force := false) { + global vd_trailing_empty_signature, vd_trailing_empty_stable_count + if !force && !VirtualDesktopTrailingEmptyEnabled() + return false + + occupied := GetOccupiedDesktopSetAcrossDesktops() + highest_occupied := 0 + for desktop_num, _ in occupied { + if (desktop_num > highest_occupied) + highest_occupied := desktop_num + } + + desired := Max(1, highest_occupied + 1) + RefreshVirtualDesktopState() + count := VD.getCount() + changed := false + signature := BuildVirtualDesktopOccupancySignature(occupied, count) + + if (signature = vd_trailing_empty_signature) + vd_trailing_empty_stable_count += 1 + else { + vd_trailing_empty_signature := signature + vd_trailing_empty_stable_count := 1 + } + + if (count < desired) { + VD.createUntil(desired) + changed := true + RefreshVirtualDesktopState() + vd_trailing_empty_signature := "" + vd_trailing_empty_stable_count := 0 + count := VD.getCount() + } + + ; Deleting a desktop can merge its windows into the current desktop, so only + ; prune after repeated identical occupancy snapshots and only remove one + ; trailing desktop per pass. + if (count > desired) && !occupied.Has(count) && (vd_trailing_empty_stable_count >= 3) { + fallback_desktop := Max(1, count - 1) + try VD.removeDesktop(count, fallback_desktop) + changed := true + RefreshVirtualDesktopState() + vd_trailing_empty_signature := "" + vd_trailing_empty_stable_count := 0 + ScheduleEnsureVirtualDesktopTrailingEmpty(1200) + } + + if changed + try ScheduleCarouselStatusBarUpdate(80) + return changed +} + +BuildVirtualDesktopOccupancySignature(occupied, count) { + desktop_nums := [] + for desktop_num, _ in occupied + desktop_nums.Push(desktop_num) + if (desktop_nums.Length > 1) + desktop_nums.Sort() + + signature := "count=" count "|occupied=" + for _, desktop_num in desktop_nums + signature .= desktop_num "," + return signature +} + +GetOccupiedDesktopSetAcrossDesktops() { + set := Map() + windows := GetWindowsAcrossDesktops() + for _, hwnd in windows { + if !WindowExistsAcrossDesktops(hwnd) + continue + if Window.IsException("ahk_id " hwnd) + continue + ex_style := 0 + try ex_style := WinGetExStyle("ahk_id " hwnd) + catch + continue + if (ex_style & 0x80) || (ex_style & 0x8000000) + continue + desktop_num := GetWindowDesktopNum(hwnd) + if (desktop_num > 0) + set[desktop_num] := true + } + return set +} + InitVirtualDesktopAutoAssign() { if !VirtualDesktopEnabled() return diff --git a/src/lib/window_manager.ahk b/src/lib/window_manager.ahk index 309ad5b..f771802 100644 --- a/src/lib/window_manager.ahk +++ b/src/lib/window_manager.ahk @@ -47,21 +47,31 @@ class Window static __New() { HotIf (*) => IsSuperKeyPressed() + && GetKeyState('Ctrl', 'P') && !GetKeyState('Shift', 'P') - && !GetKeyState('Ctrl', 'P') && !GetKeyState('LAlt', 'P') && !GetKeyState('RAlt', 'P') + && !CarouselModeEnabled() && !this.IsMoveMode() Hotkey('*k', ObjBindMethod(this, 'HotkeyCallback', ObjBindMethod(this, 'MoveUp'))) Hotkey('*h', ObjBindMethod(this, 'HotkeyCallback', ObjBindMethod(this, 'MoveLeft'))) Hotkey('*j', ObjBindMethod(this, 'HotkeyCallback', ObjBindMethod(this, 'MoveDown'))) Hotkey('*l', ObjBindMethod(this, 'HotkeyCallback', ObjBindMethod(this, 'MoveRight'))) - Hotkey('*u', ObjBindMethod(this, 'HotkeyCallback', ObjBindMethod(this, 'MoveToPreviousMonitor'))) - Hotkey('*o', ObjBindMethod(this, 'HotkeyCallback', ObjBindMethod(this, 'MoveToNextMonitor'))) Hotkey('*n', ObjBindMethod(this, 'HotkeyCallback', ObjBindMethod(this, 'MoveToNearestPosition'))) Hotkey('*m', ObjBindMethod(this, 'Maximize')) HotIf + HotIf (*) => IsSuperKeyPressed() + && GetKeyState('Shift', 'P') + && !GetKeyState('Ctrl', 'P') + && !GetKeyState('LAlt', 'P') + && !GetKeyState('RAlt', 'P') + && !CarouselModeEnabled() + && !this.IsMoveMode() + Hotkey('*u', ObjBindMethod(this, 'HotkeyCallback', ObjBindMethod(this, 'MoveToPreviousMonitor'))) + Hotkey('*i', ObjBindMethod(this, 'HotkeyCallback', ObjBindMethod(this, 'MoveToNextMonitor'))) + HotIf + ; releasing modifier key destroys gui guides RegisterSuperKeyHotkey("*", " up", ObjBindMethod(Gui_Guides, 'Destroy_Guis')) } @@ -186,7 +196,13 @@ class Window - static IsException(id := 'A') => InStr(Window.exceptions, WinGetClass(id)) + static IsException(id := 'A') { + ; Windows can disappear between enumeration and class lookup. + try class_name := WinGetClass(id) + catch + return true + return InStr(Window.exceptions, class_name) + } diff --git a/src/lib/window_walker.ahk b/src/lib/window_walker.ahk index f72e15d..dddb9ac 100644 --- a/src/lib/window_walker.ahk +++ b/src/lib/window_walker.ahk @@ -13,7 +13,6 @@ class WindowWalker static visible := false static image_list := "" static icon_cache := Map() - static corner_radius := 8 static last_monitor := "" static last_monitor_work_area_key := "" static excluded_exes := Map( @@ -73,7 +72,7 @@ class WindowWalker if WindowWalker.gui return - WindowWalker.gui := Gui("+AlwaysOnTop +ToolWindow -Caption", "harken Window Selector") + WindowWalker.gui := Gui("+AlwaysOnTop +ToolWindow -Caption +Border", "harken Window Selector") WindowWalker.gui.MarginX := 12 WindowWalker.gui.MarginY := 10 WindowWalker.gui.SetFont("s10", "Segoe UI") @@ -134,28 +133,6 @@ class WindowWalker pos_x := left + (right - left - w) / 2 pos_y := top + (bottom - top - h) / 2 WindowWalker.gui.Show("x" pos_x " y" pos_y) - ; Query final dimensions after positioning so rounded-corner clipping uses current - ; monitor scaling instead of stale dimensions captured from another monitor context. - WindowWalker.gui.GetPos(,, &w, &h) - WindowWalker.ApplyRoundedCorners(w, h) - } - - static ApplyRoundedCorners(width := 0, height := 0) - { - if !WindowWalker.gui - return - ; Always refresh dimensions from the live window so the region is never based on stale - ; size values from a previous monitor/DPI context. - WindowWalker.gui.GetPos(,, &width, &height) - - if (width <= 0 || height <= 0) { - ; Clear any old clip region instead of leaving the GUI content partially cropped. - try WinSetRegion(, WindowWalker.gui) - return - } - - radius := WindowWalker.corner_radius - try WinSetRegion("0-0 w" width " h" height " r" radius "-" radius, WindowWalker.gui) } static StartFocusWatch()