Compare commits

...
15 Commits
Author SHA1 Message Date
N0VA 0ce2854d72 Port fixes from wl-pick 2026-09-10 09:36:55 +02:00
N0VA e1d8760a43 Update README.adoc 2026-09-10 09:12:31 +02:00
N0VA f78fd7ee41 Update Cargo.toml 2026-09-10 08:55:25 +02:00
N0VA 6559956c3c Update cli.rs 2026-09-10 08:55:06 +02:00
N0VA 77efdf03e9 rename 2026-09-10 08:53:44 +02:00
N0VA 314e474341 colours 2026-09-10 08:50:07 +02:00
N0VA 0afdcf4c83 Update cli.rs 2026-09-10 07:37:21 +02:00
N0VA 21cbb5450e help text 2026-09-10 07:33:57 +02:00
N0VA 3abf610fbf metadata 2026-09-10 07:29:39 +02:00
N0VA 66c2d49ffb cleanup 2026-09-09 23:40:21 +02:00
N0VA 3ad0b59d8c Update Cargo.lock 2026-09-09 21:55:36 +02:00
N0VA 782a21f864 Update Cargo.toml 2026-09-09 19:16:07 +02:00
N0VA 01c1b31636 horizontal 2026-09-09 15:23:53 +02:00
N0VA 53cebf14f3 fix: alt-tab focus history MRU ordering, repeat handling, and quick release 2026-09-09 12:39:10 +02:00
N0VA 50caed0110 modkey 2026-09-09 11:44:23 +02:00
16 changed files with 662 additions and 787 deletions
Generated
+1 -1
View File
@@ -605,7 +605,7 @@ dependencies = [
] ]
[[package]] [[package]]
name = "wl-pick" name = "wl-tab"
version = "0.4.0" version = "0.4.0"
dependencies = [ dependencies = [
"cosmic-text", "cosmic-text",
+5 -6
View File
@@ -1,14 +1,13 @@
[package] [package]
name = "wl-pick" name = "wl-tab"
version = "0.4.0" version = "0.4.0"
edition = "2024" edition = "2024"
description = "A live grid of window and display previews, for picking one" description = "An simple alt-tab window switcher for sway"
license = "MIT" license = "MIT"
repository = "https://github.com/mil-ad/wl-pick" repository = "https://git.krzak.org/N0VA/wl-tab"
readme = "README.md" readme = "README.adoc"
keywords = ["wayland", "sway", "wlroots", "screencast", "switcher"] keywords = ["wayland", "sway", "wlroots", "alt-tab", "switcher"]
categories = ["command-line-utilities", "os::unix-apis"] categories = ["command-line-utilities", "os::unix-apis"]
# The floor is cosmic-text, which needs 1.89; let-chains here need 1.88.
rust-version = "1.89" rust-version = "1.89"
[dependencies] [dependencies]
+2 -1
View File
@@ -1,6 +1,7 @@
MIT License MIT License
Copyright (c) 2026 Milad Alizadeh Copyright (c) 2026 N0\A
Copyright (c) 2026-2026 Milad Alizadeh
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+4
View File
@@ -0,0 +1,4 @@
= wl-tab
A simple alt-tab switcher for sway
Originally forked from https://github.com/mil-ad/wl-pick[wl-pick]
-279
View File
@@ -1,279 +0,0 @@
# wl-pick
A window switcher for wlroots compositors: a grid overlay of **live** window
previews that looks like a rofi theme, and tells you which one you picked.
It replaces a `wlthumbs | rofi` pipeline, and doubles as a screencast source
picker for the desktop portal. The difference is that no thumbnails
exist: each window is captured straight into a `wl_shm` buffer that is handed to
its own `wl_subsurface`, and `wp_viewporter` tells the compositor which rectangle
to scale it into. There is no image encoding, no scaler, and no full-resolution
bitmap in this process — which is also why it appears in about 60 ms and holds
~18 MB of RSS however many windows are open.
```
sway-tree 0.6ms window list + con_ids over sway IPC
toplevels 0.2ms ext-foreign-toplevel-list handles
constraints 1.5ms every capture session's buffer size, in one roundtrip
capture 52.5ms 8 windows, all frames in flight at once
labels 0.0ms shaped on a worker thread while the captures ran
mapped 4.9ms layer surface + subsurfaces on screen
```
The capture phase is the compositor reading full-resolution window pixels out of
the GPU. It is bandwidth-bound (~1.1 GB/s here) and unaffected by how large the
thumbnails are — which also makes it a free window to do other work in. Loading
a font and rasterising its first glyphs costs ~20ms, so labels are shaped on a
worker thread started before the captures and joined after them, and cost
nothing in wall clock.
## Status
Working: a labelled grid of live previews with keyboard navigation. Type-to-filter
is the one thing the rofi version had that this doesn't — see the roadmap.
## Usage
```
wl-pick [--format tsv|json|portal] [--live all|current|none] [--fps N]
[--outputs|--no-outputs] [--labels|--no-labels]
[--order mru|tree] [--alt-tab|--no-alt-tab]
[--font FAMILY] [--font-size PX]
[--timeout SECS] [--verbose]
```
- `--format tsv|json|portal` how to report the pick (default `tsv`)
- `--live all|current|none` which tiles keep updating (default `all`; displays
are always a single snapshot)
- `--fps N` cap on live updates per tile per second (default 12)
- `--outputs` / `--no-outputs` whether whole displays are tiles too (default
off). Both directions exist so either can override the config file
- `--labels` / `--no-labels` whether a label is drawn under each thumbnail
(default on); `--hide-labels` is the old spelling and still works
- `--order mru|tree` window ordering: Most-Recently-Used focus order or tree
layout order (default `mru`)
- `--alt-tab` / `--no-alt-tab` switcher mode: automatically pick on modifier
release (default `auto`, enabled whenever a modifier was held on enter)
- `--font FAMILY` label font family (default: the system monospace font)
- `--font-size PX` label size in logical px
- `--config PATH` config file (default `~/.config/wl-pick/config`)
- `--timeout SECS` exits after a deadline, in case the keyboard grab ever traps
you
- `--verbose` phase timings, the tile list, and capture stats
wl-pick is a chooser: the pick goes to stdout, nothing does if you cancel, and
the exit status is 0 for a pick and 1 for a cancel. It never acts on the choice —
it has no idea what you want to do with it. Focusing on sway looks like this:
```sh
#!/usr/bin/env bash
# ~/.local/bin/winmenu, bound to $mod+Tab
IFS=$'\t' read -r type id toplevel app title < <(wl-pick) || exit 0
case $type in
window) swaymsg "[con_id=$id] focus" ;;
output) swaymsg "focus output $id" ;;
esac
```
Windows only, as a one-liner:
```sh
swaymsg "[con_id=$(wl-pick --no-outputs | cut -f2)] focus"
```
Three formats, because the identifiers different consumers need differ:
| `--format` | output |
|---|---|
| `tsv` (default) | `TYPE⇥ID⇥TOPLEVEL_ID⇥APP⇥TITLE` — `ID` is the sway `con_id`, or the output name for a display; `TOPLEVEL_ID` is the ext-foreign-toplevel-list-v1 identifier that `grim -T` and the portal capture by |
| `json` | the same record with every key always present, for `jq` |
| `portal` | `Monitor: NAME` or `Window: TOPLEVEL_ID` |
`portal` is exactly what xdg-desktop-portal-wlr's `simple` chooser reads, so
wl-pick can be the picker for `getDisplayMedia` and friends — with live previews
of both windows and displays:
```ini
[screencast]
chooser_type=simple
chooser_cmd=wl-pick --format portal
```
**Starting a second wl-pick replaces the first.** The new overlay takes the
keyboard grab, and the one that loses it exits without printing anything — so
hitting the keybinding twice leaves you with one overlay, not a stranded
process. The catch is that sway answers a capture request for a toplevel
another client is already capturing with silence — no frame, no failure — so
the replacement's thumbnails are mostly blank until the first instance has
gone. Every wait before the overlay is interactive is capped at two seconds
for that reason: a tile that never arrives is drawn as a bare label, and the
grid still works.
| key | |
|---|---|
| `→` `←` / `l` `h` / `Tab` `Shift+Tab` | next / previous tile |
| `↓` `↑` / `j` `k` | move a row |
| `Home` `End` / `PgUp` `PgDn` | first / last, or a screen at a time |
| `Enter` / release modifier | pick the selection (release Alt/Super in Alt+Tab mode) |
| `Escape` / `q` | cancel |
| click | pick that tile |
| scroll | next / previous tile |
Hovering deliberately does not move the selection — the keyboard keeps it, and a
click acts on whatever is under the cursor. Clicking the margin, a gap, or an
empty cell of a ragged last row does nothing. Tiles are subsurfaces, so a click
on a thumbnail identifies its tile by surface; only clicks on the chrome around
them need hit-testing.
Navigation reads raw evdev keycodes, so it is layout-independent — but it also
means virtual-keyboard clients such as `wtype` (which invent their own keymap)
cannot drive it. That goes away with xkb support, which filtering needs anyway.
## Live previews
Capture sessions stay open, so a tile can be refreshed. Three things keep that
from being expensive:
- **It is damage-driven.** After a session's first frame the compositor only
produces another once the window content changes, so a request left
outstanding on an idle window costs nothing. Measured over 4s with one
animating window out of ten: `52,52,1,1,1,1,1,1,13,1` frames — the static
windows delivered exactly their first frame and nothing more.
- **Frame callbacks are the clock.** Re-captures are driven by the overlay's own
`wl_surface.frame` callbacks, so they stop when it isn't being presented, and
`--fps` throttles per tile on top of that (12 fps measured as 12.1).
- **Two buffers per window, alternating.** A capture must not write into a buffer
the compositor is reading, so each window gets two and `wl_buffer.release`
decides which is free. Note that release is the entire contract: with `wl_shm`
the compositor copies the pixels out at commit and hands the buffer straight
back, so the slot on screen is usually free too — waiting for it to stop being
displayed instead deadlocks after two frames.
The cost is memory and bandwidth: two full-resolution buffers per window (138 MB
of shm for eight windows and a display here, against 83 MB with `--live none`)
and a readback per refreshed frame. `--live current` refreshes only the selected tile,
which is much cheaper and still reads as alive.
## Config
`~/.config/wl-pick/config`, or `--config PATH`. Flat `key = value` lines with
`#` comments, everything optional, and a flag always beats the file. No TOML
dependency, because there is nothing to nest.
```ini
background = #282828 # the grid's backdrop
foreground = #ebdbb2 # label text
selection = #d79921 # the highlighted tile
selection-text = #282828 # its label
border = #d79921
border-width = 2px
max-width = 90ppt # the box the grid may fill
max-height = 90ppt
max-columns = 4 # thumbnails are that box divided by these
max-rows = 4
font = monospace
font-size = 13.3
labels = yes
outputs = no # include whole displays as tiles (default no)
order = mru # mru (default) or tree
alt-tab = auto # auto (default), yes or no
live = all
fps = 12
format = tsv
timeout = 0 # seconds; 0 means none
```
Sizes take sway's units: `600px` is absolute, `90ppt` a percentage — and the
percentage resolves against **the display the grid actually appears on**, every
time it runs. On a mixed setup one file gives 90% of a 1280-wide laptop panel and
90% of a 3840-wide monitor, rather than a pixel count that suits one and looks
wrong on the other. The overlay maps explicitly on that display, at its scale, so
mixed-DPI renders crisply either way.
All four sizing settings are **caps**:
- `max-width` and `max-height` bound the overlay.
- `max-columns` and `max-rows` bound the grid inside it.
A thumbnail is simply that box divided by those caps, which means **its size
never depends on how many windows are open**: one window gets the same
thumbnail as thirty, in a smaller overlay, because the overlay hugs whatever is
actually there. Rows past `max-rows` scroll, with a scrollbar in the right
margin, `PgUp`/`PgDn`, and the selection always kept in view. Tiles scrolled out
of sight are unmapped, so live capture skips them too.
Turning labels off gives that row back to the thumbnails rather than shrinking
the window, since the box is what you asked for either way.
## Look
The defaults come from the rofi theme this replaces: gruvbox dark, a yellow
selection filling the element padding, `ceil(sqrt(n))` columns capped at 4,
`title · app` centred underneath. Padding, gaps and margins are still fixed, in
`src/theme.rs`.
The label font defaults to the system monospace font — whatever `fc-match
monospace` answers, which is what the rest of the desktop uses. (cosmic-text's
own generic resolves through a built-in preference that is usually not
installed, and then lands on an arbitrary face, so it is asked directly
instead; if fontconfig isn't available, a short list of common distribution
defaults is tried.) `--font` names a family instead, and `--verbose` reports
which family the labels were actually shaped with.
Naming a family scans your own font directories first because they are small;
the full system scan (~37ms) happens only if it isn't found there. An unknown
family falls back to whatever cosmic-text picks rather than failing. Long titles
are ellipsised to the cell.
## Requirements
A wlroots compositor advertising `ext-image-copy-capture-v1`,
`ext-image-capture-source-v1` (with the foreign-toplevel source manager),
`ext-foreign-toplevel-list-v1`, `wlr-layer-shell-unstable-v1` and
`wp_viewporter` — sway 1.11+, and in principle Hyprland, labwc and jay, though
only sway is tested. sway is also the source of truth for the window list, over
its IPC socket, which is the one thing that would need replacing to run
elsewhere (`ext-foreign-toplevel-list-v1` already reports app id and title).
The socket is found from `SWAYSOCK`/`I3SOCK` when those point at something that
exists, and otherwise by looking for the running sway's socket in
`$XDG_RUNTIME_DIR`. Inheriting a stale path is easy — any process that outlives
the sway that started it hands one to every shell it spawns — and a picker on a
keybinding should not be the thing that notices.
Known upstream issue: holding per-toplevel capture sessions open makes windows
blurry on **fractionally scaled** outputs
([sway#9113](https://github.com/swaywm/sway/issues/9113)). Integer scales are
unaffected. It matters more once previews are live.
## Roadmap
- type-to-filter with fzf-quality fuzzy matching (and the xkb keyboard input it
needs, which would also let virtual-keyboard clients drive the overlay)
- dmabuf capture, so the pixels never leave the GPU at all — and live previews
stop costing a readback per frame
## Source layout
```
main.rs orchestration: list, capture, map, report the pick
cli.rs flags, defaults, and the help text that documents them
sway.rs the window list and display names, over sway's IPC socket
target.rs what a tile stands for, and the three output formats
app.rs the Wayland client state every event dispatches into
capture.rs capture sessions, their buffers, and the live clock
overlay.rs the layer surface, the drawing, and the keyboard
theme.rs colours, grid geometry, aspect fitting
text.rs label shaping on a worker thread
shm.rs memfd allocation and the ARGB painter
```
## Building
```
cargo build --release
cargo test # grid geometry and hit-testing, ellipsising, output
# formats, glyph output
```
+23 -30
View File
@@ -46,8 +46,7 @@ use wayland_protocols::wp::viewporter::client::{
}; };
use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_shell_v1::ZwlrLayerShellV1; use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_shell_v1::ZwlrLayerShellV1;
use crate::capture::{Live, Tile}; use crate::capture::Tile;
use crate::config::AltTabMode;
use crate::overlay; use crate::overlay;
use crate::shm; use crate::shm;
use crate::target::Target; use crate::target::Target;
@@ -55,17 +54,14 @@ use crate::text;
use crate::theme::{Layout, Theme}; use crate::theme::{Layout, Theme};
/// What the caller decided before any of this started: the look, and how much /// What the caller decided before any of this started: the look, and how much
/// live capture to do. Passed as one value because `theme`, `live`, `fps` and /// live capture to do. `live` is always on for the alt-tab switcher mode.
/// `scale` all arrive together and two of them are bare integers.
pub struct Settings { pub struct Settings {
pub theme: Theme, pub theme: Theme,
pub live: Live,
pub fps: u32, pub fps: u32,
/// Integer scale of the display the overlay renders on, and its name, so /// Integer scale of the display the overlay renders on, and its name, so
/// the overlay maps there rather than wherever the compositor would put it. /// the overlay maps there rather than wherever the compositor would put it.
pub scale: i32, pub scale: i32,
pub output: String, pub output: String,
pub alt_tab: AltTabMode,
} }
pub struct App { pub struct App {
@@ -87,7 +83,6 @@ pub struct App {
pub(crate) theme: Theme, pub(crate) theme: Theme,
pub(crate) layout: Layout, pub(crate) layout: Layout,
pub(crate) live: Live,
pub(crate) fps: u32, pub(crate) fps: u32,
pub(crate) scale: i32, pub(crate) scale: i32,
pub(crate) sel: usize, pub(crate) sel: usize,
@@ -123,15 +118,20 @@ pub struct App {
pub(crate) seat: Option<WlSeat>, pub(crate) seat: Option<WlSeat>,
pub(crate) inhibit_mgr: Option<ZwpKeyboardShortcutsInhibitManagerV1>, pub(crate) inhibit_mgr: Option<ZwpKeyboardShortcutsInhibitManagerV1>,
pub(crate) inhibitor: Option<ZwpKeyboardShortcutsInhibitorV1>, pub(crate) inhibitor: Option<ZwpKeyboardShortcutsInhibitorV1>,
pub(crate) alt_tab: AltTabMode,
pub(crate) is_alt_tab: bool,
pub(crate) latched_modifiers: std::collections::BTreeSet<u32>, pub(crate) latched_modifiers: std::collections::BTreeSet<u32>,
pub(crate) initial_stepped: bool,
/// The navigation key currently held down, and when the next repeat fires.
pub(crate) repeat_key: Option<u32>,
pub(crate) repeat_next: Option<std::time::Instant>,
/// Milliseconds before the first repeat fires. From wl_keyboard::RepeatInfo.
pub(crate) repeat_delay_ms: u32,
/// Milliseconds between subsequent repeats. From wl_keyboard::RepeatInfo.
pub(crate) repeat_rate_ms: u32,
} }
/// Counters worth reporting with --verbose. Live capture is easy to get subtly /// Counters worth reporting with --verbose. Live capture is easy to get subtly
/// wrong — a starved buffer pool or a clock that never ticks both look like /// wrong - a starved buffer pool or a clock that never ticks both look like
/// "nothing updates" — so the numbers that distinguish those stay available. /// "nothing updates" - so the numbers that distinguish those stay available.
#[derive(Default)] #[derive(Default)]
pub struct Stats { pub struct Stats {
/// Frame callbacks received, i.e. how often the live clock fired. /// Frame callbacks received, i.e. how often the live clock fired.
@@ -161,7 +161,7 @@ impl Ending {
Ending::Picked => "picked", Ending::Picked => "picked",
Ending::Cancelled => "cancelled", Ending::Cancelled => "cancelled",
Ending::Closed => "the compositor closed the overlay", Ending::Closed => "the compositor closed the overlay",
Ending::Unfocused => "lost the keyboard to another surface", Ending::Unfocused => "another surface holds the keyboard",
} }
} }
} }
@@ -176,19 +176,12 @@ impl App {
) -> Result<Self, Box<dyn Error>> { ) -> Result<Self, Box<dyn Error>> {
let Settings { let Settings {
theme, theme,
live,
fps, fps,
scale, scale,
output, output,
alt_tab, ..
} = settings; } = settings;
let focused_idx = targets.iter().position(|t| t.focused).unwrap_or(0); let sel = if targets.len() > 1 { 1 } else { 0 };
let sel = if alt_tab == AltTabMode::Yes && targets.len() > 1 {
(focused_idx + 1) % targets.len()
} else {
focused_idx
};
let is_alt_tab = alt_tab == AltTabMode::Yes;
// Bind everything up front so a compositor missing a protocol fails // Bind everything up front so a compositor missing a protocol fails
// here, with a name, rather than halfway through a capture. // here, with a name, rather than halfway through a capture.
let mut app = Self { let mut app = Self {
@@ -206,7 +199,6 @@ impl App {
tiles: targets.into_iter().map(Tile::new).collect(), tiles: targets.into_iter().map(Tile::new).collect(),
theme, theme,
layout, layout,
live,
fps, fps,
scale, scale,
sel, sel,
@@ -229,10 +221,11 @@ impl App {
seat: None, seat: None,
inhibit_mgr: None, inhibit_mgr: None,
inhibitor: None, inhibitor: None,
alt_tab,
is_alt_tab,
latched_modifiers: std::collections::BTreeSet::new(), latched_modifiers: std::collections::BTreeSet::new(),
initial_stepped: alt_tab == AltTabMode::Yes, repeat_key: None,
repeat_next: None,
repeat_delay_ms: 600,
repeat_rate_ms: 25,
}; };
let _: ExtForeignToplevelListV1 = globals.bind(qh, 1..=1, ())?; let _: ExtForeignToplevelListV1 = globals.bind(qh, 1..=1, ())?;
// One wl_output per display, bound at v4 so it tells us its name. // One wl_output per display, bound at v4 so it tells us its name.
@@ -267,7 +260,7 @@ impl App {
eprintln!(" [{i}] {}{mark}", t.target.tsv()); eprintln!(" [{i}] {}{mark}", t.target.tsv());
} }
eprintln!( eprintln!(
"wl-pick: {} tile(s), {} captured; grid {}x{}, surface {}x{} logical \ "wl-tab: {} tile(s), {} captured; grid {}x{}, surface {}x{} logical \
at scale {}, {} MB of capture buffers, labels in {:?}", at scale {}, {} MB of capture buffers, labels in {:?}",
self.tiles.len(), self.tiles.len(),
self.tiles.iter().filter(|t| t.ready).count(), self.tiles.iter().filter(|t| t.ready).count(),
@@ -281,7 +274,7 @@ impl App {
); );
if self.layout.scrollable() { if self.layout.scrollable() {
eprintln!( eprintln!(
"wl-pick: {} of {} rows fit; the rest scroll", "wl-tab: {} of {} rows fit; the rest scroll",
self.layout.visible_rows, self.layout.rows self.layout.visible_rows, self.layout.rows
); );
} }
@@ -292,7 +285,7 @@ impl App {
let frames: u32 = self.tiles.iter().map(|t| t.frames).sum(); let frames: u32 = self.tiles.iter().map(|t| t.frames).sum();
let secs = open_for.as_secs_f64(); let secs = open_for.as_secs_f64();
eprintln!( eprintln!(
"wl-pick: {}, {frames} frame(s) over {secs:.1}s = {:.1}/s, {} tick(s), \ "wl-tab: {}, {frames} frame(s) over {secs:.1}s = {:.1}/s, {} tick(s), \
{} starved; per tile: {}", {} starved; per tile: {}",
self.ending.as_str(), self.ending.as_str(),
frames as f64 / secs, frames as f64 / secs,
@@ -321,7 +314,7 @@ impl App {
.map(|t| t.target.title.as_str()) .map(|t| t.target.title.as_str())
.collect(); .collect();
eprintln!( eprintln!(
"wl-pick: no frame for {} of {} tiles ({}); \ "wl-tab: no frame for {} of {} tiles ({}); \
another capture client may hold these sources", another capture client may hold these sources",
stuck.len(), stuck.len(),
self.tiles.len(), self.tiles.len(),
+12 -42
View File
@@ -7,12 +7,14 @@
//! //!
//! The pixels are never mapped into this process. A capture buffer goes straight //! The pixels are never mapped into this process. A capture buffer goes straight
//! to a subsurface for display, so the compositor writes those pages and samples //! to a subsurface for display, so the compositor writes those pages and samples
//! them again itself. //! them again itself. Live previews are always on.
use std::error::Error; use std::error::Error;
use std::os::fd::AsFd; use std::os::fd::AsFd;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use crate::Target;
use wayland_client::protocol::{ use wayland_client::protocol::{
wl_buffer::{self, WlBuffer}, wl_buffer::{self, WlBuffer},
wl_callback, wl_output, wl_shm, wl_callback, wl_output, wl_shm,
@@ -30,32 +32,10 @@ use wayland_protocols::wp::viewporter::client::wp_viewport::WpViewport;
use crate::app::App; use crate::app::App;
use crate::shm; use crate::shm;
use crate::target::{Kind, Target}; use crate::target::Kind;
/// Which tiles keep updating after the first frame. /// One capture buffer. `busy` means the compositor still holds it - either it is
#[derive(Clone, Copy, Debug, PartialEq, Eq)] /// on screen or a capture is writing into it - so we must not scribble over it.
pub enum Live {
/// Every tile.
All,
/// Only the selected tile: much cheaper, and still reads as alive.
Current,
/// Nothing: one snapshot each, a picker rather than an expose.
None,
}
impl Live {
pub fn parse(s: &str) -> Result<Self, String> {
match s.trim() {
"all" => Ok(Live::All),
"current" => Ok(Live::Current),
"none" => Ok(Live::None),
other => Err(format!("{other:?} is not all, current or none")),
}
}
}
/// One capture buffer. `busy` means the compositor still holds it — either it is
/// on screen or a capture is writing into it — so we must not scribble over it.
pub struct Slot { pub struct Slot {
pub(crate) buffer: WlBuffer, pub(crate) buffer: WlBuffer,
pub(crate) busy: bool, pub(crate) busy: bool,
@@ -202,9 +182,8 @@ impl App {
tile.settled = true; tile.settled = true;
continue; continue;
} }
// Only a tile that will be re-captured needs a second buffer, and a // Always 2 buffers for live preview; display gets full-screen buffer.
// display's is the size of the whole screen. let slots = if tile.target.kind == Kind::Output {
let slots = if self.live == Live::None || tile.target.kind == Kind::Output {
1 1
} else { } else {
2 2
@@ -222,7 +201,7 @@ impl App {
self.stats.pool_bytes = total; self.stats.pool_bytes = total;
// Note: no mmap. The compositor writes these pages and samples them // Note: no mmap. The compositor writes these pages and samples them
// again for display; mapping them here would only cost us the faults. // again for display; mapping them here would only cost us the faults.
let file = shm::memfd("wl-pick-capture", total)?; let file = shm::memfd("wl-tab-capture", total)?;
let pool = self.shm.create_pool(file.as_fd(), total as i32, qh, ()); let pool = self.shm.create_pool(file.as_fd(), total as i32, qh, ());
for (i, slot_offsets) in offsets.iter().enumerate() { for (i, slot_offsets) in offsets.iter().enumerate() {
let (w, h, format) = { let (w, h, format) = {
@@ -301,9 +280,6 @@ impl App {
/// Ask for the next frame callback. A commit is needed for the compositor to /// Ask for the next frame callback. A commit is needed for the compositor to
/// schedule one, and an empty commit is enough. /// schedule one, and an empty commit is enough.
pub fn arm_frame_callback(&mut self, qh: &QueueHandle<Self>) { pub fn arm_frame_callback(&mut self, qh: &QueueHandle<Self>) {
if self.live == Live::None {
return;
}
if let Some(surface) = self.surface.clone() { if let Some(surface) = self.surface.clone() {
surface.frame(qh, ()); surface.frame(qh, ());
surface.commit(); surface.commit();
@@ -314,22 +290,16 @@ impl App {
/// the overlay is not being presented. /// the overlay is not being presented.
pub fn tick(&mut self, qh: &QueueHandle<Self>) { pub fn tick(&mut self, qh: &QueueHandle<Self>) {
self.stats.ticks += 1; self.stats.ticks += 1;
if self.live == Live::None {
return;
}
let interval = Duration::from_secs_f64(1.0 / self.fps.max(1) as f64); let interval = Duration::from_secs_f64(1.0 / self.fps.max(1) as f64);
let now = Instant::now(); let now = Instant::now();
for i in 0..self.tiles.len() { for i in 0..self.tiles.len() {
if self.live == Live::Current && i != self.sel {
continue;
}
// A display tile shows this overlay, which shows the display tile: // A display tile shows this overlay, which shows the display tile:
// refreshing it never settles and costs a whole screen per frame. // refreshing it never settles and costs a whole screen per frame.
if self.tiles[i].target.kind == Kind::Output { if self.tiles[i].target.kind == Kind::Output {
continue; continue;
} }
// Nor is there any point refreshing a tile that is scrolled out of // Nor is there any point refreshing a tile that is scrolled out of
// sight — that is a readback for pixels nobody sees. // sight - that is a readback for pixels nobody sees.
if self.layout.tile(i as i32, self.scroll).is_none() { if self.layout.tile(i as i32, self.scroll).is_none() {
continue; continue;
} }
@@ -402,7 +372,7 @@ impl Dispatch<ExtImageCopyCaptureFrameV1, usize> for App {
// frame yet leaves the tile without a thumbnail. // frame yet leaves the tile without a thumbnail.
if tile.frames == 0 { if tile.frames == 0 {
eprintln!( eprintln!(
"wl-pick: capture failed for {:?} ({reason:?})", "wl-tab: capture failed for {:?} ({reason:?})",
tile.target.title tile.target.title
); );
} }
@@ -424,7 +394,7 @@ impl Dispatch<ExtImageCopyCaptureFrameV1, usize> for App {
/// Release is the whole contract: with wl_shm the compositor copies the pixels /// Release is the whole contract: with wl_shm the compositor copies the pixels
/// out at commit and hands the buffer straight back, so the slot currently on /// out at commit and hands the buffer straight back, so the slot currently on
/// screen is usually free too. (Waiting for it to stop being the displayed slot /// screen is usually free too. (Waiting for it to stop being the displayed slot
/// instead would deadlock — that release never comes twice.) /// instead would deadlock - that release never comes twice.)
impl Dispatch<WlBuffer, (usize, usize)> for App { impl Dispatch<WlBuffer, (usize, usize)> for App {
fn event( fn event(
app: &mut Self, app: &mut Self,
+28 -55
View File
@@ -4,40 +4,30 @@ use std::path::PathBuf;
use std::time::Duration; use std::time::Duration;
use crate::app::Settings; use crate::app::Settings;
use crate::capture::Live; use crate::config::{Config, Length};
use crate::config::{AltTabMode, Config, Length};
use crate::sway::{Display, Order}; use crate::sway::{Display, Order};
use crate::target::Format; use crate::target::Format;
use crate::theme::Theme; use crate::theme::Theme;
const HELP: &str = "\ const HELP: &str = "\
wl-pick — a live grid of window and display previews, for picking one wl-tab - a simple alt-tab switcher for sway
usage: wl-pick [options] usage: wl-tab [options]
--config PATH config file [~/.config/wl-pick/config] --config PATH config file [~/.config/wl-tab/config]
--format tsv|json|portal how to report the pick [tsv] --format tsv|json|portal how to report the pick [tsv]
--live all|current|none which tiles keep updating live [all]
(displays are always a single snapshot)
--fps N cap on live updates per tile per second [12] --fps N cap on live updates per tile per second [12]
--outputs, --no-outputs include whole displays as tiles [no]
--labels, --no-labels a label under each thumbnail [yes] --labels, --no-labels a label under each thumbnail [yes]
--order mru|tree window ordering: mru or layout tree [mru] --order mru|tree window ordering: mru or layout tree [mru]
--alt-tab, --no-alt-tab alt-tab switcher mode (commit on release) [auto] --focus, --no-focus focus the picked target directly [no]
--focus, --no-focus focus the picked target in sway directly [no] --font NAME label font family, optionally with a style, as
--font FAMILY label font family [the system monospace font] in 'FiraCode Mono' [system monospace]
--font-size PX label size in logical px [13.3] --font-size PX label size in logical px [13.3]
--timeout SECS exit anyway after SECS, in case the keyboard --timeout SECS exit anyway after SECS, in case the keyboard
grab ever traps you [off] grab ever traps you [off]
-v, --verbose phase timings, tile list and capture stats -v, --verbose phase timings, tile list and capture stats
-h, --help this -h, --help this
keys: arrows, hjkl or Tab/Shift+Tab move; PgUp/PgDn and Home/End jump;
Enter picks; Escape or q cancels; in Alt+Tab mode, releasing
the modifier (Alt/Super) picks the selection.
mouse: click a tile to pick it, scroll to move. Hovering does not move the
selection, and a click outside a tile does nothing.
The pick goes to stdout and nothing does if you cancel, so exit status is The pick goes to stdout and nothing does if you cancel, so exit status is
0 for a pick and 1 for a cancel. Acting on it is the caller's job. 0 for a pick and 1 for a cancel. Acting on it is the caller's job.
@@ -48,20 +38,17 @@ config:
percentage of the display the grid appears on, so one file suits monitors percentage of the display the grid appears on, so one file suits monitors
of different sizes. of different sizes.
background = #282828 # the grid's backdrop background = #222222 # the grid's backdrop
foreground = #ebdbb2 # label text foreground = #888888 # label text
selection = #d79921 # the highlighted tile selection = #285577 # the highlighted tile
selection-text = #282828 # its label selection-text = #ffffff # its label
border = #d79921 border = #4c7899
border-width = 2px border-width = 2px
max-width = 90ppt # the box the grid may fill max-width = 90ppt # the box the grid may fill
max-height = 90ppt max-height = 90ppt
max-columns = 4 # thumbnails are the box divided by these,
max-rows = 4 # so their size never depends on how many
# windows are open; further rows scroll
font = monospace # also --font font = monospace # a family, optionally with a style
font-size = 13.3 font-size = 13.3
labels = yes labels = yes
outputs = no # include whole displays as tiles outputs = no # include whole displays as tiles
@@ -92,18 +79,7 @@ formats:
[screencast] [screencast]
chooser_type=simple chooser_type=simple
chooser_cmd=wl-pick --format portal chooser_cmd=wl-tab --format portal";
focusing on sway:
wl-pick --focus or:
IFS=$'\\t' read -r type id toplevel app title < <(wl-pick) &&
case $type in
window) swaymsg \"[con_id=$id] focus\" ;;
output) swaymsg \"focus output $id\" ;;
esac
";
/// What the command line asked for. Every setting is optional so the config file /// What the command line asked for. Every setting is optional so the config file
/// can fill the gaps: a flag beats the file, the file beats the default. /// can fill the gaps: a flag beats the file, the file beats the default.
@@ -116,11 +92,9 @@ pub struct Args {
pub(crate) labels: Option<bool>, pub(crate) labels: Option<bool>,
pub(crate) font: Option<String>, pub(crate) font: Option<String>,
pub(crate) font_size: Option<f32>, pub(crate) font_size: Option<f32>,
pub(crate) live: Option<Live>,
pub(crate) fps: Option<u32>, pub(crate) fps: Option<u32>,
pub(crate) timeout: Option<Duration>, pub(crate) timeout: Option<Duration>,
pub(crate) order: Option<Order>, pub(crate) order: Option<Order>,
pub(crate) alt_tab: Option<AltTabMode>,
pub(crate) focus: Option<bool>, pub(crate) focus: Option<bool>,
} }
@@ -144,7 +118,7 @@ pub fn arm_timeout(timeout: Option<Duration>) {
if let Some(d) = timeout { if let Some(d) = timeout {
std::thread::spawn(move || { std::thread::spawn(move || {
std::thread::sleep(d); std::thread::sleep(d);
eprintln!("wl-pick: timeout"); eprintln!("wl-tab: timeout");
std::process::exit(2); std::process::exit(2);
}); });
} }
@@ -204,11 +178,9 @@ impl Args {
display: (display.width, display.height), display: (display.width, display.height),
settings: Settings { settings: Settings {
theme, theme,
live: self.live.or(cfg.live).unwrap_or(Live::All),
fps: self.fps.or(cfg.fps).unwrap_or(12), fps: self.fps.or(cfg.fps).unwrap_or(12),
scale: display.scale, scale: display.scale,
output: display.name.clone(), output: display.name.clone(),
alt_tab: self.alt_tab.or(cfg.alt_tab).unwrap_or(AltTabMode::Auto),
}, },
} }
} }
@@ -233,8 +205,6 @@ fn parse(it: impl Iterator<Item = String>) -> Result<Args, String> {
let v = it.next().ok_or("--order needs mru|tree")?; let v = it.next().ok_or("--order needs mru|tree")?;
args.order = Some(Order::parse(&v)?); args.order = Some(Order::parse(&v)?);
} }
"--alt-tab" => args.alt_tab = Some(AltTabMode::Yes),
"--no-alt-tab" => args.alt_tab = Some(AltTabMode::No),
"--focus" => args.focus = Some(true), "--focus" => args.focus = Some(true),
"--no-focus" => args.focus = Some(false), "--no-focus" => args.focus = Some(false),
"--config" => { "--config" => {
@@ -245,15 +215,11 @@ fn parse(it: impl Iterator<Item = String>) -> Result<Args, String> {
// --hide-labels was the only spelling before --labels existed, and // --hide-labels was the only spelling before --labels existed, and
// is still accepted for whatever it is wired into. // is still accepted for whatever it is wired into.
"--no-labels" | "--hide-labels" => args.labels = Some(false), "--no-labels" | "--hide-labels" => args.labels = Some(false),
"--live" => {
let v = it.next().ok_or("--live needs all|current|none")?;
args.live = Some(Live::parse(&v)?);
}
"--fps" => { "--fps" => {
let v = it.next().ok_or("--fps needs a number")?; let v = it.next().ok_or("--fps needs a number")?;
args.fps = Some(v.parse().map_err(|_| format!("bad --fps: {v}"))?); args.fps = Some(v.parse().map_err(|_| format!("bad --fps: {v}"))?);
} }
"--font" => args.font = Some(it.next().ok_or("--font needs a family name")?), "--font" => args.font = Some(it.next().ok_or("--font needs a font name")?),
"--font-size" => { "--font-size" => {
let v = it.next().ok_or("--font-size needs px")?; let v = it.next().ok_or("--font-size needs px")?;
args.font_size = Some(v.parse().map_err(|_| format!("bad --font-size: {v}"))?); args.font_size = Some(v.parse().map_err(|_| format!("bad --font-size: {v}"))?);
@@ -307,8 +273,6 @@ mod tests {
assert_eq!(args(&["--labels"]).labels, Some(true)); assert_eq!(args(&["--labels"]).labels, Some(true));
assert_eq!(args(&["--no-labels"]).labels, Some(false)); assert_eq!(args(&["--no-labels"]).labels, Some(false));
assert_eq!(args(&["--hide-labels"]).labels, Some(false), "old spelling"); assert_eq!(args(&["--hide-labels"]).labels, Some(false), "old spelling");
assert_eq!(args(&["--alt-tab"]).alt_tab, Some(AltTabMode::Yes));
assert_eq!(args(&["--no-alt-tab"]).alt_tab, Some(AltTabMode::No));
// Unset is what lets the file have its say. // Unset is what lets the file have its say.
assert_eq!(args(&[]).outputs, None); assert_eq!(args(&[]).outputs, None);
assert_eq!(args(&[]).labels, None); assert_eq!(args(&[]).labels, None);
@@ -330,10 +294,19 @@ mod tests {
// With no flag the file decides, and with no file either, the default (outputs: false). // With no flag the file decides, and with no file either, the default (outputs: false).
assert!(!args(&[]).resolve(&file(false), &display()).outputs); assert!(!args(&[]).resolve(&file(false), &display()).outputs);
assert!(!args(&[]).resolve(&Config::default(), &display()).outputs); assert!(!args(&[]).resolve(&Config::default(), &display()).outputs);
assert!(args(&["--outputs"]).resolve(&Config::default(), &display()).outputs); assert!(
assert_eq!(args(&[]).resolve(&Config::default(), &display()).order, Order::Mru); args(&["--outputs"])
.resolve(&Config::default(), &display())
.outputs
);
assert_eq!( assert_eq!(
args(&["--order", "tree"]).resolve(&Config::default(), &display()).order, args(&[]).resolve(&Config::default(), &display()).order,
Order::Mru
);
assert_eq!(
args(&["--order", "tree"])
.resolve(&Config::default(), &display())
.order,
Order::Tree Order::Tree
); );
} }
+7 -46
View File
@@ -1,43 +1,23 @@
//! The config file: `~/.config/wl-pick/config`. //! The config file: `~/.config/wl-tab/config`.
//! //!
//! Flat `key = value` lines with `#` comments — no sections, no nesting, so a //! Flat `key = value` lines with `#` comments - no sections, no nesting, so a
//! TOML parser would be a dependency bought for nothing. Every setting is //! TOML parser would be a dependency bought for nothing. Every setting is
//! optional; anything absent keeps its default, and a command-line flag beats //! optional; anything absent keeps its default, and a command-line flag beats
//! the file. //! the file.
//! //!
//! Sizes take sway's syntax: `600px` is absolute, `70ppt` is 70 percent of the //! Sizes take sway's syntax: `600px` is absolute, `70ppt` is 70 percent of the
//! display the grid appears on. That matters on a multi-monitor setup, where a //! display the grid appears on. That matters on a multi-monitor setup, where a
//! pixel size that suits one screen is wrong on the next — percentages are //! pixel size that suits one screen is wrong on the next - percentages are
//! resolved against whichever display the overlay actually maps on, each time //! resolved against whichever display the overlay actually maps on, each time
//! it runs. //! it runs.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::Duration; use std::time::Duration;
use crate::capture::Live;
use crate::sway::Order; use crate::sway::Order;
use crate::target::Format; use crate::target::Format;
use crate::theme::Argb; use crate::theme::Argb;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum AltTabMode {
#[default]
Auto,
Yes,
No,
}
impl AltTabMode {
pub fn parse(s: &str) -> Result<Self, String> {
match s.trim() {
"auto" => Ok(AltTabMode::Auto),
"yes" | "true" | "on" | "1" => Ok(AltTabMode::Yes),
"no" | "false" | "off" | "0" => Ok(AltTabMode::No),
other => Err(format!("{other:?} is not auto, yes or no")),
}
}
}
/// A size, either absolute or relative to the display it will be shown on. /// A size, either absolute or relative to the display it will be shown on.
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub enum Length { pub enum Length {
@@ -114,12 +94,10 @@ pub struct Config {
pub font_size: Option<f32>, pub font_size: Option<f32>,
pub labels: Option<bool>, pub labels: Option<bool>,
pub outputs: Option<bool>, pub outputs: Option<bool>,
pub live: Option<Live>,
pub fps: Option<u32>, pub fps: Option<u32>,
pub format: Option<Format>, pub format: Option<Format>,
pub timeout: Option<Duration>, pub timeout: Option<Duration>,
pub order: Option<Order>, pub order: Option<Order>,
pub alt_tab: Option<AltTabMode>,
pub focus: Option<bool>, pub focus: Option<bool>,
} }
@@ -171,7 +149,7 @@ impl Config {
"font-size" => self.font_size = Some(number(value)?), "font-size" => self.font_size = Some(number(value)?),
"labels" => self.labels = Some(boolean(value)?), "labels" => self.labels = Some(boolean(value)?),
"outputs" => self.outputs = Some(boolean(value)?), "outputs" => self.outputs = Some(boolean(value)?),
"live" => self.live = Some(Live::parse(value)?),
"fps" => self.fps = Some(number(value)?), "fps" => self.fps = Some(number(value)?),
"format" => self.format = Some(Format::parse(value)?), "format" => self.format = Some(Format::parse(value)?),
// Zero is how you say "no timeout"; an immediate deadline would // Zero is how you say "no timeout"; an immediate deadline would
@@ -181,7 +159,6 @@ impl Config {
self.timeout = (secs > 0.0).then(|| Duration::from_secs_f64(secs)); self.timeout = (secs > 0.0).then(|| Duration::from_secs_f64(secs));
} }
"order" => self.order = Some(Order::parse(value)?), "order" => self.order = Some(Order::parse(value)?),
"alt-tab" => self.alt_tab = Some(AltTabMode::parse(value)?),
"focus" => self.focus = Some(boolean(value)?), "focus" => self.focus = Some(boolean(value)?),
other => return Err(format!("unknown setting {other:?}")), other => return Err(format!("unknown setting {other:?}")),
} }
@@ -209,13 +186,13 @@ fn number<T: std::str::FromStr>(s: &str) -> Result<T, String> {
.map_err(|_| format!("{s:?} is not a number")) .map_err(|_| format!("{s:?} is not a number"))
} }
/// `$XDG_CONFIG_HOME/wl-pick/config`, or `~/.config/wl-pick/config`. /// `$XDG_CONFIG_HOME/wl-tab/config`, or `~/.config/wl-tab/config`.
fn default_path() -> PathBuf { fn default_path() -> PathBuf {
let dir = std::env::var_os("XDG_CONFIG_HOME") let dir = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from) .map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))) .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
.unwrap_or_default(); .unwrap_or_default();
dir.join("wl-pick").join("config") dir.join("wl-tab").join("config")
} }
#[cfg(test)] #[cfg(test)]
@@ -264,12 +241,10 @@ max-width = 70ppt
max-columns = 4 max-columns = 4
max-rows = 3 max-rows = 3
live = current
fps = 30 fps = 30
labels = no labels = no
timeout = 0 timeout = 0
order = mru order = mru
alt-tab = yes
", ",
) )
.expect("should parse"); .expect("should parse");
@@ -283,8 +258,6 @@ alt-tab = yes
assert_eq!(cfg.labels, Some(false)); assert_eq!(cfg.labels, Some(false));
assert_eq!(cfg.timeout, None, "zero means no timeout"); assert_eq!(cfg.timeout, None, "zero means no timeout");
assert_eq!(cfg.order, Some(Order::Mru)); assert_eq!(cfg.order, Some(Order::Mru));
assert_eq!(cfg.alt_tab, Some(AltTabMode::Yes));
assert!(cfg.live.is_some());
// Untouched settings stay unset, so defaults survive. // Untouched settings stay unset, so defaults survive.
assert_eq!(cfg.foreground, None); assert_eq!(cfg.foreground, None);
assert_eq!(cfg.max_height, None); assert_eq!(cfg.max_height, None);
@@ -315,7 +288,7 @@ alt-tab = yes
#[test] #[test]
fn a_missing_file_is_not_an_error() { fn a_missing_file_is_not_an_error() {
let missing = Path::new("/nonexistent/wl-pick/config"); let missing = Path::new("/nonexistent/wl-tab/config");
assert!( assert!(
Config::load(Some(missing)).is_err(), Config::load(Some(missing)).is_err(),
"named file must exist" "named file must exist"
@@ -324,16 +297,4 @@ alt-tab = yes
unsafe { std::env::set_var("XDG_CONFIG_HOME", "/nonexistent") }; unsafe { std::env::set_var("XDG_CONFIG_HOME", "/nonexistent") };
assert!(Config::load(None).is_ok()); assert!(Config::load(None).is_ok());
} }
#[test]
fn alt_tab_mode_parses() {
assert_eq!(AltTabMode::parse("auto"), Ok(AltTabMode::Auto));
assert_eq!(AltTabMode::parse("yes"), Ok(AltTabMode::Yes));
assert_eq!(AltTabMode::parse("true"), Ok(AltTabMode::Yes));
assert_eq!(AltTabMode::parse("1"), Ok(AltTabMode::Yes));
assert_eq!(AltTabMode::parse("no"), Ok(AltTabMode::No));
assert_eq!(AltTabMode::parse("false"), Ok(AltTabMode::No));
assert_eq!(AltTabMode::parse("0"), Ok(AltTabMode::No));
assert!(AltTabMode::parse("maybe").is_err());
}
} }
+54 -12
View File
@@ -1,4 +1,4 @@
//! wl-pick shows a live grid of every window and display as a layer-shell //! wl-tab shows a live grid of every window and display as a layer-shell
//! overlay and reports which one you picked. That is all it does: acting on the //! overlay and reports which one you picked. That is all it does: acting on the
//! choice belongs to whatever called it. //! choice belongs to whatever called it.
//! //!
@@ -11,13 +11,13 @@
//! is no thumbnail encoding, no scaler, and no full-resolution image in our //! is no thumbnail encoding, no scaler, and no full-resolution image in our
//! address space. //! address space.
//! //!
//! - `cli` — flags and help //! - `cli` - flags and help
//! - `sway` — the window list, over sway's IPC socket //! - `sway` - the window list, over sway's IPC socket
//! - `target` — what a tile stands for, and how a pick is reported //! - `target` - what a tile stands for, and how a pick is reported
//! - `app` — the Wayland client state everything dispatches into //! - `app` - the Wayland client state everything dispatches into
//! - `capture` — capture sessions and their buffers //! - `capture` - capture sessions and their buffers
//! - `overlay` — the layer surface, the drawing, the keyboard //! - `overlay` - the layer surface, the drawing, the keyboard
//! - `theme`, `text`, `shm` — look, labels, and shared memory //! - `theme`, `text`, `shm` - look, labels, and shared memory
// `slice::as_chunks` and friends, which clippy suggests in place of // `slice::as_chunks` and friends, which clippy suggests in place of
// `chunks_exact`, are newer than the toolchain this crate says it supports. // `chunks_exact`, are newer than the toolchain this crate says it supports.
@@ -61,7 +61,7 @@ fn main() -> ExitCode {
match run() { match run() {
Ok(code) => code, Ok(code) => code,
Err(e) => { Err(e) => {
eprintln!("wl-pick: {e}"); eprintln!("wl-tab: {e}");
ExitCode::FAILURE ExitCode::FAILURE
} }
} }
@@ -169,12 +169,53 @@ fn run() -> Result<ExitCode, Box<dyn Error>> {
phases.mark("mapped"); phases.mark("mapped");
// The keyboard grab is what makes the overlay usable, so losing it for // The keyboard grab is what makes the overlay usable, so losing it for
// good ends the run: that is how a second wl-pick, started from the same // good ends the run: that is how a second wl-tab, started from the same
// keybinding, replaces the first instead of leaving it stranded on screen. // keybinding, replaces the first instead of leaving it stranded on screen.
// A leave only counts once it has failed to come back, because sway also // A leave only counts once it has failed to come back, because sway also
// cycles focus off and on in a single batch as the pointer crosses us. // cycles focus off and on in a single batch as the pointer crosses us.
loop { loop {
if app.finished() {
break;
}
// When a navigation key is held, we need to fire repeat events on a
// timer rather than blocking indefinitely. Use a timed poll so we
// wake up when the next repeat is due without burning the CPU.
if let Some(next) = app.repeat_next {
let now = Instant::now();
if now >= next {
let qh = queue.handle();
app.fire_repeat(&qh);
conn.flush()?;
} else {
// Poll for events with a timeout set to when the next repeat fires.
let left = next - now;
queue.dispatch_pending(&mut app)?;
if !app.finished() {
conn.flush()?;
if let Some(guard) = conn.prepare_read() {
let fd = guard.connection_fd();
let mut fds = [PollFd::new(&fd, PollFlags::IN)];
let timeout = Timespec {
tv_sec: left.as_secs() as _,
tv_nsec: left.subsec_nanos() as _,
};
match rustix::event::poll(&mut fds, Some(&timeout)) {
Ok(0) => {
// Timeout expired: do NOT call guard.read() because
// nothing is pending on the socket. Dropping guard cancels read.
}
Ok(_) | Err(rustix::io::Errno::INTR) => {
let _ = guard.read();
}
Err(e) => return Err(Box::new(e)),
}
}
}
continue;
}
} else {
queue.blocking_dispatch(&mut app)?; queue.blocking_dispatch(&mut app)?;
}
if !app.finished() if !app.finished()
&& !app.focused && !app.focused
&& !pump_for( && !pump_for(
@@ -204,6 +245,7 @@ fn run() -> Result<ExitCode, Box<dyn Error>> {
target::Kind::Window => { target::Kind::Window => {
if let Some(con_id) = target.con_id { if let Some(con_id) = target.con_id {
let _ = sway.run_command(format!("[con_id={con_id}] focus")); let _ = sway.run_command(format!("[con_id={con_id}] focus"));
sway::record_focus(con_id);
} }
} }
target::Kind::Output => { target::Kind::Output => {
@@ -217,7 +259,7 @@ fn run() -> Result<ExitCode, Box<dyn Error>> {
// Only the portal format can fail to name something: it identifies a // Only the portal format can fail to name something: it identifies a
// window by its foreign-toplevel identifier, and this one has none. // window by its foreign-toplevel identifier, and this one has none.
None => { None => {
eprintln!("wl-pick: {:?} has no toplevel identifier", target.title); eprintln!("wl-tab: {:?} has no toplevel identifier", target.title);
return Ok(ExitCode::FAILURE); return Ok(ExitCode::FAILURE);
} }
} }
@@ -230,7 +272,7 @@ fn run() -> Result<ExitCode, Box<dyn Error>> {
/// Every wait before the overlay is interactive is bounded, because a /// Every wait before the overlay is interactive is bounded, because a
/// compositor is entitled to simply never answer. sway does exactly that for a /// compositor is entitled to simply never answer. sway does exactly that for a
/// capture request on a toplevel another client is already capturing: no frame, /// capture request on a toplevel another client is already capturing: no frame,
/// no `failed`, no `stopped`, just silence — and an unbounded wait on that is a /// no `failed`, no `stopped`, just silence - and an unbounded wait on that is a
/// picker with no window that has to be killed from another terminal. /// picker with no window that has to be killed from another terminal.
fn pump_for( fn pump_for(
conn: &Connection, conn: &Connection,
+105 -47
View File
@@ -3,7 +3,7 @@
//! //!
//! Scaling is the compositor's job. A tile attaches its capture buffer directly //! Scaling is the compositor's job. A tile attaches its capture buffer directly
//! and wp_viewporter names the rectangle to fit it into, so nothing here touches //! and wp_viewporter names the rectangle to fit it into, so nothing here touches
//! a pixel of window content — only the background, selection and labels. //! a pixel of window content - only the background, selection and labels.
use std::error::Error; use std::error::Error;
use std::os::fd::AsFd; use std::os::fd::AsFd;
@@ -24,7 +24,6 @@ use wayland_protocols_wlr::layer_shell::v1::client::{
use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::Shape; use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::Shape;
use crate::app::{App, Ending}; use crate::app::{App, Ending};
use crate::config::AltTabMode;
use crate::shm; use crate::shm;
use crate::theme::{Rect, fit_centred}; use crate::theme::{Rect, fit_centred};
@@ -35,11 +34,6 @@ const KEY_TAB: u32 = 15;
const KEY_Q: u32 = 16; const KEY_Q: u32 = 16;
const KEY_ENTER: u32 = 28; const KEY_ENTER: u32 = 28;
const KEY_LEFTCTRL: u32 = 29; const KEY_LEFTCTRL: u32 = 29;
// hjkl, by physical position: the same keys as vim on a qwerty layout.
const KEY_H: u32 = 35;
const KEY_J: u32 = 36;
const KEY_K: u32 = 37;
const KEY_L: u32 = 38;
const KEY_LEFTSHIFT: u32 = 42; const KEY_LEFTSHIFT: u32 = 42;
const KEY_RIGHTSHIFT: u32 = 54; const KEY_RIGHTSHIFT: u32 = 54;
const KEY_LEFTALT: u32 = 56; const KEY_LEFTALT: u32 = 56;
@@ -60,12 +54,23 @@ const KEY_RIGHTMETA: u32 = 126;
fn is_trigger_modifier(code: u32) -> bool { fn is_trigger_modifier(code: u32) -> bool {
matches!( matches!(
code, code,
KEY_LEFTALT KEY_LEFTALT | KEY_RIGHTALT | KEY_LEFTMETA | KEY_RIGHTMETA | KEY_LEFTCTRL | KEY_RIGHTCTRL
| KEY_RIGHTALT )
| KEY_LEFTMETA }
| KEY_RIGHTMETA
| KEY_LEFTCTRL /// Keys that should fire repeatedly while held.
| KEY_RIGHTCTRL fn is_repeatable_key(code: u32) -> bool {
matches!(
code,
KEY_TAB
| KEY_RIGHT
| KEY_LEFT
| KEY_DOWN
| KEY_UP
| KEY_HOME
| KEY_END
| KEY_PGUP
| KEY_PGDN
) )
} }
@@ -98,7 +103,7 @@ impl App {
&surface, &surface,
output, output,
Layer::Overlay, Layer::Overlay,
"wl-pick".to_string(), "wl-tab".to_string(),
qh, qh,
(), (),
); );
@@ -109,7 +114,7 @@ impl App {
let (pw, ph) = (lw * self.scale, lh * self.scale); let (pw, ph) = (lw * self.scale, lh * self.scale);
let len = shm::Chrome::slot_len(pw, ph) * shm::Chrome::SLOTS; let len = shm::Chrome::slot_len(pw, ph) * shm::Chrome::SLOTS;
let file = shm::memfd("wl-pick-chrome", len)?; let file = shm::memfd("wl-tab-chrome", len)?;
let pool = self.shm.create_pool(file.as_fd(), len as i32, qh, ()); let pool = self.shm.create_pool(file.as_fd(), len as i32, qh, ());
for slot in 0..shm::Chrome::SLOTS { for slot in 0..shm::Chrome::SLOTS {
self.chrome_buffers.push(pool.create_buffer( self.chrome_buffers.push(pool.create_buffer(
@@ -134,7 +139,7 @@ impl App {
/// Put every visible tile where the viewport says, and unmap the rest. /// Put every visible tile where the viewport says, and unmap the rest.
/// ///
/// Runs again after each scroll, so a tile scrolled off screen gets a null /// Runs again after each scroll, so a tile scrolled off screen gets a null
/// buffer — the way to hide a subsurface — rather than being left behind. /// buffer - the way to hide a subsurface - rather than being left behind.
/// Scaling stays the compositor's job: the capture buffer is attached as it /// Scaling stays the compositor's job: the capture buffer is attached as it
/// is, and wp_viewporter names the rectangle to fit it into. /// is, and wp_viewporter names the rectangle to fit it into.
pub fn sync_tiles(&mut self, qh: &QueueHandle<Self>) { pub fn sync_tiles(&mut self, qh: &QueueHandle<Self>) {
@@ -159,8 +164,8 @@ impl App {
let surface = self.compositor.create_surface(qh, ()); let surface = self.compositor.create_surface(qh, ());
let subsurface = self.subcompositor.get_subsurface(&surface, &parent, qh, ()); let subsurface = self.subcompositor.get_subsurface(&surface, &parent, qh, ());
let viewport = self.viewporter.get_viewport(&surface, qh, ()); let viewport = self.viewporter.get_viewport(&surface, qh, ());
// Tiles change independently of the chrome — a live frame // Tiles change independently of the chrome - a live frame
// arrives whenever its window does — so they must not wait on a // arrives whenever its window does - so they must not wait on a
// parent commit. // parent commit.
subsurface.set_desync(); subsurface.set_desync();
// The capture protocol reports the transform the compositor // The capture protocol reports the transform the compositor
@@ -234,7 +239,7 @@ impl App {
let (cw, ch) = (chrome.w, chrome.h); let (cw, ch) = (chrome.w, chrome.h);
let mut p = chrome.painter(); let mut p = chrome.painter();
p.fill(bg); p.fill(bg);
// The selection fills the whole element box, padding included — the same // The selection fills the whole element box, padding included - the same
// thing rofi's element background does. It can be scrolled out of sight. // thing rofi's element background does. It can be scrolled out of sight.
if let Some(elem) = elem { if let Some(elem) = elem {
p.rect(elem, sel_bg); p.rect(elem, sel_bg);
@@ -288,7 +293,7 @@ impl App {
} }
/// The tile under the pointer, if it is over one. A tile's own subsurface /// The tile under the pointer, if it is over one. A tile's own subsurface
/// answers directly; over the parent surface — padding, labels, gaps — the /// answers directly; over the parent surface - padding, labels, gaps - the
/// layout is asked instead. /// layout is asked instead.
fn tile_at_pointer(&self) -> Option<usize> { fn tile_at_pointer(&self) -> Option<usize> {
let hover = self.hover.as_ref()?; let hover = self.hover.as_ref()?;
@@ -303,8 +308,8 @@ impl App {
}) })
} }
/// Press and release on the same tile picks it. Anywhere else — the margin, /// Press and release on the same tile picks it. Anywhere else - the margin,
/// a gap, an empty cell of the last row — does nothing at all. /// a gap, an empty cell of the last row - does nothing at all.
fn click(&mut self, pressed: bool) { fn click(&mut self, pressed: bool) {
if pressed { if pressed {
self.pressed = self.tile_at_pointer(); self.pressed = self.tile_at_pointer();
@@ -318,9 +323,19 @@ impl App {
} }
fn key(&mut self, code: u32, qh: &QueueHandle<Self>) { fn key(&mut self, code: u32, qh: &QueueHandle<Self>) {
if self.is_alt_tab && is_trigger_modifier(code) { if is_trigger_modifier(code) {
self.latched_modifiers.insert(code); self.latched_modifiers.insert(code);
} }
// Arm client-side repeat for navigation keys.
if is_repeatable_key(code) {
let delay = std::time::Duration::from_millis(self.repeat_delay_ms as u64);
self.repeat_key = Some(code);
self.repeat_next = Some(std::time::Instant::now() + delay);
} else {
// Non-repeating key clears any held repeat.
self.repeat_key = None;
self.repeat_next = None;
}
match code { match code {
KEY_LEFTSHIFT | KEY_RIGHTSHIFT => self.shift = true, KEY_LEFTSHIFT | KEY_RIGHTSHIFT => self.shift = true,
KEY_ESC | KEY_Q => self.ending = Ending::Cancelled, KEY_ESC | KEY_Q => self.ending = Ending::Cancelled,
@@ -329,10 +344,10 @@ impl App {
self.ending = Ending::Picked; self.ending = Ending::Picked;
} }
KEY_TAB if self.shift => self.move_sel(-1, qh), KEY_TAB if self.shift => self.move_sel(-1, qh),
KEY_TAB | KEY_RIGHT | KEY_L => self.move_sel(1, qh), KEY_TAB | KEY_RIGHT => self.move_sel(1, qh),
KEY_LEFT | KEY_H => self.move_sel(-1, qh), KEY_LEFT => self.move_sel(-1, qh),
KEY_DOWN | KEY_J => self.move_row(1, qh), KEY_DOWN => self.move_sel(1, qh),
KEY_UP | KEY_K => self.move_row(-1, qh), KEY_UP => self.move_sel(-1, qh),
KEY_HOME => self.select(0, qh), KEY_HOME => self.select(0, qh),
KEY_END => self.select(self.tiles.len().saturating_sub(1), qh), KEY_END => self.select(self.tiles.len().saturating_sub(1), qh),
KEY_PGUP => self.move_row(-self.layout.visible_rows, qh), KEY_PGUP => self.move_row(-self.layout.visible_rows, qh),
@@ -345,10 +360,12 @@ impl App {
if code == KEY_LEFTSHIFT || code == KEY_RIGHTSHIFT { if code == KEY_LEFTSHIFT || code == KEY_RIGHTSHIFT {
self.shift = false; self.shift = false;
} }
if self.is_alt_tab // Clear repeat if this is the key that was held.
&& self.latched_modifiers.remove(&code) if self.repeat_key == Some(code) {
&& self.latched_modifiers.is_empty() self.repeat_key = None;
{ self.repeat_next = None;
}
if self.latched_modifiers.remove(&code) && self.latched_modifiers.is_empty() {
if self.ending == Ending::Running { if self.ending == Ending::Running {
self.picked = self.tiles.get(self.sel).map(|t| t.target.clone()); self.picked = self.tiles.get(self.sel).map(|t| t.target.clone());
self.ending = Ending::Picked; self.ending = Ending::Picked;
@@ -356,14 +373,38 @@ impl App {
} }
} }
fn keyboard_enter(&mut self, keys: Vec<u8>, qh: &QueueHandle<Self>) { /// Called by the main loop when the key-repeat timer fires. Fires the
/// currently held navigation action, then arms the next repeat tick.
pub fn fire_repeat(&mut self, qh: &QueueHandle<Self>) {
let Some(code) = self.repeat_key else { return };
let rate = std::time::Duration::from_millis(self.repeat_rate_ms as u64);
self.repeat_next = Some(std::time::Instant::now() + rate);
// Re-run the navigation action without re-arming the delay.
match code {
KEY_TAB if self.shift => self.move_sel(-1, qh),
KEY_TAB | KEY_RIGHT => self.move_sel(1, qh),
KEY_LEFT => self.move_sel(-1, qh),
KEY_DOWN => self.move_sel(1, qh),
KEY_UP => self.move_sel(-1, qh),
KEY_HOME => self.select(0, qh),
KEY_END => self.select(self.tiles.len().saturating_sub(1), qh),
KEY_PGUP => self.move_row(-self.layout.visible_rows, qh),
KEY_PGDN => self.move_row(self.layout.visible_rows, qh),
_ => {}
}
}
fn keyboard_enter(&mut self, keys: Vec<u8>, _qh: &QueueHandle<Self>) {
self.focused = true; self.focused = true;
let held_keys: Vec<u32> = keys let held_keys: Vec<u32> = keys
.chunks_exact(4) .chunks_exact(4)
.map(|chunk| u32::from_ne_bytes(chunk.try_into().unwrap())) .map(|chunk| u32::from_ne_bytes(chunk.try_into().unwrap()))
.collect(); .collect();
if held_keys.iter().any(|&k| k == KEY_LEFTSHIFT || k == KEY_RIGHTSHIFT) { if held_keys
.iter()
.any(|&k| k == KEY_LEFTSHIFT || k == KEY_RIGHTSHIFT)
{
self.shift = true; self.shift = true;
} }
@@ -373,27 +414,26 @@ impl App {
.filter(|&k| is_trigger_modifier(k)) .filter(|&k| is_trigger_modifier(k))
.collect(); .collect();
if !held_modifiers.is_empty() && self.alt_tab != AltTabMode::No {
self.is_alt_tab = true;
for &m in &held_modifiers { for &m in &held_modifiers {
self.latched_modifiers.insert(m); self.latched_modifiers.insert(m);
} }
}
if self.is_alt_tab && !self.initial_stepped { // If no modifier is held on enter, the modifier (and/or Tab) was
self.initial_stepped = true; // released before focus was acquired: commit selection immediately!
if self.alt_tab == AltTabMode::Yes && self.latched_modifiers.is_empty() { if self.latched_modifiers.is_empty() {
// In explicit alt-tab mode, if no modifier was held on enter,
// the modifier was released before focus was acquired: commit immediately!
if self.ending == Ending::Running { if self.ending == Ending::Running {
self.picked = self.tiles.get(self.sel).map(|t| t.target.clone()); self.picked = self.tiles.get(self.sel).map(|t| t.target.clone());
self.ending = Ending::Picked; self.ending = Ending::Picked;
} }
} else if self.alt_tab == AltTabMode::Auto { return;
// In auto mode, step selection now that we know a modifier was held:
let step = if self.shift { -1 } else { 1 };
self.move_sel(step, qh);
} }
// A modifier is held. If Tab is also held upon enter, arm key-repeat
// immediately so holding Tab cycles through windows.
if held_keys.iter().any(|&k| k == KEY_TAB) {
let delay = std::time::Duration::from_millis(self.repeat_delay_ms as u64);
self.repeat_key = Some(KEY_TAB);
self.repeat_next = Some(std::time::Instant::now() + delay);
} }
} }
} }
@@ -463,18 +503,36 @@ impl Dispatch<WlKeyboard, ()> for App {
WEnum::Value(wl_keyboard::KeyState::Released) => app.key_up(key), WEnum::Value(wl_keyboard::KeyState::Released) => app.key_up(key),
_ => {} _ => {}
}, },
// Store compositor key-repeat settings for our client-side timer.
wl_keyboard::Event::RepeatInfo { rate, delay } => {
// rate == 0 means repeat is disabled.
if rate > 0 {
app.repeat_rate_ms = (1000 / rate as u32).max(1);
app.repeat_delay_ms = delay as u32;
} else {
app.repeat_key = None;
app.repeat_next = None;
app.repeat_delay_ms = 0;
app.repeat_rate_ms = 0;
}
}
// Focus is only tracked here. sway sends leave immediately // Focus is only tracked here. sway sends leave immediately
// followed by enter on the same surface when the pointer crosses // followed by enter on the same surface when the pointer crosses
// it, so whether the grab is really gone is decided by the main // it, so whether the grab is really gone is decided by the main
// loop, once the event batch has been dispatched. // loop, once the event batch has been dispatched.
wl_keyboard::Event::Enter { keys, .. } => app.keyboard_enter(keys, qh), wl_keyboard::Event::Enter { keys, .. } => app.keyboard_enter(keys, qh),
wl_keyboard::Event::Leave { .. } => app.focused = false, wl_keyboard::Event::Leave { .. } => {
app.focused = false;
// Clear any held repeat - we no longer have the keyboard.
app.repeat_key = None;
app.repeat_next = None;
}
_ => {} _ => {}
} }
} }
} }
/// Hovering does not move the selection — that belongs to the keyboard — so the /// Hovering does not move the selection - that belongs to the keyboard - so the
/// pointer only tracks where it is and what it clicked. Scrolling is a /// pointer only tracks where it is and what it clicked. Scrolling is a
/// deliberate gesture, so that does move the selection. /// deliberate gesture, so that does move the selection.
impl Dispatch<WlPointer, ()> for App { impl Dispatch<WlPointer, ()> for App {
+1 -1
View File
@@ -3,7 +3,7 @@
//! //!
//! Capture buffers deliberately never get mapped into this process. The //! Capture buffers deliberately never get mapped into this process. The
//! compositor writes the window pixels and then samples them again for display, //! compositor writes the window pixels and then samples them again for display,
//! so we only need the fd — mapping them would fault ~7 MB per window into our //! so we only need the fd - mapping them would fault ~7 MB per window into our
//! address space for nothing. //! address space for nothing.
use std::fs::File; use std::fs::File;
+65 -27
View File
@@ -2,7 +2,7 @@
//! Wayland side only supplies pixels. The join between the two is //! Wayland side only supplies pixels. The join between the two is
//! `foreign_toplevel_identifier`, which sway reports per view. //! `foreign_toplevel_identifier`, which sway reports per view.
//! //!
//! Acting on the choice is deliberately not here: wl-pick reports what was picked //! Acting on the choice is deliberately not here: wl-tab reports what was picked
//! and the caller decides what that means. //! and the caller decides what that means.
use std::os::unix::net::UnixStream; use std::os::unix::net::UnixStream;
@@ -33,7 +33,7 @@ pub fn connect() -> Result<Connection, String> {
let live = live_sockets(); let live = live_sockets();
let [path] = live.as_slice() else { let [path] = live.as_slice() else {
return Err(if live.is_empty() { return Err(if live.is_empty() {
"cannot reach sway; wl-pick reads the window list from its IPC \ "cannot reach sway; wl-tab reads the window list from its IPC \
socket, and no running sway has one" socket, and no running sway has one"
.to_string() .to_string()
} else { } else {
@@ -119,22 +119,75 @@ impl Order {
} }
} }
fn history_path() -> PathBuf {
std::env::var_os("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.unwrap_or_else(std::env::temp_dir)
.join("wl-tab-history")
}
pub fn record_focus(con_id: i64) {
let path = history_path();
let mut ids: Vec<i64> = std::fs::read_to_string(&path)
.ok()
.map(|s| {
s.lines()
.filter_map(|l| l.trim().parse::<i64>().ok())
.collect()
})
.unwrap_or_default();
ids.retain(|&id| id != con_id);
ids.insert(0, con_id);
ids.truncate(50);
let content = ids
.iter()
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join("\n");
let _ = std::fs::write(&path, content);
}
pub fn read_focus_history() -> Vec<i64> {
std::fs::read_to_string(history_path())
.ok()
.map(|s| {
s.lines()
.filter_map(|l| l.trim().parse::<i64>().ok())
.collect()
})
.unwrap_or_default()
}
/// Views in the tree, either in MRU focus order or tree layout order. /// Views in the tree, either in MRU focus order or tree layout order.
pub fn windows(conn: &mut Connection, order: Order) -> Result<Vec<Target>, swayipc::Error> { pub fn windows(conn: &mut Connection, order: Order) -> Result<Vec<Target>, swayipc::Error> {
let mut out = Vec::new(); let mut out = Vec::new();
let tree = conn.get_tree()?; let tree = conn.get_tree()?;
match order { collect_tree(&tree, &mut out);
Order::Mru => {
collect_mru(&tree, &mut out); if out.is_empty() {
// Ensure the currently focused window is at index 0 return Ok(out);
}
// Record currently focused window into history
if let Some(pos) = out.iter().position(|t| t.focused) { if let Some(pos) = out.iter().position(|t| t.focused) {
if pos > 0 { if let Some(con_id) = out[pos].con_id {
let focused = out.remove(pos); record_focus(con_id);
out.insert(0, focused);
} }
} }
if order == Order::Mru {
let history = read_focus_history();
out.sort_by_key(|t| {
if t.focused {
return (0, 0, 0);
} }
Order::Tree => collect_tree(&tree, &mut out), if let Some(con_id) = t.con_id {
if let Some(idx) = history.iter().position(|&id| id == con_id) {
return (1, idx, 0);
}
}
if t.visible { (2, 0, 0) } else { (3, 0, 0) }
});
} }
Ok(out) Ok(out)
} }
@@ -152,6 +205,7 @@ fn collect_target(node: &Node) -> Option<Target> {
node.app_id.clone().or(class).unwrap_or_default(), node.app_id.clone().or(class).unwrap_or_default(),
node.name.clone().unwrap_or_default(), node.name.clone().unwrap_or_default(),
node.focused, node.focused,
node.visible.unwrap_or(true),
)) ))
} else { } else {
None None
@@ -167,26 +221,10 @@ fn collect_tree(node: &Node, out: &mut Vec<Target>) {
} }
} }
fn collect_mru(node: &Node, out: &mut Vec<Target>) {
if let Some(target) = collect_target(node) {
out.push(target);
}
let mut children: Vec<&Node> = node.nodes.iter().chain(node.floating_nodes.iter()).collect();
children.sort_by_key(|child| {
node.focus
.iter()
.position(|&id| id == child.id)
.unwrap_or(usize::MAX)
});
for child in children {
collect_mru(child, out);
}
}
/// One active display: what the overlay needs to size itself against. /// One active display: what the overlay needs to size itself against.
/// ///
/// The overlay maps on the focused display, so percentages and the buffer scale /// The overlay maps on the focused display, so percentages and the buffer scale
/// are resolved against *that* one — on a mixed-DPI, mixed-size setup the /// are resolved against *that* one - on a mixed-DPI, mixed-size setup the
/// numbers differ per monitor, and taking the largest of everything would be /// numbers differ per monitor, and taking the largest of everything would be
/// wrong on all but one. /// wrong on all but one.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
+26 -8
View File
@@ -1,7 +1,7 @@
//! What a tile stands for: a window, or a whole display. //! What a tile stands for: a window, or a whole display.
//! //!
//! Both are capture sources as far as the protocol is concerned — one from a //! Both are capture sources as far as the protocol is concerned - one from a
//! foreign-toplevel handle, one from a `wl_output` — so the grid treats them //! foreign-toplevel handle, one from a `wl_output` - so the grid treats them
//! alike and only differs in how it labels them and what picking one does. //! alike and only differs in how it labels them and what picking one does.
use std::fmt; use std::fmt;
@@ -57,10 +57,19 @@ pub struct Target {
pub title: String, pub title: String,
/// Whether this window was the focused container when sway was queried. /// Whether this window was the focused container when sway was queried.
pub focused: bool, pub focused: bool,
/// Whether this window is currently visible on screen.
pub visible: bool,
} }
impl Target { impl Target {
pub fn window(con_id: i64, ft_id: String, app: String, title: String, focused: bool) -> Self { pub fn window(
con_id: i64,
ft_id: String,
app: String,
title: String,
focused: bool,
visible: bool,
) -> Self {
Self { Self {
kind: Kind::Window, kind: Kind::Window,
id: con_id.to_string(), id: con_id.to_string(),
@@ -69,6 +78,7 @@ impl Target {
app, app,
title, title,
focused, focused,
visible,
} }
} }
@@ -83,6 +93,7 @@ impl Target {
app: "display".to_string(), app: "display".to_string(),
title: name, title: name,
focused: false, focused: false,
visible: true,
} }
} }
@@ -99,8 +110,8 @@ impl Target {
/// `IFS=$'\t' read -r type id toplevel app title`. /// `IFS=$'\t' read -r type id toplevel app title`.
/// ///
/// Both identifiers are there because both get used: sway scripting acts on /// Both identifiers are there because both get used: sway scripting acts on
/// the con_id (`[con_id=N] focus`), while tools that capture a window — /// the con_id (`[con_id=N] focus`), while tools that capture a window -
/// grim -T, the desktop portal — want the foreign-toplevel identifier. /// grim -T, the desktop portal - want the foreign-toplevel identifier.
pub fn tsv(&self) -> String { pub fn tsv(&self) -> String {
format!( format!(
"{}\t{}\t{}\t{}\t{}", "{}\t{}\t{}\t{}\t{}",
@@ -151,7 +162,7 @@ impl Target {
/// What xdg-desktop-portal-wlr's `simple` chooser accepts: `Monitor: NAME` /// What xdg-desktop-portal-wlr's `simple` chooser accepts: `Monitor: NAME`
/// or `Window: <foreign-toplevel identifier>`. A window the compositor never /// or `Window: <foreign-toplevel identifier>`. A window the compositor never
/// gave an identifier for cannot be named this way, hence the Option — and /// gave an identifier for cannot be named this way, hence the Option - and
/// an empty stdout is exactly how that chooser says "declined". /// an empty stdout is exactly how that chooser says "declined".
pub fn portal(&self) -> Option<String> { pub fn portal(&self) -> Option<String> {
match self.kind { match self.kind {
@@ -198,7 +209,14 @@ mod tests {
use super::*; use super::*;
fn win() -> Target { fn win() -> Target {
Target::window(42, "abc123".into(), "kitty".into(), "zsh\tin\na tab".into(), false) Target::window(
42,
"abc123".into(),
"kitty".into(),
"zsh\tin\na tab".into(),
false,
true,
)
} }
#[test] #[test]
@@ -232,7 +250,7 @@ mod tests {
Some("Monitor: DP-1") Some("Monitor: DP-1")
); );
// No identifier means the portal cannot be told about this window. // No identifier means the portal cannot be told about this window.
let anon = Target::window(7, String::new(), "x".into(), "y".into(), false); let anon = Target::window(7, String::new(), "x".into(), "y".into(), false, false);
assert_eq!(anon.portal(), None); assert_eq!(anon.portal(), None);
} }
+245 -31
View File
@@ -1,18 +1,19 @@
//! Labels. //! Labels.
//! //!
//! Building a font system and rasterising the first glyphs costs ~55ms, which is //! Building a font system and rasterising the first glyphs costs ~55ms, about
//! almost exactly the window the compositor spends copying window pixels back //! what the compositor spends copying window pixels back for a handful of
//! for us. So all of it happens on a worker thread started before the captures //! windows. So all of it happens on a worker thread started before the captures
//! and joined after them: by the time anything is drawn, every label is shaped //! and joined after them: by the time anything is drawn, every label is shaped
//! and its glyphs are already in the cache, and painting one costs ~0.1ms. //! and its glyphs are already in the cache, and painting one costs ~0.1ms.
//! //!
//! Sizes here are physical pixels — the caller scales logical units first, //! Sizes here are physical pixels - the caller scales logical units first,
//! because the chrome buffer it paints into is physical too. //! because the chrome buffer it paints into is physical too.
use std::thread::{self, JoinHandle}; use std::thread::{self, JoinHandle};
use cosmic_text::{ use cosmic_text::{
Align, Attrs, Buffer, Color, Family, FontSystem, Metrics, Shaping, SwashCache, Wrap, fontdb, Align, Attrs, Buffer, Color, Family, FontSystem, Metrics, Shaping, Stretch, SwashCache, Weight,
Wrap, fontdb,
}; };
use crate::shm::Painter; use crate::shm::Painter;
@@ -54,7 +55,7 @@ const MONO_CANDIDATES: &[&str] = &[
/// Load the smallest font database that can render `family`. /// Load the smallest font database that can render `family`.
/// ///
/// `FontSystem::new()` scans every system font, which costs ~37ms — most of the /// `FontSystem::new()` scans every system font, which costs ~37ms - most of the
/// startup budget. A user's own font directories are tiny by comparison, so try /// startup budget. A user's own font directories are tiny by comparison, so try
/// those first and only pay for the full scan when the family really isn't there /// those first and only pay for the full scan when the family really isn't there
/// (which is also what makes an unknown family fall back gracefully). The /// (which is also what makes an unknown family fall back gracefully). The
@@ -66,7 +67,7 @@ fn font_db(family: &str) -> FontSystem {
db.load_fonts_dir(format!("{home}/.fonts")); db.load_fonts_dir(format!("{home}/.fonts"));
db.load_fonts_dir(format!("{home}/.local/share/fonts")); db.load_fonts_dir(format!("{home}/.local/share/fonts"));
} }
if has_family(&db, family) { if interpret(&db, family).is_some() {
// The locale only orders CJK fallbacks; labels are ids and titles. // The locale only orders CJK fallbacks; labels are ids and titles.
return FontSystem::new_with_locale_and_db("en-US".to_string(), db); return FontSystem::new_with_locale_and_db("en-US".to_string(), db);
} }
@@ -79,31 +80,178 @@ fn is_generic(family: &str) -> bool {
family.eq_ignore_ascii_case(SYSTEM_MONO) family.eq_ignore_ascii_case(SYSTEM_MONO)
} }
fn has_family(db: &fontdb::Database, family: &str) -> bool { fn family_named(db: &fontdb::Database, want: &str) -> Option<String> {
db.faces() db.faces()
.any(|f| f.families.iter().any(|(name, _)| name == family)) .flat_map(|face| face.families.iter())
.find(|(name, _)| name.eq_ignore_ascii_case(want))
.map(|(name, _)| name.clone())
} }
/// Turn the generic default into a real family name. /// A resolved family and the face style requested within it.
/// ///
/// cosmic-text's own generic resolves through fontdb's built-in preference /// cosmic-text's own generic resolves through fontdb's built-in preference
/// ("FreeMono"), which is usually absent and then lands on an arbitrary face — so /// ("FreeMono"), which is usually absent and then lands on an arbitrary face - so
/// ask fontconfig instead, since that is what the rest of the desktop uses. A /// ask fontconfig instead, since that is what the rest of the desktop uses.
/// named family passes through untouched; if it turns out to be missing, #[derive(Debug, PartialEq)]
/// cosmic-text falls back on its own. struct Choice {
fn resolve_family(db: &fontdb::Database, family: &str) -> String { family: String,
if !is_generic(family) { weight: Weight,
return family.to_string(); stretch: Stretch,
} }
impl Choice {
fn plain(family: &str) -> Self {
Self {
family: family.to_string(),
weight: Weight::NORMAL,
stretch: Stretch::Normal,
}
}
fn attrs(&self) -> Attrs<'_> {
Attrs::new()
.family(Family::Name(&self.family))
.weight(self.weight)
.stretch(self.stretch)
}
fn name(&self) -> String {
let mut parts = vec![self.family.as_str()];
if self.weight != Weight::NORMAL {
parts.extend(spelling(WEIGHTS, self.weight));
}
if self.stretch != Stretch::Normal {
parts.extend(spelling(WIDTHS, self.stretch));
}
parts.join(" ")
}
}
fn interpret(db: &fontdb::Database, request: &str) -> Option<Choice> {
split_request(request, |name| family_named(db, name))
}
fn split_request(request: &str, lookup: impl Fn(&str) -> Option<String>) -> Option<Choice> {
let words: Vec<&str> = request.split_whitespace().collect();
for split in (1..=words.len()).rev() {
let Some(family) = lookup(&words[..split].join(" ")) else {
continue;
};
let mut choice = Choice::plain(&family);
if read_style(&words[split..], &mut choice) {
return Some(choice);
}
}
None
}
fn read_style(words: &[&str], choice: &mut Choice) -> bool {
let mut i = 0;
while i < words.len() {
let pair = words.get(i..i + 2).map(|two| two.concat());
if pair
.as_deref()
.is_some_and(|pair| apply_style(pair, choice))
{
i += 2;
} else if apply_style(words[i], choice) {
i += 1;
} else {
return false;
}
}
true
}
fn apply_style(word: &str, choice: &mut Choice) -> bool {
if let Some(weight) = lookup(WEIGHTS, word) {
choice.weight = weight;
} else if let Some(stretch) = lookup(WIDTHS, word) {
choice.stretch = stretch;
} else {
return false;
}
true
}
fn normalise(word: &str) -> String {
word.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect()
}
const WEIGHTS: &[(&str, Weight)] = &[
("Thin", Weight::THIN),
("Hairline", Weight::THIN),
("ExtraLight", Weight::EXTRA_LIGHT),
("UltraLight", Weight::EXTRA_LIGHT),
("Light", Weight::LIGHT),
("Regular", Weight::NORMAL),
("Normal", Weight::NORMAL),
("Book", Weight::NORMAL),
("Medium", Weight::MEDIUM),
("SemiBold", Weight::SEMIBOLD),
("DemiBold", Weight::SEMIBOLD),
("Bold", Weight::BOLD),
("ExtraBold", Weight::EXTRA_BOLD),
("UltraBold", Weight::EXTRA_BOLD),
("Black", Weight::BLACK),
("Heavy", Weight::BLACK),
];
const WIDTHS: &[(&str, Stretch)] = &[
("UltraCondensed", Stretch::UltraCondensed),
("ExtraCondensed", Stretch::ExtraCondensed),
("Condensed", Stretch::Condensed),
("SemiCondensed", Stretch::SemiCondensed),
("Normal", Stretch::Normal),
("SemiExpanded", Stretch::SemiExpanded),
("Expanded", Stretch::Expanded),
("ExtraExpanded", Stretch::ExtraExpanded),
("UltraExpanded", Stretch::UltraExpanded),
];
fn lookup<T: Copy>(table: &[(&str, T)], word: &str) -> Option<T> {
let word = normalise(word);
table
.iter()
.find(|(spelling, _)| normalise(spelling) == word)
.map(|(_, value)| *value)
}
fn spelling<T: PartialEq>(table: &[(&'static str, T)], value: T) -> Option<&'static str> {
table
.iter()
.find(|(_, known)| *known == value)
.map(|(word, _)| *word)
}
fn choose(db: &fontdb::Database, request: &str) -> Choice {
if !is_generic(request) {
if let Some(choice) = interpret(db, request) {
return choice;
}
let fallback = system_mono(db);
eprintln!(
"wl-tab: no font matching {request:?}, using {:?}; `fc-match -f '%{{family}}\\n' {request:?}` names the family",
fallback.family
);
return fallback;
}
system_mono(db)
}
fn system_mono(db: &fontdb::Database) -> Choice {
fc_match_mono() fc_match_mono()
.filter(|name| has_family(db, name)) .filter(|name| family_named(db, name).is_some())
.or_else(|| { .or_else(|| {
MONO_CANDIDATES MONO_CANDIDATES
.iter() .iter()
.find(|name| has_family(db, name)) .find(|name| family_named(db, name).is_some())
.map(|name| name.to_string()) .map(|name| name.to_string())
}) })
.unwrap_or_else(|| family.to_string()) .map_or_else(|| Choice::plain(SYSTEM_MONO), |name| Choice::plain(&name))
} }
/// What fontconfig says "monospace" means here. A system without the fontconfig /// What fontconfig says "monospace" means here. A system without the fontconfig
@@ -122,8 +270,8 @@ fn fc_match_mono() -> Option<String> {
fn build(texts: Vec<String>, family: String, font_px: f32, line_h: f32, box_w: f32) -> Labels { fn build(texts: Vec<String>, family: String, font_px: f32, line_h: f32, box_w: f32) -> Labels {
let mut fs = font_db(&family); let mut fs = font_db(&family);
let mut cache = SwashCache::new(); let mut cache = SwashCache::new();
let family = resolve_family(fs.db(), &family); let choice = choose(fs.db(), &family);
let attrs = Attrs::new().family(Family::Name(&family)); let attrs = choice.attrs();
let metrics = Metrics::new(font_px, line_h); let metrics = Metrics::new(font_px, line_h);
let mut lines = Vec::with_capacity(texts.len()); let mut lines = Vec::with_capacity(texts.len());
@@ -141,11 +289,11 @@ fn build(texts: Vec<String>, family: String, font_px: f32, line_h: f32, box_w: f
fs, fs,
cache, cache,
lines, lines,
family, family: choice.name(),
} }
} }
/// Shorten `text` until it fits in `box_w`, ending with an ellipsis — window /// Shorten `text` until it fits in `box_w`, ending with an ellipsis - window
/// titles are arbitrarily long, and rofi ellipsised them too. /// titles are arbitrarily long, and rofi ellipsised them too.
fn ellipsize( fn ellipsize(
fs: &mut FontSystem, fs: &mut FontSystem,
@@ -242,14 +390,80 @@ mod tests {
#[test] #[test]
fn the_generic_default_resolves_to_a_real_monospace_family() { fn the_generic_default_resolves_to_a_real_monospace_family() {
let fs = font_db(SYSTEM_MONO); let fs = font_db(SYSTEM_MONO);
let resolved = resolve_family(fs.db(), SYSTEM_MONO); let choice = choose(fs.db(), SYSTEM_MONO);
assert_ne!(resolved, SYSTEM_MONO, "should have named a real family"); assert_ne!(
assert!( choice.family, SYSTEM_MONO,
has_family(fs.db(), &resolved), "should have named a real family"
"{resolved:?} is not in the database"
); );
// A named family passes through, present or not. assert!(
assert_eq!(resolve_family(fs.db(), "Some Font"), "Some Font"); family_named(fs.db(), &choice.family).is_some(),
"{:?} is not in the database",
choice.family
);
}
#[test]
fn an_unknown_font_falls_back_to_the_default() {
let fs = font_db(SYSTEM_MONO);
let choice = choose(fs.db(), "No Such Family At All");
assert_eq!(choice, choose(fs.db(), SYSTEM_MONO));
}
fn db(families: &[&'static str]) -> impl Fn(&str) -> Option<String> {
let families = families.to_vec();
move |want| {
families
.iter()
.find(|name| name.eq_ignore_ascii_case(want))
.map(|name| name.to_string())
}
}
#[test]
fn a_full_font_name_splits_into_family_and_style() {
let choice =
split_request("Berkeley Mono Medium SemiCondensed", db(&["Berkeley Mono"])).unwrap();
assert_eq!(choice.family, "Berkeley Mono");
assert_eq!(choice.weight, Weight::MEDIUM);
assert_eq!(choice.stretch, Stretch::SemiCondensed);
assert_eq!(choice.name(), "Berkeley Mono Medium SemiCondensed");
}
#[test]
fn a_family_that_ends_in_a_style_word_wins() {
let choice =
split_request("Fira Code Light", db(&["Fira Code", "Fira Code Light"])).unwrap();
assert_eq!(choice.family, "Fira Code Light");
assert_eq!(choice.weight, Weight::NORMAL);
}
#[test]
fn style_words_accept_joined_spaced_and_mixed_case_forms() {
let cases = [
("Iosevka demibold", Weight::SEMIBOLD, Stretch::Normal),
("Iosevka Extra Light", Weight::EXTRA_LIGHT, Stretch::Normal),
(
"Iosevka ULTRACONDENSED",
Weight::NORMAL,
Stretch::UltraCondensed,
),
("Iosevka Bold Condensed", Weight::BOLD, Stretch::Condensed),
];
for (request, weight, stretch) in cases {
let choice = split_request(request, db(&["Iosevka"])).unwrap();
assert_eq!(
(choice.weight, choice.stretch),
(weight, stretch),
"{request:?}"
);
}
}
#[test]
fn unreadable_trailing_words_do_not_match() {
let known = db(&["Berkeley Mono"]);
assert_eq!(split_request("Berkeley Mono Nonsense", &known), None);
assert_eq!(split_request("Comic Sans", &known), None);
} }
#[test] #[test]
+74 -191
View File
@@ -1,13 +1,14 @@
//! Look and layout. //! Look and layout.
//! //!
//! The colours and spacing come from the rofi setup this replaces (mytheme.rasi //! The colours and spacing come from sway's default client colours:
//! plus the -theme-str rofigrid built): gruvbox dark, a yellow selection filling //! unfocused background `#222222` and text `#888888` for the grid
//! the element padding, `title · app` centred under each thumbnail. //! backdrop and labels, focused `#285577`/`#ffffff` for the selection,
//! and focused border `#4c7899`.
//! //!
//! Sizing works from caps rather than from a thumbnail size. The config gives a //! Sizing works from caps rather than from a thumbnail size. The config gives a
//! box the grid may fill and a column and row limit; a thumbnail is that box //! box the grid may fill and a column and row limit; a thumbnail is that box
//! divided by those limits. So a thumbnail is the same size whether one window //! divided by those limits. So a thumbnail is the same size whether one window
//! is open or thirty — the overlay hugs whatever is there, and rows past the //! is open or thirty - the overlay hugs whatever is there, and rows past the
//! limit scroll. //! limit scroll.
/// 0xAARRGGBB, premultiplied (everything here is opaque). /// 0xAARRGGBB, premultiplied (everything here is opaque).
@@ -24,7 +25,7 @@ pub struct Theme {
pub border_px: i32, pub border_px: i32,
/// The box the grid may not exceed, in logical px. Thumbnails are sized to /// The box the grid may not exceed, in logical px. Thumbnails are sized to
/// divide it by the column and row caps below, so a thumbnail is the same /// divide it by the column and row caps below, so a thumbnail is the same
/// size whether one window is open or thirty — only the window around them /// size whether one window is open or thirty - only the window around them
/// shrinks to hug what is there. /// shrinks to hug what is there.
pub max_w: i32, pub max_w: i32,
pub max_h: i32, pub max_h: i32,
@@ -53,11 +54,11 @@ pub struct Theme {
impl Default for Theme { impl Default for Theme {
fn default() -> Self { fn default() -> Self {
Self { Self {
bg: 0xff282828, // gruvbox-dark-bg0 bg: 0xff222222, // sway unfocused background
fg: 0xffebdbb2, // gruvbox-dark-fg1 fg: 0xff888888, // sway unfocused text
sel_bg: 0xffd79921, // gruvbox-dark-yellow-dark sel_bg: 0xff285577, // sway focused background
sel_fg: 0xff282828, sel_fg: 0xffffffff, // sway focused text
border: 0xffd79921, border: 0xff4c7899, // sway focused border
border_px: 2, border_px: 2,
// No cap of their own: Layout clamps to the display, and the // No cap of their own: Layout clamps to the display, and the
// command line resolves the configured percentage over the top. // command line resolves the configured percentage over the top.
@@ -108,47 +109,56 @@ impl Layout {
/// it does not change with how many windows are open: one window gets a /// it does not change with how many windows are open: one window gets a
/// normal thumbnail in a small overlay, thirty get the same thumbnail and /// normal thumbnail in a small overlay, thirty get the same thumbnail and
/// scroll. Columns follow ceil(sqrt(n)) up to the cap, so a handful of /// scroll. Columns follow ceil(sqrt(n)) up to the cap, so a handful of
/// windows makes a tidy grid rather than one long row — the rule rofigrid /// windows makes a tidy grid rather than one long row - the rule rofigrid
/// used — and the overlay hugs whatever is there. /// used - and the overlay hugs whatever is there.
/// Lay out `n` tiles in a single row for a display of the given logical size.
///
/// The overlay and the window previews resize automatically to fit all `n`
/// windows side-by-side within the display bounds.
pub fn new(t: &Theme, n: i32, display: (i32, i32)) -> Self { pub fn new(t: &Theme, n: i32, display: (i32, i32)) -> Self {
let n = n.max(0); let n = n.max(0);
let (cap_cols, cap_rows) = (t.max_cols.max(1), t.max_rows.max(1)); let cols = n.max(1);
// The box may never exceed the display, whatever the config says.
let box_w = t.max_w.clamp(1, display.0.max(1)); let box_w = t.max_w.clamp(1, display.0.max(1));
let box_h = t.max_h.clamp(1, display.1.max(1)); let box_h = t.max_h.clamp(1, display.1.max(1));
let aspect = display.0 as f64 / (display.1.max(1) as f64);
let margin = t.margin.min(box_w / 10).max(2);
let avail_for_items = (box_w - 2 * margin).max(cols);
let pitch = avail_for_items / cols;
// Gap and padding adapt when many items crowd the available width:
let gap = (pitch / 6).min(t.gap).max(0);
let max_elem_w = (pitch - gap).max(1);
let pad = (max_elem_w / 8).min(t.pad).max(1);
let label_row = if t.labels { t.spacing + t.line_h } else { 0 }; let label_row = if t.labels { t.spacing + t.line_h } else { 0 };
let furniture_h = 2 * margin + 2 * pad + label_row;
let max_thumb_h = (box_h - furniture_h)
.min((display.1 as f64 * 0.35).round() as i32)
.max(1);
let ideal_tile_w = (max_thumb_h as f64 * aspect).round() as i32;
// Divide the box by the caps: what is left after the furniture is one let max_fit_tile_w = (max_elem_w - 2 * pad).max(1);
// thumbnail. let tile_w = ideal_tile_w.min(max_fit_tile_w).max(1);
let per_col = 2 * t.pad + t.gap; let tile_h = ((tile_w as f64 / aspect).round() as i32).max(1);
let per_row = 2 * t.pad + label_row + t.gap;
let tile_w = ((box_w - 2 * t.margin + t.gap) / cap_cols - per_col).max(1);
let tile_h = ((box_h - 2 * t.margin + t.gap) / cap_rows - per_row).max(1);
let (elem_w, elem_h) = (tile_w + 2 * t.pad, tile_h + label_row + 2 * t.pad);
// Columns: the balanced rule, so a handful of windows makes a tidy grid let elem_w = tile_w + 2 * pad;
// rather than one long row, capped by the config. let elem_h = tile_h + label_row + 2 * pad;
let mut cols = (n as f64).sqrt() as i32; let rows = 1;
if cols * cols < n { let visible_rows = 1;
cols += 1;
}
cols = cols.clamp(1, cap_cols);
// i32::div_ceil is still unstable; only the unsigned one is not.
let rows = (n + cols - 1) / cols;
let visible_rows = cap_rows.clamp(1, rows.max(1));
Self { Self {
cols, cols,
rows, rows,
visible_rows, visible_rows,
n, n,
width: cols * elem_w + (cols - 1) * t.gap + 2 * t.margin, width: (cols * elem_w + (cols - 1) * gap + 2 * margin).min(box_w),
height: visible_rows * elem_h + (visible_rows - 1) * t.gap + 2 * t.margin, height: (elem_h + 2 * margin).min(box_h),
elem_w, elem_w,
elem_h, elem_h,
margin: t.margin, margin,
gap: t.gap, gap,
pad: t.pad, pad,
tile_h, tile_h,
spacing: t.spacing, spacing: t.spacing,
line_h: t.line_h, line_h: t.line_h,
@@ -323,53 +333,37 @@ mod tests {
} }
#[test] #[test]
fn a_thumbnail_is_the_box_divided_by_the_caps() { fn previews_and_overlay_resize_automatically() {
let t = theme(1000, 900, 4, 3);
let l = Layout::new(&t, 12, ROOMY);
let tile = l.tile(0, 0).expect("visible");
// Four columns of (tile + padding) plus three gaps plus two margins fill
// the box, give or take integer division.
let used = 4 * (tile.w + 2 * t.pad) + 3 * t.gap + 2 * t.margin;
assert!((1000 - used).abs() <= 4, "width {used} should fill 1000");
let label_row = t.spacing + t.line_h;
let used = 3 * (tile.h + label_row + 2 * t.pad) + 2 * t.gap + 2 * t.margin;
assert!((900 - used).abs() <= 4, "height {used} should fill 900");
}
#[test]
fn one_window_gets_the_same_thumbnail_as_thirty() {
let t = theme(1000, 900, 4, 3); let t = theme(1000, 900, 4, 3);
let one = Layout::new(&t, 1, ROOMY); let one = Layout::new(&t, 1, ROOMY);
let many = Layout::new(&t, 30, ROOMY); let two = Layout::new(&t, 2, ROOMY);
assert_eq!( let eight = Layout::new(&t, 8, ROOMY);
one.tile(0, 0).expect("visible").w,
many.tile(0, 0).expect("visible").w, assert_eq!((one.rows, one.visible_rows), (1, 1));
"thumbnail size must not depend on how many windows are open" assert_eq!((two.rows, two.visible_rows), (1, 1));
); assert_eq!((eight.rows, eight.visible_rows), (1, 1));
// The overlay hugs what is there: one tile is a small window.
assert_eq!((one.cols, one.rows), (1, 1)); assert_eq!(one.cols, 1);
assert_eq!(two.cols, 2);
assert_eq!(eight.cols, 8);
// Previews shrink automatically as more windows are added
assert!( assert!(
one.width < many.width && one.height < many.height, two.tile(0, 0).expect("visible").w >= eight.tile(0, 0).expect("visible").w,
"{one:?}" "previews should scale down to fit"
); );
assert!(!one.scrollable() && many.scrollable()); // Overlay width adjusts with the count
assert!(one.width <= two.width);
assert!(eight.width <= 1000);
} }
#[test] #[test]
fn grids_stay_balanced_and_within_the_caps() { fn single_row_holds_all_windows() {
let t = theme(1000, 900, 4, 3); let t = theme(1000, 900, 4, 3);
// (n, cols, rows): ceil(sqrt(n)) columns, capped at four. for n in 1..=10 {
for (n, cols, rows) in [
(1, 1, 1),
(2, 2, 1),
(4, 2, 2),
(6, 3, 2),
(12, 4, 3),
(30, 4, 8),
] {
let l = Layout::new(&t, n, ROOMY); let l = Layout::new(&t, n, ROOMY);
assert_eq!((l.cols, l.rows), (cols, rows), "n = {n}"); assert_eq!((l.cols, l.rows, l.visible_rows), (n, 1, 1), "n = {n}");
assert!(l.visible_rows <= t.max_rows, "n = {n}"); assert!(!l.scrollable());
} }
} }
@@ -389,29 +383,14 @@ mod tests {
#[test] #[test]
fn labels_take_their_room_from_the_thumbnail() { fn labels_take_their_room_from_the_thumbnail() {
let mut t = theme(1000, 900, 4, 3); let mut t = theme(1000, 900, 4, 3);
let with = Layout::new(&t, 12, ROOMY); let with = Layout::new(&t, 4, ROOMY);
t.labels = false; t.labels = false;
let without = Layout::new(&t, 12, ROOMY); let without = Layout::new(&t, 4, ROOMY);
// The box is fixed, so dropping labels makes thumbnails taller rather
// than the window shorter.
assert!( assert!(
without.tile(0, 0).expect("visible").h > with.tile(0, 0).expect("visible").h, without.tile(0, 0).expect("visible").h >= with.tile(0, 0).expect("visible").h,
"thumbnails should grow into the freed row" "thumbnails should grow into the freed space"
); );
assert!(with.label(0, 0).is_some() && without.label(0, 0).is_none()); assert!(with.label(0, 0).is_some() && without.label(0, 0).is_none());
let t = theme(1000, 900, 4, 3);
let l = Layout::new(&t, 4, ROOMY);
for i in 0..4 {
let (tile, label, elem) = (
l.tile(i, 0).expect("visible"),
l.label(i, 0).unwrap(),
l.elem(i, 0).expect("visible"),
);
assert_eq!(label.y, tile.y + tile.h + t.spacing);
assert_eq!(label.w, tile.w);
assert!(label.y + label.h + t.pad <= elem.y + elem.h);
}
} }
#[test] #[test]
@@ -421,15 +400,13 @@ mod tests {
let l = Layout::new(&t, 30, (640, 480)); let l = Layout::new(&t, 30, (640, 480));
assert!(l.width <= 640 && l.height <= 480, "{l:?}"); assert!(l.width <= 640 && l.height <= 480, "{l:?}");
assert!(l.tile(0, 0).expect("visible").w >= 1); assert!(l.tile(0, 0).expect("visible").w >= 1);
assert!(l.scrollable());
} }
#[test] #[test]
fn hit_testing_is_the_inverse_of_the_layout() { fn hit_testing_is_the_inverse_of_the_layout() {
let t = Theme::default(); let t = Theme::default();
// 7 tiles over 3 columns: the last row holds one, so two cells are empty. let l = Layout::new(&t, 5, ROOMY);
let l = Layout::new(&t, 7, ROOMY); for i in 0..5 {
for i in 0..7 {
let e = l.elem(i, 0).expect("visible"); let e = l.elem(i, 0).expect("visible");
for (x, y, what) in [ for (x, y, what) in [
(e.x, e.y, "top left"), (e.x, e.y, "top left"),
@@ -439,8 +416,6 @@ mod tests {
assert_eq!(l.hit(x, y, 0), Some(i as usize), "{what} of element {i}"); assert_eq!(l.hit(x, y, 0), Some(i as usize), "{what} of element {i}");
} }
} }
// The window margin, the gap between elements, and the empty cells of
// the last row all belong to no tile.
assert_eq!(l.hit(0, 0, 0), None, "margin"); assert_eq!(l.hit(0, 0, 0), None, "margin");
let first = l.elem(0, 0).expect("visible"); let first = l.elem(0, 0).expect("visible");
assert_eq!( assert_eq!(
@@ -448,101 +423,9 @@ mod tests {
None, None,
"gap between columns" "gap between columns"
); );
assert_eq!(
l.hit(first.x, first.y + first.h + 1, 0),
None,
"gap between rows"
);
// Row 2, column 2 is past the seventh tile: take its column from the top
// row and its row from the first column.
let col2 = l.elem(2, 0).expect("visible");
let row2 = l.elem(6, 0).expect("visible");
assert_eq!(l.hit(col2.x + 4, row2.y + 4, 0), None, "empty cell");
assert_eq!(l.hit(-5, -5, 0), None, "outside"); assert_eq!(l.hit(-5, -5, 0), None, "outside");
} }
#[test]
fn rows_beyond_the_display_scroll_instead_of_shrinking() {
let t = theme(1000, 900, 4, 3);
// Thirty tiles need more rows than the cap allows, so they scroll.
let l = Layout::new(&t, 30, ROOMY);
assert!(l.scrollable(), "{l:?} should scroll");
assert!(l.visible_rows < l.rows);
// The viewport shows a window of rows, and nothing outside it.
let per_screen = (l.visible_rows * l.cols) as usize;
assert!(l.elem(0, 0).is_some());
assert!(
l.elem(per_screen as i32, 0).is_none(),
"first row below the fold"
);
assert!(
l.elem(per_screen as i32, 1).is_some(),
"and visible once scrolled"
);
}
#[test]
fn max_rows_keeps_the_grid_compact() {
let mut t = theme(1000, 900, 4, 3);
let full = Layout::new(&t, 30, ROOMY);
t.max_rows = 2;
let capped = Layout::new(&t, 30, ROOMY);
assert!(
capped.visible_rows == 2 && full.visible_rows > 2,
"{capped:?}"
);
assert!(capped.height < full.height, "a shorter overlay");
assert!(capped.scrollable());
// The cap cannot invent rows: four tiles make a 2x2 grid, and a cap of
// five leaves it alone.
t.max_rows = 5;
let few = Layout::new(&t, 4, ROOMY);
assert_eq!((few.cols, few.rows, few.visible_rows), (2, 2, 2), "{few:?}");
assert!(!few.scrollable());
}
#[test]
fn revealing_moves_the_viewport_as_little_as_possible() {
let t = theme(1000, 900, 4, 3);
let l = Layout::new(&t, 30, ROOMY);
let last_visible = (l.visible_rows * l.cols - 1) as usize;
assert_eq!(l.reveal(0, 0), 0, "already on screen");
assert_eq!(l.reveal(last_visible, 0), 0, "still on screen");
// One row further down scrolls by exactly one row.
assert_eq!(l.reveal(last_visible + 1, 0), 1);
// Jumping to the end goes as far as it can, and no further.
assert_eq!(l.reveal(29, 0), l.max_scroll());
// Coming back up scrolls the other way.
assert_eq!(l.reveal(0, l.max_scroll()), 0);
}
#[test]
fn hit_testing_follows_the_scroll() {
let t = theme(1000, 900, 4, 3);
let l = Layout::new(&t, 30, ROOMY);
let first = l.elem(0, 0).expect("visible");
let probe = (first.x + first.w / 2, first.y + first.h / 2);
assert_eq!(l.hit(probe.0, probe.1, 0), Some(0));
// The same pixel is a different tile once the grid has scrolled.
assert_eq!(l.hit(probe.0, probe.1, 1), Some(l.cols as usize));
}
#[test]
fn a_scrollbar_appears_only_when_there_is_more_to_see() {
let t = theme(1000, 900, 4, 3);
assert!(Layout::new(&t, 4, ROOMY).scrollbar(0, 4).is_none());
let l = Layout::new(&t, 30, ROOMY);
let (track, top) = l.scrollbar(0, 4).expect("scrollable");
assert_eq!(top.y, track.y, "thumb starts at the top");
assert!(top.h < track.h, "thumb is shorter than its track");
let (_, bottom) = l.scrollbar(l.max_scroll(), 4).expect("scrollable");
assert_eq!(
bottom.y + bottom.h,
track.y + track.h,
"and ends at the bottom"
);
}
#[test] #[test]
fn fit_preserves_aspect_and_centres() { fn fit_preserves_aspect_and_centres() {
let box_ = Rect { let box_ = Rect {