Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

updated desktop context menu

oxydizer45db6ed30e59
diff --git a/docs/plans/theme-packs.md b/docs/plans/theme-packs.md
deleted file mode 100644
index 2b54330..0000000
--- a/docs/plans/theme-packs.md
+++ /dev/null
@@ -1,325 +0,0 @@
-# Plan: theme packs (colours plus icons, wallpapers and cursors)
-
-Status: implemented, 2026-10-13. Phases 0–6 use the proposed D1–D5 design.
-The implementation and author instructions are in `docs/themes.md`; the
-fixture and integration gates are in `tests/theme_packs.py`.
-
-The inventory below records the pre-implementation baseline. Pack discovery
-now lives in `config/theme_pack.zig`, application in `config_runtime/`, and
-archive handling in the separate `rediwm-theme` helper. The helper reuses
-Files' archive path normalization and direct image codecs; bounded ZIP
-streaming, cursor aliases and atomic publication have their own native path.
-
-Scope: a theme becomes a *pack*: the `[theme]` tokens it is today, plus the
-pictures that go with them (wallpapers, the start logo, shell glyphs, folder
-and file icons, optionally a cursor theme). A pack is shared as one file (a
-zip), installed with one click and applied as one choice in Appearance. No
-code, shaders or fonts travel in a pack.
-
-## Baseline before implementation
-
-A theme is TOML only, and only colours, sizes and font names:
-
-* **Tokens.** `ui/theme.zig`'s `Theme` struct (over 200 fields: colours,
- radii, sizes, `font`, `mono_font`, `start_button_icon`). The tiny parser
- reads a `[theme]` section; `writeInto` writes only the values that differ
- from the built-in defaults.
-* **Where they live.** The applied theme is the `[theme]` section of
- `config.toml` (plus `[taskbar_theme]`, the taskbar's own colours), with
- `REDIWM_THEME` overlaid on top.
-* **Presets.** Three TOMLs embedded at build time (`assets/themes/`, listed by
- `ui/theme_presets.zig`) plus every `*.toml` in `~/.config/rediwm/themes/`.
- Picking one **copies** its values into `theme.global` and saves them to
- `[theme]`. Which preset is active is not stored: Appearance re-parses every
- preset and selects the one equal to the current theme, else "Custom".
-* **App clients.** Files, Images and PDF follow `config.toml`'s `[theme]`
- through `files/settings.zig` (stat once per second, re-read on change). PDF
- reads it once, before its sandbox closes the filesystem.
-
-Everything visual that is not a token is a separate setting, chosen
-separately:
-
-| What | Today | Chosen by |
-| --- | --- | --- |
-| Wallpaper | `[compositor] wallpaper`: file name in `share/rediwm/wallpapers` or `~/.local/share/rediwm/wallpapers`, or a path | Appearance strip |
-| Apps light/dark | `[compositor] dark_mode` (settings portal) | Appearance |
-| Start logo | `[theme] start_button_icon`, an **absolute** path | Appearance |
-| Shell glyphs (wifi, battery, sidebar, toolbar icons) | 49 SVGs `@embedFile`d into `ui/shell_icons.zig`, alpha masks tinted at paint time | nothing: compiled in |
-| Folder icons in Files | hand-drawn vector, `file_folder_back/front` tokens | tokens only |
-| File icons in Files, desktop icons, app icons | freedesktop icon theme, `icon_theme.zig` | `REDIWM_ICON_THEME` env only (default Adwaita), read at startup |
-| Cursors | Xcursor theme by name, `[input] cursor_theme`; phinger built and installed to `share/icons` | Appearance |
-| Sounds | freedesktop sound theme by name, `sound_theme` | config |
-
-So the user's reading is right: switching "theme" today changes colours and
-geometry; the wallpaper, glyphs and folder icons stay put. Two inconsistencies
-fall out of the survey and this plan fixes them in passing: the desktop draws
-folders with the icon theme's `folder` while Files draws its own vector one,
-and the icon theme is the only appearance setting with no UI and no config key.
-
-## Design
-
-### A pack on disk
-
-A pack is a directory; the zip is only how it travels (D1).
-
-```
-nord/
- theme.toml required
- preview.png optional, picker thumbnail (≤ 512×320)
- logo.svg optional, start button
- wallpapers/ optional, *.png *.jpg *.jpeg *.webp
- glyphs/ optional, monochrome shell glyph overrides
- icons/ optional, flat colour icon overrides (D4)
- cursors/ optional, a built Xcursor theme (Phase 6)
-```
-
-`theme.toml` is today's format with two more sections. Everything in
-`[theme]` and `[taskbar_theme]` is read by the existing parser, so a single
-`.toml` preset is already a pack without assets, and keeps working:
-
-```toml
-[meta]
-format = 1 # packs from a newer format are refused with a message
-id = "nord" # [a-z0-9-], ≤ 64; defaults to the directory name
-name = "Nord"
-version = "1.2"
-author = "…"
-license = "CC-BY-SA-4.0"
-description = "Arctic blues."
-
-[theme] # unchanged token set
-accent = "#88c0d0"
-start_button_icon = "logo.svg" # relative: inside the pack
-
-[taskbar_theme] # optional, unchanged
-
-[assets]
-wallpaper = "nord-night.jpg" # default wallpaper, from wallpapers/
-color_scheme = "dark" # sets [compositor] dark_mode
-icon_theme = "Papirus-Dark" # optional base icon theme, by name (D4)
-cursor_theme = "pack" # "pack" = cursors/, or an installed name
-```
-
-Rules that keep packs safe and forward compatible:
-
-* Asset paths are relative and must resolve inside the pack (no `..`, no
- absolute paths, no symlinks). An absolute `start_button_icon` stays legal in
- `config.toml` only.
-* Unknown `[theme]` keys in a pack are logged and skipped, not fatal (today the
- config loader fails on them), so a pack made for a newer RediWM still loads.
-* Glyphs are named like `assets/icons/` (`wifi.svg`, `view-grid.svg`,
- `trash-outline.svg`), so an author starts by copying that directory. Only
- alpha is used: they are tinted like the built-in ones.
-
-### Where packs are found
-
-In order, the first id wins (as `wallpapers.zig` does for file names):
-
-1. `$XDG_DATA_HOME/rediwm/themes/<id>/` (installed by the user)
-2. `~/.config/rediwm/themes/*.toml` (today's single-file presets; id = stem)
-3. `<prefix>/share/rediwm/themes/<id>/`, then `$XDG_DATA_DIRS/rediwm/themes/`
- (distribution packs)
-4. The embedded presets (`rediwm-dark`, `rediwm-light`, `redi-blue`), which
- stay embedded so a broken install still has a theme.
-
-Discovery and parsing go in `config/theme_pack.zig` (parsing is `config/`);
-applying goes in `config_runtime/`, beside today's reload path.
-
-### Config: a reference plus overrides (D2)
-
-`config.toml` names the pack and keeps only what the user changed on top:
-
-```toml
-[theme]
-base = "nord" # new key; absent = built-in defaults, i.e. today
-font_size = 14 # the user's own tweak, kept across pack updates
-```
-
-Layering: built-in defaults ← pack `[theme]` ← `config.toml [theme]` ←
-`REDIWM_THEME`. `writeInto` diffs against the resolved pack instead of
-`Theme{}`, so Appearance edits stay small and an updated pack reaches the
-user. Picking a pack clears the overrides (the same as a preset replacing
-everything today), and a "Reset to theme" button does the same without
-switching. Configs without `base` read exactly as today: that is Phase 1's
-regression test.
-
-`files/settings.zig` resolves `base` the same way, so Files and Images follow
-a pack switch; PDF keeps the pack it was started with (it has to read before
-its sandbox), as it already does for colours.
-
-### Assets at runtime
-
-* **Wallpaper.** An empty `[compositor] wallpaper` means "the theme's" (the
- pack's `[assets] wallpaper`, else `default.png`). Picking an image in the
- strip pins it; applying a pack resets it to "the theme's" (D3). The strip
- gains the active pack's `wallpapers/` as a group. The lock screen uses the
- same image, so it follows for free.
-* **Start logo.** `start_button_icon` relative to the pack.
-* **Glyphs.** `shell_icons.source` asks the active pack for `glyphs/<name>.svg`
- first, then the embedded SVG. The mask cache is flushed on a pack switch
- (`shell_icons.deinit`). Rasterising is synchronous on the caller's thread
- (the compositor paints with it), so install-time validation bounds a glyph's
- size and render time (below).
-* **Folder and file icons (D4).** A flat `icons/` directory (`<name>.svg` or
- `<name>.png`, freedesktop names) is searched before the icon theme chain in
- `icon_theme.zig`, which every icon user goes through: Files, the desktop, the
- taskbar and the start menu. That makes overriding an *app* icon
- (`firefox.svg`) free as well. The chain behind it is `[assets] icon_theme`,
- else a new `[compositor] icon_theme` setting, else `REDIWM_ICON_THEME`, else
- Adwaita. Files then draws a directory with the first icon found among its
- XDG special name (`user-home`, `user-desktop`, `folder-documents`,
- `folder-download`, `folder-music`, `folder-pictures`, `folder-videos`,
- `folder-templates`, `folder-publicshare`, `user-trash`, from
- `user-dirs.dirs`) and `folder`, and keeps today's vector folder when the
- pack supplies neither. The desktop uses the same lookup, which ends the
- Files/desktop mismatch. Icon caches (`icon_cache`, `icon_service`, Files'
- and the desktop's) key on a pack generation so a switch re-resolves.
-* **Cursors (Phase 6).** `cursors/` is a built Xcursor theme (`index.theme`
- plus `cursors/`). Installing links it as
- `~/.local/share/icons/rediwm-<id>-cursors`, which is on `XCURSOR_PATH` for
- wlroots, Xwayland and children, and applying sets `cursor_theme` through the
- existing picker path. Xcursor aliases are symlinks, so the installer allows
- exactly one kind: inside `cursors/cursors/`, a target with no `/`.
-
-Nothing here adds a wakeup: packs are read on apply, on config reload and on
-start, and no pack directory is watched.
-
-### Installing, removing, sharing
-
-The compositor never opens an untrusted archive and does not link libarchive.
-A small helper, `rediwm-theme`, does, reusing `files/archive.zig` (libarchive,
-already rejecting unsafe paths, links, special files and oversized entry
-counts):
-
-```
-rediwm-theme install <file.rediwm-theme|.zip|dir> # validate, extract, print id
-rediwm-theme validate <dir> # for authors
-rediwm-theme pack <dir> <out.rediwm-theme> # for authors
-rediwm-theme remove <id>
-```
-
-Install extracts into `themes/.staging-XXXXXX/`, validates there, then renames
-into `themes/<id>/` (`RENAME_EXCHANGE` when upgrading, then deletes the old
-copy), so a running compositor never sees half a pack. Validation:
-
-* Zip only; the pack is the archive root or its single top-level directory.
-* Regular files and directories only (plus the cursor alias exception); at
- most 4,000 entries, 128 MiB unpacked in total, 40 MiB per file, counted
- while streaming so a bomb stops early.
-* Allowed by place: `theme.toml`, `preview.png`, `logo.svg|png`,
- `wallpapers/*.{png,jpg,jpeg,webp}`, `glyphs/*.svg`, `icons/*.{svg,png}`,
- `cursors/**`, and `README*`, `LICENSE*`. Anything else is refused by name.
-* `theme.toml` parses; every image decodes; every SVG renders at 256 px.
- Glyphs: ≤ 64 KiB and under 10 ms to render at 256 px; icons: ≤ 512 KiB.
- Wallpapers: ≤ 16384 px a side. A failure names the file and the rule.
-* An id already installed asks "Replace Nord 1.1 with 1.2?" in Appearance.
-
-The helper is a child of the compositor (or of Files), runs with no
-privileges, and can enter a Landlock/seccomp sandbox limited to the staging
-directory, like PDF's (`rediwm_pdf_sandbox_enter`); a crafted archive that
-breaks libarchive or librsvg then crashes the helper, not the session.
-Appearance runs it as a job with an eventfd, as it does the GTK/Qt colour
-export (`AppColorsJob`).
-
-Entry points:
-
-* Appearance: "Install theme…" (file chooser), and "Remove" on user-installed
- packs. Removing the active pack switches to RediWM Dark first.
-* Files: a `.rediwm-theme` file opens with "Install theme" (a shared-mime-info
- type `application/x-rediwm-theme`, glob `*.rediwm-theme`, in `data/`).
-* IPC: `theme.list`, `theme.apply`, `theme.install` for tests and scripts.
- They are settings writes: `SessionLocked` while locked, and sandboxed callers
- need an `[[sandbox_allow]]` allowance like the rest of settings IPC.
-* "Save current look as theme…" (Phase 5): writes a pack from the current
- tokens, wallpaper and logo into `themes/<id>/`; `rediwm-theme pack` zips it.
-
-### Security notes
-
-* The greeter loads no packs (it reads nothing from a user's home and
- writes nothing under `$HOME`); `tests/greeter.py` must still pass. Login
- theming was deferred from this plan; it now follows each account's public
- appearance snapshot without discovering packs (see `docs/themes.md`).
-* A broken or missing pack never blocks locking: lock UI and wallpaper are
- already optional there, and every asset falls back to the built-in one.
-* SVGs are rendered from data with no base URI, so they cannot pull in files
- outside themselves.
-* No fonts, scripts, shaders, `.desktop` files or anything executable. Fonts
- are referenced by family name; bundling them (private `FcConfigAppFontAddDir`
- for RediWM processes only) is a possible later item.
-
-## Decisions
-
-* **D1, zip at runtime or only in transit.** Chosen: only in transit; the
- installed form is a directory. Xcursor and icon loaders, the wallpaper
- decoder, Files, the desktop and the sandboxed PDF viewer all take paths;
- the compositor would otherwise need libarchive and decompression on its
- paths; validation happens once instead of on every read; and authors edit a
- directory and see the result. Cost: a pack takes its unpacked size on disk.
-* **D2, reference or copy.** Chosen: `[theme] base = "<id>"` plus overrides
- (above). Alternative: keep copying tokens and only add `base` for assets;
- simpler, but pack updates never reach colours and Appearance keeps guessing
- the active preset by equality.
-* **D3, wallpaper on switch.** Chosen: applying a pack resets the wallpaper
- to the pack's; a later pick in the strip pins it until the next switch.
- Alternative: keep the user's wallpaper unless it was the theme's.
-* **D4, icons.** Chosen: a flat `icons/` override directory in packs, plus a
- base icon theme referenced by name. Full freedesktop icon themes (10,000 to
- 50,000 files, tens of MiB) are not carried inside packs.
-* **D5, file name.** Chosen: `.rediwm-theme` (a zip) registered for
- double-click install, and plain `.zip` accepted by the helper and the file
- chooser.
-
-## Phases
-
-Each phase ends with the usual gate: Debug and ReleaseSafe builds,
-`zig build test`, the touched integration tests, HEAD comparison for
-known-failing suites.
-
-0. **Inventory** (no code). The glyphs each surface uses (compositor, Files,
- Images, PDF, desktop), the icon names Files and the desktop ask for, and a
- sample pack in `tests/fixtures/theme-pack/` (one glyph, `folder.svg`, a
- small wallpaper, a logo) that every later phase tests with.
-1. **Packs without assets.** `config/theme_pack.zig` (format, discovery,
- `[meta]`), `[theme] base`, layered resolve, `writeInto` against the base,
- unknown pack keys skipped. Appearance lists packs with their names and
- remembers the active one; "Reset to theme". `files/settings.zig` resolves
- `base`. Unit tests: a config without `base` resolves to today's theme; a
- save writes only overrides; the three presets resolve as before.
-2. **Wallpaper, logo, colour scheme.** `[assets] wallpaper` and
- `color_scheme`, relative `start_button_icon`, the strip's pack group, D3's
- reset. The lock screen check that it follows.
-3. **Glyphs.** Override lookup in `shell_icons`, cache flush on switch, app
- clients follow, PDF reads its pack before the sandbox.
-4. **Folder and file icons.** The flat `icons/` lookup in `icon_theme.zig`,
- `[compositor] icon_theme` with a picker, generation-keyed caches, Files'
- special-folder names, the desktop on the same lookup.
-5. **Install, remove, share.** `rediwm-theme` (install, validate, pack,
- remove), its sandbox, Appearance install/remove/replace, Files double-click
- and the MIME type, IPC `theme.*`, "Save current look as theme…".
-6. **Cursors.** `cursors/` in packs, the alias exception, the
- `~/.local/share/icons` link, applied through the cursor picker path.
-
-Phases 2 to 4 can land in any order after 1; 5 needs only 1, so packs can be
-installed (and tested from a zip) as soon as there is anything to install.
-
-## Tests
-
-* Unit: pack parsing (format, ids, relative paths, unknown keys), layering
- and saving, discovery order and id collisions, the installer's path rules.
-* Integration, a new `tests/theme_packs.py` on the fixture pack: install by
- IPC from a zip, apply, then check by IPC screenshot that a glyph, the Files
- folder icon, the desktop folder, the wallpaper and the start logo changed;
- switch back and check they return; remove the active pack.
-* Hostile archives, each refused with its message and nothing left in
- `themes/`: `../` and absolute paths, a symlink out, a device node, a zip
- bomb, 10,000 entries, a disallowed file, a glyph that takes 2 s to render,
- a wallpaper of 40000×40000, a malformed `theme.toml`.
-* `tests/greeter.py` (no packs read), and the existing Appearance and
- wallpaper tests with a scratch `XDG_STATE_HOME` and `XDG_DATA_HOME`.
-
-## Not in this plan
-
-* Downloading packs (no catalog, no network).
-* Fonts inside packs; exporting a pack's icons to GTK/Qt apps (the GTK/Qt
- colour export stays as it is); light and dark variants in one pack (one pack
- per look, like RediWM Dark and Light today); sounds; themed login screens.
diff --git a/src/desktop/app.zig b/src/desktop/app.zig
index 205579c..756ddb0 100644
--- a/src/desktop/app.zig
+++ b/src/desktop/app.zig
@@ -78,10 +78,12 @@ pub const App = struct {
menu_icon: ?usize = null,
menu_x: i32 = 0,
menu_y: i32 = 0,
- edit: enum { none, rename, folder, file, trash, properties, add_file, add_app, open_with } = .none,
+ edit: enum { none, rename, folder, file, trash, properties, add_app, open_with } = .none,
folder_token: u64 = 0,
deletion: deletion.State = .{},
catalog: []const @import("dotdesktop.zig").parser.AppEntry = &.{},
+ applications: ?@import("../files/open_with.zig").State = null,
+ picker_theme: @import("../icon_theme.zig").Config = .{ .theme_name = "", .base_dirs = &.{} },
choice: usize = 0,
last_tick: i64 = 0,
last_tick_active: bool = false,
@@ -148,6 +150,7 @@ pub const App = struct {
self.damageRect(damage_mod.expand(self.geometry.rect(self.geometry.snap(self.x, self.y)), 1));
}
pub fn deinit(self: *App) void {
+ self.closePicker();
self.deletion.deinit();
self.rename_editor.deinit();
if (self.wallpaper) |im| a.free(im.pixels);
@@ -181,6 +184,7 @@ pub const App = struct {
self.refreshBottom();
self.icon_only = snap.icon_only;
self.catalog = snap.catalog;
+ if (self.applications) |*picker| picker.shortcut_catalog = self.catalog;
for (self.icons.items) |*ic| {
var found = false;
for (snap.items) |item| if (std.mem.eql(u8, item.path, ic.item.path)) {
@@ -284,6 +288,8 @@ pub const App = struct {
pub const menuHint = app_actions.menuHint;
pub const untrustedLauncher = app_actions.untrustedLauncher;
pub const menuAction = app_actions.menuAction;
+ pub const closePicker = app_actions.closePicker;
+ pub const pickerAction = app_actions.pickerAction;
pub const beginEdit = app_actions.beginEdit;
pub const deleteAction = app_actions.deleteAction;
pub const finishEdit = app_actions.finishEdit;
diff --git a/src/desktop/app_actions.zig b/src/desktop/app_actions.zig
index c5475eb..a68b5e5 100644
--- a/src/desktop/app_actions.zig
+++ b/src/desktop/app_actions.zig
@@ -43,7 +43,7 @@ pub fn menuLabels(self: *App) []const []const u8 {
}
const icon_labels = [_][]const u8{ "Open", "Open With…", "Cut", "Copy", "Rename", "Move to Trash", "Properties", "Allow Launching" };
if (self.menu_icon) |index| return if (self.untrustedLauncher(index)) &icon_labels else icon_labels[0 .. icon_labels.len - 1];
- return &.{ "New Folder", "New File", "Add Application…", "Add File…", "Paste", "Refresh", "Change Wallpaper", "Desktop Settings" };
+ return &.{ "New Folder", "New File", "Add Application…", "Paste", "Refresh", "Change Wallpaper", "Desktop Settings" };
}
pub fn menuIcon(self: *App, row: usize) @import("ui").layout.IconId {
@@ -52,14 +52,14 @@ pub fn menuIcon(self: *App, row: usize) @import("ui").layout.IconId {
return if (self.menu_icon != null)
([_]IconId{ .chevron_right, .grid, .cut, .copy, .edit, .trash, .view_list, .checkmark })[row]
else
- ([_]IconId{ .plus, .edit, .grid, .open, .paste, .refresh, .display, .settings })[row];
+ ([_]IconId{ .plus, .edit, .grid, .paste, .refresh, .display, .settings })[row];
}
pub fn menuHint(self: *App, row: usize) ?[]const u8 {
if (self.menuBuiltin() != .none) return if (row == 0) "ENTER" else null;
return if (self.menu_icon != null)
([_]?[]const u8{ "ENTER", null, "CTRL+X", "CTRL+C", "F2", "DELETE", null, null })[row]
- else if (row == 4) "CTRL+V" else null;
+ else if (row == 3) "CTRL+V" else null;
}
pub fn untrustedLauncher(self: *const App, index: usize) bool {
@@ -97,21 +97,41 @@ pub fn menuAction(self: *App, row: usize) void {
0 => self.beginEdit(.folder),
1 => self.beginEdit(.file),
2 => self.beginEdit(.add_app),
- 3 => self.beginEdit(.add_file),
- 4 => self.paste(),
- 5 => self.worker.requestRefresh(),
- 6 => self.host.openAppearance() catch |err| switch (err) {
+ 3 => self.paste(),
+ 4 => self.worker.requestRefresh(),
+ 5 => self.host.openAppearance() catch |err| switch (err) {
error.Unsupported => self.worker.enqueue(.{ .kind = .settings, .path = "" }),
else => self.notify("Could not open Appearance: {s}", .{@errorName(err)}),
},
- 7 => self.worker.enqueue(.{ .kind = .settings, .path = "" }),
+ 6 => self.host.openDesktopSettings() catch |err| switch (err) {
+ error.Unsupported => self.worker.enqueue(.{ .kind = .settings, .path = "" }),
+ else => self.notify("Could not open Desktop Settings: {s}", .{@errorName(err)}),
+ },
else => {},
}
}
}
+pub fn closePicker(self: *App) void {
+ if (self.applications) |*picker| picker.deinit();
+ self.applications = null;
+}
+
+pub fn pickerAction(self: *App, action: @import("../files/open_with.zig").Action) void {
+ switch (action) {
+ .cancel => {
+ self.closePicker();
+ self.edit = .none;
+ },
+ .open => self.finishEdit(),
+ .none => {},
+ }
+ self.invalidate();
+}
+
pub fn beginEdit(self: *App, kind: @FieldType(App, "edit")) void {
self.deletion.deinit();
+ self.closePicker();
self.edit = kind;
if (kind == .folder) {
const path = std.fmt.allocPrint(a, "{s}/New Folder", .{self.worker.dir}) catch {
@@ -135,6 +155,7 @@ pub fn beginEdit(self: *App, kind: @FieldType(App, "edit")) void {
if (self.deletion.paths.items.len == 0) self.edit = .none;
return;
}
+ if (kind == .add_app) self.applications = @import("../files/open_with.zig").State.initShortcuts(a, self.catalog);
self.choice = 0;
if (kind == .add_app or kind == .open_with) self.worker.enqueue(.{ .kind = .catalog, .path = "" });
self.edit_text.clearRetainingCapacity();
@@ -184,8 +205,16 @@ pub fn finishEdit(self: *App) void {
self.edit_text.clearRetainingCapacity();
self.edit_text.appendSlice(a, self.rename_editor.value()) catch return;
}
- if ((self.edit == .add_app or self.edit == .open_with) and self.choiceEntry(self.choice) == null) return;
- if (self.edit == .add_file and !std.fs.path.isAbsolute(self.edit_text.items)) return;
+ if (self.edit == .add_app) {
+ const entry = if (self.applications) |*picker| picker.shortcut() orelse return else return;
+ const dest = std.fmt.allocPrint(a, "{s}/{s}", .{ self.worker.dir, std.fs.path.basename(entry.desktop_file_path) }) catch return;
+ defer a.free(dest);
+ self.worker.enqueue(.{ .kind = .copy, .path = entry.desktop_file_path, .value = dest });
+ self.closePicker();
+ self.edit = .none;
+ return;
+ }
+ if (self.edit == .open_with and self.choiceEntry(self.choice) == null) return;
if (self.edit == .file or self.edit == .rename) {
const name = self.edit_text.items;
if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null or std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) return;
@@ -202,27 +231,13 @@ pub fn finishEdit(self: *App) void {
self.deletion.deinit();
return;
}
- if (self.edit == .add_app or self.edit == .open_with) {
+ if (self.edit == .open_with) {
const entry = self.choiceEntry(self.choice) orelse return;
- if (self.edit == .add_app) {
- const dest = std.fmt.allocPrint(a, "{s}/{s}", .{ self.worker.dir, std.fs.path.basename(entry.desktop_file_path) }) catch return;
- defer a.free(dest);
- self.worker.enqueue(.{ .kind = .copy, .path = entry.desktop_file_path, .value = dest });
- } else {
- for (self.icons.items) |ic| {
- if (ic.selected) self.worker.enqueue(.{ .kind = .launch, .path = ic.item.path, .value = entry.exec, .terminal = entry.terminal, .launch_file = true });
- }
+ for (self.icons.items) |ic| {
+ if (ic.selected) self.worker.enqueue(.{ .kind = .launch, .path = ic.item.path, .value = entry.exec, .terminal = entry.terminal, .launch_file = true });
}
return;
}
- if (self.edit == .add_file) {
- const path = self.edit_text.items;
- if (!std.fs.path.isAbsolute(path)) return;
- const dest = std.fmt.allocPrint(a, "{s}/{s}", .{ self.worker.dir, std.fs.path.basename(path) }) catch return;
- defer a.free(dest);
- self.worker.enqueue(.{ .kind = .link, .path = path, .value = dest });
- return;
- }
if (self.edit == .properties) return;
const name = self.edit_text.items;
if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null or std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) return;
diff --git a/src/desktop/app_keyboard.zig b/src/desktop/app_keyboard.zig
index 0a55dc7..7aef172 100644
--- a/src/desktop/app_keyboard.zig
+++ b/src/desktop/app_keyboard.zig
@@ -15,6 +15,7 @@ pub fn keyboardLeft(self: *App, refocusing: bool) void {
if (!refocusing) {
self.menu = false;
self.deletion.deinit();
+ self.closePicker();
self.edit = .none;
}
self.invalidate();
@@ -43,6 +44,29 @@ pub fn key(self: *App, sym: u32, utf8: []const u8) void {
self.deleteAction(self.deletion.key(sym));
return;
}
+ if (self.edit == .add_app) {
+ if (self.applications) |*picker| {
+ // Preserve application search from the desktop's original chooser.
+ if (self.ctrl and (sym == c.XKB_KEY_a or sym == c.XKB_KEY_A)) {
+ self.edit_text.clearRetainingCapacity();
+ picker.search("");
+ } else if (sym == c.XKB_KEY_BackSpace) {
+ if (self.edit_text.items.len > 0) {
+ var n = self.edit_text.items.len - 1;
+ while (n > 0 and self.edit_text.items[n] & 0xc0 == 0x80) n -= 1;
+ self.edit_text.shrinkRetainingCapacity(n);
+ }
+ picker.search(self.edit_text.items);
+ } else if (!self.ctrl and utf8.len > 0 and utf8[0] >= 32 and (sym != c.XKB_KEY_space or self.edit_text.items.len > 0) and self.edit_text.items.len + utf8.len < 255) {
+ self.edit_text.appendSlice(a, utf8) catch {};
+ picker.search(self.edit_text.items);
+ } else {
+ const action = picker.key(sym, self.shift, self.geometry.w, self.geometry.h - self.geometry.bottom);
+ self.pickerAction(action);
+ }
+ }
+ return;
+ }
if (sym == c.XKB_KEY_Escape) {
self.edit = .none;
self.menu = false;
@@ -70,7 +94,7 @@ pub fn key(self: *App, sym: u32, utf8: []const u8) void {
self.choice = 0;
return;
}
- if (self.edit == .add_app or self.edit == .open_with) {
+ if (self.edit == .open_with) {
if (sym == c.XKB_KEY_Down) {
if (self.choiceEntry(self.choice + 1) != null) self.choice += 1;
return;
diff --git a/src/desktop/app_paint.zig b/src/desktop/app_paint.zig
index 480d7e7..d41650c 100644
--- a/src/desktop/app_paint.zig
+++ b/src/desktop/app_paint.zig
@@ -159,7 +159,13 @@ pub fn promptRect(self: *App) ?grid.Rect {
const g = self.deletion.geometry(self.geometry.w, self.geometry.h - self.geometry.bottom);
return .{ .x = @intFromFloat(@floor(g.x)), .y = @intFromFloat(@floor(g.y)), .w = @intFromFloat(@ceil(g.width)), .h = @intFromFloat(@ceil(g.height)) };
}
- if (self.edit == .add_app or self.edit == .open_with) return .{ .x = @divTrunc(self.geometry.w - 480, 2), .y = @divTrunc(self.geometry.h - 360, 2), .w = 480, .h = 360 };
+ if (self.edit == .add_app) {
+ if (self.applications) |*picker| {
+ const r = picker.geometry(self.geometry.w, self.geometry.h - self.geometry.bottom).box;
+ return .{ .x = @intFromFloat(@floor(r.x)), .y = @intFromFloat(@floor(r.y)), .w = @intFromFloat(@ceil(r.x + r.w) - @floor(r.x)), .h = @intFromFloat(@ceil(r.y + r.h) - @floor(r.y)) };
+ }
+ }
+ if (self.edit == .open_with) return .{ .x = @divTrunc(self.geometry.w - 480, 2), .y = @divTrunc(self.geometry.h - 360, 2), .w = 480, .h = 360 };
if (self.edit != .none and self.edit != .folder) return .{ .x = @divTrunc(self.geometry.w - 420, 2), .y = @divTrunc(self.geometry.h - 120, 2), .w = 420, .h = 120 };
if (self.menu) return .{ .x = self.menu_x, .y = self.menu_y, .w = context_menu.width, .h = Menu.height(self.menuLabels().len, self.menu_icon != null) };
return null;
@@ -215,7 +221,9 @@ pub fn paintOverlay(self: *App, cr: *c.cairo_t, now: i64) void {
}, true);
}
}
- if (self.edit == .add_app or self.edit == .open_with) {
+ if (self.edit == .add_app) {
+ if (self.applications) |*picker| picker.drawWindow(@ptrCast(cr), self.geometry.w, self.geometry.h - self.geometry.bottom, self.x, self.y, self.picker_theme, self.worker.io);
+ } else if (self.edit == .open_with) {
const px = @divTrunc(self.geometry.w - 480, 2);
const py = @divTrunc(self.geometry.h - 360, 2);
rounded(cr, px, py, 480, 360, 10);
@@ -247,7 +255,6 @@ pub fn paintOverlay(self: *App, cr: *c.cairo_t, now: i64) void {
c.cairo_fill(cr);
const title: []const u8 = switch (self.edit) {
.properties => "Properties — Escape closes",
- .add_file => "Add File — enter an absolute path, then Enter",
.rename => "Rename — Enter saves, Escape cancels",
.file => "New File — Enter creates",
else => "",
diff --git a/src/desktop/app_pointer.zig b/src/desktop/app_pointer.zig
index ee14470..51c4051 100644
--- a/src/desktop/app_pointer.zig
+++ b/src/desktop/app_pointer.zig
@@ -18,6 +18,17 @@ pub fn motion(self: *App, x: f64, y: f64) void {
}
pub fn pointerMotion(self: *App, x: f64, y: f64) void {
+ if (self.edit == .add_app) {
+ if (self.applications) |*picker| {
+ const w = self.geometry.w;
+ const h = self.geometry.h - self.geometry.bottom;
+ const old_hit = picker.hit(w, h, self.x, self.y);
+ if (picker.motion(w, h, x, y) or old_hit != picker.hit(w, h, x, y)) self.invalidate();
+ }
+ self.x = x;
+ self.y = y;
+ return;
+ }
if (self.edit == .trash) {
if (self.deletion.motion(self.geometry.w, self.geometry.h - self.geometry.bottom, x, y)) self.invalidate();
const g = self.deletion.geometry(self.geometry.w, self.geometry.h - self.geometry.bottom);
@@ -71,6 +82,7 @@ pub fn pointerMotion(self: *App, x: f64, y: f64) void {
pub fn leave(self: *App) void {
self.deletion.placement.grab = null;
+ if (self.applications) |*picker| picker.placement.grab = null;
if (self.hover != null) {
self.damageIcon(self.hover.?);
self.hover = null;
@@ -101,6 +113,20 @@ pub fn button(self: *App, button_code: u32, pressed: bool) void {
pub fn pointerButton(self: *App, button_code: u32, pressed: bool) void {
self.invalidate();
+ if (self.edit == .add_app) {
+ if (button_code == 272) {
+ if (self.applications) |*picker| {
+ const w = self.geometry.w;
+ const h = self.geometry.h - self.geometry.bottom;
+ if (picker.pointerButton(w, h, self.x, self.y, pressed)) return;
+ if (pressed) {
+ const action = picker.click(w, h, self.x, self.y);
+ self.pickerAction(action);
+ }
+ }
+ }
+ return;
+ }
if (self.edit == .trash and button_code == 272 and self.deletion.pointerButton(self.geometry.w, self.geometry.h - self.geometry.bottom, self.x, self.y, pressed)) return;
if (self.renameGeometry()) |g| {
if (button_code != 272) return;
@@ -144,7 +170,7 @@ pub fn pointerButton(self: *App, button_code: u32, pressed: bool) void {
return;
}
if (self.edit != .none) {
- if (button_code == 272 and (self.edit == .add_app or self.edit == .open_with)) {
+ if (button_code == 272 and self.edit == .open_with) {
const px = @divTrunc(self.geometry.w - 480, 2);
const py = @divTrunc(self.geometry.h - 360, 2);
if (self.x >= @as(f64, @floatFromInt(px)) and self.x < @as(f64, @floatFromInt(px + 480)) and self.y >= @as(f64, @floatFromInt(py + 64))) {
diff --git a/src/desktop/app_tests.zig b/src/desktop/app_tests.zig
index 84b95ca..c414d89 100644
--- a/src/desktop/app_tests.zig
+++ b/src/desktop/app_tests.zig
@@ -24,6 +24,40 @@ test "button release does not cancel the launch triggered by its press" {
try std.testing.expectEqual(@as(i64, 30000), app.launching_until);
}
+test "desktop shortcut picker searches, confirms separately and cancels without work" {
+ const picker = @import("../files/open_with.zig");
+ const entries = [_]@import("dotdesktop.zig").parser.AppEntry{
+ .{ .id = "first.desktop", .desktop_file_path = "/apps/first.desktop", .name = "First App", .exec = "true" },
+ .{ .id = "second.desktop", .desktop_file_path = "/apps/second.desktop", .name = "Second App", .exec = "true" },
+ };
+ var app = App{ .worker = undefined, .edit = .add_app, .applications = picker.State.initShortcuts(a, &entries) };
+ defer app.deinit();
+ try std.testing.expectEqual(@as(usize, 7), app.menuLabels().len);
+ try std.testing.expectEqualStrings("Paste", app.menuLabels()[3]);
+ try std.testing.expectEqualStrings("CTRL+V", app.menuHint(3).?);
+ app.key(c.XKB_KEY_s, "S");
+ app.key(c.XKB_KEY_e, "e");
+ try std.testing.expectEqualStrings("second.desktop", app.applications.?.shortcut().?.id);
+ app.key(c.XKB_KEY_space, " ");
+ try std.testing.expect(app.applications.?.shortcut() == null);
+ // An empty result cannot enqueue work, even on confirmation.
+ app.key(c.XKB_KEY_Return, "");
+ try std.testing.expectEqual(.add_app, app.edit);
+ app.ctrl = true;
+ app.key(c.XKB_KEY_a, "");
+ app.ctrl = false;
+ const g = app.applications.?.geometry(app.geometry.w, app.geometry.h - app.geometry.bottom);
+ app.motion(g.box.x + g.list.x + 20, g.box.y + g.list.y + 40);
+ app.button(272, true);
+ app.button(272, false);
+ try std.testing.expectEqualStrings("second.desktop", app.applications.?.shortcut().?.id);
+ try std.testing.expectEqual(.add_app, app.edit);
+ app.key(c.XKB_KEY_Tab, "");
+ app.key(c.XKB_KEY_Return, "");
+ try std.testing.expectEqual(.none, app.edit);
+ try std.testing.expect(app.applications == null);
+}
+
test "desktop pointer motion repaints only when visible state changes" {
var icons = [_]Icon{.{ .item = .{ .path = "", .name = "", .icon = null }, .cell = .{}, .born = 0 }};
var app = App{ .worker = undefined, .icons = .{ .items = &icons, .capacity = icons.len }, .dirty = false };
diff --git a/src/desktop/embedded.zig b/src/desktop/embedded.zig
index bb9a856..44407ff 100644
--- a/src/desktop/embedded.zig
+++ b/src/desktop/embedded.zig
@@ -402,6 +402,7 @@ pub const Desktop = struct {
if (c.cairo_status(cr) != c.CAIRO_STATUS_SUCCESS) return error.CairoFailed;
c.cairo_scale(cr, self.scale, self.scale);
c.cairo_translate(cr, -@as(f64, @floatFromInt(rect.x)), -@as(f64, @floatFromInt(rect.y)));
+ self.app.picker_theme = self.server.icon_theme_cfg;
self.app.paintOverlay(cr, app_mod.nowMs());
c.cairo_surface_flush(surface);
const opening = self.overlay_rect == null;
@@ -527,6 +528,15 @@ pub const Desktop = struct {
self.schedule();
}
+ pub fn scroll(self: *Desktop, delta: f64) void {
+ if (self.app.edit != .add_app) return;
+ if (self.app.applications) |*picker| {
+ picker.wheel(delta, self.app.geometry.w, self.app.geometry.h - self.app.geometry.bottom);
+ self.app.invalidate();
+ self.schedule();
+ }
+ }
+
/// Whether `Keyboard` repeats a held key into the desktop.
pub fn keyRepeats(self: *Desktop, sym: u32, utf8: []const u8) bool {
self.syncModifiers();
@@ -724,6 +734,14 @@ pub const Desktop = struct {
return false;
}
}.f,
+ .openDesktopSettings = struct {
+ fn f(ctx: ?*anyopaque) anyerror!void {
+ const server = from(ctx).server;
+ const output = server.getDefaultOutput() orelse return;
+ output.toggleControlCenter();
+ if (server.input.open_control_center) |cc| cc.selectPage(.desktop);
+ }
+ }.f,
.openAppearance = struct {
fn f(ctx: ?*anyopaque) anyerror!void {
from(ctx).server.openAppearance();
diff --git a/src/desktop/host.zig b/src/desktop/host.zig
index 1413253..ad67bcc 100644
--- a/src/desktop/host.zig
+++ b/src/desktop/host.zig
@@ -45,6 +45,7 @@ pub const Host = struct {
/// error.Unsupported means the host has no Appearance settings, and
/// the caller opens the desktop's own config file instead.
openAppearance: *const fn (ctx: ?*anyopaque) anyerror!void,
+ openDesktopSettings: *const fn (ctx: ?*anyopaque) anyerror!void,
};
pub fn keyboard(self: Host, wanted: bool) void {
@@ -72,6 +73,10 @@ pub const Host = struct {
return self.vtable.openAppearance(self.ctx);
}
+ pub fn openDesktopSettings(self: Host) anyerror!void {
+ return self.vtable.openDesktopSettings(self.ctx);
+ }
+
/// Displays nothing and knows nothing: unit tests, and the app before a
/// host attaches.
pub const none: Host = .{};
@@ -107,6 +112,11 @@ const none_vtable: Host.VTable = .{
return false;
}
}.f,
+ .openDesktopSettings = struct {
+ fn f(_: ?*anyopaque) anyerror!void {
+ return error.Unsupported;
+ }
+ }.f,
.openAppearance = struct {
fn f(_: ?*anyopaque) anyerror!void {
return error.Unsupported;
diff --git a/src/desktop/menu.zig b/src/desktop/menu.zig
index ccc7c6f..f1e2c7d 100644
--- a/src/desktop/menu.zig
+++ b/src/desktop/menu.zig
@@ -6,7 +6,7 @@ pub const Menu = struct {
rows: [8]ui.Widget = undefined,
count: usize = 0,
pub fn separatorBefore(icon: bool, row: usize) bool {
- return if (icon) row == 2 or row == 6 else row == 4 or row == 6;
+ return if (icon) row == 2 or row == 6 else row == 3 or row == 5;
}
pub fn height(count: usize, icon: bool) i32 {
var result: i32 = @intCast(count * appearance.row_height + 2 * appearance.padding);
diff --git a/src/desktop/watcher.zig b/src/desktop/watcher.zig
index aa08071..a00020f 100644
--- a/src/desktop/watcher.zig
+++ b/src/desktop/watcher.zig
@@ -499,7 +499,15 @@ pub const Worker = struct {
}
},
.catalog => {
- if (self.catalog.len == 0) self.catalog = (try desktop.parser.scanAll(self.catalog_arena.allocator(), self.io, self.environ)).entries;
+ if (self.catalog.len == 0) {
+ const entries = (try desktop.parser.scanAll(self.catalog_arena.allocator(), self.io, self.environ)).entries;
+ std.mem.sort(desktop.parser.AppEntry, entries, {}, struct {
+ fn less(_: void, lhs: desktop.parser.AppEntry, rhs: desktop.parser.AppEntry) bool {
+ return std.ascii.lessThanIgnoreCase(lhs.name, rhs.name);
+ }
+ }.less);
+ self.catalog = entries;
+ }
},
.settings => {
const path = try std.fmt.allocPrint(a, "{s}/config.toml", .{std.fs.path.dirname(self.layout).?});
diff --git a/src/files/associations.zig b/src/files/associations.zig
index 65e2a63..5a73f44 100644
--- a/src/files/associations.zig
+++ b/src/files/associations.zig
@@ -94,6 +94,13 @@ extern fn g_app_info_get_display_name(app: *anyopaque) [*:0]const u8;
extern fn g_app_info_supports_files(app: *anyopaque) c_int;
extern fn g_app_info_supports_uris(app: *anyopaque) c_int;
extern fn g_app_info_set_as_default_for_type(app: *anyopaque, content_type: [*:0]const u8, err: ?*?*anyopaque) c_int;
+extern fn g_content_type_equals(a: [*:0]const u8, b: [*:0]const u8) c_int;
+extern fn g_get_user_config_dir() [*:0]const u8;
+extern fn g_key_file_new() *anyopaque;
+extern fn g_key_file_unref(key_file: *anyopaque) void;
+extern fn g_key_file_load_from_file(key_file: *anyopaque, filename: [*:0]const u8, flags: c_int, err: ?*?*anyopaque) c_int;
+extern fn g_key_file_get_keys(key_file: *anyopaque, group: [*:0]const u8, length: ?*usize, err: ?*?*anyopaque) ?[*:null]?[*:0]u8;
+extern fn g_strfreev(strings: ?[*:null]?[*:0]u8) void;
extern fn g_file_new_for_path(path: [*:0]const u8) *anyopaque;
extern fn g_app_info_launch(app: *anyopaque, files: ?*List, context: ?*anyopaque, err: ?*?*anyopaque) c_int;
@@ -170,6 +177,29 @@ pub const Applications = struct {
self.arena.deinit();
}
+ fn saveDefault(self: *Applications, app: *anyopaque) !void {
+ // GIO merges aliases in file order when reading defaults, but its
+ // setter updates only the exact key. An older video/x-matroska entry
+ // can therefore override a newly saved video/matroska preference.
+ const a = self.arena.child_allocator;
+ const filename = try std.fmt.allocPrintSentinel(a, "{s}/mimeapps.list", .{g_get_user_config_dir()}, 0);
+ defer a.free(filename);
+ const key_file = g_key_file_new();
+ defer g_key_file_unref(key_file);
+ if (g_key_file_load_from_file(key_file, filename, 0, null) != 0) {
+ if (g_key_file_get_keys(key_file, "Default Applications", null, null)) |keys| {
+ defer g_strfreev(keys);
+ var i: usize = 0;
+ while (keys[i]) |key| : (i += 1) {
+ if (std.mem.eql(u8, std.mem.span(key), self.content_type)) continue;
+ if (g_content_type_equals(key, self.content_type) == 0) continue;
+ if (g_app_info_set_as_default_for_type(app, key, null) == 0) return error.DefaultFailed;
+ }
+ }
+ }
+ if (g_app_info_set_as_default_for_type(app, self.content_type, null) == 0) return error.DefaultFailed;
+ }
+
pub fn launch(self: *Applications, index: usize, remember: bool) !void {
const app = self.entries.items[index].app;
const a = self.arena.child_allocator;
@@ -182,7 +212,7 @@ pub const Applications = struct {
};
defer for (files) |file| g_object_unref(file.data);
if (g_app_info_launch(app, if (files.len > 0) &files[0] else null, null, null) == 0) return error.LaunchFailed;
- if (remember and self.same_type and g_app_info_set_as_default_for_type(app, self.content_type, null) == 0) return error.DefaultFailed;
+ if (remember and self.same_type) self.saveDefault(app) catch return error.DefaultFailed;
}
};
diff --git a/src/files/open_with.zig b/src/files/open_with.zig
index c7c94e5..dd962f8 100644
--- a/src/files/open_with.zig
+++ b/src/files/open_with.zig
@@ -1,4 +1,4 @@
-//! Files' modal application picker. Geometry is shared by painting and input.
+//! Shared modal application picker for Open With and desktop shortcuts. Geometry is shared by painting and input.
const std = @import("std");
const associations = @import("associations.zig");
const c = @import("c.zig").api;
@@ -12,6 +12,7 @@ const checkbox = @import("ui").widgets.checkbox;
const icons = @import("../icon_cache.zig");
const icon_theme = @import("../icon_theme.zig");
const Rect = ui.Rect;
+const AppEntry = @import("../start_menu/applications.zig").AppEntry;
pub const Action = enum { none, cancel, open };
const Focus = enum { list, more, remember, cancel, open };
@@ -30,12 +31,16 @@ pub const Geometry = struct {
rows: usize,
pub fn init(w: i32, h: i32, count: usize) Geometry {
+ return initMode(w, h, count, false);
+ }
+
+ fn initMode(w: i32, h: i32, count: usize, shortcut: bool) Geometry {
const width: f32 = @min(480, @as(f32, @floatFromInt(w)) - 24);
const header: f32 = @floatFromInt((chrome.Metrics{}).titlebarHeight());
- const height: f32 = @min(@min(500, header + 236 + @as(f32, @floatFromInt(@max(1, count))) * row_height), @as(f32, @floatFromInt(h)) - 16);
+ const height: f32 = @min(@min(500, header + @as(f32, if (shortcut) 140 else 236) + @as(f32, @floatFromInt(@max(1, count))) * row_height), @as(f32, @floatFromInt(h)) - 16);
const compact = height < header + 290;
const list_y = header + @as(f32, if (compact) 34 else 64);
- const rows: usize = @intFromFloat(@max(1, @floor((height - @as(f32, if (compact) 112 else 172) - list_y) / row_height)));
+ const rows: usize = @intFromFloat(@max(1, @floor((height - @as(f32, if (shortcut) 70 else if (compact) 112 else 172) - list_y) / row_height)));
const more_y = height - @as(f32, if (compact) 100 else 140);
const small: f32 = if (compact) 26 else 30;
const button_y = height - @as(f32, if (compact) 42 else 58);
@@ -45,8 +50,8 @@ pub const Geometry = struct {
.list = .{ .x = 16, .y = list_y, .w = width - 32, .h = @as(f32, @floatFromInt(rows)) * row_height },
.more = .{ .x = 16, .y = more_y, .w = width - 32, .h = small },
.remember = .{ .x = 16, .y = height - @as(f32, if (compact) 72 else 102), .w = width - 32, .h = small },
- .cancel = .{ .x = width - 188, .y = button_y, .w = 80, .h = button_h },
- .open = .{ .x = width - 100, .y = button_y, .w = 84, .h = button_h },
+ .cancel = .{ .x = width - @as(f32, if (shortcut) 228 else 188), .y = button_y, .w = 80, .h = button_h },
+ .open = .{ .x = width - @as(f32, if (shortcut) 140 else 100), .y = button_y, .w = if (shortcut) 124 else 84, .h = button_h },
.close = frame.closeBox(width),
.divider = more_y - @as(f32, if (compact) 8 else 18),
.rows = rows,
@@ -57,6 +62,9 @@ pub const Geometry = struct {
pub const State = struct {
placement: frame.Placement = .{},
apps: associations.Applications,
+ /// Borrowed from the desktop worker, whose catalogue outlives the picker.
+ shortcut_catalog: ?[]const AppEntry = null,
+ query: []const u8 = "",
selected: usize = 0,
offset: usize = 0,
all: bool = false,
@@ -64,18 +72,51 @@ pub const State = struct {
focus: Focus = .list,
message: []const u8 = "",
+ fn baseGeometry(self: *const State, w: i32, h: i32) Geometry {
+ // Filtering keeps the card still while the user types.
+ const layout_count = if (self.shortcut_catalog) |catalog| catalog.len else self.count();
+ return Geometry.initMode(w, h, layout_count, self.shortcut_catalog != null);
+ }
+
+ pub fn initShortcuts(allocator: std.mem.Allocator, catalog: []const AppEntry) State {
+ return .{ .apps = .{ .arena = std.heap.ArenaAllocator.init(allocator) }, .shortcut_catalog = catalog, .all = true };
+ }
+
+ pub fn shortcut(self: *const State) ?AppEntry {
+ return self.shortcutAt(self.selected);
+ }
+
+ fn shortcutAt(self: *const State, index: usize) ?AppEntry {
+ const catalog = self.shortcut_catalog orelse return null;
+ var n: usize = 0;
+ for (catalog) |entry| {
+ if (std.ascii.indexOfIgnoreCase(entry.name, self.query) == null) continue;
+ if (n == index) return entry;
+ n += 1;
+ }
+ return null;
+ }
+
+ /// The query borrows the desktop editor's storage until the next update.
+ pub fn search(self: *State, query: []const u8) void {
+ self.query = query;
+ self.selected = 0;
+ self.offset = 0;
+ self.focus = .list;
+ }
+
pub fn geometry(self: *const State, w: i32, h: i32) Geometry {
- var g = Geometry.init(w, h, self.count());
+ var g = self.baseGeometry(w, h);
g.box = self.placement.box(g.box, w, h);
return g;
}
pub fn pointerButton(self: *State, w: i32, h: i32, x: f64, y: f64, pressed: bool) bool {
- return self.placement.button(Geometry.init(w, h, self.count()).box, w, h, x, y, pressed);
+ return self.placement.button(self.baseGeometry(w, h).box, w, h, x, y, pressed);
}
pub fn motion(self: *State, w: i32, h: i32, x: f64, y: f64) bool {
- return self.placement.motion(Geometry.init(w, h, self.count()).box, w, h, x, y);
+ return self.placement.motion(self.baseGeometry(w, h).box, w, h, x, y);
}
pub fn init(a: std.mem.Allocator, paths: []const []const u8) !State {
@@ -88,6 +129,13 @@ pub const State = struct {
}
fn count(self: *const State) usize {
+ if (self.shortcut_catalog) |catalog| {
+ var n: usize = 0;
+ for (catalog) |entry| {
+ if (std.ascii.indexOfIgnoreCase(entry.name, self.query) != null) n += 1;
+ }
+ return n;
+ }
return if (self.all) self.apps.entries.items.len else self.apps.recommended;
}
@@ -110,8 +158,9 @@ pub const State = struct {
const rows = self.geometry(w, h).rows;
if (sym == c.XKB_KEY_Escape) return .cancel;
if (sym == c.XKB_KEY_Tab or sym == c.XKB_KEY_ISO_Left_Tab) {
- const n = @typeInfo(Focus).@"enum".fields.len;
- self.focus = @enumFromInt((@intFromEnum(self.focus) + @as(usize, if (shift or sym == c.XKB_KEY_ISO_Left_Tab) n - 1 else 1)) % n);
+ const focuses: []const Focus = if (self.shortcut_catalog != null) &.{ .list, .cancel, .open } else &.{ .list, .more, .remember, .cancel, .open };
+ const index = std.mem.indexOfScalar(Focus, focuses, self.focus) orelse 0;
+ self.focus = focuses[(index + (if (shift or sym == c.XKB_KEY_ISO_Left_Tab) focuses.len - 1 else @as(usize, 1))) % focuses.len];
} else if (sym == c.XKB_KEY_Up or sym == c.XKB_KEY_Down or sym == c.XKB_KEY_Home or sym == c.XKB_KEY_End or sym == c.XKB_KEY_Page_Up or sym == c.XKB_KEY_Page_Down) {
self.focus = .list;
if (sym == c.XKB_KEY_Up) self.selected -|= 1;
@@ -121,7 +170,7 @@ pub const State = struct {
if (sym == c.XKB_KEY_Page_Up) self.selected -|= rows;
if (sym == c.XKB_KEY_Page_Down) self.selected = @min(self.selected + rows, self.count() -| 1);
self.reveal(rows);
- } else if (sym == c.XKB_KEY_Return or sym == c.XKB_KEY_space) {
+ } else if (sym == c.XKB_KEY_Return or sym == c.XKB_KEY_KP_Enter or sym == c.XKB_KEY_space) {
switch (self.focus) {
.list, .open => if (self.count() > 0) return .open,
.cancel => return .cancel,
@@ -141,8 +190,8 @@ pub const State = struct {
if (contains(g.close, px, py)) return 1;
if (contains(g.cancel, px, py)) return 2;
if (contains(g.open, px, py)) return 3;
- if (contains(g.more, px, py)) return 4;
- if (contains(g.remember, px, py)) return 5;
+ if (self.shortcut_catalog == null and contains(g.more, px, py)) return 4;
+ if (self.shortcut_catalog == null and contains(g.remember, px, py)) return 5;
if (contains(g.list, px, py)) {
const row = @as(usize, @intFromFloat((py - g.list.y) / row_height)) + self.offset;
if (row < self.count()) return 10 + row;
@@ -174,6 +223,7 @@ pub const State = struct {
}
pub fn open(self: *State) bool {
+ if (self.shortcut_catalog != null) return false;
if (self.selected >= self.count()) return false;
self.apps.launch(self.selected, self.remember) catch |err| {
self.message = if (err == error.DefaultFailed) "Opened, but could not save the default app" else "Could not open with this app. Choose another.";
@@ -183,10 +233,20 @@ pub const State = struct {
}
pub fn draw(self: *State, cr: *c.cairo_t, w: i32, h: i32, mx: f64, my: f64, cfg: icon_theme.Config, io: std.Io) void {
+ self.drawImpl(cr, w, h, mx, my, cfg, io, true);
+ }
+
+ pub fn drawWindow(self: *State, cr: *c.cairo_t, w: i32, h: i32, mx: f64, my: f64, cfg: icon_theme.Config, io: std.Io) void {
+ self.drawImpl(cr, w, h, mx, my, cfg, io, false);
+ }
+
+ fn drawImpl(self: *State, cr: *c.cairo_t, w: i32, h: i32, mx: f64, my: f64, cfg: icon_theme.Config, io: std.Io, backdrop: bool) void {
const g = self.geometry(w, h);
self.offset = @min(self.offset, self.count() -| g.rows);
- @import("ui").cairo.setSource(cr, frame.backdropColor());
- c.cairo_paint(cr);
+ if (backdrop) {
+ ui.setSource(cr, frame.backdropColor());
+ c.cairo_paint(cr);
+ }
var layer = ui.Layer.begin(cr, g.box) orelse return;
defer layer.finish();
const r = &layer.renderer;
@@ -197,16 +257,24 @@ pub const State = struct {
palette.button_font_size = ui.textSize();
r.palette = palette;
frame.paintWindowFrame(r, layer.local(), theme.global.app_toolbar);
- frame.paintWindowTitle(r, layer.local(), "Open With", .grid, null);
+ frame.paintWindowTitle(r, layer.local(), if (self.shortcut_catalog != null) "Add Application Shortcut" else "Open With", .grid, null);
var buffer: [256]u8 = undefined;
- const subtitle = if (self.message.len > 0) self.message else if (self.apps.paths.len == 1) std.fs.path.basename(self.apps.paths[0]) else std.fmt.bufPrint(&buffer, "{d} selected files", .{self.apps.paths.len}) catch "Selected files";
+ const subtitle = if (self.message.len > 0) self.message else if (self.shortcut_catalog != null) (if (self.query.len > 0) std.fmt.bufPrint(&buffer, "Search: {s}", .{self.query}) catch self.query else "Choose an application to add to the desktop") else if (self.apps.paths.len == 1) std.fs.path.basename(self.apps.paths[0]) else std.fmt.bufPrint(&buffer, "{d} selected files", .{self.apps.paths.len}) catch "Selected files";
if (g.list.y - @as(f32, @floatFromInt((chrome.Metrics{}).titlebarHeight())) > 50) r.drawText(16, g.list.y - 50, g.box.w - 32, 20, .{ .content = subtitle, .font_size = ui.textSize(), .color = palette.fg });
r.drawText(16, g.list.y - 26, g.box.w - 32, 20, .{ .content = if (self.all) "All Applications" else "Recommended Apps", .font_size = ui.headingSize(), .weight = 600, .color = palette.fg });
const hovered = self.hit(w, h, mx, my);
if (self.count() == 0) r.drawText(24, g.list.y, g.list.w - 16, row_height, .{ .content = "No applications available", .font_size = ui.textSize(), .color = palette.fg });
const end = @min(self.count(), self.offset + g.rows);
for (self.offset..end) |i| {
- const entry = self.apps.entries.items[i];
+ var shortcut_icons: [1][]const u8 = undefined;
+ const entry: struct { name: []const u8, icons: []const []const u8, is_default: bool } = if (self.shortcut_catalog != null) blk: {
+ const app = self.shortcutAt(i) orelse continue;
+ if (app.icon) |name| shortcut_icons[0] = name;
+ break :blk .{ .name = app.name, .icons = if (app.icon != null) &shortcut_icons else &.{}, .is_default = false };
+ } else blk: {
+ const app = self.apps.entries.items[i];
+ break :blk .{ .name = app.name, .icons = app.icons, .is_default = app.is_default };
+ };
const y = g.list.y + @as(f32, @floatFromInt(i - self.offset)) * row_height;
if (i == self.selected or hovered == 10 + i) r.fillRect(g.list.x, y, g.list.w, row_height - 2, .{
.color = if (i == self.selected) theme.global.app_nav_selected else theme.global.app_item_hover,
@@ -226,16 +294,18 @@ pub const State = struct {
const strip = scrollbar.gutter(theme.global.scrollbar_width);
if (scrollbar.Geometry.compute(.vertical, .{ .x = g.box.w - strip, .y = g.list.y, .w = strip, .h = g.list.h }, @floatFromInt(g.rows), @floatFromInt(self.count()), @floatFromInt(self.offset))) |bar|
scrollbar.paint(r, scrollbar.look(bar, .{}, theme.global.scrollbar_width, palette));
- r.fillRect(16, g.divider, g.box.w - 32, 1, .{ .color = theme.global.app_divider });
- button.paint(r, g.more, .{ .size = .sm, .variant = .ghost, .alignment = .left, .leading_icon = .plus, .label = if (self.all) "Back to recommended apps" else "Choose another app…" }, .{ .focused = self.focus == .more, .pointer = if (hovered == 4) .hover else .idle });
- const extension = std.fs.path.extension(self.apps.paths[0]);
- const remember_label = if (extension.len > 0 and self.apps.paths.len == 1)
- std.fmt.bufPrint(&buffer, "Always use this app for {s} files", .{extension}) catch "Always use this app for this file type"
- else
- "Always use this app for this file type";
- checkbox.paint(r, g.remember, remember_label, .{ .checked = self.remember, .focused = self.focus == .remember, .disabled = !self.apps.same_type or self.count() == 0 });
+ if (self.shortcut_catalog == null) {
+ r.fillRect(16, g.divider, g.box.w - 32, 1, .{ .color = theme.global.app_divider });
+ button.paint(r, g.more, .{ .size = .sm, .variant = .ghost, .alignment = .left, .leading_icon = .plus, .label = if (self.all) "Back to recommended apps" else "Choose another app…" }, .{ .focused = self.focus == .more, .pointer = if (hovered == 4) .hover else .idle });
+ const extension = std.fs.path.extension(self.apps.paths[0]);
+ const remember_label = if (extension.len > 0 and self.apps.paths.len == 1)
+ std.fmt.bufPrint(&buffer, "Always use this app for {s} files", .{extension}) catch "Always use this app for this file type"
+ else
+ "Always use this app for this file type";
+ checkbox.paint(r, g.remember, remember_label, .{ .checked = self.remember, .focused = self.focus == .remember, .disabled = !self.apps.same_type or self.count() == 0 });
+ }
button.paint(r, g.cancel, .{ .size = .sm, .label = "Cancel" }, .{ .focused = self.focus == .cancel, .pointer = if (hovered == 2) .hover else .idle });
- button.paint(r, g.open, .{ .size = .sm, .label = "Open", .variant = .primary }, .{ .focused = self.focus == .open, .pointer = if (self.count() == 0) .disabled else if (hovered == 3) .hover else .idle });
+ button.paint(r, g.open, .{ .size = .sm, .label = if (self.shortcut_catalog != null) "Add Shortcut" else "Open", .variant = .primary }, .{ .focused = self.focus == .open, .pointer = if (self.count() == 0) .disabled else if (hovered == 3) .hover else .idle });
button.paint(r, g.close, .{ .icon = .close, .variant = .chrome, .label = "Close" }, .{ .pointer = if (hovered == 1) .hover else .idle });
}
};
diff --git a/src/input/axis.zig b/src/input/axis.zig
index 82cd83f..9c1c5a2 100644
--- a/src/input/axis.zig
+++ b/src/input/axis.zig
@@ -146,6 +146,10 @@ pub fn processAxis(
// Detented wheel clicks glide in shell panels; touchpads are already smooth.
const notch = source == .wheel and delta_discrete != 0;
switch (scroll_hit) {
+ .desktop => |hit| {
+ if (orientation == .vertical_scroll) hit.desktop.scroll(delta);
+ return;
+ },
.wifi_popup => |hit| {
if (orientation == .vertical_scroll) hit.popup.scrollWheel(ui_scroll.axisDeltaPx(delta, delta_discrete));
return;
diff --git a/tests/desktop_icons.py b/tests/desktop_icons.py
index f975721..d0dc2bc 100644
--- a/tests/desktop_icons.py
+++ b/tests/desktop_icons.py
@@ -368,12 +368,26 @@ def run():
assert (desktop/'New Folder').is_dir()
assert (desktop/'New Folder (2)').read_text() == 'existing file'
assert not (desktop/'New Folder (3)').exists()
- # Installed desktop entries populate the Add Application chooser.
+ # Add Application uses the shared Open With card: selecting a row
+ # needs confirmation, and Cancel must not create a shortcut.
click(600,300,273);click(640,375)
action('type_text',{'text':'RediWM Test Fixture'})
time.sleep(.8)
+ assert not (desktop/'rediwm-test.desktop').exists()
+ key(15);key(28) # Tab from the list to Cancel.
+ assert not (desktop/'rediwm-test.desktop').exists(), 'Cancel added a launcher'
+ click(600,300,273);click(640,375)
+ action('type_text',{'text':'No such installed application'})
+ key(28)
+ assert not list(desktop.glob('*.desktop')), 'empty search added an application'
+ action('key', {'keycode':29,'pressed':True}) # Clear the search using Ctrl+A.
+ key(30)
+ action('key',{'keycode':29,'pressed':False})
+ action('type_text',{'text':'RediWM Test Fixture'})
+ time.sleep(.2)
key(28)
wait_for(lambda: (desktop/'rediwm-test.desktop').exists(),'application chooser did not add the launcher')
+ assert (desktop/'rediwm-test.desktop').read_bytes() == (applications/'rediwm-test.desktop').read_bytes()
# Remove fixture icons before transfer checks.
for path in desktop.iterdir():
if path.is_dir():path.rmdir()
@@ -411,7 +425,7 @@ def run():
key(1)
# Escape releases keyboard focus, so use menu Paste to reacquire it.
click(1000,400,273)
- click(1050,541) # Paste follows four 32px rows, 6px padding and a 7px separator in the clamped menu.
+ key(108);key(108);key(108);key(28) # Paste follows the three creation actions.
wait_for(lambda: (desktop/original.name).is_file(),'clipboard paste failed')
assert not (desktop/original.name).is_symlink()
assert (desktop/original.name).read_text()=='transfer fixture'