forge
Explore
Log in

Don't you dare go Hollow

Implement recent windows switcher (Alt-Tab)

Browse files at this commit

933ffcb229e9e678b271d4043b1d4d5e2b6fa073rustN00bParent: b774fc1
Historic commit description log:

The MRU actions `focus-window-mru-previous` and `focus-window-mru-next`
are used to navigate windows in most-recently-used or
least-recently-used order.

Whenever a window is focused, it records a timestamp that be used to
sort windows in MRU order. This timestamp is not updated immediately,
but only after a small delay (lock-in period) to ensure that the
focus wasn't transfered to another window in the meantime. This
strategy avoids upsetting the MRU order with focus events generated by
intermediate windows when moving between two non contiguous windows.

The lock-in delay can be configured using the `focus-lockin-ms`
configuration argument.

Calling either of the `focus-window-mru` actions starts an MRU window
traversal sequence if one isn't already in progress. When a sequence is
in progress, focus timestamps are no longer updated.

A traversal sequence ends when:
- either the `Mod` key is released, the focus then stays on the chosen
  window  and its timestamp is immediately refreshed,
- or if the `Escape` key is pressed, the focus returns to the window
  that initially had the focus when the sequence was started.

Rename WindowMRU fields

Improve window close handling during MRU traversal

When the focused window is closed during an MRU traversal, it moves
to the previous window in MRU order instead of the default behavior.

Removed dbg! calls

Merge remote-tracking branch 'upstream/main' into window-mru

Hardcode Alt-Tab/Alt-shift-Tab for MRU window nav

- Add a `PRESET_BINDINGS` containing MRU navigation actions.
  `PRESET_BINDINGS` are overridden by user configuration so these remain
  available if the user needs them for another purpose
- Releasing the `Alt` key ends any in-progress MRU window traversal

Remove `focus-window-mru` actions from config

These actions are configured in presets but no longer available
for the bindings section of the configuration

Cancel MRU traversal with Alt-Esc

Had been forgotten in prior commit and was using `Mod` instead of `Alt`

Rephrase some comments

Fix Alt-Esc not cancelling window-mru

Merge remote-tracking branch 'upstream/main' into window-mru

Lock-in focus immediately on user interaction

As per suggestion by @bbb651, focus is locked-in immediately if a window
is interacted with, ie. receives key events or pointer clicks.

This change is also an opportunity to make the lockin timer less aggresive.

Merge remote-tracking branch 'upstream/main' into window-mru

Simplify WindowMRU::new

Now that there is a more general Niri::lockin_focus method, leverage
it in WindowMRU.

Replace Duration with Instant in WindowMRU timestamp

Merge remote-tracking branch 'upstream/main' into window-mru

Address PR comments - partial

- Swapped meaning of next and previous for MRU traversal
- Fixed comment that still referred to `Mod` as leader key for MRU traversal
  instead of `Alt`
- Fixed doc comments that were missing a period
- Stop using BinaryHeap in `WindowMRU::new()`
- Replaced `WindowMRU::mru_with()` method with a simpler `advance()`
- Simplified `Alt` key release handling code in `State::on_keyboard()`

Simplify early-mru-commit logic

No longer perform the mru-commit/lockin_focus in the next event loop callback.
Instead it is handled directly when it is determined that an event (pointer
or kbd) is forwarded to the active window.

Handle PR comments

- `focus_lockin` variables and configuration item renamed to `mru_commit`.
- added the Esc key to `suppressed_keys` if it was used to cancel an MRU
  traversal.
- removed `WindowMRU::mru_next` and `WindowMRU::mru_previous` methods
  as they didn't really provide more than the generic `WindowMRU::advance`
  method.
- removed obsolete `Niri::event_forwarded_to_focused_client` boolean
- added calls to `mru_commit()` (formerly `focus_lockin`) in:
  - `State::on_pointer_axis()`
  - `State::on_tablet_tool_axis()`
  - `State::on_tablet_tool_tip()`
  - `State::on_tablet_tool_proximity()`
  - `State::on_tablet_tool_button()`
  - `State::on_gesture_swipe_begin()`
  - `State::on_gesture_pinch_begin()`
  - `State::on_gesture_hold_begin()`
  - `State::on_touch_down()`

Merge remote-tracking branch 'upstream/main' into window-mru

Merge remote-tracking branch 'upstream/main' into window-mru

Add MRU window navigation actions

The MRU actions `focus-window-mru-previous` and `focus-window-mru-next`
are used to navigate windows in most-recently-used or
least-recently-used order.

Whenever a window is focused, it records a timestamp that be used to
sort windows in MRU order. This timestamp is not updated immediately,
but only after a small delay (lock-in period) to ensure that the
focus wasn't transfered to another window in the meantime. This
strategy avoids upsetting the MRU order with focus events generated by
intermediate windows when moving between two non contiguous windows.

The lock-in delay can be configured using the `focus-lockin-ms`
configuration argument.

Calling either of the `focus-window-mru` actions starts an MRU window
traversal sequence if one isn't already in progress. When a sequence is
in progress, focus timestamps are no longer updated.

A traversal sequence ends when:
- either the `Mod` key is released, the focus then stays on the chosen
  window  and its timestamp is immediately refreshed,
- or if the `Escape` key is pressed, the focus returns to the window
  that initially had the focus when the sequence was started.

Rename WindowMRU fields

Improve window close handling during MRU traversal

When the focused window is closed during an MRU traversal, it moves
to the previous window in MRU order instead of the default behavior.

Removed dbg! calls

Merge remote-tracking branch 'upstream/main' into window-mru

Hardcode Alt-Tab/Alt-shift-Tab for MRU window nav

- Add a `PRESET_BINDINGS` containing MRU navigation actions.
  `PRESET_BINDINGS` are overridden by user configuration so these remain
  available if the user needs them for another purpose
- Releasing the `Alt` key ends any in-progress MRU window traversal

Remove `focus-window-mru` actions from config

These actions are configured in presets but no longer available
for the bindings section of the configuration

Cancel MRU traversal with Alt-Esc

Had been forgotten in prior commit and was using `Mod` instead of `Alt`

Rephrase some comments

Fix Alt-Esc not cancelling window-mru

Merge remote-tracking branch 'upstream/main' into window-mru

Lock-in focus immediately on user interaction

As per suggestion by @bbb651, focus is locked-in immediately if a window
is interacted with, ie. receives key events or pointer clicks.

This change is also an opportunity to make the lockin timer less aggresive.

Merge remote-tracking branch 'upstream/main' into window-mru

Simplify WindowMRU::new

Now that there is a more general Niri::lockin_focus method, leverage
it in WindowMRU.

Replace Duration with Instant in WindowMRU timestamp

Merge remote-tracking branch 'upstream/main' into window-mru

Address PR comments - partial

- Swapped meaning of next and previous for MRU traversal
- Fixed comment that still referred to `Mod` as leader key for MRU traversal
  instead of `Alt`
- Fixed doc comments that were missing a period
- Stop using BinaryHeap in `WindowMRU::new()`
- Replaced `WindowMRU::mru_with()` method with a simpler `advance()`
- Simplified `Alt` key release handling code in `State::on_keyboard()`

Simplify early-mru-commit logic

No longer perform the mru-commit/lockin_focus in the next event loop callback.
Instead it is handled directly when it is determined that an event (pointer
or kbd) is forwarded to the active window.

Handle PR comments

- `focus_lockin` variables and configuration item renamed to `mru_commit`.
- added the Esc key to `suppressed_keys` if it was used to cancel an MRU
  traversal.
- removed `WindowMRU::mru_next` and `WindowMRU::mru_previous` methods
  as they didn't really provide more than the generic `WindowMRU::advance`
  method.
- removed obsolete `Niri::event_forwarded_to_focused_client` boolean
- added calls to `mru_commit()` (formerly `focus_lockin`) in:
  - `State::on_pointer_axis()`
  - `State::on_tablet_tool_axis()`
  - `State::on_tablet_tool_tip()`
  - `State::on_tablet_tool_proximity()`
  - `State::on_tablet_tool_button()`
  - `State::on_gesture_swipe_begin()`
  - `State::on_gesture_pinch_begin()`
  - `State::on_gesture_hold_begin()`
  - `State::on_touch_down()`

Merge remote-tracking branch 'upstream/main' into window-mru

Merge remote-tracking branch 'upstream/main' into window-mru

Include never focused windows in MRU list

Remove mru_commit_ms from configurable options

For now the value is hard-coded to 750ms

Merge remote-tracking branch 'upstream/main' into HEAD

Add hotkey_overlay_tile for PRESET_BINDINGS

Merge remote-tracking branch 'origin/window-mru' into HEAD

Merge remote-tracking branch 'upstream/main' into window-mru

Merge remote-tracking branch 'upstream/main' into window-mru

Merge remote-tracking branch 'upstream/main' into window-mru

Firt shot an MruUi

The UI doesn't actually do anything yet. For now it just puts up thumbnails
for existing windows in MRU order.

Added MRU texture cache + simplifications

Working version

Removed previous Mru code

Tidy up Action names

Added Home/End bindings

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Add scope and filtering to Mru window navigation

Feed todo list

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Clippy: Boxed the focus ring

The UI object doesn't get moved around much so it isn't clear if
this actually important. Boxing keeps clippy happy because of the
size difference between an Open vs a Closed MRU UI.

Bump rust version to 1.83

Avoids getting yelled at by clippy for using features that weren't yet available in 1.80.1

Applied clippy lints

Fix MruFilter::None conversion

MruFilter variant was getting ignored

cargo fmt

Update rust tool chain in CI

Had only been updated in Cargo.toml, this causes build
failures on Github

Support changing Mru modes with the Mru UI open

Fix texture cache optimization

When the Mru parameters were changed while the MruUI was open, the
texture cache is rebuilt but attempts to reuse existing Textures
that are still usable in the updated Mru list. The index of the
retained texture could be miscalculated and resulted in the wrong
texture being used for a given window Id.

Make MruAdvance available as a Bind action

For consistency, MruAdvance bindings are carried over when the MruUI is open.

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Preset binds added as a source for MRU UI binds

Surprisingly the status prior to the patch should have prevented the UI
bindings to advance through the Mru list from working properly.

Use iterators to find bindings

This allows the caller, eg. `on_keyboard` to choose the full list
of bindings that should be searched through by composing iterators.
Prior to the change the PRESET_BINDINGS were always included regardless
of caller. With this approach, `on_keyboard` can add in the MRU_UI-
specific bindings if it detects that the MRU UI is open.

Make scope and filter optional in mru-advance

This avoids unexpected behavior when navigating MRU with a filter, e.g. App-Id,
with arrow keys for instance, which would result in changing navigation
to ignore the app-id filter. With the change, mru-advance has an optional
scope and filter that allows a key bind to leave the current navigation mode
unchanged.

Add title under window thumbnails

- Reworked the texture cache to use TextureBuffer-s instead of BakedBuffer.
- Add convenience methods to access TextureCache content.

Some tidying up.

Fade title out if it doesn't fit in available size

Add bindings to change the MruScope

Fix panic rendering title when cairo surface was busy

Also avoid interpreting markup in window titles.

Bring branch in line with window-mru-ui-squashed

Add navigation animation in MRU UI

Only handles motion between thumbnails

Add thumbnail close animation

For now, the animation only tracks when the corresponding window is closed.

Add animations on filter and scope changes

Add open/close animation to MRU Ui

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Fix animations on scope/filter changes

Previous implementation would evict wrong textures from the cache.
And get thumbnail animations wrong.

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Fix panic on change of scope/filter when Mru list is empty.

Add doc comment to method that could trigger a panic

Simplify thumbnail ordering logic

Improve scope/filter change animations

