This was debugged by Lando Calrissian on Discord who submitted this text
patch. The rest of this commit message is from Lando's investigation
summary shared on Discord:
The left panel in komorebi-bar uses `Align2::LEFT_CENTER` anchor, which
vertically centers the panel content within the bar. When switching
between workspaces with windows (icons) and empty workspaces (text
labels only), the content height differed by ~1-2px, causing the
vertical center point to shift - resulting in visible "bobbing" of the
workspace indicators.
The height inconsistency occurred because:
1. `show_icons()` wrapped content in a Frame with inner_margin
2. `show_fallback_icon()` had NO Frame wrapper
3. `show_label()` had NO Frame wrapper and used default text height
Fix:
1. Wrap `show_fallback_icon()` in the same Frame with inner_margin as
show_icons
2. Wrap `show_label()` in the same Frame with inner_margin as show_icons
3. Add `ui.set_min_height(self.icon_size.y)` to show_label to ensure the
label has the same minimum height as icons
4. Change show_label from static to instance method (&self) to access
icon_size
This ensures all three rendering functions produce consistent content
height, preventing the LEFT_CENTER anchor from shifting when workspace
content changes.
This was debugged by Lando Calrissian on Discord who submitted this text
patch. The rest of this commit message is from Lando's investigation
summary shared on Discord:
Every frame, the update() method checks if egui's window rect matches
the stored size_rect. The comparison code multiplied egui's outer_rect
(which is in logical pixels) by scale_factor, producing physical pixel
values (e.g., 3584x40 on a 2x Retina display). But size_rect stores
logical pixel values (1792x20). These can never match on a HiDPI
display, so every frame:
1. `size_rect != current_rect` evaluates to `true`
2. `position_bar()` is called, sending `ViewportCommand::OuterPosition`
and `ViewportCommand::InnerSize`
3. Each `send_viewport_cmd` internally calls `request_repaint()` in egui
4. egui schedules another frame → go to step 1
Result: 120fps continuous rendering, consuming ~12% CPU.
Debugging Method:
Instrumented the code with frame counters, FPS tracking, and repaint
cause logging. Systematically disabled components (repaint thread,
komorebi notifications, widget rendering) to isolate the cause. Traced
egui's repaint causes to context.rs:3853 (send_viewport_cmd_to), then
found the size_rect mismatch firing 1112 times in 10 seconds.
Fix:
Removed the erroneous scale_factor multiplication from the rect
comparison, since outer_rect already reports in logical pixels — the
same coordinate space as size_rect.
Result:
┌────────────┬───────────┬───────────────────┐
│ Metric │ Before │ After │
├────────────┼───────────┼───────────────────┤
│ CPU (idle) │ 12-13% │ 0.0-0.1% │
├────────────┼───────────┼───────────────────┤
│ Frames/sec │ 120 │ ~1 (timer-driven) │
├────────────┼───────────┼───────────────────┤
│ CPU spikes │ Up to 20% │ None observed │
└────────────┴───────────┴───────────────────┘
This commit is largely lift and shift of LGUG2Z/komorebi@c165172:
The implementation adds a new layout-ratio CLI command to komorebi that
allows users to dynamically set column and row ratios for layouts at
runtime via komorebic layout-ratio --columns 0.3 0.4 --rows 0.5.
A public validate_ratios function was added to komorebi-layouts that
clamps ratio values between 0.1 and 0.9, truncates when the cumulative
sum would reach or exceed 1.0, and limits to a maximum of 5 ratios. This
function is shared between config file deserialization and the new CLI
command, ensuring consistent validation behavior.
The SocketMessage enum in komorebi/src/core/mod.rs has a new
LayoutRatios variant. The handler in process_command.rs uses the shared
validate_ratios function to process the ratios before applying them to
the focused workspace's layout options.
When the CLI command is called without any arguments, it prints a
helpful message instead of returning an error.
This commit adds parity with the layout_options and ratio support added
to LGUG2Z/komorebi@22e8a79833 by @CtByte,
which is largely integrated into komorebi for Mac through the importing
of the new komorebi-layouts crate.
The implementation adds a new layout-ratio CLI command to komorebi that
allows users to dynamically set column and row ratios for layouts at
runtime via komorebic layout-ratio --columns 0.3 0.4 --rows 0.5.
A public validate_ratios function was added to komorebi-layouts that
clamps ratio values between 0.1 and 0.9, truncates when the cumulative
sum would reach or exceed 1.0, and limits to a maximum of 5 ratios. This
function is shared between config file deserialization and the new CLI
command, ensuring consistent validation behavior.
The SocketMessage enum in komorebi/src/core/mod.rs has a new
LayoutRatios variant. The handler in process_command.rs uses the shared
validate_ratios function to process the ratios before applying them to
the focused workspace's layout options.
When the CLI command is called without any arguments, it prints a
helpful message instead of returning an error.
The Media widget has been enhanced with a new MediaDisplayFormat
configuration option that controls how the widget is displayed. It
supports seven formats: Icon, Text, IconAndText (the default),
ControlsOnly, IconAndControls, TextAndControls, and Full.
The widget now detects whether the Previous and Next buttons are
actually available for the current media session using the Windows Media
Control API. When a button is not available, it appears dimmed at 50
percent opacity and clicking it has no effect.
Tooltips were added to improve usability. Hovering over the media info
label shows the full artist and title text, which is helpful when the
text is truncated. The Play/Pause button also shows the media info on
hover.
The rendering logic was refactored to properly handle right-aligned
widgets.
When the Media widget is placed in right_widgets, the UI renders items
from right to left, so the code now renders elements in reverse order to
ensure the visual appearance remains consistent regardless of which
panel the widget is placed in.
This prevents a race where OS-initiated minimizes prematurely
remove windows that should be transiently restored.
Problem: a display-change can trigger a a fast reconciliation path (same
count), and shortly after Windows may emit a SystemMinimizeStart for
affected windows. The minimize handler treated those as user-initiated
and removed the window, making later reconciliation unable to restore
it.
Fix: timestamp display-change notifications and add a
display_change_in_progress(period) check to the minimize handler. While
that grace period is active the minimize handler skips remove_window(),
preserving windows so the reconciliator can restore them.
This change adds verification steps and robustness improvements
to the monitor reconciliator.
- Retry display enumeration if it fails, up to 5 times, instead of silently
ignoring errors.
- When a potential monitor removal is detected, drop locks and wait briefly,
then re-query the Win32 display API. If the monitor reappears, treat the
event as transient and do not remove the monitor.
- Re-acquire locks when needed, so the verification wait doesn't hold
internal state locks.
Why:
- Win32 device/display notifications are noisy and not always immediately
available; enumeration can fail (e.g. "Invalid monitor handle" / HRESULT
0x80070585), or multiple DBT_DEVICEARRIVAL/DBT_DEVICEREMOVECOMPLETE events
can arrive in quick succession.
- Without verification the reconciliator could treat transient events (for
example, power-plan–induced monitor sleep where Removes+Adds occur within
milliseconds) as real removals, resulting in fewer detected monitors than
are actually present.
This commit moves layout-related code into a new workspace crate
komorebi-layouts, with the intention of re-using it all in komorebi for
Mac instead of maintaining two separate implementations.
Added customizable split ratios for layouts via layout_options
configuration. Users can now specify column_ratios and row_ratios arrays
to control window sizing in various layouts.
Ratios are validated at config load time: values are clamped between 0.1
and 0.9 to prevent zero-sized windows, and arrays are automatically
truncated when their cumulative sum would reach or exceed 1.0. This
ensures there's always remaining space for additional windows.
Ratio support varies by layout:
- Columns and Rows layouts use the full arrays for each column/row width
or height
- VerticalStack, RightMainVerticalStack, and HorizontalStack use the
first ratio for the primary split and the remaining ratios for stack
windows
- BSP uses the first value from each array for horizontal and vertical
splits respectively
- Grid only supports column_ratios since row counts vary dynamically.
- UltrawideVerticalStack uses the first two column ratios for center and
left columns.
All ratio-related values are now defined as constants in
default_layout.rs: MAX_RATIOS (5), MIN_RATIO (0.1), MAX_RATIO (0.9),
DEFAULT_RATIO (0.5), and DEFAULT_SECONDARY_RATIO (0.25 for
UltrawideVerticalStack).
This commit migrates to the new komorebi-layouts crate exposed in the
LGUG2Z/komorebi repository, significantly reducing duplication and
change maintenance between the two komorebi implementations.
This commit attempts tofixfixes a use-after-free bug in the
border_manager that was causing crashes with exception code 0xc000041d
(FATAL_USER_CALLBACK_EXCEPTION) when borders were being destroyed during
config updates.
The root cause was a race condition between the main thread destroying a
border window and the border's window thread still processing queued
window messages (EVENT_OBJECT_LOCATIONCHANGE, WM_PAINT).
The crash occurred when these callbacks invoked render_target.EndDraw(),
which internally calls HwndPresenter::Present() to present the rendered
frame to the HWND. By this point, the HWND and its associated Direct2D
surfaces had been freed by WM_DESTROY, resulting in Direct2D attempting
to dereference freed memory (0xbaadf00dbaadf00d - debug heap poison
value).
The previous attempts at fixing this issue (bdef1448, dbde351e)
addressed symptoms but not the fundamental race condition. bdef1448
attempted to release resources on the main thread before destruction,
but this created a cross-thread race. dbde351e moved resource cleanup to
WM_DESTROY, but this still allowed EVENT_OBJECT_LOCATIONCHANGE/WM_PAINT
handlers to check `render_target.is_some()`, context-switch to
WM_DESTROY which clears it, then context-switch back and call EndDraw()
on a now-invalid reference.
This commit attempts to eliminate the race condition by introducing an
atomic destruction flag that serves as a memory barrier between the
destruction path and the rendering paths:
- Added `is_destroying: Arc<AtomicBool>` field to the Border struct
- In destroy(): Sets the flag with Release ordering, sleeps 10ms to
allow in-flight operations to complete, then proceeds with cleanup
- In EVENT_OBJECT_LOCATIONCHANGE and WM_PAINT: Checks the flag with
Acquire ordering both at handler entry and immediately before calling
BeginDraw/EndDraw, exiting early if destruction is in progress
The Acquire/Release memory ordering creates a synchronizes-with
relationship that ensures:
1. When the destruction flag is set, all subsequent handler checks will
see it (no stale cached values)
2. Handlers that pass the first check but race with destruction will be
caught by the second check before touching D2D resources
3. The 10ms sleep window allows any handler already past both checks to
complete its EndDraw() before resources are freed
This is a lock-free solution with zero overhead on the hot rendering
path (atomic loads are nearly free) and provides defense-in-depth with
multiple barriers against the use-after-free condition.
This commit ensures that we check if a window is already managed in any
workspaces even after checking known_hwnds, because windows moved as
part of the earlier ensure_workspace_rules call can slip through the
cracks.
When a border is destroyed, the main thread was forcefully releasing D2D
resources, while the border window thread might still be trying to use
them in its message loop.
Releasing the RenderTarget on one thread while another is calling
EndDraw on it leads to a use-after-free scenario or invalid state for
the COM object, resulting in the crash.
This commit applies a fix that moves the resource cleanup logic from the
main thread to the window thread. Now, resources are only released
during the WM_DESTROY message processing, which guarantees
synchronization with other window messages like WM_PAINT.
When Finder is configured as a tabbed application, opening multiple
separate Finder windows (not tabs within the same window) prevented
focusing between those windows using komorebic focus commands.
The tab detection logic uses geometry comparison (tab_rect == main_rect)
to determine if a window event represents a tab change. This fails when
separate windows from the same application have identical geometry after
tiling, causing them to be incorrectly treated as tabs within a single
window.
This commit adds window ID verification as an additional requirement for
tab detection. For Show events, both geometry AND window IDs must match
for the event to be classified as a tab (preventing new container
creation). For FocusChange events, we verify the stored element's window
ID matches the container's stored ID to confirm legitimate tab switches
within the same window.
The geometry check is preserved to maintain existing tab detection, but
now requires window ID confirmation to prevent false positives when
separate windows happen to share identical positions and dimensions.
Additionally, this commit fixes the Window::focus() function for tabbed
applications to prefer using the stored element when valid, only falling
back to main_window() when the element is invalid (tab was closed). This
allows focusing specific windows even for tabbed applications instead of
always focusing the main/frontmost window.
This commit removes the hardcoded entries in TABBED_APPLICATIONS for
Finder and Ghostty, and instead leaves this for users to source either
through their own configs using the "tabbed_applications" config option
or via an ASC file.
There is a slight discrepancy in the two schemas as the personal config
file will accept an Exe string identifying the app, whereas the ASC goes
with a full MatchingRule to keep the ASC consistent.
However, for both tabbed and titleless application options as exposed on
the ASC schema, when read in komorebi it will only accept
MatchingRule::Simple with an Exe identifier.
Resize adjustments can cause container layouts to overflow beyond the
monitor's work area boundaries, bleeding into adjacent monitors.
This happens because the resize adjustment system modifies container
dimensions without validating that the final calculated positions stay
within the monitor's bounds.
On multi-monitor setups (e.g. ultrawide + MacBook display), a large
resize adjustment on one container can push adjacent containers past the
monitor edge, making them visible on the neighboring display.
This commit adds boundary clamping after layout calculation but before
padding is applied. If a layout's calculated position exceeds the work
area bounds (horizontally or vertically), we clamp it to stay within the
monitor's usable space.
Additionally, a unit test validates that layouts with aggressive resize
adjustments (matching the reported issue) are properly clamped to
prevent overflow.
This commit fixes a use-after-free bug in the border_manager that was
causing crashes with exception code 0xc000041d when borders were being
destroyed during workspace/monitor changes.
The root cause was a race condition between the main thread destroying a
border window and the border's window thread still processing queued
window messages (WM_PAINT, EVENT_OBJECT_LOCATIONCHANGE). The crash
occurred when these callbacks invoked render_target.EndDraw(), which
internally calls HwndPresenter::Present() to present the rendered frame
to the HWND. By this point, the HWND and its associated DirectX surfaces
had already been freed, resulting in Direct2D attempting to dereference
freed memory (0xFEEEFEEEFEEEFEEE - Windows heap poison value).
The issue stemmed from two problems in destroy_border():
1. Direct2D resources (render_target and brushes) were not being
released before closing the window. These COM objects hold internal
pointers to the HWND and its DirectX swap chain/surfaces. When
close_window() was called, Windows began tearing down these resources
while the Direct2D objects still held dangling pointers to them.
2. GWLP_USERDATA was not being cleared before closing the window. This
meant that any messages already queued in the window's message queue
could still retrieve the border_pointer and attempt to render using
the now-invalid Direct2D resources.
This commit addresses both issues:
- In destroy_border() (mod.rs): Explicitly set render_target to None and
clear the brushes HashMap before calling destroy(). This ensures that
Direct2D COM objects are properly released while the HWND is still
valid, preventing EndDraw() from accessing freed HWND resources.
- In destroy() (border.rs): Clear GWLP_USERDATA before calling
close_window(). This ensures that any pending window messages will see
a null pointer and exit early from the callbacks (which already have
null pointer checks in place).
These changes create two layers of defense against the race condition:
the callbacks won't access the border_pointer (it's null), and even if
they somehow did, the render_target would be None so no rendering
operations would occur.
I think this is the root cause of a lot of crash tickets that people are
mistakenly attributing to specific applications which lack
reproducibility across different users/machines, i.e. #1626, #1624.
Apparently there is a quirk of GetWindowLongPtr when querying styles. If
the style bits are genuinely 0, the API returns 0 but does not clear the
last error.
If a previous API call set an error, GetWindowLongPtr might define
"failure" as "return 0 AND GetLastError != 0".
Hence, it is important to clear the last/previous error before calling
GetWindowLongPtrW to ensure that we don't misinterpret a valid 0 return
value as an error.
When the last window on a workspace is closed, macOS automatically
activates another app (often on a different workspace). This app's focus
event triggers workspace reconciliation, switching the user away from
the now-empty workspace they (presumably) intended to stay on.
The issue is a race condition: by the time we try to activate Finder to
prevent the unwanted focus change, the other app's activation event has
already been queued and will still get processed.
This commit enusres that we skip reconciliation when the current
workspace is empty; this indicates the user just closed the last window
and should stay on that workspace, not follow workspace focus to
wherever macOS arbitrarily activates an app.
Additionally, we activate Finder when a workspace becomes empty to match
native macOS behavior (clicking on empty desktop activates Finder
without opening a window).
Some Electron apps like Discord hijack CMD+W to send
`AXApplicationHidden` instead of properly closing/destroying the window.
This causes ghost tiles because the window still exists in the
accessibility API with valid geometry even though it is no longer
visible on the screen.
When `AXApplicationHidden` fires for an app with exactly 1 window, we
now force-reap that window by passing an empty `valid_window_ids` list.
This treats single- window hide events as closes, which is the correct
behavior for apps that hijack CMD+W. Apps with multiple windows continue
to use normal orphan reaping.
I'm still not sure if this is too broad; we may need to use an allowlist
approach for this if it causes changes with other apps.
This commit adds a dedicated `komorebic permissions` command so that
users can quickly open the relevant Permissions dialogs in System
Settings at any time (i.e. after upgrades).
This commit updates the plist generated by `komorebic enable-autostart`
to add RunAtLoad = true and paths in /tmp/ for StandardOutPath and
StandardErrorPath.