- direction is no longer a factor when an Mru UI is opened (previously
  the first thumbnail would be the currently focused window when
  moving in the "forward" direction, and when moving in the "backward"
  direction the focused window would have its thumbnail last in the
  list. This made animations kind of confusing when switching scopes
  or filtering.

  The updated version always places the thumbnails in most recent
  focus order. So when the MRU UI is brought up in the "backward"
  direction, the last thumbnail in the MRU list starts selected.

- closing animations no longer use the view referential, but use
  the output referential instead. This makes disappearing thumbnails
  appear stationary on screen even if the view is moving. This tends to
  look less confusing than the previous approach.

Applied clippy lints

Preserve scope during fwd/backward navigation

Change preset keybinding declarations from const to static

Add thumbnail selection animation

This is still very much a work in progress:
- the focus ring is not shown until the animation completes
- if the tile is resized during the animation, the net effect looks
  pretty bad because proportions skip directly to those requested
  instead of transitioning smoothly.

Both points should be addressed by using regular tile rendering to an
OffscreenBuffer but I haven't much success there.

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Fix niri-config parse test

Use OffscreenBuffer to render ThumbnailSelection animation

todo: fix thumbnail destination if the target workspace is being swapped.

Handle workspace switch during thumbnail select animation

Close Overview when MRU UI is opened

Add configuration option to disable MRU UI

Make mod-key for MRU UI configurable

Avoid collecting MRU UI bindings on each input

Bindings are cached when first accessed, the cache is invalidated
whenever the configuration changes.

Close MRU UI when Overview is opened

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Fix MRU UI opened bindings always active

Remove mru-advance from actions available for config keybind

Because the MRU UI assumes that all key-bindings use the mod-key
defined in for `recent-windows`, behavior can be disconcerting
if arbitrary keybindings are allowed in the configuration (e.g.
UI opens and immediately closes because the mod-key is not being
held).

Include focus timestamp in Window IPC messages

Timestamps are serialized as time::SystemTime, which in JSON form is represented
as *two* fields, secs and nanos.

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Only do Thumbnail Select Anim if MRU UI stayed open long enough

Threshold is hard coded in window_mru_ui.rs (250ms).

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Add a few WindowMru tests

Forward Mod-key release when closing MRU UI

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Remove extraneous thumbnail motion on Mru filter change

Fix missing alpha in Mru thumbnail open animation

Add Mod+h and Mod+l bindings for MRU navigation

Change CloseWindow binding in MRU to Mod+Shift+q

Keep MRU UI on display it was initially opened on

Bump up the MRU IU selection anim threshold

Allow MRU thumbnail selection with mouse pointer

Allow MRU thumbnail selection using touch

Needs testing, Idk if this works for lack of a touchscreen.

Fix missing fade-out animation for thumbnails on MRU UI close

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Make thumbnail selection animation optional

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Fix niri-config parse test case

Add shortcut to cycle through MRU scopes

- added MruCycleScope action to trigger cycling
- added an indication panel to show the current scope
- recall previous scope when opening the MRU UI

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Improve MRU thumbnail scaling

Prior to the commit, thumbnails were just 2x downscaling of their corresponding
window. Now they are also scaled based on the relative height of the window
on its output display. This avoids having a thumbnail taking up the entire
screen on the display where the MRU UI is displayed.

Merge remote-tracking branch 'upstream/main' into window-mru-ui

Use resolved window rules for thumbnails

Previously parameters such as the corner-radius didn't follow the general
config and used an MRU UI specific default.

Align thumbnail size and position to physical pixels

clarify param names in generate_tile_texture

Revert MSRV 1.83

Close MRU UI on click/touch outside of a thumbnail

MRU - display window title under all thumbnails

MRU - revert to pre-defined thumbnail corner radius

MRU - Removed thumb title font size adjustment

This didn't look as if it was necessary. (unscientific assesment)

MRU - reverted to Mod+Q to quit selected thumbnail

Merge remote-tracking branch 'upstream/main' into window-mru-ui

MRU - Update focus ring when moving mouse over a thumbnail

restore code that went missing

switch focus timestamp to monotonic time

We don't want the monotonicity of SystemClock here. Instant itself isn't
serializable, but our monotonic clock timestamps are, and they are
consistent across processes too.

axe thumbnail close animation

I'm still not quite convinced about it. Maybe we'll reintroduce it later
with better architecture; for now though, it causes quite a bit of
complexity.

minor cleanups

remove unnecessary option

replace open animation with delay

Avoids flashing the whole screen for quick Alt-Tabs. Duration taken from
GNOME Shell.

make mod key different in nested

replace SelectedThumbnail with MappedId

don't hide focus ring during alt tab

wip refactor everything and render live windows

rename some constants

replace focus ring with background + border

extract thumbnail constructors

reimplement title fade with a shader

reimplement ui fade out on closing

fix preview scaling

add min scale for very small windows

add keyboard focus for mru

fixes activating alt on target window

revert/simplify pointer code changes

fixes mouse not clamped to output when in alt-tab; should fix touch
going through

move touch handling to below screenshot ui

remove unneeded touch overview grab code

rename to mru.rs

move mru tests into separate file

also close mru when clicking on other outputs

roll back no longer necessary event filtering

rework mru keyboard binds

convert some regular binds to MRU binds

hide window title when blocked out

verify that mru bind uses a keyboard key

improve selection visibility & indicate urgency

freeze alt-tab view on pointer motion

add WindowFocusTimestampChanged event, separate struct for Timestamp

minor cleanups

scope panel fixes

simplify scope cycling

honor geometry corner radius

don't trigger focus-follows-mouse in the MRU

remove unnecessary argument

cache backdrop buffers

remove unnecessary mru close

allow to screenshot the mru

support bob offset

improve mru redraws

pass config instead of options

add open-delay-ms option

add highlight options

rename window-mru-ui-open-close to recent-windows-close

add preview options

fix scope change and remove window delta anim

improve unselected scope panel text contrast

move panel back up so it doesn't overlap the screenshot one

rename preview to previews in config

render highlight background with focusring

fix highlight pos rounding

add highlight corner-radius setting

remove allocation from inner render

use offscreen for mru closing fade

make scope only affect MRU open

otherwise you can't change scope at runtime easily

replace todo with fixme

include title height in thumbnail under

remove cloning from set scope/filter

remove animate close todo

update field name in mapped

remove commented out closing thumbnails

I decided not to do this for now.

rename filter from None to All and skip in knuffel

None is confusing with Option

write docs

make inactive urgent more prominent

remove reopen from scartch todo

explicitly mention app id in filter

make scroll binds work in the mru

add fixmes

don't select next window when nothing is focused

add missing anim config merge

fixes

replace click selection with pointer motion + confirm

simplify close mru ui call

rename mrucloserequest variants

mru confirm fixes

support tablet input

mru commit cleanups

remove most mru commit calls

they didn't actualy do anything as implemented. If we want to bring them
back we need to refactor a bit to join them with activate_window() call.

make regular mouse binds also work in mru

fixes

fixes

move types up

fix tracy span
docs/mkdocs.yamlmodified+1 -0
@@ -103,6 +103,7 @@ nav:
103103 - Layer Rules: Configuration:-Layer-Rules.md
104104 - Animations: Configuration:-Animations.md
105105 - Gestures: Configuration:-Gestures.md
106+ - Recent Windows: Configuration:-Recent-Windows.md
106107 - Debug Options: Configuration:-Debug-Options.md
107108 - Include: Configuration:-Include.md
108109 - Development:
docs/wiki/Configuration:-Animations.mdmodified+18 -0
@@ -58,6 +58,10 @@ animations {
5858 overview-open-close {
5959 spring damping-ratio=1.0 stiffness=800 epsilon=0.0001
6060 }
61+
62+ recent-windows-close {
63+ spring damping-ratio=1.0 stiffness=800 epsilon=0.001
64+ }
6165 }
6266 ```
6367
@@ -422,6 +426,20 @@ animations {
422426 }
423427 ```
424428
429+#### `recent-windows-close`
430+
431+<sup>Since: next release</sup>
432+
433+The close fade-out animation of the recent windows switcher.
434+
435+```kdl
436+animations {
437+ recent-windows-close {
438+ spring damping-ratio=1.0 stiffness=800 epsilon=0.001
439+ }
440+}
441+```
442+
425443 ### Synchronized Animations
426444
427445 <sup>Since: 0.1.5</sup>
docs/wiki/Configuration:-Introduction.mdmodified+1 -0
@@ -12,6 +12,7 @@ You can find documentation for various sections of the config on these wiki page
1212 * [`layer-rule {}`](./Configuration:-Layer-Rules.md)
1313 * [`animations {}`](./Configuration:-Animations.md)
1414 * [`gestures {}`](./Configuration:-Gestures.md)
15+* [`recent-windows {}`](./Configuration:-Recent-Windows.md)
1516 * [`debug {}`](./Configuration:-Debug-Options.md)
1617 * [`include "other.kdl"`](./Configuration:-Include.md)
1718
docs/wiki/Configuration:-Recent-Windows.mdadded+166 -0
@@ -0,0 +1,166 @@
1+### Overview
2+
3+<sup>Since: next release</sup>
4+
5+In this section you can configure the recent windows switcher (Alt-Tab).
6+
7+Here is an outline of the available settings and their default values:
8+
9+```kdl
10+recent-windows {
11+ // off
12+ open-delay-ms 150
13+
14+ highlight {
15+ active-color "#999999ff"
16+ urgent-color "#ff9999ff"
17+ padding 30
18+ corner-radius 0
19+ }
20+
21+ previews {
22+ max-height 480
23+ max-scale 0.5
24+ }
25+
26+ binds {
27+ Alt+Tab { next-window; }
28+ Alt+Shift+Tab { previous-window; }
29+ Alt+grave { next-window filter="app-id"; }
30+ Alt+Shift+grave { previous-window filter="app-id"; }
31+
32+ Mod+Tab { next-window; }
33+ Mod+Shift+Tab { previous-window; }
34+ Mod+grave { next-window filter="app-id"; }
35+ Mod+Shift+grave { previous-window filter="app-id"; }
36+ }
37+}
38+```
39+
40+`off` disables the recent windows switcher altogether.
41+
42+### `open-delay-ms`
43+
44+Delay, in milliseconds, between pressing the Alt-Tab bind and the recent windows switcher visually appearing on screen.
45+
46+The switcher is delayed by default so that quickly tapping Alt-Tab to switch windows wouldn't cause annoying fullscreen visual changes.
47+
48+```kdl
49+recent-windows {
50+ // Make the switcher appear instantly.
51+ open-delay-ms 0
52+}
53+```
54+
55+### `highlight`
56+
57+Controls the highlight behind the focused window preview in the recent windows switcher.
58+
59+- `active-color`: normal color of the focused window highlight.
60+- `urgent-color`: color of an urgent focused window highlight, also visible in a darker shade on unfocused windows.
61+- `padding`: padding of the highlight around the window preview, in logical pixels.
62+- `corner-radius`: corner radius of the highlight.
63+
64+```kdl
65+recent-windows {
66+ // Round the corners on the highlight.
67+ highlight {
68+ corner-radius 14
69+ }
70+}
71+```
72+
73+### `previews`
74+
75+Controls the window previews in the switcher.
76+
77+- `max-scale`: maximum scale of the window previews.
78+Windows cannot be scaled bigger than this value.
79+- `max-height`: maximum height of the window previews.
80+Further limits the size of the previews in order to occupy less space on large monitors.
81+
82+On smaller monitors, the previews will be primarily limited by `max-scale`, and on larger monitors they will be primarily limited by `max-height`.
83+
84+The `max-scale` limit is imposed twice: on the final window scale, and on the window height which cannot exceed `monitor height × max scale`.
85+
86+```kdl
87+recent-windows {
88+ // Make the previews smaller to fit more on screen.
89+ previews {
90+ max-height 320
91+ }
92+}
93+```
94+
95+```kdl
96+recent-windows {
97+ // Make the previews larger to see the window contents.
98+ previews {
99+ max-height 1080
100+ max-scale 0.75
101+ }
102+}
103+```
104+
105+### `binds`
106+
107+Configure binds that open and navigate the recent windows switcher.
108+
109+The defaults are <kbd>Alt</kbd><kbd>Tab</kbd> / <kbd>Mod</kbd><kbd>Tab</kbd> to switch across all windows, and <kbd>Alt</kbd><kbd>\`</kbd> / <kbd>Mod</kbd><kbd>\`</kbd> to switch between windows of the current application.
110+Adding <kbd>Shift</kbd> will switch windows backwards.
111+
112+Adding the recent windows `binds {}` section to your config removes all default binds.
113+You can copy the ones you need from the summary at the top of this wiki page.
114+
115+```kdl
116+recent-windows {
117+ // Even an empty binds {} section will remove all default binds.
118+ binds {
119+ }
120+}
121+```
122+
123+The available actions are `next-window` and `previous-window`.
124+They can optionally have the following properties:
125+
126+- `filter="app-id"`: filters the switcher to the windows of the currently selected application, as determined by the Wayland app ID.
127+- `scope="all"`, `scope="output"`, `scope="workspace"`: sets the pre-selected scope when this bind is used to open the recent windows switcher.
128+
129+```kdl
130+recent-windows {
131+ // Pre-select the "Output" scope when switching windows.
132+ binds {
133+ Mod+Tab { next-window scope="output"; }
134+ Mod+Shift+Tab { previous-window scope="output"; }
135+ Mod+grave { next-window scope="output" filter="app-id"; }
136+ Mod+Shift+grave { previous-window scope="output" filter="app-id"; }
137+ }
138+}
139+```
140+
141+The recent windows binds have a precedence over the [normal binds](./Configuration:-Key-Bindings.md), meaning that if you have <kbd>Alt</kbd><kbd>Tab</kbd> bound to something else in the normal binds, the `recent-windows` bind will override it.
142+
143+All binds in this section must have a modifier key like <kbd>Alt</kbd> or <kbd>Mod</kbd> because the recent windows switcher remains open only while you hold any modifier key.
144+
145+#### Bindings inside the switcher
146+
147+When the switcher is open, some hardcoded binds are available:
148+
149+- <kbd>Escape</kbd> cancels the switcher.
150+- <kbd>Enter</kbd> closes the switcher confirming the current window.
151+- <kbd>A</kbd>, <kbd>W</kbd>, <kbd>O</kbd> select a specific scope.
152+- <kbd>S</kbd> cycles between scopes, as indicated by the panel at the top.
153+- <kbd>←</kbd>, <kbd>→</kbd>, <kbd>Home</kbd>, <kbd>End</kbd> move the selection directionally.
154+
155+Additionally, certain regular binds will automatically work in the switcher:
156+
157+- focus column left/right and their variants: will move the selection left/right inside the switcher.
158+- focus column first/last: will move the selection to the first or last window.
159+- close window: will close the window currently focused in the switcher.
160+- screenshot: will open the screenshot UI.
161+
162+The way this works is by finding all regular binds corresponding to these actions and taking just the trigger key without modifiers.
163+For example, if you have <kbd>Mod</kbd><kbd>Shift</kbd><kbd>C</kbd> bound to `close-window`, in the window switcher pressing <kbd>C</kbd> on its own will close the window.
164+
165+This way we don't need to hardcode things like HJKL directional movements.
166+If you have, say, Colemak-DH MNEI binds instead, they will work for you in the window switcher (as long as they don't conflict with the hardcoded ones).
docs/wiki/_Sidebar.mdmodified+1 -0
@@ -33,6 +33,7 @@
3333 * [Layer Rules](./Configuration:-Layer-Rules.md)
3434 * [Animations](./Configuration:-Animations.md)
3535 * [Gestures](./Configuration:-Gestures.md)
36+* [Recent Windows](./Configuration:-Recent-Windows.md)
3637 * [Debug Options](./Configuration:-Debug-Options.md)
3738 * [Include](./Configuration:-Include.md)
3839
niri-config/src/animations.rsmodified+36 -0
@@ -18,6 +18,7 @@ pub struct Animations {
1818 pub exit_confirmation_open_close: ExitConfirmationOpenCloseAnim,
1919 pub screenshot_ui_open: ScreenshotUiOpenAnim,
2020 pub overview_open_close: OverviewOpenCloseAnim,
21+ pub recent_windows_close: RecentWindowsCloseAnim,
2122 }
2223
2324 impl Default for Animations {
@@ -35,6 +36,7 @@ impl Default for Animations {
3536 exit_confirmation_open_close: Default::default(),
3637 screenshot_ui_open: Default::default(),
3738 overview_open_close: Default::default(),
39+ recent_windows_close: Default::default(),
3840 }
3941 }
4042 }
@@ -67,6 +69,8 @@ pub struct AnimationsPart {
6769 pub screenshot_ui_open: Option<ScreenshotUiOpenAnim>,
6870 #[knuffel(child)]
6971 pub overview_open_close: Option<OverviewOpenCloseAnim>,
72+ #[knuffel(child)]
73+ pub recent_windows_close: Option<RecentWindowsCloseAnim>,
7074 }
7175
7276 impl MergeWith<AnimationsPart> for Animations {
@@ -92,6 +96,7 @@ impl MergeWith<AnimationsPart> for Animations {
9296 exit_confirmation_open_close,
9397 screenshot_ui_open,
9498 overview_open_close,
99+ recent_windows_close,
95100 );
96101 }
97102 }
@@ -305,6 +310,22 @@ impl Default for OverviewOpenCloseAnim {
305310 }
306311 }
307312
313+#[derive(Debug, Clone, Copy, PartialEq)]
314+pub struct RecentWindowsCloseAnim(pub Animation);
315+
316+impl Default for RecentWindowsCloseAnim {
317+ fn default() -> Self {
318+ Self(Animation {
319+ off: false,
320+ kind: Kind::Spring(SpringParams {
321+ damping_ratio: 1.,
322+ stiffness: 800,
323+ epsilon: 0.001,
324+ }),
325+ })
326+ }
327+}
328+
308329 impl<S> knuffel::Decode<S> for WorkspaceSwitchAnim
309330 where
310331 S: knuffel::traits::ErrorSpan,
@@ -488,6 +509,21 @@ where
488509 }
489510 }
490511
512+impl<S> knuffel::Decode<S> for RecentWindowsCloseAnim
513+where
514+ S: knuffel::traits::ErrorSpan,
515+{
516+ fn decode_node(
517+ node: &knuffel::ast::SpannedNode<S>,
518+ ctx: &mut knuffel::decode::Context<S>,
519+ ) -> Result<Self, DecodeError<S>> {
520+ let default = Self::default().0;
521+ Ok(Self(Animation::decode_node(node, ctx, default, |_, _| {
522+ Ok(false)
523+ })?))
524+ }
525+}
526+
491527 impl Animation {
492528 pub fn new_off() -> Self {
493529 Self {
niri-config/src/binds.rsmodified+21 -0
@@ -12,6 +12,7 @@ use smithay::input::keyboard::keysyms::KEY_NoSymbol;
1212 use smithay::input::keyboard::xkb::{keysym_from_name, KEYSYM_CASE_INSENSITIVE, KEYSYM_NO_FLAGS};
1313 use smithay::input::keyboard::Keysym;
1414
15+use crate::recent_windows::{MruDirection, MruFilter, MruScope};
1516 use crate::utils::{expect_only_children, MergeWith};
1617
1718 #[derive(Debug, Default, PartialEq)]
@@ -364,6 +365,26 @@ pub enum Action {
364365 UnsetWindowUrgent(u64),
365366 #[knuffel(skip)]
366367 LoadConfigFile,
368+ #[knuffel(skip)]
369+ MruAdvance {
370+ direction: MruDirection,
371+ scope: Option<MruScope>,
372+ filter: Option<MruFilter>,
373+ },
374+ #[knuffel(skip)]
375+ MruConfirm,
376+ #[knuffel(skip)]
377+ MruCancel,
378+ #[knuffel(skip)]
379+ MruCloseCurrentWindow,
380+ #[knuffel(skip)]
381+ MruFirst,
382+ #[knuffel(skip)]
383+ MruLast,
384+ #[knuffel(skip)]
385+ MruSetScope(MruScope),
386+ #[knuffel(skip)]
387+ MruCycleScope,
367388 }
368389
369390 impl From<niri_ipc::Action> for Action {
niri-config/src/lib.rsmodified+155 -1
@@ -13,7 +13,7 @@
1313 #[macro_use]
1414 extern crate tracing;
1515
16-use std::cell::RefCell;
16+use std::cell::{Cell, RefCell};
1717 use std::collections::HashSet;
1818 use std::ffi::OsStr;
1919 use std::fs::{self, File};
@@ -39,6 +39,7 @@ pub mod layer_rule;
3939 pub mod layout;
4040 pub mod misc;
4141 pub mod output;
42+pub mod recent_windows;
4243 pub mod utils;
4344 pub mod window_rule;
4445 pub mod workspace;
@@ -54,6 +55,10 @@ pub use crate::layer_rule::LayerRule;
5455 pub use crate::layout::*;
5556 pub use crate::misc::*;
5657 pub use crate::output::{Output, OutputName, Outputs, Position, Vrr};
58+use crate::recent_windows::RecentWindowsPart;
59+pub use crate::recent_windows::{
60+ MruDirection, MruFilter, MruPreviews, MruScope, RecentWindows, DEFAULT_MRU_COMMIT_MS,
61+};
5762 pub use crate::utils::FloatOrInt;
5863 use crate::utils::{Flag, MergeWith as _};
5964 pub use crate::window_rule::{FloatingPosition, RelativeTo, WindowRule};
@@ -85,6 +90,7 @@ pub struct Config {
8590 pub switch_events: SwitchBinds,
8691 pub debug: Debug,
8792 pub workspaces: Vec<Workspace>,
93+ pub recent_windows: RecentWindows,
8894 }
8995
9096 #[derive(Debug, Clone)]
@@ -118,6 +124,7 @@ struct IncludeErrors(Vec<knuffel::Error>);
118124 //
119125 // We don't *need* it because we have a recursion limit, but it makes for nicer error messages.
120126 struct IncludeStack(HashSet<PathBuf>);
127+struct SawMruBinds(Rc<Cell<bool>>);
121128
122129 // Rather than listing all fields and deriving knuffel::Decode, we implement
123130 // knuffel::DecodeChildren by hand, since we need custom logic for every field anyway: we want to
@@ -140,6 +147,7 @@ where
140147 let includes = ctx.get::<Rc<RefCell<Includes>>>().unwrap().clone();
141148 let include_errors = ctx.get::<Rc<RefCell<IncludeErrors>>>().unwrap().clone();
142149 let recursion = ctx.get::<Recursion>().unwrap().0;
150+ let saw_mru_binds = ctx.get::<SawMruBinds>().unwrap().0.clone();
143151
144152 let mut seen = HashSet::new();
145153
@@ -269,6 +277,21 @@ where
269277 config.borrow_mut().layout.merge_with(&part);
270278 }
271279
280+ "recent-windows" => {
281+ let part = RecentWindowsPart::decode_node(node, ctx)?;
282+
283+ let mut config = config.borrow_mut();
284+
285+ // When an MRU binds section is encountered for the first time, clear out the
286+ // default MRU binds.
287+ if !saw_mru_binds.get() && part.binds.is_some() {
288+ saw_mru_binds.set(true);
289+ config.recent_windows.binds.clear();
290+ }
291+
292+ config.recent_windows.merge_with(&part);
293+ }
294+
272295 "include" => {
273296 let path: PathBuf = utils::parse_arg_node("include", node, ctx)?;
274297 let base = ctx.get::<BasePath>().unwrap();
@@ -331,6 +354,7 @@ where
331354 ctx.set(includes.clone());
332355 ctx.set(include_errors.clone());
333356 ctx.set(IncludeStack(include_stack));
357+ ctx.set(SawMruBinds(saw_mru_binds.clone()));
334358 ctx.set(config.clone());
335359 });
336360
@@ -424,6 +448,7 @@ impl Config {
424448 ctx.set(includes.clone());
425449 ctx.set(include_errors.clone());
426450 ctx.set(IncludeStack(include_stack));
451+ ctx.set(SawMruBinds(Rc::new(Cell::new(false))));
427452 ctx.set(config.clone());
428453 },
429454 );
@@ -766,6 +791,10 @@ mod tests {
766791 window-close {
767792 curve "cubic-bezier" 0.05 0.7 0.1 1
768793 }
794+
795+ recent-windows-close {
796+ off
797+ }
769798 }
770799
771800 gestures {
@@ -848,6 +877,25 @@ mod tests {
848877 }
849878 workspace "workspace-2"
850879 workspace "workspace-3"
880+
881+ recent-windows {
882+ off
883+
884+ highlight {
885+ padding 15
886+ active-color "#00ff00"
887+ }
888+
889+ previews {
890+ max-height 960
891+ }
892+
893+ binds {
894+ Alt+Tab { next-window; }
895+ Alt+grave { next-window filter="app-id"; }
896+ Super+Tab { next-window scope="output"; }
897+ }
898+ }
851899 "##,
852900 );
853901
@@ -1507,6 +1555,18 @@ mod tests {
15071555 ),
15081556 },
15091557 ),
1558+ recent_windows_close: RecentWindowsCloseAnim(
1559+ Animation {
1560+ off: true,
1561+ kind: Spring(
1562+ SpringParams {
1563+ damping_ratio: 1.0,
1564+ stiffness: 800,
1565+ epsilon: 0.001,
1566+ },
1567+ ),
1568+ },
1569+ ),
15101570 },
15111571 gestures: Gestures {
15121572 dnd_edge_view_scroll: DndEdgeViewScroll {
@@ -2119,6 +2179,100 @@ mod tests {
21192179 layout: None,
21202180 },
21212181 ],
2182+ recent_windows: RecentWindows {
2183+ on: false,
2184+ open_delay_ms: 150,
2185+ highlight: MruHighlight {
2186+ active_color: Color {
2187+ r: 0.0,
2188+ g: 1.0,
2189+ b: 0.0,
2190+ a: 1.0,
2191+ },
2192+ urgent_color: Color {
2193+ r: 1.0,
2194+ g: 0.6,
2195+ b: 0.6,
2196+ a: 1.0,
2197+ },
2198+ padding: 15.0,
2199+ corner_radius: 0.0,
2200+ },
2201+ previews: MruPreviews {
2202+ max_height: 960.0,
2203+ max_scale: 0.5,
2204+ },
2205+ binds: [
2206+ Bind {
2207+ key: Key {
2208+ trigger: Keysym(
2209+ XK_Tab,
2210+ ),
2211+ modifiers: Modifiers(
2212+ ALT,
2213+ ),
2214+ },
2215+ action: MruAdvance {
2216+ direction: Forward,
2217+ scope: None,
2218+ filter: Some(
2219+ All,
2220+ ),
2221+ },
2222+ repeat: true,
2223+ cooldown: None,
2224+ allow_when_locked: false,
2225+ allow_inhibiting: true,
2226+ hotkey_overlay_title: None,
2227+ },
2228+ Bind {
2229+ key: Key {
2230+ trigger: Keysym(
2231+ XK_grave,
2232+ ),
2233+ modifiers: Modifiers(
2234+ ALT,
2235+ ),
2236+ },
2237+ action: MruAdvance {
2238+ direction: Forward,
2239+ scope: None,
2240+ filter: Some(
2241+ AppId,
2242+ ),
2243+ },
2244+ repeat: true,
2245+ cooldown: None,
2246+ allow_when_locked: false,
2247+ allow_inhibiting: true,
2248+ hotkey_overlay_title: None,
2249+ },
2250+ Bind {
2251+ key: Key {
2252+ trigger: Keysym(
2253+ XK_Tab,
2254+ ),
2255+ modifiers: Modifiers(
2256+ SUPER,
2257+ ),
2258+ },
2259+ action: MruAdvance {
2260+ direction: Forward,
2261+ scope: Some(
2262+ Output,
2263+ ),
2264+ filter: Some(
2265+ All,
2266+ ),
2267+ },
2268+ repeat: true,
2269+ cooldown: None,
2270+ allow_when_locked: false,
2271+ allow_inhibiting: true,
2272+ hotkey_overlay_title: None,
2273+ },
2274+ ],
2275+ },
21222276 }
21232277 "#);
21242278 }
niri-config/src/recent_windows.rsadded+401 -0
@@ -0,0 +1,401 @@
1+use std::collections::HashSet;
2+
3+use knuffel::errors::DecodeError;
4+use smithay::input::keyboard::Keysym;
5+
6+use crate::utils::{expect_only_children, MergeWith};
7+use crate::{Action, Bind, Color, FloatOrInt, Key, Modifiers, Trigger};
8+
9+/// Delay before the window focus is considered to be locked-in for Window
10+/// MRU ordering. For now the delay is not configurable.
11+pub const DEFAULT_MRU_COMMIT_MS: u64 = 750;
12+
13+#[derive(Debug, PartialEq)]
14+pub struct RecentWindows {
15+ pub on: bool,
16+ pub open_delay_ms: u16,
17+ pub highlight: MruHighlight,
18+ pub previews: MruPreviews,
19+ pub binds: Vec<Bind>,
20+}
21+
22+impl Default for RecentWindows {
23+ fn default() -> Self {
24+ RecentWindows {
25+ on: true,
26+ open_delay_ms: 150,
27+ highlight: MruHighlight::default(),
28+ previews: MruPreviews::default(),
29+ binds: default_binds(),
30+ }
31+ }
32+}
33+
34+#[derive(knuffel::Decode, Debug, Default, PartialEq)]
35+pub struct RecentWindowsPart {
36+ #[knuffel(child)]
37+ pub on: bool,
38+ #[knuffel(child)]
39+ pub off: bool,
40+ #[knuffel(child, unwrap(argument))]
41+ pub open_delay_ms: Option<u16>,
42+ #[knuffel(child)]
43+ pub highlight: Option<MruHighlightPart>,
44+ #[knuffel(child)]
45+ pub previews: Option<MruPreviewsPart>,
46+ #[knuffel(child)]
47+ pub binds: Option<MruBinds>,
48+}
49+
50+impl MergeWith<RecentWindowsPart> for RecentWindows {
51+ fn merge_with(&mut self, part: &RecentWindowsPart) {
52+ self.on |= part.on;
53+ if part.off {
54+ self.on = false;
55+ }
56+
57+ merge_clone!((self, part), open_delay_ms);
58+ merge!((self, part), highlight, previews);
59+
60+ if let Some(part) = &part.binds {
61+ // Remove existing binds matching any new bind.
62+ self.binds
63+ .retain(|bind| !part.0.iter().any(|new| new.key == bind.key));
64+ // Add all new binds.
65+ self.binds.extend(part.0.iter().cloned().map(Bind::from));
66+ }
67+ }
68+}
69+
70+#[derive(Debug, PartialEq)]
71+pub struct MruHighlight {
72+ pub active_color: Color,
73+ pub urgent_color: Color,
74+ pub padding: f64,
75+ pub corner_radius: f64,
76+}
77+
78+impl Default for MruHighlight {
79+ fn default() -> Self {
80+ Self {
81+ active_color: Color::new_unpremul(0.6, 0.6, 0.6, 1.),
82+ urgent_color: Color::new_unpremul(1., 0.6, 0.6, 1.),
83+ padding: 30.,
84+ corner_radius: 0.,
85+ }
86+ }
87+}
88+
89+#[derive(knuffel::Decode, Debug, Default, PartialEq)]
90+pub struct MruHighlightPart {
91+ #[knuffel(child)]
92+ pub active_color: Option<Color>,
93+ #[knuffel(child)]
94+ pub urgent_color: Option<Color>,
95+ #[knuffel(child, unwrap(argument))]
96+ pub padding: Option<FloatOrInt<0, 65535>>,
97+ #[knuffel(child, unwrap(argument))]
98+ pub corner_radius: Option<FloatOrInt<0, 65535>>,
99+}
100+
101+impl MergeWith<MruHighlightPart> for MruHighlight {
102+ fn merge_with(&mut self, part: &MruHighlightPart) {
103+ merge_clone!((self, part), active_color, urgent_color);
104+ merge!((self, part), padding, corner_radius);
105+ }
106+}
107+
108+#[derive(Debug, Clone, Copy, PartialEq)]
109+pub struct MruPreviews {
110+ pub max_height: f64,
111+ pub max_scale: f64,
112+}
113+
114+impl Default for MruPreviews {
115+ fn default() -> Self {
116+ Self {
117+ max_height: 480.,
118+ max_scale: 0.5,
119+ }
120+ }
121+}
122+
123+#[derive(knuffel::Decode, Debug, Default, PartialEq)]
124+pub struct MruPreviewsPart {
125+ #[knuffel(child, unwrap(argument))]
126+ pub max_height: Option<FloatOrInt<1, 65535>>,
127+ #[knuffel(child, unwrap(argument))]
128+ pub max_scale: Option<FloatOrInt<0, 1>>,
129+}
130+
131+impl MergeWith<MruPreviewsPart> for MruPreviews {
132+ fn merge_with(&mut self, part: &MruPreviewsPart) {
133+ merge!((self, part), max_height, max_scale);
134+ }
135+}
136+
137+#[derive(Debug, Clone, PartialEq)]
138+pub struct MruBind {
139+ // MRU bind keys must have a modifier, this is enforced during parsing. The switcher will close
140+ // once all modifiers are released.
141+ pub key: Key,
142+ pub action: MruAction,
143+ pub allow_inhibiting: bool,
144+ pub hotkey_overlay_title: Option<Option<String>>,
145+}
146+
147+impl From<MruBind> for Bind {
148+ fn from(x: MruBind) -> Self {
149+ Self {
150+ key: x.key,
151+ action: Action::from(x.action),
152+ repeat: true,
153+ cooldown: None,
154+ allow_when_locked: false,
155+ allow_inhibiting: x.allow_inhibiting,
156+ hotkey_overlay_title: x.hotkey_overlay_title,
157+ }
158+ }
159+}
160+
161+#[derive(Clone, Copy, Debug, Default, PartialEq)]
162+pub enum MruDirection {
163+ /// Most recently used to least.
164+ #[default]
165+ Forward,
166+ /// Least recently used to most.
167+ Backward,
168+}
169+
170+#[derive(knuffel::DecodeScalar, Clone, Copy, Debug, Default, PartialEq)]
171+pub enum MruScope {
172+ /// All windows.
173+ #[default]
174+ All,
175+ /// Windows on the active output.
176+ Output,
177+ /// Windows on the active workspace.
178+ Workspace,
179+}
180+
181+#[derive(knuffel::DecodeScalar, Clone, Copy, Debug, Default, PartialEq)]
182+pub enum MruFilter {
183+ /// All windows.
184+ #[default]
185+ #[knuffel(skip)]
186+ All,
187+ /// Windows with the same app id as the active window.
188+ AppId,
189+}
190+
191+#[derive(knuffel::Decode, Debug, Clone, PartialEq)]
192+pub enum MruAction {
193+ NextWindow(
194+ #[knuffel(property(name = "scope"))] Option<MruScope>,
195+ #[knuffel(property(name = "filter"), default)] MruFilter,
196+ ),
197+ PreviousWindow(
198+ #[knuffel(property(name = "scope"))] Option<MruScope>,
199+ #[knuffel(property(name = "filter"), default)] MruFilter,
200+ ),
201+}
202+
203+impl From<MruAction> for Action {
204+ fn from(x: MruAction) -> Self {
205+ match x {
206+ MruAction::NextWindow(scope, filter) => Self::MruAdvance {
207+ direction: MruDirection::Forward,
208+ scope,
209+ filter: Some(filter),
210+ },
211+ MruAction::PreviousWindow(scope, filter) => Self::MruAdvance {
212+ direction: MruDirection::Backward,
213+ scope,
214+ filter: Some(filter),
215+ },
216+ }
217+ }
218+}
219+
220+#[derive(Debug, Default, PartialEq)]
221+pub struct MruBinds(pub Vec<MruBind>);
222+
223+fn default_binds() -> Vec<Bind> {
224+ let mut rv = Vec::new();
225+
226+ let mut push = |trigger, base_mod, filter| {
227+ rv.push(Bind::from(MruBind {
228+ key: Key {
229+ trigger: Trigger::Keysym(trigger),
230+ modifiers: base_mod,
231+ },
232+ action: MruAction::NextWindow(None, filter),
233+ allow_inhibiting: true,
234+ hotkey_overlay_title: None,
235+ }));
236+ rv.push(Bind::from(MruBind {
237+ key: Key {
238+ trigger: Trigger::Keysym(trigger),
239+ modifiers: base_mod | Modifiers::SHIFT,
240+ },
241+ action: MruAction::PreviousWindow(None, filter),
242+ allow_inhibiting: true,
243+ hotkey_overlay_title: None,
244+ }));
245+ };
246+
247+ for base_mod in [Modifiers::ALT, Modifiers::COMPOSITOR] {
248+ push(Keysym::Tab, base_mod, MruFilter::All);
249+ push(Keysym::grave, base_mod, MruFilter::AppId);
250+ }
251+
252+ rv
253+}
254+
255+impl<S> knuffel::Decode<S> for MruBinds
256+where
257+ S: knuffel::traits::ErrorSpan,
258+{
259+ fn decode_node(
260+ node: &knuffel::ast::SpannedNode<S>,
261+ ctx: &mut knuffel::decode::Context<S>,
262+ ) -> Result<Self, DecodeError<S>> {
263+ expect_only_children(node, ctx);
264+
265+ let mut seen_keys = HashSet::new();
266+
267+ let mut binds = Vec::new();
268+
269+ for child in node.children() {
270+ match MruBind::decode_node(child, ctx) {
271+ Ok(bind) => {
272+ if !seen_keys.insert(bind.key) {
273+ ctx.emit_error(DecodeError::unexpected(
274+ &child.node_name,
275+ "keybind",
276+ "duplicate keybind",
277+ ));
278+ continue;
279+ }
280+
281+ binds.push(bind);
282+ }
283+ Err(e) => {
284+ ctx.emit_error(e);
285+ }
286+ }
287+ }
288+
289+ Ok(Self(binds))
290+ }
291+}
292+
293+impl<S> knuffel::Decode<S> for MruBind
294+where
295+ S: knuffel::traits::ErrorSpan,
296+{
297+ fn decode_node(
298+ node: &knuffel::ast::SpannedNode<S>,
299+ ctx: &mut knuffel::decode::Context<S>,
300+ ) -> Result<Self, DecodeError<S>> {
301+ if let Some(type_name) = &node.type_name {
302+ ctx.emit_error(DecodeError::unexpected(
303+ type_name,
304+ "type name",
305+ "no type name expected for this node",
306+ ));
307+ }
308+
309+ for val in node.arguments.iter() {
310+ ctx.emit_error(DecodeError::unexpected(
311+ &val.literal,
312+ "argument",
313+ "no arguments expected for this node",
314+ ));
315+ }
316+
317+ let key = node
318+ .node_name
319+ .parse::<Key>()
320+ .map_err(|e| DecodeError::conversion(&node.node_name, e.wrap_err("invalid keybind")))?;
321+
322+ // A modifier is required because MRU remains on screen as long as any modifier is held.
323+ if key.modifiers.is_empty() {
324+ ctx.emit_error(DecodeError::unexpected(
325+ &node.node_name,
326+ "keybind",
327+ "keybind must have a modifier key",
328+ ));
329+ }
330+
331+ // FIXME: To support this, all the mods_with_mouse_binds()/mods_with_wheel_binds()/etc.
332+ // will need to learn about recent-windows bindings.
333+ if !matches!(key.trigger, Trigger::Keysym(_)) {
334+ ctx.emit_error(DecodeError::unexpected(
335+ &node.node_name,
336+ "key",
337+ "key must be a keyboard key (others are unsupported here for now)",
338+ ));
339+ }
340+
341+ let mut allow_inhibiting = true;
342+ let mut hotkey_overlay_title = None;
343+ for (name, val) in &node.properties {
344+ match &***name {
345+ "allow-inhibiting" => {
346+ allow_inhibiting = knuffel::traits::DecodeScalar::decode(val, ctx)?;
347+ }
348+ "hotkey-overlay-title" => {
349+ hotkey_overlay_title = Some(knuffel::traits::DecodeScalar::decode(val, ctx)?);
350+ }
351+ name_str => {
352+ ctx.emit_error(DecodeError::unexpected(
353+ name,
354+ "property",
355+ format!("unexpected property `{}`", name_str.escape_default()),
356+ ));
357+ }
358+ }
359+ }
360+
361+ let mut children = node.children();
362+
363+ // If the action is invalid but the key is fine, we still want to return something.
364+ // That way, the parent can handle the existence of duplicate keybinds,
365+ // even if their contents are not valid.
366+ let dummy = Self {
367+ key,
368+ action: MruAction::NextWindow(None, MruFilter::All),
369+ allow_inhibiting: true,
370+ hotkey_overlay_title: None,
371+ };
372+
373+ if let Some(child) = children.next() {
374+ for unwanted_child in children {
375+ ctx.emit_error(DecodeError::unexpected(
376+ unwanted_child,
377+ "node",
378+ "only one action is allowed per keybind",
379+ ));
380+ }
381+ match MruAction::decode_node(child, ctx) {
382+ Ok(action) => Ok(Self {
383+ key,
384+ action,
385+ allow_inhibiting,
386+ hotkey_overlay_title,
387+ }),
388+ Err(e) => {
389+ ctx.emit_error(e);
390+ Ok(dummy)
391+ }
392+ }
393+ } else {
394+ ctx.emit_error(DecodeError::missing(
395+ node,
396+ "expected an action for this keybind",
397+ ));
398+ Ok(dummy)
399+ }
400+ }
401+}
src/a11y.rsmodified+7 -0
@@ -16,6 +16,7 @@ const ID_ANNOUNCEMENT: NodeId = NodeId(1);
1616 const ID_SCREENSHOT_UI: NodeId = NodeId(2);
1717 const ID_EXIT_CONFIRM_DIALOG: NodeId = NodeId(3);
1818 const ID_OVERVIEW: NodeId = NodeId(4);
19+const ID_MRU: NodeId = NodeId(5);
1920
2021 pub struct A11y {
2122 event_loop: LoopHandle<'static, State>,
@@ -205,6 +206,7 @@ impl Niri {
205206 KeyboardFocus::ScreenshotUi => ID_SCREENSHOT_UI,
206207 KeyboardFocus::ExitConfirmDialog => ID_EXIT_CONFIRM_DIALOG,
207208 KeyboardFocus::Overview => ID_OVERVIEW,
209+ KeyboardFocus::Mru => ID_MRU,
208210 _ => ID_ROOT,
209211 }
210212 }
@@ -237,12 +239,16 @@ impl Niri {
237239 let mut overview = Node::new(Role::Group);
238240 overview.set_label("Overview");
239241
242+ let mut mru = Node::new(Role::Group);
243+ mru.set_label("Recent windows");
244+
240245 let mut root = Node::new(Role::Window);
241246 root.set_children(vec![
242247 ID_ANNOUNCEMENT,
243248 ID_SCREENSHOT_UI,
244249 ID_EXIT_CONFIRM_DIALOG,
245250 ID_OVERVIEW,
251+ ID_MRU,
246252 ]);
247253
248254 let tree = Tree {
@@ -260,6 +266,7 @@ impl Niri {
260266 (ID_SCREENSHOT_UI, screenshot_ui),
261267 (ID_EXIT_CONFIRM_DIALOG, exit_confirm_dialog),
262268 (ID_OVERVIEW, overview),
269+ (ID_MRU, mru),
263270 ],
264271 tree: Some(tree),
265272 focus,
src/handlers/compositor.rsmodified+8 -0
@@ -291,6 +291,7 @@ impl CompositorHandler for State {
291291 self.niri
292292 .stop_casts_for_target(CastTarget::Window { id: id.get() });
293293
294+ self.niri.window_mru_ui.remove_window(id);
294295 self.niri.layout.remove_window(&window, transaction.clone());
295296 self.add_default_dmabuf_pre_commit_hook(surface);
296297
@@ -311,6 +312,7 @@ impl CompositorHandler for State {
311312
312313 if let Some(output) = output {
313314 self.niri.queue_redraw(&output);
315+ self.niri.queue_redraw_mru_output();
314316 }
315317 return;
316318 }
@@ -337,6 +339,7 @@ impl CompositorHandler for State {
337339 }
338340
339341 // The toplevel remains mapped.
342+ self.niri.window_mru_ui.update_window(&self.niri.layout, id);
340343 self.niri.layout.update_window(&window, serial);
341344
342345 // Move the toplevel according to the attach offset.
@@ -357,6 +360,7 @@ impl CompositorHandler for State {
357360
358361 if let Some(output) = output {
359362 self.niri.queue_redraw(&output);
363+ self.niri.queue_redraw_mru_output();
360364 }
361365 return;
362366 }
@@ -370,9 +374,13 @@ impl CompositorHandler for State {
370374 let window = mapped.window.clone();
371375 let output = output.cloned();
372376 window.on_commit();
377+ self.niri
378+ .window_mru_ui
379+ .update_window(&self.niri.layout, mapped.id());
373380 self.niri.layout.update_window(&window, None);
374381 if let Some(output) = output {
375382 self.niri.queue_redraw(&output);
383+ self.niri.queue_redraw_mru_output();
376384 }
377385 return;
378386 }
src/handlers/xdg_shell.rsmodified+5 -3
@@ -864,9 +864,9 @@ impl XdgShellHandler for State {
864864 let window = mapped.window.clone();
865865 let output = output.cloned();
866866
867- self.niri.stop_casts_for_target(CastTarget::Window {
868- id: mapped.id().get(),
869- });
867+ let id = mapped.id();
868+ self.niri
869+ .stop_casts_for_target(CastTarget::Window { id: id.get() });
870870
871871 self.backend.with_primary_renderer(|renderer| {
872872 self.niri.layout.store_unmap_snapshot(renderer, &window);
@@ -883,6 +883,7 @@ impl XdgShellHandler for State {
883883 let active_window = self.niri.layout.focus().map(|m| &m.window);
884884 let was_active = active_window == Some(&window);
885885
886+ self.niri.window_mru_ui.remove_window(id);
886887 self.niri.layout.remove_window(&window, transaction.clone());
887888 self.add_default_dmabuf_pre_commit_hook(surface.wl_surface());
888889
@@ -898,6 +899,7 @@ impl XdgShellHandler for State {
898899
899900 if let Some(output) = output {
900901 self.niri.queue_redraw(&output);
902+ self.niri.queue_redraw_mru_output();
901903 }
902904 }
903905
src/input/mod.rsmodified+303 -70
@@ -6,7 +6,9 @@ use std::time::Duration;
66
77 use calloop::timer::{TimeoutAction, Timer};
88 use input::event::gesture::GestureEventCoordinates as _;
9-use niri_config::{Action, Bind, Binds, Key, ModKey, Modifiers, SwitchBinds, Trigger};
9+use niri_config::{
10+ Action, Bind, Binds, Config, Key, ModKey, Modifiers, MruDirection, SwitchBinds, Trigger,
11+};
1012 use niri_ipc::LayoutSwitchTarget;
1113 use smithay::backend::input::{
1214 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Device, DeviceCapability, Event,
@@ -43,6 +45,7 @@ use self::spatial_movement_grab::SpatialMovementGrab;
4345 use crate::layout::scrolling::ScrollDirection;
4446 use crate::layout::{ActivateWindow, LayoutElement as _};
4547 use crate::niri::{CastTarget, PointerVisibility, State};
48+use crate::ui::mru::{WindowMru, WindowMruUi};
4649 use crate::ui::screenshot_ui::ScreenshotUi;
4750 use crate::utils::spawning::{spawn, spawn_sh};
4851 use crate::utils::{center, get_monotonic_time, ResizeEdge};
@@ -385,6 +388,7 @@ impl State {
385388 let key_code = event.key_code();
386389 let modified = keysym.modified_sym();
387390 let raw = keysym.raw_latin_sym_or_raw_current_sym();
391+ let modifiers = modifiers_from_state(*mods);
388392
389393 if this.niri.exit_confirm_dialog.is_open() && pressed {
390394 if raw == Some(Keysym::Return) {
@@ -397,6 +401,18 @@ impl State {
397401 return FilterResult::Intercept(None);
398402 }
399403
404+ // Check if all modifiers were released while the MRU UI was open. If so, close the
405+ // UI (which will also transfer the focus to the current MRU UI selection).
406+ if this.niri.window_mru_ui.is_open() && !pressed && modifiers.is_empty() {
407+ this.do_action(Action::MruConfirm, false);
408+
409+ if this.niri.suppressed_keys.remove(&key_code) {
410+ return FilterResult::Intercept(None);
411+ } else {
412+ return FilterResult::Forward;
413+ }
414+ }
415+
400416 if pressed
401417 && raw == Some(Keysym::Escape)
402418 && (this.niri.pick_window.is_some() || this.niri.pick_color.is_some())
@@ -416,20 +432,25 @@ impl State {
416432 this.niri.screenshot_ui.set_space_down(pressed);
417433 }
418434
419- let bindings = &this.niri.config.borrow().binds;
420- let res = should_intercept_key(
421- &mut this.niri.suppressed_keys,
422- &bindings.0,
423- mod_key,
424- key_code,
425- modified,
426- raw,
427- pressed,
428- *mods,
429- &this.niri.screenshot_ui,
430- this.niri.config.borrow().input.disable_power_key_handling,
431- is_inhibiting_shortcuts,
432- );
435+ let res = {
436+ let config = this.niri.config.borrow();
437+ let bindings =
438+ make_binds_iter(&config, &mut this.niri.window_mru_ui, modifiers);
439+
440+ should_intercept_key(
441+ &mut this.niri.suppressed_keys,
442+ bindings,
443+ mod_key,
444+ key_code,
445+ modified,
446+ raw,
447+ pressed,
448+ *mods,
449+ &this.niri.screenshot_ui,
450+ this.niri.config.borrow().input.disable_power_key_handling,
451+ is_inhibiting_shortcuts,
452+ )
453+ };
433454
434455 if matches!(res, FilterResult::Forward) {
435456 // If we didn't find any bind, try other hardcoded keys.
@@ -440,6 +461,10 @@ impl State {
440461 return FilterResult::Intercept(Some(bind));
441462 }
442463 }
464+
465+ // Interaction with the active window, immediately update the active window's
466+ // focus timestamp without waiting for a possible pending MRU lock-in delay.
467+ this.niri.mru_apply_keyboard_commit();
443468 }
444469
445470 res
@@ -641,6 +666,7 @@ impl State {
641666 }
642667 Action::Screenshot(show_cursor, path) => {
643668 self.open_screenshot_ui(show_cursor, path);
669+ self.niri.cancel_mru();
644670 }
645671 Action::ScreenshotWindow(write_to_disk, path) => {
646672 let focus = self.niri.layout.focus_with_output();
@@ -2179,6 +2205,90 @@ impl State {
21792205 watcher.load_config();
21802206 }
21812207 }
2208+ Action::MruConfirm => {
2209+ self.confirm_mru();
2210+ }
2211+ Action::MruCancel => {
2212+ self.niri.cancel_mru();
2213+ }
2214+ Action::MruAdvance {
2215+ direction,
2216+ scope,
2217+ filter,
2218+ } => {
2219+ if self.niri.window_mru_ui.is_open() {
2220+ self.niri.window_mru_ui.advance(direction, filter);
2221+ self.niri.queue_redraw_mru_output();
2222+ } else if self.niri.config.borrow().recent_windows.on {
2223+ self.niri.mru_apply_keyboard_commit();
2224+
2225+ let config = self.niri.config.borrow();
2226+ let scope = scope.unwrap_or(self.niri.window_mru_ui.scope());
2227+
2228+ let mut wmru = WindowMru::new(&self.niri);
2229+ if !wmru.is_empty() {
2230+ wmru.set_scope(scope);
2231+ if let Some(filter) = filter {
2232+ wmru.set_filter(filter);
2233+ }
2234+
2235+ if let Some(output) = self.niri.layout.active_output() {
2236+ self.niri.window_mru_ui.open(
2237+ self.niri.clock.clone(),
2238+ wmru,
2239+ output.clone(),
2240+ );
2241+
2242+ // Only select the *next* window if some window (which should be the
2243+ // first one) is already focused. If nothing is focused, keep the first
2244+ // window (which is logically the "previously selected" one).
2245+ let keep_first = direction == MruDirection::Forward
2246+ && self.niri.layout.focus().is_none();
2247+ if !keep_first {
2248+ self.niri.window_mru_ui.advance(direction, None);
2249+ }
2250+
2251+ drop(config);
2252+ self.niri.queue_redraw_all();
2253+ }
2254+ }
2255+ }
2256+ }
2257+ Action::MruCloseCurrentWindow => {
2258+ if self.niri.window_mru_ui.is_open() {
2259+ if let Some(id) = self.niri.window_mru_ui.current_window_id() {
2260+ if let Some(w) = self.niri.find_window_by_id(id) {
2261+ if let Some(tl) = w.toplevel() {
2262+ tl.send_close();
2263+ }
2264+ }
2265+ }
2266+ }
2267+ }
2268+ Action::MruFirst => {
2269+ if self.niri.window_mru_ui.is_open() {
2270+ self.niri.window_mru_ui.first();
2271+ self.niri.queue_redraw_mru_output();
2272+ }
2273+ }
2274+ Action::MruLast => {
2275+ if self.niri.window_mru_ui.is_open() {
2276+ self.niri.window_mru_ui.last();
2277+ self.niri.queue_redraw_mru_output();
2278+ }
2279+ }
2280+ Action::MruSetScope(scope) => {
2281+ if self.niri.window_mru_ui.is_open() {
2282+ self.niri.window_mru_ui.set_scope(scope);
2283+ self.niri.queue_redraw_mru_output();
2284+ }
2285+ }
2286+ Action::MruCycleScope => {
2287+ if self.niri.window_mru_ui.is_open() {
2288+ self.niri.window_mru_ui.cycle_scope();
2289+ self.niri.queue_redraw_mru_output();
2290+ }
2291+ }
21822292 }
21832293 }
21842294
@@ -2301,6 +2411,14 @@ impl State {
23012411 self.niri.screenshot_ui.pointer_motion(point, None);
23022412 }
23032413
2414+ if let Some(mru_output) = self.niri.window_mru_ui.output() {
2415+ if let Some((output, pos_within_output)) = self.niri.output_under(new_pos) {
2416+ if mru_output == output {
2417+ self.niri.window_mru_ui.pointer_motion(pos_within_output);
2418+ }
2419+ }
2420+ }
2421+
23042422 let under = self.niri.contents_under(new_pos);
23052423
23062424 // Handle confined pointer.
@@ -2431,6 +2549,14 @@ impl State {
24312549 self.niri.screenshot_ui.pointer_motion(point, None);
24322550 }
24332551
2552+ if let Some(mru_output) = self.niri.window_mru_ui.output() {
2553+ if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
2554+ if mru_output == output {
2555+ self.niri.window_mru_ui.pointer_motion(pos_within_output);
2556+ }
2557+ }
2558+ }
2559+
24342560 let under = self.niri.contents_under(pos);
24352561
24362562 self.niri.handle_focus_follows_mouse(&under);
@@ -2509,7 +2635,29 @@ impl State {
25092635 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
25102636 let modifiers = modifiers_from_state(mods);
25112637
2512- if self.niri.mods_with_mouse_binds.contains(&modifiers) {
2638+ let mut is_mru_open = false;
2639+ if let Some(mru_output) = self.niri.window_mru_ui.output() {
2640+ is_mru_open = true;
2641+ if let Some(MouseButton::Left) = button {
2642+ let location = pointer.current_location();
2643+ let (output, pos_within_output) = self.niri.output_under(location).unwrap();
2644+ if mru_output == output {
2645+ let id = self.niri.window_mru_ui.pointer_motion(pos_within_output);
2646+ if id.is_some() {
2647+ self.confirm_mru();
2648+ } else {
2649+ self.niri.cancel_mru();
2650+ }
2651+ } else {
2652+ self.niri.cancel_mru();
2653+ }
2654+
2655+ self.niri.suppressed_buttons.insert(button_code);
2656+ return;
2657+ }
2658+ }
2659+
2660+ if is_mru_open || self.niri.mods_with_mouse_binds.contains(&modifiers) {
25132661 if let Some(bind) = match button {
25142662 Some(MouseButton::Left) => Some(Trigger::MouseLeft),
25152663 Some(MouseButton::Right) => Some(Trigger::MouseRight),
@@ -2520,7 +2668,8 @@ impl State {
25202668 }
25212669 .and_then(|trigger| {
25222670 let config = self.niri.config.borrow();
2523- let bindings = &config.binds.0;
2671+ let bindings =
2672+ make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
25242673 find_configured_bind(bindings, mod_key, trigger, mods)
25252674 }) {
25262675 self.niri.suppressed_buttons.insert(button_code);
@@ -2824,59 +2973,66 @@ impl State {
28242973 false
28252974 };
28262975
2976+ let is_mru_open = self.niri.window_mru_ui.is_open();
2977+
28272978 // Handle wheel scroll bindings.
28282979 if source == AxisSource::Wheel {
28292980 // If we have a scroll bind with current modifiers, then accumulate and don't pass to
28302981 // Wayland. If there's no bind, reset the accumulator.
28312982 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
28322983 let modifiers = modifiers_from_state(mods);
2833- let should_handle =
2834- should_handle_in_overview || self.niri.mods_with_wheel_binds.contains(&modifiers);
2984+ let should_handle = should_handle_in_overview
2985+ || is_mru_open
2986+ || self.niri.mods_with_wheel_binds.contains(&modifiers);
28352987 if should_handle {
28362988 let horizontal = horizontal_amount_v120.unwrap_or(0.);
28372989 let ticks = self.niri.horizontal_wheel_tracker.accumulate(horizontal);
28382990 if ticks != 0 {
2839- let (bind_left, bind_right) = if should_handle_in_overview
2840- && modifiers.is_empty()
2841- {
2842- let bind_left = Some(Bind {
2843- key: Key {
2844- trigger: Trigger::WheelScrollLeft,
2845- modifiers: Modifiers::empty(),
2846- },
2847- action: Action::FocusColumnLeftUnderMouse,
2848- repeat: true,
2849- cooldown: None,
2850- allow_when_locked: false,
2851- allow_inhibiting: false,
2852- hotkey_overlay_title: None,
2853- });
2854- let bind_right = Some(Bind {
2855- key: Key {
2856- trigger: Trigger::WheelScrollRight,
2857- modifiers: Modifiers::empty(),
2858- },
2859- action: Action::FocusColumnRightUnderMouse,
2860- repeat: true,
2861- cooldown: None,
2862- allow_when_locked: false,
2863- allow_inhibiting: false,
2864- hotkey_overlay_title: None,
2865- });
2866- (bind_left, bind_right)
2867- } else {
2868- let config = self.niri.config.borrow();
2869- let bindings = &config.binds.0;
2870- let bind_left =
2871- find_configured_bind(bindings, mod_key, Trigger::WheelScrollLeft, mods);
2872- let bind_right = find_configured_bind(
2873- bindings,
2874- mod_key,
2875- Trigger::WheelScrollRight,
2876- mods,
2877- );
2878- (bind_left, bind_right)
2879- };
2991+ let (bind_left, bind_right) =
2992+ if should_handle_in_overview && modifiers.is_empty() {
2993+ let bind_left = Some(Bind {
2994+ key: Key {
2995+ trigger: Trigger::WheelScrollLeft,
2996+ modifiers: Modifiers::empty(),
2997+ },
2998+ action: Action::FocusColumnLeftUnderMouse,
2999+ repeat: true,
3000+ cooldown: None,
3001+ allow_when_locked: false,
3002+ allow_inhibiting: false,
3003+ hotkey_overlay_title: None,
3004+ });
3005+ let bind_right = Some(Bind {
3006+ key: Key {
3007+ trigger: Trigger::WheelScrollRight,
3008+ modifiers: Modifiers::empty(),
3009+ },
3010+ action: Action::FocusColumnRightUnderMouse,
3011+ repeat: true,
3012+ cooldown: None,
3013+ allow_when_locked: false,
3014+ allow_inhibiting: false,
3015+ hotkey_overlay_title: None,
3016+ });
3017+ (bind_left, bind_right)
3018+ } else {
3019+ let config = self.niri.config.borrow();
3020+ let bindings =
3021+ make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
3022+ let bind_left = find_configured_bind(
3023+ bindings.clone(),
3024+ mod_key,
3025+ Trigger::WheelScrollLeft,
3026+ mods,
3027+ );
3028+ let bind_right = find_configured_bind(
3029+ bindings,
3030+ mod_key,
3031+ Trigger::WheelScrollRight,
3032+ mods,
3033+ );
3034+ (bind_left, bind_right)
3035+ };
28803036
28813037 if let Some(right) = bind_right {
28823038 for _ in 0..ticks {
@@ -2948,9 +3104,14 @@ impl State {
29483104 (bind_up, bind_down)
29493105 } else {
29503106 let config = self.niri.config.borrow();
2951- let bindings = &config.binds.0;
2952- let bind_up =
2953- find_configured_bind(bindings, mod_key, Trigger::WheelScrollUp, mods);
3107+ let bindings =
3108+ make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
3109+ let bind_up = find_configured_bind(
3110+ bindings.clone(),
3111+ mod_key,
3112+ Trigger::WheelScrollUp,
3113+ mods,
3114+ );
29543115 let bind_down =
29553116 find_configured_bind(bindings, mod_key, Trigger::WheelScrollDown, mods);
29563117 (bind_up, bind_down)
@@ -3081,16 +3242,21 @@ impl State {
30813242 }
30823243 }
30833244
3084- if self.niri.mods_with_finger_scroll_binds.contains(&modifiers) {
3245+ if is_mru_open || self.niri.mods_with_finger_scroll_binds.contains(&modifiers) {
30853246 let ticks = self
30863247 .niri
30873248 .horizontal_finger_scroll_tracker
30883249 .accumulate(horizontal);
30893250 if ticks != 0 {
30903251 let config = self.niri.config.borrow();
3091- let bindings = &config.binds.0;
3092- let bind_left =
3093- find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollLeft, mods);
3252+ let bindings =
3253+ make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
3254+ let bind_left = find_configured_bind(
3255+ bindings.clone(),
3256+ mod_key,
3257+ Trigger::TouchpadScrollLeft,
3258+ mods,
3259+ );
30943260 let bind_right =
30953261 find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollRight, mods);
30963262 drop(config);
@@ -3113,9 +3279,14 @@ impl State {
31133279 .accumulate(vertical);
31143280 if ticks != 0 {
31153281 let config = self.niri.config.borrow();
3116- let bindings = &config.binds.0;
3117- let bind_up =
3118- find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollUp, mods);
3282+ let bindings =
3283+ make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
3284+ let bind_up = find_configured_bind(
3285+ bindings.clone(),
3286+ mod_key,
3287+ Trigger::TouchpadScrollUp,
3288+ mods,
3289+ );
31193290 let bind_down =
31203291 find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollDown, mods);
31213292 drop(config);
@@ -3234,6 +3405,14 @@ impl State {
32343405 self.niri.screenshot_ui.pointer_motion(point, None);
32353406 }
32363407
3408+ if let Some(mru_output) = self.niri.window_mru_ui.output() {
3409+ if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
3410+ if mru_output == output {
3411+ self.niri.window_mru_ui.pointer_motion(pos_within_output);
3412+ }
3413+ }
3414+ }
3415+
32373416 let under = self.niri.contents_under(pos);
32383417
32393418 let tablet_seat = self.niri.seat.tablet_seat();
@@ -3311,6 +3490,19 @@ impl State {
33113490 self.niri.queue_redraw_all();
33123491 }
33133492 }
3493+ } else if let Some(mru_output) = self.niri.window_mru_ui.output() {
3494+ if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
3495+ if mru_output == output {
3496+ let id = self.niri.window_mru_ui.pointer_motion(pos_within_output);
3497+ if id.is_some() {
3498+ self.confirm_mru();
3499+ } else {
3500+ self.niri.cancel_mru();
3501+ }
3502+ } else {
3503+ self.niri.cancel_mru();
3504+ }
3505+ }
33143506 } else if let Some((window, _)) = under.window {
33153507 if let Some(output) = is_overview_open.then_some(under.output).flatten() {
33163508 let mut workspaces = self.niri.layout.workspaces();
@@ -3425,6 +3617,11 @@ impl State {
34253617 }
34263618
34273619 fn on_gesture_swipe_begin<I: InputBackend>(&mut self, event: I::GestureSwipeBeginEvent) {
3620+ if self.niri.window_mru_ui.is_open() {
3621+ // Don't start swipe gestures while in the MRU.
3622+ return;
3623+ }
3624+
34283625 if event.fingers() == 3 {
34293626 self.niri.gesture_swipe_3f_cumulative = Some((0., 0.));
34303627
@@ -3772,6 +3969,19 @@ impl State {
37723969 self.niri.queue_redraw_all();
37733970 }
37743971 }
3972+ } else if let Some(mru_output) = self.niri.window_mru_ui.output() {
3973+ if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
3974+ if mru_output == output {
3975+ let id = self.niri.window_mru_ui.pointer_motion(pos_within_output);
3976+ if id.is_some() {
3977+ self.confirm_mru();
3978+ } else {
3979+ self.niri.cancel_mru();
3980+ }
3981+ } else {
3982+ self.niri.cancel_mru();
3983+ }
3984+ }
37753985 } else if !handle.is_grabbed() {
37763986 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
37773987 let mods = modifiers_from_state(mods);
@@ -4696,6 +4906,29 @@ fn grab_allows_hot_corner(grab: &(dyn PointerGrab<State> + 'static)) -> bool {
46964906 true
46974907 }
46984908
4909+/// Returns an iterator over bindings.
4910+///
4911+/// Includes dynamically populated bindings like the MRU UI.
4912+fn make_binds_iter<'a>(
4913+ config: &'a Config,
4914+ mru: &'a mut WindowMruUi,
4915+ mods: Modifiers,
4916+) -> impl Iterator<Item = &'a Bind> + Clone {
4917+ // Figure out the binds to use depending on whether the MRU is enabled and/or open.
4918+ let general_binds = (!mru.is_open()).then_some(config.binds.0.iter());
4919+ let general_binds = general_binds.into_iter().flatten();
4920+
4921+ let mru_binds =
4922+ (config.recent_windows.on || mru.is_open()).then_some(config.recent_windows.binds.iter());
4923+ let mru_binds = mru_binds.into_iter().flatten();
4924+
4925+ let mru_open_binds = mru.is_open().then(|| mru.opened_bindings(mods));
4926+ let mru_open_binds = mru_open_binds.into_iter().flatten();
4927+
4928+ // MRU binds take precedence over general ones.
4929+ mru_binds.chain(mru_open_binds).chain(general_binds)
4930+}
4931+
46994932 #[cfg(test)]
47004933 mod tests {
47014934 use std::cell::Cell;
src/niri.rsmodified+150 -4
@@ -16,7 +16,7 @@ use calloop::futures::Scheduler;
1616 use niri_config::debug::PreviewRender;
1717 use niri_config::{
1818 Config, FloatOrInt, Key, Modifiers, OutputName, TrackLayout, WarpMouseToFocusMode,
19- WorkspaceReference, Xkb,
19+ WorkspaceReference, Xkb, DEFAULT_MRU_COMMIT_MS,
2020 };
2121 use smithay::backend::allocator::Fourcc;
2222 use smithay::backend::input::Keycode;
@@ -165,6 +165,7 @@ use crate::render_helpers::{
165165 use crate::ui::config_error_notification::ConfigErrorNotification;
166166 use crate::ui::exit_confirm_dialog::{ExitConfirmDialog, ExitConfirmDialogRenderElement};
167167 use crate::ui::hotkey_overlay::HotkeyOverlay;
168+use crate::ui::mru::{MruCloseRequest, WindowMruUi, WindowMruUiRenderElement};
168169 use crate::ui::screen_transition::{self, ScreenTransition};
169170 use crate::ui::screenshot_ui::{OutputScreenshot, ScreenshotUi, ScreenshotUiRenderElement};
170171 use crate::utils::scale::{closest_representable_scale, guess_monitor_scale};
@@ -384,6 +385,9 @@ pub struct Niri {
384385 pub hotkey_overlay: HotkeyOverlay,
385386 pub exit_confirm_dialog: ExitConfirmDialog,
386387
388+ pub window_mru_ui: WindowMruUi,
389+ pub pending_mru_commit: Option<PendingMruCommit>,
390+
387391 pub pick_window: Option<async_channel::Sender<Option<MappedId>>>,
388392 pub pick_color: Option<async_channel::Sender<Option<niri_ipc::PickedColor>>>,
389393
@@ -520,6 +524,7 @@ pub enum KeyboardFocus {
520524 ScreenshotUi,
521525 ExitConfirmDialog,
522526 Overview,
527+ Mru,
523528 }
524529
525530 #[derive(Default, Clone, PartialEq)]
@@ -582,6 +587,14 @@ pub enum CastTarget {
582587 Window { id: u64 },
583588 }
584589
590+/// Pending update to a window's focus timestamp.
591+#[derive(Debug)]
592+pub struct PendingMruCommit {
593+ id: MappedId,
594+ token: RegistrationToken,
595+ stamp: Duration,
596+}
597+
585598 impl RedrawState {
586599 fn queue_redraw(self) -> Self {
587600 match self {
@@ -620,6 +633,7 @@ impl KeyboardFocus {
620633 KeyboardFocus::ScreenshotUi => None,
621634 KeyboardFocus::ExitConfirmDialog => None,
622635 KeyboardFocus::Overview => None,
636+ KeyboardFocus::Mru => None,
623637 }
624638 }
625639
@@ -631,6 +645,7 @@ impl KeyboardFocus {
631645 KeyboardFocus::ScreenshotUi => None,
632646 KeyboardFocus::ExitConfirmDialog => None,
633647 KeyboardFocus::Overview => None,
648+ KeyboardFocus::Mru => None,
634649 }
635650 }
636651
@@ -939,6 +954,12 @@ impl State {
939954 self.niri.queue_redraw_all();
940955 }
941956
957+ pub fn confirm_mru(&mut self) {
958+ if let Some(window) = self.niri.close_mru(MruCloseRequest::Confirm) {
959+ self.focus_window(&window);
960+ }
961+ }
962+
942963 pub fn maybe_warp_cursor_to_focus(&mut self) -> bool {
943964 let focused = match self.niri.config.borrow().input.warp_mouse_to_focus {
944965 None => return false,
@@ -1099,6 +1120,8 @@ impl State {
10991120 }
11001121 } else if self.niri.screenshot_ui.is_open() {
11011122 KeyboardFocus::ScreenshotUi
1123+ } else if self.niri.window_mru_ui.is_open() {
1124+ KeyboardFocus::Mru
11021125 } else if let Some(output) = self.niri.layout.active_output() {
11031126 let mon = self.niri.layout.monitor_for_output(output).unwrap();
11041127 let layers = layer_map_for_output(output);
@@ -1225,6 +1248,38 @@ impl State {
12251248 {
12261249 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
12271250 mapped.set_is_focused(true);
1251+
1252+ // If `mapped` does not have a focus timestamp, then the window is newly
1253+ // created/mapped and a timestamp is unconditionally created.
1254+ //
1255+ // If `mapped` already has a timestamp only update it after the focus lock-in
1256+ // period has gone by without the focus having elsewhere.
1257+ let stamp = get_monotonic_time();
1258+
1259+ if mapped.get_focus_timestamp().is_none() {
1260+ mapped.set_focus_timestamp(stamp);
1261+ } else {
1262+ let timer =
1263+ Timer::from_duration(Duration::from_millis(DEFAULT_MRU_COMMIT_MS));
1264+
1265+ let focus_token = self
1266+ .niri
1267+ .event_loop
1268+ .insert_source(timer, move |_, _, state| {
1269+ state.niri.mru_apply_keyboard_commit();
1270+ TimeoutAction::Drop
1271+ })
1272+ .unwrap();
1273+ if let Some(PendingMruCommit { token, .. }) =
1274+ self.niri.pending_mru_commit.replace(PendingMruCommit {
1275+ id: mapped.id(),
1276+ token: focus_token,
1277+ stamp,
1278+ })
1279+ {
1280+ self.niri.event_loop.remove(token);
1281+ }
1282+ }
12281283 }
12291284 }
12301285
@@ -1411,6 +1466,7 @@ impl State {
14111466 let mut layer_rules_changed = false;
14121467 let mut shaders_changed = false;
14131468 let mut cursor_inactivity_timeout_changed = false;
1469+ let mut recent_windows_changed = false;
14141470 let mut xwls_changed = false;
14151471 let mut old_config = self.niri.config.borrow_mut();
14161472
@@ -1459,8 +1515,9 @@ impl State {
14591515 preserved_output_config = Some(mem::take(&mut old_config.outputs));
14601516 }
14611517
1518+ let binds_changed = config.binds != old_config.binds;
14621519 let new_mod_key = self.backend.mod_key(&config);
1463- if new_mod_key != self.backend.mod_key(&old_config) || config.binds != old_config.binds {
1520+ if new_mod_key != self.backend.mod_key(&old_config) || binds_changed {
14641521 self.niri
14651522 .hotkey_overlay
14661523 .on_hotkey_config_updated(new_mod_key);
@@ -1530,6 +1587,10 @@ impl State {
15301587 output_config_changed = true;
15311588 }
15321589
1590+ if config.recent_windows != old_config.recent_windows {
1591+ recent_windows_changed = true;
1592+ }
1593+
15331594 if config.xwayland_satellite != old_config.xwayland_satellite {
15341595 xwls_changed = true;
15351596 }
@@ -1600,6 +1661,14 @@ impl State {
16001661 self.niri.reset_pointer_inactivity_timer();
16011662 }
16021663
1664+ if binds_changed {
1665+ self.niri.window_mru_ui.update_binds();
1666+ }
1667+
1668+ if recent_windows_changed {
1669+ self.niri.window_mru_ui.update_config();
1670+ }
1671+
16031672 if xwls_changed {
16041673 // If xwl-s was previously working and is now off, we don't try to kill it or stop
16051674 // watching the sockets, for simplicity's sake.
@@ -2552,6 +2621,7 @@ impl Niri {
25522621 let mods_with_finger_scroll_binds = mods_with_finger_scroll_binds(mod_key, &config_.binds);
25532622
25542623 let screenshot_ui = ScreenshotUi::new(animation_clock.clone(), config.clone());
2624+ let window_mru_ui = WindowMruUi::new(config.clone());
25552625 let config_error_notification =
25562626 ConfigErrorNotification::new(animation_clock.clone(), config.clone());
25572627
@@ -2753,6 +2823,9 @@ impl Niri {
27532823 hotkey_overlay,
27542824 exit_confirm_dialog,
27552825
2826+ window_mru_ui,
2827+ pending_mru_commit: None,
2828+
27562829 pick_window: None,
27572830 pick_color: None,
27582831
@@ -3109,6 +3182,10 @@ impl Niri {
31093182 .set_cursor_image(CursorImageStatus::default_named());
31103183 self.queue_redraw_all();
31113184 }
3185+
3186+ if self.window_mru_ui.output() == Some(output) {
3187+ self.cancel_mru();
3188+ }
31123189 }
31133190
31143191 pub fn output_resized(&mut self, output: &Output) {
@@ -3376,7 +3453,11 @@ impl Niri {
33763453 /// The cursor may be inside the window's activation region, but not within the window's input
33773454 /// region.
33783455 pub fn window_under(&self, pos: Point<f64, Logical>) -> Option<&Mapped> {
3379- if self.exit_confirm_dialog.is_open() || self.is_locked() || self.screenshot_ui.is_open() {
3456+ if self.exit_confirm_dialog.is_open()
3457+ || self.is_locked()
3458+ || self.screenshot_ui.is_open()
3459+ || self.window_mru_ui.is_open()
3460+ {
33803461 return None;
33813462 }
33823463
@@ -3455,7 +3536,7 @@ impl Niri {
34553536 return rv;
34563537 }
34573538
3458- if self.screenshot_ui.is_open() {
3539+ if self.screenshot_ui.is_open() || self.window_mru_ui.is_open() {
34593540 return rv;
34603541 }
34613542
@@ -3732,6 +3813,13 @@ impl Niri {
37323813 Some((target_output.cloned(), target_workspace_index))
37333814 }
37343815
3816+ pub fn find_window_by_id(&self, id: MappedId) -> Option<Window> {
3817+ self.layout
3818+ .windows()
3819+ .find(|(_, m)| m.id() == id)
3820+ .map(|(_, m)| m.window.clone())
3821+ }
3822+
37353823 pub fn output_for_tablet(&self) -> Option<&Output> {
37363824 let config = self.config.borrow();
37373825 let map_to_output = config.input.tablet.map_to_output.as_ref();
@@ -4059,6 +4147,7 @@ impl Niri {
40594147 KeyboardFocus::ScreenshotUi => true,
40604148 KeyboardFocus::ExitConfirmDialog => true,
40614149 KeyboardFocus::Overview => true,
4150+ KeyboardFocus::Mru => true,
40624151 };
40634152
40644153 self.layout.refresh(layout_is_active);
@@ -4190,6 +4279,7 @@ impl Niri {
41904279 self.config_error_notification.advance_animations();
41914280 self.exit_confirm_dialog.advance_animations();
41924281 self.screenshot_ui.advance_animations();
4282+ self.window_mru_ui.advance_animations();
41934283
41944284 for state in self.output_state.values_mut() {
41954285 if let Some(transition) = &mut state.screen_transition {
@@ -4346,6 +4436,15 @@ impl Niri {
43464436 elements.push(element.into());
43474437 }
43484438
4439+ // Then, the Alt-Tab switcher.
4440+ let mru_elements = self
4441+ .window_mru_ui
4442+ .render_output(self, output, renderer, target)
4443+ .into_iter()
4444+ .flatten()
4445+ .map(OutputRenderElements::from);
4446+ elements.extend(mru_elements);
4447+
43494448 // Don't draw the focus ring on the workspaces while interactively moving above those
43504449 // workspaces, since the interactively-moved window already has a focus ring.
43514450 let focus_ring = !self.layout.interactive_move_is_moving_above_output(output);
@@ -4537,6 +4636,7 @@ impl Niri {
45374636 self.config_error_notification.are_animations_ongoing();
45384637 state.unfinished_animations_remain |= self.exit_confirm_dialog.are_animations_ongoing();
45394638 state.unfinished_animations_remain |= self.screenshot_ui.are_animations_ongoing();
4639+ state.unfinished_animations_remain |= self.window_mru_ui.are_animations_ongoing();
45404640 state.unfinished_animations_remain |= state.screen_transition.is_some();
45414641
45424642 // Also keep redrawing if the current cursor is animated.
@@ -5923,6 +6023,7 @@ impl Niri {
59236023 self.screenshot_ui.close();
59246024 self.cursor_manager
59256025 .set_cursor_image(CursorImageStatus::default_named());
6026+ self.cancel_mru();
59266027
59276028 if self.output_state.is_empty() {
59286029 // There are no outputs, lock the session right away.
@@ -6181,6 +6282,10 @@ impl Niri {
61816282 return;
61826283 }
61836284
6285+ if self.window_mru_ui.is_open() {
6286+ return;
6287+ }
6288+
61846289 // Recompute the current pointer focus because we don't update it during animations.
61856290 let current_focus = self.contents_under(pointer.current_location());
61866291
@@ -6407,6 +6512,46 @@ impl Niri {
64076512
64086513 self.notified_activity_this_iteration = true;
64096514 }
6515+
6516+ pub fn close_mru(&mut self, close_request: MruCloseRequest) -> Option<Window> {
6517+ if !self.window_mru_ui.is_open() {
6518+ return None;
6519+ }
6520+ self.queue_redraw_all();
6521+
6522+ let id = self.window_mru_ui.close(close_request)?;
6523+ self.find_window_by_id(id)
6524+ }
6525+
6526+ pub fn cancel_mru(&mut self) {
6527+ self.close_mru(MruCloseRequest::Cancel);
6528+ }
6529+
6530+ /// Apply a pending MRU commit immediately.
6531+ ///
6532+ /// Called for example on keyboard events that reach the active window, which immediately adds
6533+ /// it to the MRU.
6534+ pub fn mru_apply_keyboard_commit(&mut self) {
6535+ let Some(pending) = self.pending_mru_commit.take() else {
6536+ return;
6537+ };
6538+ self.event_loop.remove(pending.token);
6539+
6540+ if let Some(window) = self
6541+ .layout
6542+ .workspaces_mut()
6543+ .flat_map(|ws| ws.windows_mut())
6544+ .find(|w| w.id() == pending.id)
6545+ {
6546+ window.set_focus_timestamp(pending.stamp);
6547+ }
6548+ }
6549+
6550+ pub fn queue_redraw_mru_output(&mut self) {
6551+ if let Some(output) = self.window_mru_ui.output().cloned() {
6552+ self.queue_redraw(&output);
6553+ }
6554+ }
64106555 }
64116556
64126557 pub struct NewClient {
@@ -6454,6 +6599,7 @@ niri_render_elements! {
64546599 NamedPointer = MemoryRenderBufferRenderElement<R>,
64556600 SolidColor = SolidColorRenderElement,
64566601 ScreenshotUi = ScreenshotUiRenderElement,
6602+ WindowMruUi = WindowMruUiRenderElement<R>,
64576603 ExitConfirmDialog = ExitConfirmDialogRenderElement,
64586604 Texture = PrimaryGpuTextureRenderElement,
64596605 // Used for the CPU-rendered panels.
src/ui/mod.rsmodified+1 -0
@@ -1,5 +1,6 @@
11 pub mod config_error_notification;
22 pub mod exit_confirm_dialog;
33 pub mod hotkey_overlay;
4+pub mod mru;
45 pub mod screen_transition;
56 pub mod screenshot_ui;
src/ui/mru.rsadded+1929 -0
@@ -0,0 +1,1929 @@
1+use std::cell::RefCell;
2+use std::cmp::min;
3+use std::collections::HashMap;
4+use std::mem;
5+use std::rc::Rc;
6+use std::time::Duration;
7+
8+use anyhow::ensure;
9+use niri_config::{
10+ Action, Bind, Color, Config, CornerRadius, GradientInterpolation, Key, Modifiers, MruDirection,
11+ MruFilter, MruScope, Trigger,
12+};
13+use pango::FontDescription;
14+use pangocairo::cairo::{self, ImageSurface};
15+use smithay::backend::allocator::Fourcc;
16+use smithay::backend::renderer::element::utils::{
17+ Relocate, RelocateRenderElement, RescaleRenderElement,
18+};
19+use smithay::backend::renderer::element::Kind;
20+use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
21+use smithay::backend::renderer::Color32F;
22+use smithay::input::keyboard::Keysym;
23+use smithay::output::Output;
24+use smithay::utils::{Logical, Point, Rectangle, Scale, Size, Transform};
25+
26+use crate::animation::{Animation, Clock};
27+use crate::layout::focus_ring::{FocusRing, FocusRingRenderElement};
28+use crate::layout::{Layout, LayoutElement as _, LayoutElementRenderElement};
29+use crate::niri::Niri;
30+use crate::niri_render_elements;
31+use crate::render_helpers::border::BorderRenderElement;
32+use crate::render_helpers::clipped_surface::ClippedSurfaceRenderElement;
33+use crate::render_helpers::gradient_fade_texture::GradientFadeTextureRenderElement;
34+use crate::render_helpers::offscreen::{OffscreenBuffer, OffscreenRenderElement};
35+use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
36+use crate::render_helpers::renderer::NiriRenderer;
37+use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
38+use crate::render_helpers::texture::{TextureBuffer, TextureRenderElement};
39+use crate::render_helpers::RenderTarget;
40+use crate::utils::{
41+ baba_is_float_offset, output_size, round_logical_in_physical, to_physical_precise_round,
42+ with_toplevel_role,
43+};
44+use crate::window::mapped::MappedId;
45+use crate::window::Mapped;
46+
47+#[cfg(test)]
48+mod tests;
49+
50+/// Windows up to this size don't get scaled further down.
51+const PREVIEW_MIN_SIZE: f64 = 16.;
52+
53+/// Border width on the selected window preview.
54+const BORDER: f64 = 2.;
55+
56+/// Gap from the window preview to the window title.
57+const TITLE_GAP: f64 = 14.;
58+
59+/// Gap between thumbnails.
60+const GAP: f64 = 16.;
61+
62+/// How much of the next window will always peek from the side of the screen.
63+const STRUT: f64 = 192.;
64+
65+/// Padding in the scope indication panel.
66+const PANEL_PADDING: i32 = 12;
67+
68+/// Border size of the scope indication panel.
69+const PANEL_BORDER: i32 = 4;
70+
71+/// Backdrop color behind the previews.
72+const BACKDROP_COLOR: Color32F = Color32F::new(0., 0., 0., 0.8);
73+
74+/// Font used to render the window titles.
75+const FONT: &str = "sans 14px";
76+
77+/// Scopes in the order they are cycled through.
78+///
79+/// Count must match one defined in `generate_scope_panels()`.
80+static SCOPE_CYCLE: [MruScope; 3] = [MruScope::All, MruScope::Workspace, MruScope::Output];
81+
82+/// Window MRU traversal context.
83+#[derive(Debug)]
84+pub struct WindowMru {
85+ /// Windows in MRU order.
86+ thumbnails: Vec<Thumbnail>,
87+
88+ /// Id of the currently selected window.
89+ current_id: Option<MappedId>,
90+
91+ /// Current scope.
92+ scope: MruScope,
93+
94+ /// Current filter.
95+ app_id_filter: Option<String>,
96+}
97+
98+pub struct WindowMruUi {
99+ state: UiState,
100+ preset_opened_binds: Vec<Bind>,
101+ dynamic_opened_binds: Vec<Bind>,
102+ config: Rc<RefCell<Config>>,
103+}
104+
105+pub enum MruCloseRequest {
106+ Cancel,
107+ Confirm,
108+}
109+
110+niri_render_elements! {
111+ ThumbnailRenderElement<R> => {
112+ LayoutElement = LayoutElementRenderElement<R>,
113+ ClippedSurface = ClippedSurfaceRenderElement<R>,
114+ Border = BorderRenderElement,
115+ }
116+}
117+
118+niri_render_elements! {
119+ WindowMruUiRenderElement<R> => {
120+ SolidColor = SolidColorRenderElement,
121+ TextureElement = PrimaryGpuTextureRenderElement,
122+ GradientFadeElem = GradientFadeTextureRenderElement,
123+ FocusRing = FocusRingRenderElement,
124+ Offscreen = OffscreenRenderElement,
125+ Thumbnail = RelocateRenderElement<RescaleRenderElement<ThumbnailRenderElement<R>>>,
126+ }
127+}
128+
129+enum UiState {
130+ Open(Inner),
131+ Closing {
132+ inner: Inner,
133+ anim: Animation,
134+ },
135+ Closed {
136+ /// Scope used when the UI was last opened.
137+ previous_scope: MruScope,
138+ },
139+}
140+
141+/// State of an opened MRU UI.
142+struct Inner {
143+ /// List of Window Ids to display in the MRU UI.
144+ wmru: WindowMru,
145+
146+ /// View position relative to the leftmost visible window.
147+ view_pos: ViewPos,
148+
149+ // If true, don't automatically move the current thumbnail in-view. Set on pointer motion.
150+ freeze_view: bool,
151+
152+ /// Animation clock.
153+ clock: Clock,
154+
155+ /// Current config.
156+ config: Rc<RefCell<Config>>,
157+
158+ /// Time when the UI should appear.
159+ open_at: Duration,
160+
161+ /// Output the UI was opened on.
162+ output: Output,
163+
164+ /// Scope panel textures.
165+ scope_panel: RefCell<ScopePanel>,
166+
167+ /// Backdrop buffers for each output.
168+ backdrop_buffers: RefCell<HashMap<Output, SolidColorBuffer>>,
169+
170+ /// Offscreen buffer for the closing fade animation on the main output.
171+ offscreen: OffscreenBuffer,
172+}
173+
174+#[derive(Debug)]
175+enum ViewPos {
176+ /// The view position is static.
177+ Static(f64),
178+ /// The view position is animating.
179+ Animation(Animation),
180+}
181+
182+#[derive(Debug)]
183+struct MoveAnimation {
184+ anim: Animation,
185+ from: f64,
186+}
187+
188+type MruTexture = TextureBuffer<GlesTexture>;
189+
190+/// Cached title texture.
191+#[derive(Debug, Default)]
192+struct TitleTexture {
193+ title: String,
194+ scale: f64,
195+ texture: Option<Option<MruTexture>>,
196+}
197+
198+/// Cached scope panel textures.
199+#[derive(Debug, Default)]
200+struct ScopePanel {
201+ scale: f64,
202+ textures: Option<Option<[MruTexture; 3]>>,
203+}
204+
205+#[derive(Debug)]
206+struct Thumbnail {
207+ id: MappedId,
208+
209+ /// Focus timestamp, if any.
210+ timestamp: Option<Duration>,
211+ /// Whether the window is on the current MRU workspace.
212+ on_current_workspace: bool,
213+ /// Whether the window is on the current MRU output.
214+ on_current_output: bool,
215+
216+ /// Cached app ID of the window.
217+ ///
218+ /// Currently not updated live to avoid having to refilter windows.
219+ app_id: Option<String>,
220+ /// Cached size of the window.
221+ size: Size<i32, Logical>,
222+
223+ clock: Clock,
224+ config: niri_config::MruPreviews,
225+ open_animation: Option<Animation>,
226+ move_animation: Option<MoveAnimation>,
227+ title_texture: RefCell<TitleTexture>,
228+ background: RefCell<FocusRing>,
229+ border: RefCell<FocusRing>,
230+}
231+
232+impl Thumbnail {
233+ fn from_mapped(mapped: &Mapped, clock: Clock, config: niri_config::MruPreviews) -> Self {
234+ let app_id = with_toplevel_role(mapped.toplevel(), |role| role.app_id.clone());
235+
236+ let background = FocusRing::new(niri_config::FocusRing {
237+ off: false,
238+ width: 0.,
239+ active_gradient: None,
240+ ..Default::default()
241+ });
242+ let border = FocusRing::new(niri_config::FocusRing {
243+ off: false,
244+ active_gradient: None,
245+ ..Default::default()
246+ });
247+
248+ Self {
249+ id: mapped.id(),
250+ timestamp: mapped.get_focus_timestamp(),
251+ on_current_output: false,
252+ on_current_workspace: false,
253+ app_id,
254+ size: mapped.size(),
255+ clock,
256+ config,
257+ open_animation: None,
258+ move_animation: None,
259+ title_texture: Default::default(),
260+ background: RefCell::new(background),
261+ border: RefCell::new(border),
262+ }
263+ }
264+
265+ fn are_animations_ongoing(&self) -> bool {
266+ self.open_animation.is_some() || self.move_animation.is_some()
267+ }
268+
269+ fn advance_animations(&mut self) {
270+ self.open_animation.take_if(|a| a.is_done());
271+ self.move_animation.take_if(|a| a.anim.is_done());
272+ }
273+
274+ /// Animate thumbnail motion from given location.
275+ fn animate_move_from_with_config(&mut self, from: f64, config: niri_config::Animation) {
276+ let current_offset = self.render_offset();
277+
278+ // Preserve the previous config if ongoing.
279+ let anim = self.move_animation.take().map(|ma| ma.anim);
280+ let anim = anim
281+ .map(|anim| anim.restarted(1., 0., 0.))
282+ .unwrap_or_else(|| Animation::new(self.clock.clone(), 1., 0., 0., config));
283+
284+ self.move_animation = Some(MoveAnimation {
285+ anim,
286+ from: from + current_offset,
287+ });
288+ }
289+
290+ fn animate_open_with_config(&mut self, config: niri_config::Animation) {
291+ self.open_animation = Some(Animation::new(self.clock.clone(), 0., 1., 0., config));
292+ }
293+
294+ fn render_offset(&self) -> f64 {
295+ self.move_animation
296+ .as_ref()
297+ .map(|ma| ma.from * ma.anim.value())
298+ .unwrap_or_default()
299+ }
300+
301+ fn update_window(&mut self, mapped: &Mapped) {
302+ self.size = mapped.size();
303+ }
304+
305+ fn preview_size(&self, output_size: Size<f64, Logical>, scale: f64) -> Size<f64, Logical> {
306+ let max_height = f64::max(1., self.config.max_height);
307+ let max_scale = f64::max(0.001, self.config.max_scale);
308+
309+ let max_height = f64::min(max_height, output_size.h * max_scale);
310+ let output_ratio = output_size.w / output_size.h;
311+ let max_width = max_height * output_ratio;
312+
313+ let size = self.size.to_f64();
314+ let min_scale = f64::min(1., PREVIEW_MIN_SIZE / f64::max(size.w, size.h));
315+
316+ let thumb_scale = f64::min(max_width / size.w, max_height / size.h);
317+ let thumb_scale = f64::min(max_scale, thumb_scale);
318+ let thumb_scale = f64::max(min_scale, thumb_scale);
319+ let size = size.to_f64().upscale(thumb_scale);
320+
321+ // Round to physical pixels.
322+ size.to_physical_precise_round(scale).to_logical(scale)
323+ }
324+
325+ fn title_texture(
326+ &self,
327+ renderer: &mut GlesRenderer,
328+ mapped: &Mapped,
329+ scale: f64,
330+ ) -> Option<MruTexture> {
331+ with_toplevel_role(mapped.toplevel(), |role| {
332+ role.title
333+ .as_ref()
334+ .and_then(|title| self.title_texture.borrow_mut().get(renderer, title, scale))
335+ })
336+ }
337+
338+ #[allow(clippy::too_many_arguments)]
339+ fn render<R: NiriRenderer>(
340+ &self,
341+ renderer: &mut R,
342+ config: &niri_config::RecentWindows,
343+ mapped: &Mapped,
344+ preview_geo: Rectangle<f64, Logical>,
345+ scale: f64,
346+ is_active: bool,
347+ bob_y: f64,
348+ target: RenderTarget,
349+ ) -> impl Iterator<Item = WindowMruUiRenderElement<R>> {
350+ let _span = tracy_client::span!("Thumbnail::render");
351+
352+ let round = move |logical: f64| round_logical_in_physical(scale, logical);
353+ let padding = round(config.highlight.padding);
354+ let title_gap = round(TITLE_GAP);
355+
356+ let s = Scale::from(scale);
357+
358+ let preview_alpha = self
359+ .open_animation
360+ .as_ref()
361+ .map_or(1., |a| a.clamped_value() as f32)
362+ .clamp(0., 1.);
363+
364+ let bob_y = if mapped.rules().baba_is_float == Some(true) {
365+ bob_y
366+ } else {
367+ 0.
368+ };
369+ let bob_offset = Point::new(0., bob_y);
370+
371+ // FIXME: this could use mipmaps, for that it should be rendered through an offscreen.
372+ let elems = mapped
373+ .render_normal(renderer, Point::new(0., 0.), s, preview_alpha, target)
374+ .into_iter();
375+
376+ // Clip thumbnails to their geometry.
377+ let radius = if mapped.sizing_mode().is_normal() {
378+ mapped.rules().geometry_corner_radius
379+ } else {
380+ None
381+ }
382+ .unwrap_or_default();
383+
384+ let has_border_shader = BorderRenderElement::has_shader(renderer);
385+ let clip_shader = ClippedSurfaceRenderElement::shader(renderer).cloned();
386+ let geo = Rectangle::from_size(self.size.to_f64());
387+ // FIXME: deduplicate code with Tile::render_inner()
388+ let elems = elems.map(move |elem| match elem {
389+ LayoutElementRenderElement::Wayland(elem) => {
390+ if let Some(shader) = clip_shader.clone() {
391+ if ClippedSurfaceRenderElement::will_clip(&elem, s, geo, radius) {
392+ let elem =
393+ ClippedSurfaceRenderElement::new(elem, s, geo, shader.clone(), radius);
394+ return ThumbnailRenderElement::ClippedSurface(elem);
395+ }
396+ }
397+
398+ // If we don't have the shader, render it normally.
399+ let elem = LayoutElementRenderElement::Wayland(elem);
400+ ThumbnailRenderElement::LayoutElement(elem)
401+ }
402+ LayoutElementRenderElement::SolidColor(elem) => {
403+ // In this branch we're rendering a blocked-out window with a solid
404+ // color. We need to render it with a rounded corner shader even if
405+ // clip_to_geometry is false, because in this case we're assuming that
406+ // the unclipped window CSD already has corners rounded to the
407+ // user-provided radius, so our blocked-out rendering should match that
408+ // radius.
409+ if radius != CornerRadius::default() && has_border_shader {
410+ return BorderRenderElement::new(
411+ geo.size,
412+ Rectangle::from_size(geo.size),
413+ GradientInterpolation::default(),
414+ Color::from_color32f(elem.color()),
415+ Color::from_color32f(elem.color()),
416+ 0.,
417+ Rectangle::from_size(geo.size),
418+ 0.,
419+ radius,
420+ scale as f32,
421+ 1.,
422+ )
423+ .into();
424+ }
425+
426+ // Otherwise, render the solid color as is.
427+ LayoutElementRenderElement::SolidColor(elem).into()
428+ }
429+ });
430+
431+ let elems = elems.map(move |elem| {
432+ let thumb_scale = Scale {
433+ x: preview_geo.size.w / geo.size.w,
434+ y: preview_geo.size.h / geo.size.h,
435+ };
436+ let offset = Point::new(
437+ preview_geo.size.w - (geo.size.w * thumb_scale.x),
438+ preview_geo.size.h - (geo.size.h * thumb_scale.y),
439+ )
440+ .downscale(2.);
441+ let elem = RescaleRenderElement::from_element(elem, Point::new(0, 0), thumb_scale);
442+ let elem = RelocateRenderElement::from_element(
443+ elem,
444+ (preview_geo.loc + offset + bob_offset).to_physical_precise_round(scale),
445+ Relocate::Relative,
446+ );
447+ WindowMruUiRenderElement::Thumbnail(elem)
448+ });
449+
450+ let mut title_size = None;
451+ let title_texture = self.title_texture(renderer.as_gles_renderer(), mapped, scale);
452+ let title_texture = title_texture.map(|texture| {
453+ let mut size = texture.logical_size();
454+ size.w = f64::min(size.w, preview_geo.size.w);
455+ title_size = Some(size);
456+ (texture, size)
457+ });
458+
459+ // Hide title for blocked-out windows, but only after computing the title size. This way,
460+ // the background and the border won't have to oscillate in size between normal and
461+ // screencast renders, causing excessive damage.
462+ let should_block_out = target.should_block_out(mapped.rules().block_out_from);
463+ let title_texture = title_texture.filter(|_| !should_block_out);
464+
465+ let title_elems = title_texture.map(|(texture, size)| {
466+ // Clip from the right if it doesn't fit.
467+ let src = Rectangle::from_size(size);
468+
469+ let loc = preview_geo.loc
470+ + Point::new(
471+ (preview_geo.size.w - size.w) / 2.,
472+ preview_geo.size.h + title_gap,
473+ );
474+ let loc = loc.to_physical_precise_round(scale).to_logical(scale);
475+ let texture = TextureRenderElement::from_texture_buffer(
476+ texture,
477+ loc,
478+ preview_alpha,
479+ Some(src),
480+ None,
481+ Kind::Unspecified,
482+ );
483+
484+ let renderer = renderer.as_gles_renderer();
485+ if let Some(program) = GradientFadeTextureRenderElement::shader(renderer) {
486+ let elem = GradientFadeTextureRenderElement::new(texture, program);
487+ WindowMruUiRenderElement::GradientFadeElem(elem)
488+ } else {
489+ let elem = PrimaryGpuTextureRenderElement(texture);
490+ WindowMruUiRenderElement::TextureElement(elem)
491+ }
492+ });
493+
494+ let is_urgent = mapped.is_urgent();
495+ let background_elems = (is_active || is_urgent).then(|| {
496+ let padding = Point::new(padding, padding);
497+
498+ let mut size = preview_geo.size;
499+ size += padding.to_size().upscale(2.);
500+
501+ if let Some(title_size) = title_size {
502+ size.h += title_gap + title_size.h;
503+ // Subtract half the padding so it looks more balanced visually.
504+ size.h -= round(padding.y / 2.);
505+ }
506+
507+ // FIXME: gradient support (will require passing down correct view_rect).
508+ let mut color = if is_urgent {
509+ config.highlight.urgent_color
510+ } else {
511+ config.highlight.active_color
512+ };
513+ if !is_active {
514+ color *= 0.4;
515+ }
516+
517+ let radius = CornerRadius::from(config.highlight.corner_radius as f32);
518+
519+ let loc = preview_geo.loc - padding;
520+
521+ let mut background = self.background.borrow_mut();
522+ let mut config = *background.config();
523+ config.active_color = color;
524+ background.update_config(config);
525+ background.update_render_elements(
526+ size,
527+ true,
528+ false,
529+ false,
530+ Rectangle::default(),
531+ radius,
532+ scale,
533+ 0.5,
534+ );
535+ let bg_elems = background
536+ .render(renderer, loc)
537+ .map(WindowMruUiRenderElement::FocusRing);
538+
539+ let mut border = self.border.borrow_mut();
540+ let mut config = *border.config();
541+ config.off = !is_active;
542+ config.width = round(BORDER);
543+ config.active_color = color;
544+ border.update_config(config);
545+ border.set_thicken_corners(false);
546+ border.update_render_elements(
547+ size,
548+ true,
549+ true,
550+ false,
551+ Rectangle::default(),
552+ radius.expanded_by(config.width as f32),
553+ scale,
554+ 1.,
555+ );
556+
557+ let border_elems = border
558+ .render(renderer, loc)
559+ .map(WindowMruUiRenderElement::FocusRing);
560+
561+ bg_elems.chain(border_elems)
562+ });
563+ let background_elems = background_elems.into_iter().flatten();
564+
565+ elems.chain(title_elems).chain(background_elems)
566+ }
567+}
568+
569+impl WindowMru {
570+ pub fn new(niri: &Niri) -> Self {
571+ let Some(output) = niri.layout.active_output() else {
572+ return Self {
573+ thumbnails: Vec::new(),
574+ current_id: None,
575+ scope: MruScope::All,
576+ app_id_filter: None,
577+ };
578+ };
579+
580+ let config = niri.config.borrow().recent_windows.previews;
581+ let mut thumbnails = Vec::new();
582+ for (mon, ws_idx, ws) in niri.layout.workspaces() {
583+ let mon = mon.expect("an active output exists so all workspaces have a monitor");
584+ let on_current_output = mon.output() == output;
585+ let on_current_workspace = on_current_output && mon.active_workspace_idx() == ws_idx;
586+
587+ for mapped in ws.windows() {
588+ let mut thumbnail = Thumbnail::from_mapped(mapped, niri.clock.clone(), config);
589+ thumbnail.on_current_output = on_current_output;
590+ thumbnail.on_current_workspace = on_current_workspace;
591+ thumbnails.push(thumbnail);
592+ }
593+ }
594+
595+ thumbnails
596+ .sort_by(|Thumbnail { timestamp: t1, .. }, Thumbnail { timestamp: t2, .. }| t2.cmp(t1));
597+
598+ let current_id = thumbnails.first().map(|t| t.id);
599+ Self {
600+ thumbnails,
601+ current_id,
602+ scope: MruScope::All,
603+ app_id_filter: None,
604+ }
605+ }
606+
607+ pub fn is_empty(&self) -> bool {
608+ self.thumbnails.is_empty()
609+ }
610+
611+ #[cfg(test)]
612+ fn verify_invariants(&self) {
613+ if let Some(id) = self.current_id {
614+ assert!(
615+ self.thumbnails().any(|thumbnail| thumbnail.id == id),
616+ "current_id must be present in the current filtered thumbnail list",
617+ );
618+ } else {
619+ assert!(
620+ self.thumbnails().next().is_none(),
621+ "unset current_id must mean that the filtered thumbnail list is empty",
622+ );
623+ }
624+ }
625+
626+ fn thumbnails(&self) -> impl DoubleEndedIterator<Item = &Thumbnail> {
627+ let matches = match_filter(self.scope, self.app_id_filter.as_deref());
628+ self.thumbnails.iter().filter(move |t| matches(t))
629+ }
630+
631+ fn thumbnails_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Thumbnail> {
632+ let matches = match_filter(self.scope, self.app_id_filter.as_deref());
633+ self.thumbnails.iter_mut().filter(move |t| matches(t))
634+ }
635+
636+ fn thumbnails_with_idx(&self) -> impl DoubleEndedIterator<Item = (usize, &Thumbnail)> {
637+ let matches = match_filter(self.scope, self.app_id_filter.as_deref());
638+ self.thumbnails
639+ .iter()
640+ .enumerate()
641+ .filter(move |(_, t)| matches(t))
642+ }
643+
644+ fn are_animations_ongoing(&self) -> bool {
645+ self.thumbnails.iter().any(|t| t.are_animations_ongoing())
646+ }
647+
648+ fn advance_animations(&mut self) {
649+ for thumbnail in &mut self.thumbnails {
650+ thumbnail.advance_animations();
651+ }
652+ }
653+
654+ fn forward(&mut self) {
655+ let Some(id) = self.current_id else {
656+ return;
657+ };
658+
659+ let next = self.thumbnails().skip_while(|t| t.id != id).nth(1);
660+ self.current_id = Some(if let Some(next) = next {
661+ next.id
662+ } else {
663+ // We wrapped around.
664+ self.thumbnails().next().unwrap().id
665+ });
666+ }
667+
668+ fn backward(&mut self) {
669+ let Some(id) = self.current_id else {
670+ return;
671+ };
672+
673+ let next = self.thumbnails().rev().skip_while(|t| t.id != id).nth(1);
674+ self.current_id = Some(if let Some(next) = next {
675+ next.id
676+ } else {
677+ // We wrapped around.
678+ self.thumbnails().next_back().unwrap().id
679+ });
680+ }
681+
682+ fn set_current(&mut self, id: MappedId) {
683+ if self.thumbnails().any(|thumbnail| thumbnail.id == id) {
684+ self.current_id = Some(id);
685+ }
686+ }
687+
688+ fn first_id(&self) -> Option<MappedId> {
689+ self.thumbnails().next().map(|thumbnail| thumbnail.id)
690+ }
691+
692+ fn first(&mut self) {
693+ self.current_id = self.first_id();
694+ }
695+
696+ fn last(&mut self) {
697+ let id = self.thumbnails().next_back().map(|thumbnail| thumbnail.id);
698+ self.current_id = id;
699+ }
700+
701+ pub fn set_scope(&mut self, scope: MruScope) -> Option<MruScope> {
702+ if self.scope == scope {
703+ return None;
704+ }
705+ let rv = Some(self.scope);
706+
707+ if let Some(id) = self.current_id {
708+ let (current_idx, _) = self
709+ .thumbnails_with_idx()
710+ .find(|(_, thumbnail)| thumbnail.id == id)
711+ .unwrap();
712+
713+ self.scope = scope;
714+
715+ // Try to select the same, or the first thumbnail to the left. Failing that, select the
716+ // first one to the right.
717+ let mut id = self.first_id();
718+
719+ for (idx, thumbnail) in self.thumbnails_with_idx() {
720+ if idx > current_idx {
721+ break;
722+ }
723+ id = Some(thumbnail.id);
724+ }
725+ self.current_id = id;
726+ } else {
727+ self.scope = scope;
728+ self.current_id = self.first_id();
729+ }
730+
731+ rv
732+ }
733+
734+ pub fn set_filter(&mut self, filter: MruFilter) -> Option<Option<String>> {
735+ if self.app_id_filter.is_some() == (filter == MruFilter::AppId) {
736+ // Filter unchanged.
737+ return None;
738+ }
739+
740+ if let Some(id) = self.current_id {
741+ let (current_idx, current_thumbnail) = self
742+ .thumbnails_with_idx()
743+ .find(|(_, thumbnail)| thumbnail.id == id)
744+ .unwrap();
745+
746+ let old = match filter {
747+ MruFilter::All => {
748+ let old = self.app_id_filter.take();
749+ Some(old.expect("verified by early return at the top"))
750+ }
751+ MruFilter::AppId => {
752+ // If the current thumbnail is missing an app id, we can't set the filter.
753+ let current = current_thumbnail.app_id.clone()?;
754+ let old = self.app_id_filter.replace(current);
755+ assert!(old.is_none(), "verified by early return at the top");
756+ None
757+ }
758+ };
759+
760+ // Try to select the same, or the first thumbnail to the left. Failing that, select the
761+ // first one to the right.
762+ let mut id = self.first_id();
763+
764+ for (idx, thumbnail) in self.thumbnails_with_idx() {
765+ if idx > current_idx {
766+ break;
767+ }
768+ id = Some(thumbnail.id);
769+ }
770+ self.current_id = id;
771+
772+ Some(old)
773+ } else {
774+ match filter {
775+ MruFilter::All => {
776+ let old = self.app_id_filter.take();
777+ let old = old.expect("verified by early return at the top");
778+ self.current_id = self.first_id();
779+ Some(Some(old))
780+ }
781+ MruFilter::AppId => {
782+ // We don't have a current window to set the app id filter.
783+ None
784+ }
785+ }
786+ }
787+ }
788+
789+ fn idx_of(&self, id: MappedId) -> Option<usize> {
790+ self.thumbnails.iter().position(|t| t.id == id)
791+ }
792+
793+ fn remove_by_idx(&mut self, idx: usize) -> Option<Thumbnail> {
794+ let id = self.thumbnails[idx].id;
795+
796+ // Try to pick a different window when removing the current one.
797+ if self.current_id == Some(id) {
798+ self.forward();
799+ }
800+
801+ // If we're still on the same window, that means it's the last visible one.
802+ if self.current_id == Some(id) {
803+ self.current_id = None;
804+ }
805+
806+ Some(self.thumbnails.remove(idx))
807+ }
808+
809+ /// Returns the thumbnail if it's visible to the left of the currently selected one.
810+ fn thumbnail_left_of_current(&self, id: MappedId) -> Option<&Thumbnail> {
811+ for thumbnail in self.thumbnails() {
812+ if Some(thumbnail.id) == self.current_id {
813+ // We found the current window first, so the queried one is *not* to the left.
814+ return None;
815+ } else if thumbnail.id == id {
816+ // We found the queried window first, so the current one is to the right of it.
817+ return Some(thumbnail);
818+ }
819+ }
820+ None
821+ }
822+}
823+
824+fn matches(scope: MruScope, app_id_filter: Option<&str>, thumbnail: &Thumbnail) -> bool {
825+ let x = match scope {
826+ MruScope::All => true,
827+ MruScope::Output => thumbnail.on_current_output,
828+ MruScope::Workspace => thumbnail.on_current_workspace,
829+ };
830+ if !x {
831+ return false;
832+ }
833+
834+ if let Some(app_id) = app_id_filter {
835+ thumbnail.app_id.as_deref() == Some(app_id)
836+ } else {
837+ true
838+ }
839+}
840+
841+fn match_filter(scope: MruScope, app_id_filter: Option<&str>) -> impl Fn(&Thumbnail) -> bool + '_ {
842+ move |thumbnail| matches(scope, app_id_filter, thumbnail)
843+}
844+
845+impl ViewPos {
846+ fn current(&self) -> f64 {
847+ match self {
848+ ViewPos::Static(pos) => *pos,
849+ ViewPos::Animation(anim) => anim.value(),
850+ }
851+ }
852+
853+ fn target(&self) -> f64 {
854+ match self {
855+ ViewPos::Static(pos) => *pos,
856+ ViewPos::Animation(anim) => anim.to(),
857+ }
858+ }
859+
860+ fn are_animations_ongoing(&self) -> bool {
861+ match self {
862+ ViewPos::Static(_) => false,
863+ ViewPos::Animation(_) => true,
864+ }
865+ }
866+
867+ fn advance_animations(&mut self) {
868+ if let ViewPos::Animation(anim) = self {
869+ if anim.is_done() {
870+ *self = ViewPos::Static(anim.to());
871+ }
872+ }
873+ }
874+
875+ fn animate_from_with_config(
876+ &mut self,
877+ from: f64,
878+ config: niri_config::Animation,
879+ clock: Clock,
880+ ) {
881+ // FIXME: also compute and use current velocity.
882+ let anim = Animation::new(clock, self.current() + from, self.target(), 0., config);
883+ *self = ViewPos::Animation(anim);
884+ }
885+
886+ fn offset(&mut self, delta: f64) {
887+ match self {
888+ ViewPos::Static(pos) => *pos += delta,
889+ ViewPos::Animation(anim) => anim.offset(delta),
890+ }
891+ }
892+}
893+
894+impl WindowMruUi {
895+ pub fn new(config: Rc<RefCell<Config>>) -> Self {
896+ let mut rv = Self {
897+ state: UiState::Closed {
898+ previous_scope: MruScope::default(),
899+ },
900+ preset_opened_binds: make_preset_opened_binds(),
901+ dynamic_opened_binds: Vec::new(),
902+ config,
903+ };
904+ rv.update_binds();
905+ rv
906+ }
907+
908+ pub fn update_binds(&mut self) {
909+ self.dynamic_opened_binds = make_dynamic_opened_binds(&self.config.borrow());
910+ }
911+
912+ pub fn update_config(&mut self) {
913+ let inner = match &mut self.state {
914+ UiState::Open(inner) => inner,
915+ UiState::Closing { inner, .. } => inner,
916+ UiState::Closed { .. } => return,
917+ };
918+ inner.update_config();
919+ }
920+
921+ pub fn is_open(&self) -> bool {
922+ matches!(self.state, UiState::Open { .. })
923+ }
924+
925+ pub fn open(&mut self, clock: Clock, wmru: WindowMru, output: Output) {
926+ if self.is_open() {
927+ return;
928+ }
929+
930+ let open_delay = self.config.borrow().recent_windows.open_delay_ms;
931+ let open_delay = Duration::from_millis(u64::from(open_delay));
932+
933+ let mut inner = Inner {
934+ wmru,
935+ view_pos: ViewPos::Static(0.),
936+ freeze_view: false,
937+ open_at: clock.now_unadjusted() + open_delay,
938+ clock,
939+ config: self.config.clone(),
940+ output,
941+ scope_panel: Default::default(),
942+ backdrop_buffers: Default::default(),
943+ offscreen: OffscreenBuffer::default(),
944+ };
945+ inner.view_pos = ViewPos::Static(inner.compute_view_pos());
946+
947+ self.state = UiState::Open(inner);
948+ }
949+
950+ pub fn close(&mut self, close_request: MruCloseRequest) -> Option<MappedId> {
951+ if !self.is_open() {
952+ return None;
953+ }
954+ let state = mem::replace(
955+ &mut self.state,
956+ UiState::Closed {
957+ previous_scope: MruScope::default(),
958+ },
959+ );
960+ let UiState::Open(inner) = state else {
961+ unreachable!();
962+ };
963+
964+ let response = match close_request {
965+ MruCloseRequest::Cancel => None,
966+ MruCloseRequest::Confirm => inner.wmru.current_id,
967+ };
968+
969+ if inner.clock.now_unadjusted() < inner.open_at {
970+ // Hasn't displayed yet, no need to fade out.
971+ let UiState::Closed { previous_scope } = &mut self.state else {
972+ unreachable!()
973+ };
974+ *previous_scope = inner.wmru.scope;
975+ return response;
976+ }
977+
978+ let config = self.config.borrow();
979+ let config = config.animations.recent_windows_close.0;
980+
981+ let anim = Animation::new(inner.clock.clone(), 1., 0., 0., config);
982+ self.state = UiState::Closing { inner, anim };
983+ response
984+ }
985+
986+ pub fn advance(&mut self, dir: MruDirection, filter: Option<MruFilter>) {
987+ let UiState::Open(inner) = &mut self.state else {
988+ return;
989+ };
990+ inner.freeze_view = false;
991+
992+ if let Some(filter) = filter {
993+ inner.set_filter(filter);
994+ }
995+
996+ match dir {
997+ MruDirection::Forward => inner.wmru.forward(),
998+ MruDirection::Backward => inner.wmru.backward(),
999+ }
1000+ }
1001+
1002+ pub fn set_scope(&mut self, scope: MruScope) {
1003+ let UiState::Open(inner) = &mut self.state else {
1004+ return;
1005+ };
1006+ inner.freeze_view = false;
1007+ inner.set_scope(scope);
1008+ }
1009+
1010+ pub fn cycle_scope(&mut self) {
1011+ let UiState::Open(inner) = &mut self.state else {
1012+ return;
1013+ };
1014+
1015+ let scope = inner.wmru.scope;
1016+ let scope = SCOPE_CYCLE
1017+ .into_iter()
1018+ .cycle()
1019+ .skip_while(|s| *s != scope)
1020+ .nth(1)
1021+ .unwrap();
1022+ self.set_scope(scope);
1023+ }
1024+
1025+ pub fn pointer_motion(&mut self, pos_within_output: Point<f64, Logical>) -> Option<MappedId> {
1026+ let UiState::Open(inner) = &mut self.state else {
1027+ return None;
1028+ };
1029+
1030+ inner.freeze_view = true;
1031+
1032+ let id = inner.thumbnail_under(pos_within_output);
1033+ if let Some(id) = id {
1034+ inner.wmru.set_current(id);
1035+ }
1036+ id
1037+ }
1038+
1039+ pub fn first(&mut self) {
1040+ let UiState::Open(inner) = &mut self.state else {
1041+ return;
1042+ };
1043+ inner.freeze_view = false;
1044+ inner.wmru.first();
1045+ }
1046+
1047+ pub fn last(&mut self) {
1048+ let UiState::Open(inner) = &mut self.state else {
1049+ return;
1050+ };
1051+ inner.freeze_view = false;
1052+ inner.wmru.last();
1053+ }
1054+
1055+ pub fn scope(&self) -> MruScope {
1056+ match &self.state {
1057+ UiState::Closed { previous_scope, .. } => *previous_scope,
1058+ UiState::Open(inner) | UiState::Closing { inner, .. } => inner.wmru.scope,
1059+ }
1060+ }
1061+
1062+ pub fn current_window_id(&self) -> Option<MappedId> {
1063+ let UiState::Open(inner) = &self.state else {
1064+ return None;
1065+ };
1066+ inner.wmru.current_id
1067+ }
1068+
1069+ pub fn update_window(&mut self, layout: &Layout<Mapped>, id: MappedId) {
1070+ let UiState::Open(inner) = &mut self.state else {
1071+ return;
1072+ };
1073+ inner.update_window(layout, id);
1074+ }
1075+
1076+ pub fn remove_window(&mut self, id: MappedId) {
1077+ let UiState::Open(inner) = &mut self.state else {
1078+ return;
1079+ };
1080+
1081+ let Some(_thumbnail) = inner.remove_window(id) else {
1082+ return;
1083+ };
1084+
1085+ if inner.wmru.thumbnails.is_empty() {
1086+ self.close(MruCloseRequest::Cancel);
1087+ }
1088+ }
1089+
1090+ pub fn render_output<'a, R: NiriRenderer>(
1091+ &'a self,
1092+ niri: &'a Niri,
1093+ output: &Output,
1094+ renderer: &'a mut R,
1095+ target: RenderTarget,
1096+ ) -> Option<impl Iterator<Item = WindowMruUiRenderElement<R>> + 'a> {
1097+ let (inner, progress) = match &self.state {
1098+ UiState::Closed { .. } => return None,
1099+ UiState::Closing { inner, anim } => (inner, anim.clamped_value()),
1100+ UiState::Open(inner) => {
1101+ if inner.open_at <= inner.clock.now_unadjusted() {
1102+ (inner, 1.)
1103+ } else {
1104+ return None;
1105+ }
1106+ }
1107+ };
1108+
1109+ let span = tracy_client::span!("mru render");
1110+
1111+ let alpha = progress.clamp(0., 1.) as f32;
1112+
1113+ // Put a backdrop above the current desktop view to contrast the thumbnails.
1114+ let mut buffers = inner.backdrop_buffers.borrow_mut();
1115+ let buffer = buffers.entry(output.clone()).or_default();
1116+ buffer.resize(output_size(output));
1117+ buffer.set_color(BACKDROP_COLOR);
1118+ let render_backdrop = |alpha| {
1119+ SolidColorRenderElement::from_buffer(
1120+ buffer,
1121+ Point::new(0., 0.),
1122+ alpha,
1123+ Kind::Unspecified,
1124+ )
1125+ // Can't wrap into WindowMruUiRenderElement::SolidColor() right here since we have
1126+ // different <R> generic in offscreen vs. normal path.
1127+ };
1128+
1129+ // During the closing fade, use an offscreen to avoid transparent compositing artifacts.
1130+ let offscreen_elem = if *output == inner.output && alpha < 1. {
1131+ let renderer = renderer.as_gles_renderer();
1132+ let mut elems = Vec::from_iter(inner.render(niri, renderer, target));
1133+ elems.push(WindowMruUiRenderElement::SolidColor(render_backdrop(1.)));
1134+
1135+ let scale = output.current_scale().fractional_scale();
1136+ match inner.offscreen.render(renderer, Scale::from(scale), &elems) {
1137+ Ok((elem, _sync, _data)) => {
1138+ // FIXME: would be good to passthrough offscreen data to visible windows here.
1139+ // As is, during the closing fade, windows from other workspaces stop receiving
1140+ // frame callbacks.
1141+ //
1142+ // However, we need to refactor our offscreen data a bit to make this nicer.
1143+ // Currently it supports a stack of offscreens, but not a several unrelated
1144+ // offscreens showing the same window (possibly in addition to the window
1145+ // itself).
1146+ //
1147+ // Anyhow, this is not very noticable since Alt-Tab closing happens quickly.
1148+ Some(WindowMruUiRenderElement::Offscreen(elem.with_alpha(alpha)))
1149+ }
1150+ Err(err) => {
1151+ warn!("error rendering MRU to offscreen for fade-out: {err:?}");
1152+ None
1153+ }
1154+ }
1155+ } else {
1156+ None
1157+ };
1158+
1159+ // When alpha is 1., render everything directly, without an offscreen.
1160+ //
1161+ // This is not used as fallback when offscreen fails to render because it looks better to
1162+ // hide the previews immediately than to render them with alpha = 1. during a fade-out.
1163+ let normal_elems =
1164+ (*output == inner.output && alpha == 1.).then(|| inner.render(niri, renderer, target));
1165+ let normal_elems = normal_elems.into_iter().flatten();
1166+
1167+ // This is used for both normal elems and for other outputs.
1168+ let backdrop_elem = (offscreen_elem.is_none())
1169+ .then(|| WindowMruUiRenderElement::SolidColor(render_backdrop(alpha)));
1170+
1171+ // Make sure the span includes consuming the iterator.
1172+ let drop_span = std::iter::once(span).filter_map(|_| None);
1173+
1174+ Some(
1175+ offscreen_elem
1176+ .into_iter()
1177+ .chain(normal_elems)
1178+ .chain(backdrop_elem)
1179+ .chain(drop_span),
1180+ )
1181+ }
1182+
1183+ pub fn are_animations_ongoing(&self) -> bool {
1184+ match &self.state {
1185+ UiState::Open(inner) => inner.are_animations_ongoing(),
1186+ UiState::Closing { .. } => true,
1187+ UiState::Closed { .. } => false,
1188+ }
1189+ }
1190+
1191+ pub fn advance_animations(&mut self) {
1192+ match &mut self.state {
1193+ UiState::Open(inner) => inner.advance_animations(),
1194+ UiState::Closing { inner, anim } => {
1195+ if anim.is_done() {
1196+ self.state = UiState::Closed {
1197+ previous_scope: inner.wmru.scope,
1198+ };
1199+ return;
1200+ }
1201+ inner.advance_animations();
1202+ }
1203+ UiState::Closed { .. } => {}
1204+ }
1205+ }
1206+
1207+ pub fn opened_bindings(&mut self, mods: Modifiers) -> impl Iterator<Item = &Bind> + Clone {
1208+ // Fill modifiers with the current mods.
1209+ for bind in &mut self.preset_opened_binds {
1210+ bind.key.modifiers = mods;
1211+ }
1212+ for bind in &mut self.dynamic_opened_binds {
1213+ bind.key.modifiers = mods;
1214+ }
1215+
1216+ self.preset_opened_binds
1217+ .iter()
1218+ .chain(&self.dynamic_opened_binds)
1219+ }
1220+
1221+ pub fn output(&self) -> Option<&Output> {
1222+ match &self.state {
1223+ UiState::Open(inner) => Some(&inner.output),
1224+ _ => None,
1225+ }
1226+ }
1227+}
1228+
1229+fn compute_view_offset(cur_x: f64, working_width: f64, new_col_x: f64, new_col_width: f64) -> f64 {
1230+ let new_x = new_col_x;
1231+ let new_right_x = new_col_x + new_col_width;
1232+
1233+ // If the column is already fully visible, leave the view as is.
1234+ if cur_x <= new_x && new_right_x <= cur_x + working_width {
1235+ return -(new_col_x - cur_x);
1236+ }
1237+
1238+ // Otherwise, prefer the alignment that results in less motion from the current position.
1239+ let dist_to_left = (cur_x - new_x).abs();
1240+ let dist_to_right = ((cur_x + working_width) - new_right_x).abs();
1241+ if dist_to_left <= dist_to_right {
1242+ 0.
1243+ } else {
1244+ -(working_width - new_col_width)
1245+ }
1246+}
1247+
1248+impl Inner {
1249+ fn update_config(&mut self) {
1250+ self.freeze_view = false;
1251+
1252+ let config = self.config.borrow().recent_windows.previews;
1253+ for thumbnail in &mut self.wmru.thumbnails {
1254+ thumbnail.config = config;
1255+ }
1256+ }
1257+
1258+ fn are_animations_ongoing(&self) -> bool {
1259+ self.clock.now_unadjusted() < self.open_at
1260+ || self.view_pos.are_animations_ongoing()
1261+ || self.wmru.are_animations_ongoing()
1262+ }
1263+
1264+ fn advance_animations(&mut self) {
1265+ self.view_pos.advance_animations();
1266+ self.wmru.advance_animations();
1267+
1268+ if !self.freeze_view {
1269+ let new_view_pos = self.compute_view_pos();
1270+ let delta = new_view_pos - self.view_pos.target();
1271+ let pixel = 1. / self.output.current_scale().fractional_scale();
1272+ if delta.abs() > pixel {
1273+ self.animate_view_pos_from(-delta);
1274+ }
1275+ self.view_pos.offset(delta);
1276+ }
1277+ }
1278+
1279+ fn animate_view_pos_from(&mut self, from: f64) {
1280+ let config = self.config.borrow().animations.window_movement.0;
1281+ self.view_pos
1282+ .animate_from_with_config(from, config, self.clock.clone());
1283+ }
1284+
1285+ fn compute_view_pos(&self) -> f64 {
1286+ let Some(current_id) = self.wmru.current_id else {
1287+ return 0.;
1288+ };
1289+
1290+ let output_size = output_size(&self.output);
1291+
1292+ let working_x = STRUT + GAP;
1293+ let working_width = (output_size.w - working_x * 2.).max(0.);
1294+
1295+ let mut current_geo = Rectangle::default();
1296+ let mut strip_width = 0.;
1297+ for (thumbnail, geo) in self.thumbnails() {
1298+ if thumbnail.id == current_id {
1299+ current_geo = geo;
1300+ }
1301+ strip_width = geo.loc.x + geo.size.w;
1302+
1303+ // If we found current_geo, and the strip width is already bigger than the working
1304+ // width, no need to compute further.
1305+ if current_geo.size.w != 0. && strip_width > working_width {
1306+ break;
1307+ }
1308+ }
1309+
1310+ // If the whole strip fits on screen, center it.
1311+ if strip_width <= working_width {
1312+ return -(output_size.w - strip_width) / 2.;
1313+ }
1314+
1315+ compute_view_offset(
1316+ self.view_pos.target() + working_x,
1317+ working_width,
1318+ current_geo.loc.x,
1319+ current_geo.size.w,
1320+ ) + current_geo.loc.x
1321+ - working_x
1322+ }
1323+
1324+ fn update_window(&mut self, layout: &Layout<Mapped>, id: MappedId) {
1325+ let output_size = output_size(&self.output);
1326+ let scale = self.output.current_scale().fractional_scale();
1327+
1328+ // If the updated window is to the left of the currently selected one, we need to offset
1329+ // the view position to compensate for the change in size.
1330+ let left = self.wmru.thumbnail_left_of_current(id);
1331+ let prev_size = left.map(|thumbnail| thumbnail.preview_size(output_size, scale));
1332+
1333+ let Some(thumbnail) = self.wmru.thumbnails.iter_mut().find(|t| t.id == id) else {
1334+ return;
1335+ };
1336+
1337+ let Some((_, mapped)) = layout.windows().find(|(_, m)| m.id() == id) else {
1338+ error!("window in the MRU must be present in the layout");
1339+ return;
1340+ };
1341+
1342+ thumbnail.update_window(mapped);
1343+
1344+ if let Some(prev) = prev_size {
1345+ let new = thumbnail.preview_size(output_size, scale);
1346+ let delta = new.w - prev.w;
1347+ self.view_pos.offset(delta);
1348+ }
1349+ }
1350+
1351+ fn remove_window(&mut self, id: MappedId) -> Option<Thumbnail> {
1352+ let idx = self.wmru.idx_of(id)?;
1353+
1354+ let last_visible = self.wmru.thumbnails().next_back();
1355+ let removing_last_visible = last_visible.is_some_and(|t| t.id == id);
1356+
1357+ // When removing the last visible thumbnail, nothing needs to be animated.
1358+ // - If it's not currently selected, then it can't cause changes to view position.
1359+ // - If it's currently selected, then the first step in removal (focusing the next window)
1360+ // will wrap back to the start, and no animations should happen.
1361+ if !removing_last_visible {
1362+ let output_size = output_size(&self.output);
1363+ let scale = self.output.current_scale().fractional_scale();
1364+ let round = move |logical: f64| round_logical_in_physical(scale, logical);
1365+
1366+ let padding = self.config.borrow().recent_windows.highlight.padding;
1367+ let padding = round(padding) + round(BORDER);
1368+ let gap = padding + round(GAP) + padding;
1369+
1370+ let prev_size = self.wmru.thumbnails[idx].preview_size(output_size, scale);
1371+ let delta = prev_size.w + gap;
1372+
1373+ let config = self.config.borrow().animations.window_movement.0;
1374+
1375+ // If the removed window is to the left of the currently selected one, we need to offset
1376+ // the view position to compensate for the change.
1377+ if self.wmru.thumbnail_left_of_current(id).is_some() {
1378+ self.view_pos.offset(-delta);
1379+
1380+ // And animate movement of windows left of it.
1381+ for thumbnail in self.wmru.thumbnails_mut().take_while(|t| t.id != id) {
1382+ thumbnail.animate_move_from_with_config(-delta, config);
1383+ }
1384+ } else {
1385+ // Otherwise, animate movement of windows right of it.
1386+ for thumbnail in self.wmru.thumbnails_mut().rev().take_while(|t| t.id != id) {
1387+ thumbnail.animate_move_from_with_config(delta, config);
1388+ }
1389+ }
1390+ }
1391+
1392+ self.wmru.remove_by_idx(idx)
1393+ }
1394+
1395+ fn set_scope(&mut self, scope: MruScope) {
1396+ let was_empty = self.wmru.current_id.is_none();
1397+ if let Some(old_scope) = self.wmru.set_scope(scope) {
1398+ self.animate_scope_filter_change(was_empty, old_scope, None);
1399+ }
1400+ }
1401+
1402+ fn set_filter(&mut self, filter: MruFilter) {
1403+ let was_empty = self.wmru.current_id.is_none();
1404+ if let Some(old_filter) = self.wmru.set_filter(filter) {
1405+ let old_filter = Some(old_filter.as_deref());
1406+ self.animate_scope_filter_change(was_empty, self.wmru.scope, old_filter);
1407+ }
1408+ }
1409+
1410+ fn animate_scope_filter_change(
1411+ &mut self,
1412+ was_empty: bool,
1413+ old_scope: MruScope,
1414+ old_filter: Option<Option<&str>>,
1415+ ) {
1416+ let Some(id) = self.wmru.current_id else {
1417+ // If there's no current_id then the new filter caused all windows to disappear, so
1418+ // there's nothing to animate.
1419+ return;
1420+ };
1421+ let idx = self.wmru.idx_of(id).unwrap();
1422+
1423+ // Animate opening for newly appeared thumbnails.
1424+ let config = self.config.borrow().animations.window_open.anim;
1425+ let old_filter = old_filter.unwrap_or(self.wmru.app_id_filter.as_deref());
1426+ let matches_old = match_filter(old_scope, old_filter);
1427+ let matches_new = match_filter(self.wmru.scope, self.wmru.app_id_filter.as_deref());
1428+ for thumbnail in &mut self.wmru.thumbnails {
1429+ if matches_new(thumbnail) && !matches_old(thumbnail) {
1430+ thumbnail.animate_open_with_config(config);
1431+ }
1432+ }
1433+
1434+ if was_empty {
1435+ self.view_pos = ViewPos::Static(self.compute_view_pos());
1436+ return;
1437+ }
1438+
1439+ let output_size = output_size(&self.output);
1440+ let scale = self.output.current_scale().fractional_scale();
1441+ let round = move |logical: f64| round_logical_in_physical(scale, logical);
1442+
1443+ let padding = self.config.borrow().recent_windows.highlight.padding;
1444+ let padding = round(padding) + round(BORDER);
1445+ let gap = padding + round(GAP) + padding;
1446+
1447+ let config = self.config.borrow().animations.window_movement.0;
1448+
1449+ let mut delta = 0.;
1450+ for t in &mut self.wmru.thumbnails[idx + 1..] {
1451+ match (matches_old(t), matches_new(t)) {
1452+ (true, true) => t.animate_move_from_with_config(delta, config),
1453+ (true, false) => delta += t.preview_size(output_size, scale).w + gap,
1454+ (false, true) => delta -= t.preview_size(output_size, scale).w + gap,
1455+ (false, false) => (),
1456+ }
1457+ }
1458+
1459+ let mut delta = 0.;
1460+ for t in self.wmru.thumbnails[..idx].iter_mut().rev() {
1461+ match (matches_old(t), matches_new(t)) {
1462+ (true, true) => t.animate_move_from_with_config(-delta, config),
1463+ (true, false) => delta += t.preview_size(output_size, scale).w + gap,
1464+ (false, true) => delta -= t.preview_size(output_size, scale).w + gap,
1465+ (false, false) => (),
1466+ }
1467+ }
1468+
1469+ self.view_pos.offset(-delta);
1470+ }
1471+
1472+ fn thumbnails(&self) -> impl Iterator<Item = (&Thumbnail, Rectangle<f64, Logical>)> {
1473+ let output_size = output_size(&self.output);
1474+ let scale = self.output.current_scale().fractional_scale();
1475+ let round = move |logical: f64| round_logical_in_physical(scale, logical);
1476+
1477+ let padding = self.config.borrow().recent_windows.highlight.padding;
1478+ let padding = round(padding) + round(BORDER);
1479+ let gap = padding + round(GAP) + padding;
1480+
1481+ let mut x = 0.;
1482+ self.wmru.thumbnails().map(move |thumbnail| {
1483+ let size = thumbnail.preview_size(output_size, scale);
1484+ let y = round((output_size.h - size.h) / 2.);
1485+
1486+ let loc = Point::new(x, y);
1487+ x += size.w + gap;
1488+
1489+ let geo = Rectangle::new(loc, size);
1490+ (thumbnail, geo)
1491+ })
1492+ }
1493+
1494+ fn thumbnails_in_view_static(
1495+ &self,
1496+ ) -> impl Iterator<Item = (&Thumbnail, Rectangle<f64, Logical>)> {
1497+ let output_size = output_size(&self.output);
1498+ let scale = self.output.current_scale().fractional_scale();
1499+ let round = |logical: f64| round_logical_in_physical(scale, logical);
1500+
1501+ let view_pos = round(self.view_pos.current());
1502+
1503+ let leftmost = view_pos;
1504+ let rightmost = view_pos + output_size.w;
1505+
1506+ self.thumbnails()
1507+ .skip_while(move |(_, geo)| geo.loc.x + geo.size.w <= leftmost)
1508+ .map_while(move |(thumbnail, mut geo)| {
1509+ if rightmost <= geo.loc.x {
1510+ return None;
1511+ }
1512+
1513+ geo.loc.x -= view_pos;
1514+ Some((thumbnail, geo))
1515+ })
1516+ }
1517+
1518+ fn thumbnails_in_view_render(
1519+ &self,
1520+ ) -> impl Iterator<Item = (&Thumbnail, Rectangle<f64, Logical>)> {
1521+ let output_size = output_size(&self.output);
1522+ let scale = self.output.current_scale().fractional_scale();
1523+ let round = move |logical: f64| round_logical_in_physical(scale, logical);
1524+
1525+ let view_pos = round(self.view_pos.current());
1526+
1527+ self.thumbnails().filter_map(move |(thumbnail, mut geo)| {
1528+ geo.loc.x -= view_pos;
1529+ geo.loc.x += round(thumbnail.render_offset());
1530+
1531+ if geo.loc.x + geo.size.w < 0. || output_size.w < geo.loc.x {
1532+ return None;
1533+ }
1534+
1535+ Some((thumbnail, geo))
1536+ })
1537+ }
1538+
1539+ fn render<'a, R: NiriRenderer>(
1540+ &'a self,
1541+ niri: &'a Niri,
1542+ renderer: &'a mut R,
1543+ target: RenderTarget,
1544+ ) -> impl Iterator<Item = WindowMruUiRenderElement<R>> + 'a {
1545+ let output_size = output_size(&self.output);
1546+ let scale = self.output.current_scale().fractional_scale();
1547+
1548+ let panel_texture =
1549+ self.scope_panel
1550+ .borrow_mut()
1551+ .get(renderer.as_gles_renderer(), scale, self.wmru.scope);
1552+ let panel = panel_texture.map(move |texture| {
1553+ let padding = round_logical_in_physical(scale, f64::from(PANEL_PADDING));
1554+
1555+ let size = texture.logical_size();
1556+ let location = Point::new((output_size.w - size.w) / 2., padding * 2.);
1557+ let elem = PrimaryGpuTextureRenderElement(TextureRenderElement::from_texture_buffer(
1558+ texture.clone(),
1559+ location,
1560+ 1.,
1561+ None,
1562+ None,
1563+ Kind::Unspecified,
1564+ ));
1565+ WindowMruUiRenderElement::TextureElement(elem)
1566+ });
1567+ let panel = panel.into_iter();
1568+
1569+ let current_id = self.wmru.current_id;
1570+
1571+ let bob_y = baba_is_float_offset(self.clock.now(), output_size.h);
1572+ let bob_y = round_logical_in_physical(scale, bob_y);
1573+
1574+ let config = self.config.borrow();
1575+
1576+ let thumbnails = self
1577+ .thumbnails_in_view_render()
1578+ .filter_map(move |(thumbnail, geo)| {
1579+ let id = thumbnail.id;
1580+ let Some((_, mapped)) = niri.layout.windows().find(|(_, m)| m.id() == id) else {
1581+ error!("window in the MRU must be present in the layout");
1582+ return None;
1583+ };
1584+
1585+ let config = &config.recent_windows;
1586+
1587+ let is_active = Some(id) == current_id;
1588+ let elems = thumbnail.render(
1589+ renderer, config, mapped, geo, scale, is_active, bob_y, target,
1590+ );
1591+ Some(elems)
1592+ });
1593+ let thumbnails = thumbnails.flatten();
1594+
1595+ panel.chain(thumbnails)
1596+ }
1597+
1598+ fn thumbnail_under(&self, pos: Point<f64, Logical>) -> Option<MappedId> {
1599+ let scale = self.output.current_scale().fractional_scale();
1600+ let round = move |logical: f64| round_logical_in_physical(scale, logical);
1601+ let padding = self.config.borrow().recent_windows.highlight.padding;
1602+ let padding = round(padding) + round(BORDER);
1603+ let padding = Point::new(padding, padding);
1604+ let title_gap = round(TITLE_GAP);
1605+
1606+ for (thumbnail, mut geo) in self.thumbnails_in_view_static() {
1607+ geo.loc -= padding;
1608+ geo.size += padding.to_size().upscale(2.);
1609+
1610+ // It doesn't really matter all that much if the title texture is stale here, and it
1611+ // would be annoying to thread the rendering into this function. The texture might be
1612+ // one frame stale or so.
1613+ if let Some(texture) = thumbnail.title_texture.borrow().get_stale() {
1614+ let title_size = texture.logical_size();
1615+ geo.size.h += title_gap + title_size.h;
1616+ // Subtract half the padding so it looks more balanced visually.
1617+ geo.size.h -= round(padding.y / 2.);
1618+ }
1619+
1620+ if geo.contains(pos) {
1621+ return Some(thumbnail.id);
1622+ }
1623+ }
1624+
1625+ None
1626+ }
1627+}
1628+
1629+impl TitleTexture {
1630+ fn get(&mut self, renderer: &mut GlesRenderer, title: &str, scale: f64) -> Option<MruTexture> {
1631+ if self.title != title || self.scale != scale {
1632+ self.texture = None;
1633+ self.title = title.to_owned();
1634+ self.scale = scale;
1635+ }
1636+
1637+ self.texture
1638+ .get_or_insert_with(|| generate_title_texture(renderer, title, scale).ok())
1639+ .clone()
1640+ }
1641+
1642+ fn get_stale(&self) -> Option<&MruTexture> {
1643+ if let Some(Some(texture)) = &self.texture {
1644+ Some(texture)
1645+ } else {
1646+ None
1647+ }
1648+ }
1649+}
1650+
1651+fn generate_title_texture(
1652+ renderer: &mut GlesRenderer,
1653+ title: &str,
1654+ scale: f64,
1655+) -> anyhow::Result<MruTexture> {
1656+ let _span = tracy_client::span!("mru::generate_title_texture");
1657+
1658+ let mut font = FontDescription::from_string(FONT);
1659+ font.set_absolute_size(to_physical_precise_round(scale, font.size()));
1660+
1661+ let surface = ImageSurface::create(cairo::Format::ARgb32, 0, 0)?;
1662+ let cr = cairo::Context::new(&surface)?;
1663+ let layout = pangocairo::functions::create_layout(&cr);
1664+ layout.context().set_round_glyph_positions(false);
1665+ // On Window CSD, line breaks are either stripped or replaced with the linebreak symbol anyway.
1666+ // No use rendering it as multiple lines.
1667+ layout.set_single_paragraph_mode(true);
1668+ layout.set_font_description(Some(&font));
1669+ layout.set_text(title);
1670+
1671+ let (width, height) = layout.pixel_size();
1672+ ensure!(width > 0 && height > 0);
1673+
1674+ // Guard against overly long window titles.
1675+ let width = min(width, 16383);
1676+ let height = min(height, 16383);
1677+
1678+ let surface = ImageSurface::create(cairo::Format::ARgb32, width, height)?;
1679+ let cr = cairo::Context::new(&surface)?;
1680+ cr.set_source_rgb(1., 1., 1.);
1681+ pangocairo::functions::show_layout(&cr, &layout);
1682+
1683+ drop(cr);
1684+ let data = surface.take_data().unwrap();
1685+ let buffer = TextureBuffer::from_memory(
1686+ renderer,
1687+ &data,
1688+ Fourcc::Argb8888,
1689+ (width, height),
1690+ false,
1691+ scale,
1692+ Transform::Normal,
1693+ Vec::new(),
1694+ )?;
1695+
1696+ Ok(buffer)
1697+}
1698+
1699+impl ScopePanel {
1700+ fn get(
1701+ &mut self,
1702+ renderer: &mut GlesRenderer,
1703+ scale: f64,
1704+ scope: MruScope,
1705+ ) -> Option<MruTexture> {
1706+ if self.scale != scale {
1707+ self.textures = None;
1708+ self.scale = scale;
1709+ }
1710+
1711+ self.textures
1712+ .get_or_insert_with(|| generate_scope_panels(renderer, scale).ok())
1713+ .as_ref()
1714+ .map(|x| x[scope as usize].clone())
1715+ }
1716+}
1717+
1718+fn generate_scope_panels(
1719+ renderer: &mut GlesRenderer,
1720+ scale: f64,
1721+) -> anyhow::Result<[MruTexture; 3]> {
1722+ fn make_panel_text(idx: usize) -> String {
1723+ let span_unselected = "<span fgcolor='#999999'>";
1724+ let span_end = "</span>";
1725+ let span_shortcut = "<span face='mono' bgcolor='#2C2C2C' letter_spacing='5000'><b>";
1726+ let span_shortcut_end = "</b></span>";
1727+
1728+ // Starts with a zero-width space to make letter_spacing work on the left.
1729+ let mut buf =
1730+ format!("\u{200B}{span_unselected}{span_shortcut}S{span_shortcut_end}cope:{span_end}");
1731+
1732+ for scope in SCOPE_CYCLE {
1733+ buf.push_str(" ");
1734+ if scope as usize != idx {
1735+ buf.push_str(span_unselected);
1736+ }
1737+ let text = match scope {
1738+ MruScope::All => format!("{span_shortcut}A{span_shortcut_end}ll"),
1739+ MruScope::Output => format!("{span_shortcut}O{span_shortcut_end}utput"),
1740+ MruScope::Workspace => format!("{span_shortcut}W{span_shortcut_end}orkspace"),
1741+ };
1742+ buf.push_str(&text);
1743+ if scope as usize != idx {
1744+ buf.push_str(span_end);
1745+ }
1746+ }
1747+
1748+ buf
1749+ }
1750+
1751+ // Can't wait for array::try_map()
1752+ Ok([
1753+ render_panel(renderer, scale, &make_panel_text(0))?,
1754+ render_panel(renderer, scale, &make_panel_text(1))?,
1755+ render_panel(renderer, scale, &make_panel_text(2))?,
1756+ ])
1757+}
1758+
1759+fn render_panel(renderer: &mut GlesRenderer, scale: f64, text: &str) -> anyhow::Result<MruTexture> {
1760+ let _span = tracy_client::span!("mru::render_panel");
1761+
1762+ let mut font = FontDescription::from_string(FONT);
1763+ font.set_absolute_size(to_physical_precise_round(scale, font.size()));
1764+
1765+ let padding: i32 = to_physical_precise_round(scale, PANEL_PADDING);
1766+ // Keep the border width even to avoid blurry edges.
1767+ // Render to a dummy surface to determine the size.
1768+ let surface = ImageSurface::create(cairo::Format::ARgb32, 0, 0)?;
1769+ let cr = cairo::Context::new(&surface)?;
1770+ let layout = pangocairo::functions::create_layout(&cr);
1771+ layout.context().set_round_glyph_positions(false);
1772+ layout.set_font_description(Some(&font));
1773+ layout.set_markup(text);
1774+ let (mut width, mut height) = layout.pixel_size();
1775+
1776+ width += padding * 2;
1777+ height += padding * 2;
1778+
1779+ let surface = ImageSurface::create(cairo::Format::ARgb32, width, height)?;
1780+ let cr = cairo::Context::new(&surface)?;
1781+ cr.set_source_rgb(0.1, 0.1, 0.1);
1782+ cr.paint()?;
1783+
1784+ let padding = f64::from(padding);
1785+
1786+ cr.move_to(padding, padding);
1787+
1788+ let layout = pangocairo::functions::create_layout(&cr);
1789+ layout.context().set_round_glyph_positions(false);
1790+ layout.set_font_description(Some(&font));
1791+ layout.set_markup(text);
1792+
1793+ cr.set_source_rgb(1., 1., 1.);
1794+ pangocairo::functions::show_layout(&cr, &layout);
1795+
1796+ cr.move_to(0., 0.);
1797+ cr.line_to(width.into(), 0.);
1798+ cr.line_to(width.into(), height.into());
1799+ cr.line_to(0., height.into());
1800+ cr.line_to(0., 0.);
1801+ cr.set_source_rgb(0.5, 0.5, 0.5);
1802+ cr.set_line_width((f64::from(PANEL_BORDER) / 2. * scale).round() * 2.);
1803+ cr.stroke()?;
1804+
1805+ drop(cr);
1806+ let data = surface.take_data().unwrap();
1807+ let buffer = TextureBuffer::from_memory(
1808+ renderer,
1809+ &data,
1810+ Fourcc::Argb8888,
1811+ (width, height),
1812+ false,
1813+ scale,
1814+ Transform::Normal,
1815+ Vec::new(),
1816+ )?;
1817+
1818+ Ok(buffer)
1819+}
1820+
1821+/// Returns key bindings available when the MRU UI is open.
1822+fn make_preset_opened_binds() -> Vec<Bind> {
1823+ let mut rv = Vec::new();
1824+
1825+ let mut push = |trigger, action| {
1826+ rv.push(Bind {
1827+ key: Key {
1828+ trigger: Trigger::Keysym(trigger),
1829+ // The modifier is filled dynamically.
1830+ modifiers: Modifiers::empty(),
1831+ },
1832+ action,
1833+ repeat: true,
1834+ cooldown: None,
1835+ allow_when_locked: false,
1836+ allow_inhibiting: false,
1837+ hotkey_overlay_title: None,
1838+ })
1839+ };
1840+
1841+ push(Keysym::Escape, Action::MruCancel);
1842+ push(Keysym::Return, Action::MruConfirm);
1843+ push(Keysym::a, Action::MruSetScope(MruScope::All));
1844+ push(Keysym::o, Action::MruSetScope(MruScope::Output));
1845+ push(Keysym::w, Action::MruSetScope(MruScope::Workspace));
1846+ push(Keysym::s, Action::MruCycleScope);
1847+
1848+ // Leave these in since they are the most expected and generally uncontroversial keys, so that
1849+ // they work even if these actions are absent from the normal binds.
1850+ push(Keysym::Home, Action::MruFirst);
1851+ push(Keysym::End, Action::MruLast);
1852+ push(
1853+ Keysym::Left,
1854+ Action::MruAdvance {
1855+ direction: MruDirection::Backward,
1856+ scope: None,
1857+ filter: None,
1858+ },
1859+ );
1860+ push(
1861+ Keysym::Right,
1862+ Action::MruAdvance {
1863+ direction: MruDirection::Forward,
1864+ scope: None,
1865+ filter: None,
1866+ },
1867+ );
1868+
1869+ rv
1870+}
1871+
1872+/// Returns dynamic key bindings available when the MRU UI is open.
1873+///
1874+/// These ones are generated based on the normal bindings.
1875+fn make_dynamic_opened_binds(config: &Config) -> Vec<Bind> {
1876+ let mut binds: HashMap<Trigger, Vec<Bind>> = HashMap::new();
1877+
1878+ for bind in &config.binds.0 {
1879+ let action = match &bind.action {
1880+ Action::FocusColumnRight
1881+ | Action::FocusColumnRightOrFirst
1882+ | Action::FocusColumnOrMonitorRight
1883+ | Action::FocusWindowDownOrColumnRight => Action::MruAdvance {
1884+ direction: MruDirection::Forward,
1885+ scope: None,
1886+ filter: None,
1887+ },
1888+ Action::FocusColumnLeft
1889+ | Action::FocusColumnLeftOrLast
1890+ | Action::FocusColumnOrMonitorLeft
1891+ | Action::FocusWindowUpOrColumnLeft => Action::MruAdvance {
1892+ direction: MruDirection::Backward,
1893+ scope: None,
1894+ filter: None,
1895+ },
1896+ Action::FocusColumnFirst => Action::MruFirst,
1897+ Action::FocusColumnLast => Action::MruLast,
1898+ Action::CloseWindow => Action::MruCloseCurrentWindow,
1899+ x @ Action::Screenshot(_, _) => x.clone(),
1900+ _ => continue,
1901+ };
1902+
1903+ binds.entry(bind.key.trigger).or_default().push(Bind {
1904+ action,
1905+ ..bind.clone()
1906+ });
1907+ }
1908+
1909+ let mut rv = Vec::new();
1910+
1911+ // For each trigger, take the bind with the lowest number of modifiers.
1912+ for binds in binds.into_values() {
1913+ let bind = binds
1914+ .into_iter()
1915+ .min_by_key(|bind| bind.key.modifiers.iter().count())
1916+ .unwrap();
1917+
1918+ rv.push(Bind {
1919+ key: Key {
1920+ trigger: bind.key.trigger,
1921+ // The modifier is filled dynamically.
1922+ modifiers: Modifiers::empty(),
1923+ },
1924+ ..bind
1925+ });
1926+ }
1927+
1928+ rv
1929+}
src/ui/mru/tests.rsadded+135 -0
@@ -0,0 +1,135 @@
1+use proptest::prelude::*;
2+use proptest_derive::Arbitrary;
3+
4+use super::*;
5+
6+fn create_thumbnail() -> Thumbnail {
7+ Thumbnail {
8+ id: MappedId::next(),
9+ timestamp: None,
10+ on_current_output: false,
11+ on_current_workspace: false,
12+ app_id: None,
13+ size: Size::new(100, 100),
14+ clock: Clock::with_time(Duration::ZERO),
15+ config: niri_config::MruPreviews::default(),
16+ open_animation: None,
17+ move_animation: None,
18+ title_texture: Default::default(),
19+ background: RefCell::new(FocusRing::new(Default::default())),
20+ border: RefCell::new(FocusRing::new(Default::default())),
21+ }
22+}
23+
24+#[test]
25+fn remove_last_window_out_of_two() {
26+ let ops = [Op::Backward, Op::Remove(1)];
27+
28+ let thumbnails = vec![create_thumbnail(), create_thumbnail()];
29+ let current_id = thumbnails.first().map(|t| t.id);
30+ let mut mru = WindowMru {
31+ thumbnails,
32+ current_id,
33+ scope: MruScope::All,
34+ app_id_filter: None,
35+ };
36+
37+ check_ops(&mut mru, &ops);
38+}
39+
40+fn arbitrary_scope() -> impl Strategy<Value = MruScope> {
41+ prop_oneof![
42+ Just(MruScope::All),
43+ Just(MruScope::Output),
44+ Just(MruScope::Workspace),
45+ ]
46+}
47+
48+fn arbitrary_filter() -> impl Strategy<Value = MruFilter> {
49+ prop_oneof![Just(MruFilter::All), Just(MruFilter::AppId)]
50+}
51+
52+fn arbitrary_app_id() -> impl Strategy<Value = Option<String>> {
53+ prop_oneof![Just(None), Just(Some(1)), Just(Some(2))]
54+ .prop_map(|id| id.map(|id| format!("app-{id}")))
55+}
56+
57+prop_compose! {
58+ fn arbitrary_thumbnail()(
59+ timestamp: Option<Duration>,
60+ on_current_output: bool,
61+ on_current_workspace: bool,
62+ app_id in arbitrary_app_id(),
63+ ) -> Thumbnail {
64+ let mut thumbnail = create_thumbnail();
65+ thumbnail.timestamp = timestamp;
66+ thumbnail.on_current_workspace = on_current_workspace;
67+ thumbnail.on_current_output = on_current_output;
68+ thumbnail.app_id = app_id;
69+ thumbnail
70+ }
71+}
72+
73+prop_compose! {
74+ fn arbitrary_mru()(
75+ thumbnails in proptest::collection::vec(arbitrary_thumbnail(), 1..10),
76+ ) -> WindowMru {
77+ let current_id = thumbnails.first().map(|t| t.id);
78+ WindowMru {
79+ thumbnails,
80+ current_id,
81+ scope: MruScope::All,
82+ app_id_filter: None,
83+ }
84+ }
85+}
86+
87+#[derive(Debug, Clone, Arbitrary)]
88+enum Op {
89+ Forward,
90+ Backward,
91+ First,
92+ Last,
93+ SetScope(#[proptest(strategy = "arbitrary_scope()")] MruScope),
94+ SetFilter(#[proptest(strategy = "arbitrary_filter()")] MruFilter),
95+ Remove(#[proptest(strategy = "1..10usize")] usize),
96+}
97+
98+impl Op {
99+ fn apply(&self, mru: &mut WindowMru) {
100+ match self {
101+ Op::Forward => mru.forward(),
102+ Op::Backward => mru.backward(),
103+ Op::First => mru.first(),
104+ Op::Last => mru.last(),
105+ Op::SetScope(scope) => {
106+ mru.set_scope(*scope);
107+ }
108+ Op::SetFilter(filter) => {
109+ mru.set_filter(*filter);
110+ }
111+ Op::Remove(idx) => {
112+ if *idx < mru.thumbnails.len() {
113+ mru.remove_by_idx(*idx);
114+ }
115+ }
116+ }
117+ }
118+}
119+
120+fn check_ops(mru: &mut WindowMru, ops: &[Op]) {
121+ for op in ops {
122+ op.apply(mru);
123+ mru.verify_invariants();
124+ }
125+}
126+
127+proptest! {
128+ #[test]
129+ fn random_operations_dont_panic(
130+ mut mru in arbitrary_mru(),
131+ ops: Vec<Op>,
132+ ) {
133+ check_ops(&mut mru, &ops);
134+ }
135+}
src/window/mapped.rsmodified+12 -0
@@ -183,6 +183,9 @@ pub struct Mapped {
183183 /// These have been "sent" to the window in form of configures, but the window hadn't committed
184184 /// in response yet.
185185 uncommitted_maximized: Vec<(Serial, bool)>,
186+
187+ /// Most recent monotonic time when the window had the focus.
188+ focus_timestamp: Option<Duration>,
186189 }
187190
188191 niri_render_elements! {
@@ -279,6 +282,7 @@ impl Mapped {
279282 is_maximized: false,
280283 is_pending_maximized: false,
281284 uncommitted_maximized: Vec::new(),
285+ focus_timestamp: None,
282286 };
283287
284288 rv.is_maximized = rv.sizing_mode().is_maximized();
@@ -515,6 +519,14 @@ impl Mapped {
515519 })
516520 }
517521
522+ pub fn get_focus_timestamp(&self) -> Option<Duration> {
523+ self.focus_timestamp
524+ }
525+
526+ pub fn set_focus_timestamp(&mut self, timestamp: Duration) {
527+ self.focus_timestamp.replace(timestamp);
528+ }
529+
518530 pub fn send_frame<T, F>(
519531 &mut self,
520532 output: &Output,