Skip to content

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

file manager terminal drawer

oxydizerb1c22d4cee2c
diff --git a/README.md b/README.md
index 81a6339..e1f44a8 100644
--- a/README.md
+++ b/README.md
@@ -56,7 +56,8 @@ Installing never replaces your login manager
Requirements: Zig 0.16, wlroots 0.20, and the development files for Wayland,
wayland-protocols, xkbcommon, pixman, FreeType, HarfBuzz, Fontconfig,
librsvg/GdkPixbuf, PangoCairo, libinput, PAM, libpulse, libpipewire-0.3, Poppler GLib,
-libseccomp, libarchive, libjpeg, libpng and libwebp. Optional:
+libseccomp, libarchive, libjpeg, libpng, libwebp and GNU Readline. Files embeds
+the pinned libvterm 0.3.3 source (downloaded by Zig; no system libvterm needed). Optional:
Xwayland, `foot`, `brightnessctl`, `gio`/`xdg-open`, `git` (optional).
Printer support uses an existing CUPS server (`cups`). Installing the optional
@@ -218,6 +219,7 @@ older canvas save while in workspace mode updates the saved return-to-canvas sta
- **Desktop icons:** a `.desktop` launcher only runs if it's installed, root-owned, executable, or an exact copy of an installed entry. Otherwise, choose **Allow Launching** from its menu.
- **`rediwm-dm`:** disable your current display manager, run `sudo systemctl enable rediwm-dm`, and reboot. Options are in `/etc/rediwm/dm.conf`.
- **Text editor:** `rediwm-editor [FILE ...]` opens UTF-8 files in tabs, from tiny notes to logs of hundreds of megabytes (up to 4 GiB, if they fit in free memory). Ctrl+N new, Ctrl+O open, Ctrl+S save, Ctrl+Shift+S save as, Ctrl+W close tab, Ctrl+PgUp/PgDn switch tabs, Ctrl+F or F3 find. In `rediwm-files`, Space previews images, PDFs and text.
+- **Files terminal:** F4 or the terminal button opens a resizable drawer below the file list. Hiding it keeps commands running; each Files window owns its own session. Bash follows folder navigation at an empty prompt and defers it while editing or running a command. Ctrl+Shift+C/V copies and pastes; Shift overrides application mouse reporting for selection. The header also opens your configured external terminal. See [terminal support](docs/files-terminal.md) for shell support and limits.
- **Games and VMs:** games get pointer lock and relative motion. If a VM or remote desktop grabs your shortcuts, Super+Escape takes them back.
- **Known issues (wlroots 0.20):** X11→Wayland drag-and-drop doesn't start, and X11 pointer input on a second output doesn't arrive.
diff --git a/TESTING.md b/TESTING.md
index 98e294f..dd24b2f 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -318,6 +318,8 @@ also be launched with `rediwm-files --open`, `--save` or `--folder`; it returns
a JSON result on stdout.
**Desktop, Files, Images**: `desktop_icons.py`, `desktop_damage.py`,
+`zig build test-files-terminal` (Files units plus isolated Bash/PTY and real drawer tests;
+also `python3 tests/files_terminal.py` after building; supports `REDIWM_TEST_SCALE=1.5`),
`files_browser.py` (file-path selection; with `REDIWM_FORCE_DBUS=1` on a private
`dbus-run-session` bus, also checks `FileManager1.ShowItems`), `files_controls.py`, `files_decoration.py`,
`files_controls.py --places-only` isolates navigation, Recent history and sidebar
diff --git a/assets/icons/terminal.svg b/assets/icons/terminal.svg
new file mode 100644
index 0000000..aa77a1e
--- /dev/null
+++ b/assets/icons/terminal.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="4" width="19" height="16" rx="2"/><path d="m6.5 9 3.5 3-3.5 3M13 15h4"/></svg>
diff --git a/build.zig b/build.zig
index f696451..0547002 100644
--- a/build.zig
+++ b/build.zig
@@ -194,6 +194,9 @@ pub fn build(b: *std.Build) void {
files.root_module.linkSystemLibrary("libarchive", .{});
addThumbCodec(b, files.root_module);
addVolumes(b, files.root_module);
+ addFilesTerminal(b, files.root_module, false);
+ const terminal_license = b.addInstallFileWithDir(b.dependency("vterm", .{}).path("LICENSE"), .prefix, "share/licenses/rediwm/libvterm-LICENSE");
+ b.getInstallStep().dependOn(&terminal_license.step);
const install_files = b.addInstallArtifact(files, .{});
// Advertises rediwm-files to the start menu's applications scanner
// (src/start_menu/applications.zig) and to any other XDG-aware
@@ -217,6 +220,26 @@ pub fn build(b: *std.Build) void {
const files_step = b.step("files", "Build the standalone Files and image viewer clients");
files_step.dependOn(&install_files.step);
files_step.dependOn(&install_files_desktop_entry.step);
+ files_step.dependOn(&terminal_license.step);
+ const terminal_child = b.addExecutable(.{
+ .name = "rediwm-files-terminal",
+ .root_module = b.createModule(.{ .target = target, .optimize = optimize, .link_libc = true }),
+ });
+ terminal_child.root_module.addCSourceFile(.{ .file = b.path("src/files/terminal/child.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ terminal_child.root_module.linkSystemLibrary("gio-2.0", .{});
+ const install_terminal = b.addInstallArtifact(terminal_child, .{});
+ b.getInstallStep().dependOn(&install_terminal.step);
+ files_step.dependOn(&install_terminal.step);
+ const bash_hook = b.addLibrary(.{
+ .name = "rediwm-files-bash",
+ .linkage = .dynamic,
+ .root_module = b.createModule(.{ .target = target, .optimize = .ReleaseFast, .link_libc = true, .sanitize_c = .off }),
+ });
+ bash_hook.root_module.addCSourceFile(.{ .file = b.path("src/files/terminal/bash.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ bash_hook.root_module.linkSystemLibrary("readline", .{});
+ const install_bash = b.addInstallArtifact(bash_hook, .{ .dest_dir = .{ .override = .lib }, .dest_sub_path = "rediwm/files-bash.so", .dylib_symlinks = false });
+ b.getInstallStep().dependOn(&install_bash.step);
+ files_step.dependOn(&install_bash.step);
const images = b.addExecutable(.{
.name = "rediwm-images",
@@ -672,9 +695,17 @@ pub fn build(b: *std.Build) void {
files_tests.root_module.linkSystemLibrary("libarchive", .{});
addThumbCodec(b, files_tests.root_module);
addVolumes(b, files_tests.root_module);
+ addFilesTerminal(b, files_tests.root_module, true);
const run_files_tests = b.addRunArtifact(files_tests);
test_step.dependOn(&run_files_tests.step);
b.step("test-files", "Test Files editing, navigation, transfers and layout").dependOn(&run_files_tests.step);
+ const terminal_integration = b.addSystemCommand(&.{"python3"});
+ terminal_integration.addFileArg(b.path("tests/files_terminal.py"));
+ terminal_integration.setEnvironmentVariable("REDIWM_TEST_BIN", b.getInstallPath(.bin, ""));
+ terminal_integration.step.dependOn(b.getInstallStep());
+ const terminal_tests = b.step("test-files-terminal", "Test the Files terminal against isolated PTYs and a headless compositor");
+ terminal_tests.dependOn(&run_files_tests.step);
+ terminal_tests.dependOn(&terminal_integration.step);
const share_picker_tests = b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/share_picker_tests.zig"),
.target = target,
@@ -855,7 +886,18 @@ fn addThumbCodec(b: *std.Build, module: *std.Build.Module) void {
inline for (.{ "libjpeg", "libpng16" }) |lib| module.linkSystemLibrary(lib, .{});
}
-// Files' device list: a GLib thread speaking to UDisks2 (src/files/volumes.c).
+// Pinned, Files-only emulator. No dependency on the compositor or distro ABI.
+fn addFilesTerminal(b: *std.Build, module: *std.Build.Module, for_tests: bool) void {
+ const vterm = b.dependency("vterm", .{});
+ module.addIncludePath(vterm.path("include"));
+ module.addIncludePath(vterm.path("src"));
+ module.addCSourceFiles(.{ .root = vterm.path("src"), .files = &.{ "encoding.c", "keyboard.c", "mouse.c", "parser.c", "pen.c", "screen.c", "state.c", "unicode.c", "vterm.c" }, .flags = &.{ "-std=c99", "-DNDEBUG" } });
+ module.addIncludePath(b.path("src/files/terminal"));
+ const flags: []const []const u8 = if (for_tests) &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-DFT_TEST" } else &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" };
+ module.addCSourceFile(.{ .file = b.path("src/files/terminal/engine.c"), .flags = flags });
+ module.linkSystemLibrary("util", .{});
+}
+
fn addVolumes(b: *std.Build, module: *std.Build.Module) void {
module.addIncludePath(b.path("src/files"));
module.addCSourceFile(.{ .file = b.path("src/files/volumes.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
@@ -874,7 +916,7 @@ fn addShellUi(b: *std.Build, module: *std.Build.Module) void {
fn addShellIcons(b: *std.Build, module: *std.Build.Module) void {
module.addAnonymousImport("redi-logo", .{ .root_source_file = b.path("assets/redi-logo.svg") });
module.addAnonymousImport("rediwm-settings-icon", .{ .root_source_file = b.path("assets/icons/rediwm-settings.png") });
- inline for (.{ "git-branch", "home", "folder", "settings", "keyboard", "edit", "mouse", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares" }) |name| {
+ inline for (.{ "git-branch", "home", "folder", "terminal", "settings", "keyboard", "edit", "mouse", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares" }) |name| {
module.addAnonymousImport("shell-icon-" ++ name, .{ .root_source_file = b.path("assets/icons/" ++ name ++ ".svg") });
}
}
diff --git a/build.zig.zon b/build.zig.zon
index ecad5af..a38ac11 100644
--- a/build.zig.zon
+++ b/build.zig.zon
@@ -12,6 +12,10 @@
"README.md",
},
.dependencies = .{
+ .vterm = .{
+ .url = "https://www.leonerd.org.uk/code/libvterm/libvterm-0.3.3.tar.gz",
+ .hash = "N-V-__8AAFwIBQAS1j3S14ozuJ18ebNtLQ-c5Kl6W4J7PoJt",
+ },
// v0.20.1 is the current Zig 0.16-compatible release for wlroots 0.20.
.wlroots = .{
.url = "https://github.com/swaywm/zig-wlroots/archive/refs/tags/v0.20.1.tar.gz",
diff --git a/docs/files-terminal.md b/docs/files-terminal.md
new file mode 100644
index 0000000..75d079d
--- /dev/null
+++ b/docs/files-terminal.md
@@ -0,0 +1,139 @@
+# Files terminal
+
+F4 and the bottom-right terminal button toggle a drawer in normal Files
+windows. The sidebar keeps its full height. Drag the drawer's upper divider
+to resize it. Height is remembered; a new window always starts with the drawer
+hidden and creates a fresh shell only when opened. Choosers have no drawer.
+
+Opening focuses the terminal. Clicking the file list, toolbar or sidebar
+restores Files shortcuts. F4 works in either focus and never repeats; other
+keys, including Escape, Ctrl+C/D/Z, Alt combinations and key repeat, go to the
+terminal while focused. Modal dialogs take precedence and preserve focus.
+Ctrl+Shift+C/V copies or pastes. Drag to select; Shift selects locally when an
+application enables terminal mouse reporting. Wheel/scrollbar browse history;
+typing returns to the live screen. Shift+PageUp/PageDown scroll by a page.
+
+The drawer uses the configured monospace font, shared font fallback, app text
+size, terminal palette tokens and app foreground/background fallbacks. It
+uses the normal panel animation and reduced-motion setting. It reserves 48
+pixels for the file list (less the horizontal scrollbar) and needs at least
+96 pixels for its header and terminal. Very small windows temporarily hide
+it and return input to Files, retaining the shell and preferred height.
+
+## Shells and folder following
+
+The shell is a valid executable absolute `$SHELL`, otherwise the account's
+shell, otherwise `/bin/sh`. It is interactive, with a controlling PTY and
+normal job control. Bash loads its system startup configuration normally and
+the user's `~/.bashrc` through an anonymous, session-only rcfile. No startup
+file is changed. A private loadable builtin is loaded for this session only;
+if it cannot load, the shell remains usable without automatic following.
+Other shells use their normal interactive startup configuration.
+
+| Shell | Initial directory | Automatic following |
+| --- | --- | --- |
+| Bash | Current real folder | Session builtin; qualified on Bash 5.3 with Readline 8.3 |
+| Fish | Current real folder | Unavailable |
+| Zsh and other shells | Current real folder | Unavailable; not separately qualified |
+
+Bash following uses an inherited `SOCK_SEQPACKET` socket, separate from
+terminal output. Files accepts status only with the launched shell's kernel
+credentials. The shell checks its peer's credentials and makes its channel
+close-on-exec before sourcing the user's rcfile. There is no listening socket,
+polling timer, signal-as-command transport or synthetic `cd` text.
+
+The builtin waits for terminal input and the socket together at Readline's
+input hook. It applies the latest directory request only at a primary prompt,
+with an empty line and no search, completion, key sequence, macro or builtin
+read in progress. Paths are bounded data passed directly to Bash's `cd`
+builtin with `--`; quotes, newlines and Unicode are preserved. Bash validates
+the directory and maintains PWD/OLDPWD. Failed changes are acknowledged and
+displayed without restarting the shell. The user's prompt is re-expanded
+after a successful change; prompt commands and traps are preserved.
+
+While editing, running a command, inside a nested/remote shell or a
+multiplexer, following waits for the owned Bash prompt. Background jobs are
+reported too. Only the newest navigation request is retained. The header
+shows the shell's reported directory and whether following is pending or
+unavailable. Shell navigation never navigates Files. Recent, Trash and
+archive views retain the last real folder, falling back to Home.
+
+## Terminal contract and lifetime
+
+Files statically embeds upstream libvterm **0.3.3**, pinned by URL and Zig
+content hash in `build.zig.zon`. Distro libvterm packages are not used. GNU
+Readline development files build the Bash builtin; Bash's loadable-builtin
+loader rejects unavailable symbols. The installed helper and builtin are
+`bin/rediwm-files-terminal` and `lib/rediwm/files-bash.so`, beside the Files
+installation. The libvterm license is installed under `share/licenses/rediwm`.
+
+The advertised contract is `TERM=xterm-256color` with the distribution's
+ncurses xterm-256color terminfo, and `COLORTERM=truecolor`. Supported features
+include ANSI/256/RGB colours, bold, synthetic italic, underline, strike,
+reverse/conceal, cursor visibility/shapes, application cursor keys, alternate
+screen, bracketed paste, focus reporting and terminal mouse modes. Wide cells,
+combining characters (up to libvterm's six codepoints per cell) and font
+fallback are retained. Cursor and blinking text are steady: there is no blink
+timer. Graphics protocols, hyperlinks, desktop clipboard escape sequences and
+program-launch escape sequences are not exposed. In particular OSC 52 cannot
+read or write the Wayland clipboard, and OSC output cannot authorize following.
+
+Scrollback stores at most **4,096 physical rows and 8 MiB**, whichever comes
+first. Wrapped-row metadata controls selection copying. Resize clips/pads
+physical rows, without reflowing old history. Scrolled-back reading stays in
+place as output arrives, until the retained history limit evicts it. Selection
+is cleared on a column-count change. The grid is capped at 512 by 512 cells.
+
+PTY reads and writes have a **64 KiB budget per event-loop iteration**. Input
+has a **1 MiB** queue; larger/full-queue pastes are refused with a notice.
+Writes handle partial progress and EAGAIN, and request POLLOUT only while
+queued. Pasted ESC/control bytes are filtered to prevent terminating a
+bracketed paste; tabs and line endings are retained. Hidden sessions continue
+parsing with bounded history and add no paint or cursor timer wakeups.
+Allocator failures release the emulator's tracked allocations and fail that
+session without taking down Files.
+
+A fresh helper process performs PTY setup and exec; Files never runs unsafe
+library code in a forked child of its multithreaded process. On native login,
+the helper places the shell in a separate transient app.slice scope before
+executing startup files. Placement is best effort, like compositor app scopes.
+Nested/headless sessions skip it unless `REDIWM_APP_SCOPES=1` explicitly forces
+it. The compositor publishes its resolved setting to app clients through this
+existing flag, while continuing to strip private supervisor authority. PIDfds
+join the existing poll loop for exit notifications and reaping.
+
+Hiding keeps the session alive. After exit or failure the screen/error remains
+with a Restart action. Every live shell requires confirmation on Files close,
+including hidden sessions: an earlier status snapshot cannot prove no job has
+started since. Cancel preserves the session. Confirm sends hangup to this
+session, then uses bounded asynchronous cleanup and pidfds to kill/reap it if
+necessary. Remaining members of the owned PTY session are ended when its shell
+exits; intentionally detached `setsid` processes are independent. A Files crash
+closes its PTY with ordinary terminal hangup semantics; session survival is not
+promised.
+
+Open external terminal uses `[compositor] default_terminal`, preserving its
+desktop-entry arguments, theme handling, app scope and working directory.
+A missing preference falls back to `$TERMINAL` or `foot`. It creates an
+independent session in Files' current real folder; existing jobs stay in the
+drawer. Changing the default terminal affects only this external action.
+
+## Validation
+
+`zig build test-files-terminal` runs the Files units and an isolated headless
+suite with scratch HOME/XDG paths, disabled device enumeration, no host bus
+and no host app scopes. `REDIWM_TEST_SCALE=1.5` repeats at fractional scale.
+Unit fixtures cover chunked UTF-8/escape sequences, wide/combining cells,
+alternate screen, key/mouse/paste encoding, OSC policy, history bounds,
+allocator failures, preferences, viewport geometry, focus and chooser guards.
+The PTY fixture exercises empty/partial/busy prompts, coalescing, unusual paths,
+failed directory changes, nested shells, jobs, partial writes and full-screen
+tools. UI checks cover the held F4 toggle, keyboard input, hidden continuity,
+navigation, divider preferences, idle wakeups, independent windows and close.
+The drawer also stays live through workspace slides, tiled/canvas size changes
+and minimize/restore, including the fractional-scale run.
+
+Physical output moves and real fcitx5/IBus candidate windows remain manual
+qualification, as for the other app clients. Terminal text-input-v3 handles
+bounded UTF-8 commits and local preedit; it advertises no editable surrounding
+terminal output and rejects deletion requests. No compositor exception is used.
diff --git a/docs/plans/disk-cleanup.md b/docs/plans/disk-cleanup.md
new file mode 100644
index 0000000..ae95cbc
--- /dev/null
+++ b/docs/plans/disk-cleanup.md
@@ -0,0 +1,286 @@
+# Settings storage cleanup plan
+
+Status: draft, 2026-10-17. Start with Phase 0; the first release covers
+user-owned caches, thumbnail cleanup and the home Trash.
+
+Add a **Storage** page to Settings that explains where reclaimable space is,
+lets the user review individual items, previews the exact work, and reports
+the result. Use Safe Disk Cleaner as the feature reference while building a
+native Zig implementation with RediWM's shared widgets. Filesystem work runs
+in a separate unprivileged process so slow disks cannot stall the compositor.
+
+System cleanup follows separately. RediWM currently permits only rediwm-dm
+and the accounts helper to run as root. The reference application's general
+`pkexec` cleanup helper therefore cannot be carried over under the current
+architecture.
+
+## Reference and existing integration points
+
+The reference checkout is
+`/home/alex/Downloads/safe-disk-cleaner-main`. Its `model.py`, `scanners.py`,
+`cleaner.py` and `policy.py` separate discovery, explanations, selection,
+planning and execution. Keep that separation. Its kernel cleanup supports
+APT; package-cache cleanup supports APT, DNF, pacman and zypper; unused-package
+cleanup supports APT, DNF and pacman. Capability detection must reflect those
+differences rather than presenting universal Linux support.
+
+The existing RediWM pieces to build on are:
+
+| Existing code | Integration |
+| --- | --- |
+| [`control_center/panel.zig`](../../src/control_center/panel.zig) | Add the Storage page enum, navigation entries, section ownership, build, keyboard handling and teardown. Services currently occupies the last navigation slot and is conditionally hidden; preserve that behavior when inserting Storage. |
+| [`sections/printers.zig`](../../src/control_center/sections/printers.zig) and [`printing/client.zig`](../../src/printing/client.zig) | Follow page-owned lifetime, copied snapshots, action generations and refresh callbacks. |
+| [`control_center/folder_picker.zig`](../../src/control_center/folder_picker.zig) and [`session/child.zig`](../../src/session/child.zig) | Reuse the asynchronous child-process pattern: bounded pipe reads, event-loop callbacks, pidfds and detached callbacks after the owner disappears. |
+| [`files/dirsize.zig`](../../src/files/dirsize.zig) | Reuse sizing ideas such as allocated blocks, cancellation, inode deduplication and partial results. Avoid importing the Files worker pool into the compositor. |
+| [`files/thumbs.zig`](../../src/files/thumbs.zig) and [`files/thumb_codec.c`](../../src/files/thumb_codec.c) | Match the existing freedesktop thumbnail locations and URI encoding. Cleanup needs a bounded metadata reader; the current codec's returned metadata does not expose `Thumb::URI`. |
+| [`files/ops.zig`](../../src/files/ops.zig) | Files already uses GIO for Trash operations. Its `gio trash --empty` empties everything GIO discovers, so it does not implement a reviewed selection. |
+| [`ui/widgets`](../../src/ui/widgets) | Use the existing buttons, checkboxes, rows, scroll containers and confirmation controls with Settings palette and text tokens. |
+
+The reference is MIT licensed. Preserve its attribution if copying code,
+substantial explanation text or fixtures. Feature parity does not require a
+Python or GTK runtime dependency.
+
+## User experience
+
+Storage opens with filesystem capacity cards, a **Scan** button and a short
+explanation of the cleanup scope. Capacity reads happen in the worker; opening
+Settings elsewhere starts no storage work. Scanning is explicit and
+cancellable, with incremental category results and a last-scanned time.
+
+The page has a summary, category rows and a details area. At narrow widths,
+open details within the same scrollable content column. Each category shows
+its estimated reclaimable size, selection state and availability. Details
+answer four questions: what this data is, why it grows, what deleting it
+changes, and what action will run. Show full paths on demand; escape unusual
+filenames for display without changing the underlying filename bytes.
+
+Use three labels: **Recreated when needed**, **May require downloads or
+rebuilding**, and **Review before deleting**. Diagnostic history and Trash
+belong in the last group. Start with nothing selected. A **Select recommended**
+action selects only verified, recreatable items; unknown caches, diagnostics,
+Trash and package removal never join that selection.
+
+**Review cleanup** freezes a selection and opens an explicit confirmation
+showing item counts, affected locations, estimates and consequences. An
+expandable **Show exact actions** lists direct filesystem operations or the
+fixed command arguments for each operation. This view comes from the same
+plan the executor uses. Deleting Trash items must say they cannot be restored
+through Trash afterward.
+
+During cleanup, disable selection changes and show completed items, skipped
+items and errors. **Stop** prevents subsequent operations; already completed
+deletions stay completed. Afterward, show the result per category and the
+observed free-space change on each affected filesystem. Offer **Scan again**;
+never silently retry a failed or interrupted deletion.
+
+## Feature scope
+
+| Reference category | Delivery | Required behavior |
+| --- | --- | --- |
+| App caches in the user's cache directory | First release | Start with a small reviewed catalog of cache subdirectories and app identities. Unknown folders show sizes and an Open in Files action, with deletion disabled. Keep RediWM's active caches protected. |
+| Picture previews | First release | Offer orphaned previews of definitely missing local files. Keep previews with unknown metadata, inaccessible originals or offline sources. Clearing other previews is a separate opt-in action. |
+| Trash | First release for home Trash | List individual items with original location and deletion date when available. Delete only reviewed entries and handle their restore metadata together. |
+| Flatpak and Snap app caches | Next user-data increment | Support reviewed app IDs and precise cache locations only; never whole app profiles, revision folders or app data. Block known running apps. |
+| Unused Flatpak runtimes | Later adapter | Separate user and named system installations; ask Flatpak for unused refs in the correct user context, then revalidate the approved refs before execution. |
+| Downloaded package files | Later system increment | Use the package manager's supported cleanup operation. For pacman, retain downgrade versions rather than wiping its cache. Show the retention policy in the review. |
+| System journal | Later system increment | Vacuum archived entries through a supported authority. Show loss of diagnostic history and distinguish total journal size from the amount eligible for vacuuming. |
+| Crash reports and core dumps | Later system increment | Restrict roots, file types and age; keep recent or active diagnostics. Treat them as review items. |
+| Rotated logs | Later system increment | Restrict roots and filename rules; exclude live logs and journal files. A one-hour freshness guard from the reference is a starting rule, not proof that a file is unused. |
+| Disabled Snap revisions | Later adapter | Re-query snapd and remove only the selected revision while it is still disabled. Explain the loss of that rollback version. |
+| Packages no longer needed | Final package increment | Preview a concrete removal transaction, keep user configuration, and refuse additional removals outside the approved transaction. |
+| Old kernels | Final package increment | Start with a qualified APT adapter. Keep the running kernel, newest kernel, held packages and an identified bootable fallback. Unknown bootability or dependency changes disable removal. |
+
+Mounted-volume Trash, including both `.Trash/<uid>` and `.Trash-<uid>`, follows
+the home Trash implementation. Show separate volumes and handle unmounts;
+do not discover Trash by scanning every disk recursively.
+
+Persistent journal limits and Snap revision retention are separate later
+settings with their own Apply and restore-default actions. Cleaning once
+must not change retention settings. Automatic cleanup, startup scans,
+browser history/cookies, downloads, documents, duplicate-file removal and
+arbitrary directory deletion are outside this scope.
+
+## Architecture
+
+Introduce these modules, keeping policy and filesystem code independent of
+compositor types:
+
+| Proposed file | Responsibility |
+| --- | --- |
+| `src/control_center/sections/storage.zig` | Widgets, selected item IDs, details, confirmation and progress presentation. |
+| `src/storage/client.zig` | Own the worker process, pipe readiness, generations, deadlines and callback lifetime. |
+| `src/storage/model.zig` and `protocol.zig` | Typed categories, item identities, estimates, plans, progress, results and a bounded versioned protocol. |
+| `src/storage/scan.zig`, `policy.zig` and `plan.zig` | Root discovery, capability detection, cache catalog, eligibility rules and immutable plan construction. |
+| `src/storage/fs.zig`, `thumbnails.zig` and `trash.zig` | Descriptor-relative traversal, metadata parsing, sizing and targeted deletion. |
+| `src/storage/main.zig` | Entry point for the installed, unprivileged `rediwm-storage-worker` executable. |
+| `src/storage/adapters/` | Later qualified Flatpak, Snap, package and journal integrations. |
+
+Each item carries a category and item ID, root ID and relative location,
+filesystem/object identity, size estimate, explanation, availability,
+blocked reason and typed operation. Represent unavailable, empty, incomplete,
+permission-denied and unsupported states separately. Permission failure must
+never appear as zero bytes available for cleanup.
+
+The worker retains the scan inventory. The UI requests a plan from selected
+IDs, receives its exact preview, and confirms that plan's token. Execute only
+the retained plan from the same worker and generation; reject stale, unknown
+or replayed tokens. New files and changed directories cannot silently expand
+the approved deletion set. Deduplicate overlapping roots, entries and
+operations before calculating totals or executing them.
+
+Send incremental bounded messages over private inherited pipes or a
+socketpair. Bound message size, path size, inventory memory, recursion depth
+and work per event-loop callback. Large results use paged details and report
+truncation; they must not collapse unseen items into an implicitly selected
+"everything else" operation. Disconnects invalidate pending plans.
+
+The process runs only while Storage is active. Leaving the page, closing
+Settings, locking the session or shutdown cancels discovery and requests a
+stop between filesystem operations. Detach callbacks before freeing the
+section, and reap children through `session/child.zig`; never wait for disk
+I/O on the Wayland thread. In-flight filesystem work can complete after Stop,
+so reopening starts with a fresh scan. Future package transactions need their
+own safe completion and cancellation contract before they are enabled.
+
+Use readiness notifications and deadlines only for active work. Hidden pages
+retain no worker owner; a stopped child can finish being reaped asynchronously.
+While Storage is visible, an idle worker may retain its inventory while blocked
+on its request pipe, with no recurring timer, process scan or wakeups. Copy
+display strings into the section arena before releasing worker snapshots.
+Requests and completions carry generations so older results cannot replace a
+newer selection. Follow the existing launch/scope rules for child applications.
+
+## Filesystem safety and accounting
+
+Resolve `XDG_CACHE_HOME` and `XDG_DATA_HOME` with the standard home fallbacks;
+reject relative or dangerously broad cleanup roots. Validate ownership and
+root identity, and pin approved roots by directory descriptors. Requests
+cannot supply new base directories. Refuse overlaps that would turn the
+home, configuration, application data or state directories into cache roots.
+The worker refuses to run as root; permission errors never trigger elevation.
+
+Walk and delete relative to pinned directories without following symlinks.
+Check mount identity as well as device identity so bind mounts cannot expand
+the cleanup scope. Revalidate object identity and eligibility immediately
+before deletion; skip changed objects. A selected Trash symlink can be
+unlinked as a link, without touching its target. Never delete a root itself
+or use a shell command, glob or generic `rm -r` for this engine.
+
+Phase 0 must prove the deletion strategy against link replacement, directory
+renames and changes between scan, confirmation and execution. A stat check
+followed by pathname deletion alone is insufficient. Qualify an approach
+such as private staging within the same filesystem, with identity checked
+after the atomic move and before unlinking. Unexpected replacements must be
+preserved, with recovery information if they cannot be restored. Interrupted
+staging must also have a defined recovery path before destructive UI ships.
+
+Trash metadata supplies display information only. Its original `Path=` is
+never a deletion target. Keep restore metadata until removal of its matching
+contents succeeds; interruption or failure must not leave remaining contents
+without their metadata. Recheck running-app evidence immediately before each
+app-cache action. Process names alone do not provide an exclusive lock;
+ambiguous app identity keeps the item blocked, and the UI must not promise
+that a process check prevents every concurrent write.
+
+Read thumbnail PNG metadata with bounded chunks and URI decoding, without
+decoding image pixels. Only a definite missing original on a known available
+local source qualifies as an orphan. An unknown mount, unavailable network
+location, permission error or malformed URI keeps the preview. Recheck the
+original before deletion. Do not infer all mount locations from `/media`
+and `/mnt` prefixes alone.
+
+Estimate allocated blocks, deduplicate hardlinks across selections, and
+avoid claiming hardlink space is reclaimed while unselected links remain.
+Shared extents, compression and open deleted files can make actual recovery
+smaller than the estimate. Sample available bytes before and after on each
+unique affected filesystem, distinguishing mounts that share the same
+capacity pool. Report signed observed changes separately from removed-item
+totals because other processes can allocate space concurrently. Do not call
+a machine-wide `sync` or add all mounted-filesystem free space together.
+
+## System authority and distro qualification
+
+Keep all first-release operations unprivileged. For later system actions,
+first qualify existing distro services that expose the required operation,
+enforce their own authorization and allow the actual transaction to match
+the preview. RediWM's polkit agent presents authentication; it does not grant
+the compositor permission to execute arbitrary root commands.
+
+Where no suitable existing authority exists, show the action as unsupported
+under the current architecture. A new installed privileged helper requires
+a separate architecture decision changing the root-process rule, an explicit
+operation allowlist, authorization policy and independent security review.
+Do not extend the accounts helper into a general disk-cleaning service.
+
+Every adapter must revalidate the current backend state, use fixed argument
+arrays and trusted executables, distinguish permission denial from missing
+tools, and honor package-manager locks. Never expose a command-string or
+arbitrary-path execution operation. Scanning must not refresh repositories,
+authenticate or modify package state. Unsupported backend versions fail
+closed. Prove transaction and kernel protections separately for each distro;
+the reference's APT checks do not establish equivalent DNF or pacman safety.
+
+## Delivery phases and completion criteria
+
+1. **Phase 0 — filesystem and authority prototype.** Pin the initial cache
+ catalog and root rules, define the worker protocol and prove traversal,
+ staging/recovery, cancellation and accounting on temporary trees. Record
+ the capability matrix and system-authority constraints. Completion means
+ containment tests pass under concurrent mutations and worker teardown
+ cannot block or call a destroyed Settings owner.
+2. **Phase 1 — read-only Storage page.** Add navigation, capacity cards,
+ explicit scan/cancel, known and unknown cache sizes, thumbnail groups and
+ home Trash details. Completion means partial results, inaccessible paths,
+ missing roots and large inventories remain useful, the desktop stays
+ responsive, and idle/hidden pages add no wakeups.
+3. **Phase 2 — first cleanup release.** Enable reviewed known cache contents,
+ eligible thumbnails and selected home Trash items through frozen plans.
+ Add confirmation, Stop, per-item outcomes and filesystem deltas. Completion
+ means only the reviewed inventory is eligible, changed entries are
+ skipped, and partial failure/interruption preserves recoverability of
+ surviving Trash entries and staged data.
+4. **Phase 3 — additional user locations.** Add reviewed Flatpak/Snap cache
+ adapters, mounted-volume Trash and user Flatpak runtimes once backend
+ semantics are qualified. Completion includes active-app blocking,
+ offline volumes, multiple installations and dependency changes.
+5. **Phase 4 — qualified system cleanup.** Resolve the authority design,
+ then add package caches, journal, diagnostics, system Flatpak runtimes and
+ disabled Snap revisions one adapter at a time. Completion requires real
+ distro qualification in disposable systems, authorization cancellation,
+ locked/busy backends and exact-action review. Retention settings follow
+ with independent confirmation and readback.
+6. **Phase 5 — package and kernel removal.** Add transaction previews and
+ conservative kernel protection for explicitly supported backends.
+ Completion requires testing changed dependency graphs, held packages,
+ missing/running/fallback kernels and unapproved extra removals. An adapter
+ stays disabled when those guarantees cannot be established.
+
+## Validation
+
+Extend existing coverage where it fits and add a focused storage suite for
+the destructive engine. Link unit tests into the build explicitly. Tests use
+temporary home/cache/data/state trees, private buses and fake command
+backends; they never delete host data or contact the host package manager.
+
+Required cases include symlink and bind-mount escapes, rename/replacement
+races, unsafe XDG overrides, hardlinks, sparse files, overlapping selections,
+deep/large inventories, unusual filenames, permission errors, malformed PNG
+metadata, offline originals, hostile `.trashinfo`, newly started apps, stale
+plan tokens, disconnects, cancellation and interrupted staging recovery.
+Adapters add changed package/ref state, authorization denial, busy locks and
+unapproved transaction expansion cases as they are introduced.
+
+Add `tests/storage_cleanup.py` using the existing Settings widget/IPC
+inspection and private fixture process. Cover selection and details,
+confirmation cancellation, targeted deletion, partial failure, UI
+responsiveness, page switching, close, lock, reopen and per-thread idle
+wakeups. Use stable widget names; no new destructive IPC endpoint or
+production test environment hooks are needed. Check compact layout and
+fractional scale, and confirm the greeter starts no storage worker.
+
+For implementation changes, run Debug and ReleaseSafe builds, `zig build
+test`, the focused storage suite, `tests/control_center.py` and
+`tests/greeter.py`. Run Files thumbnail/Trash regression coverage if shared
+code changes. Compare pre-existing failures against a clean HEAD worktree
+before assigning regressions. Actual privilege/backend qualification belongs
+in disposable distro environments, with results recorded per adapter.
diff --git a/docs/plans/files-terminal.md b/docs/plans/files-terminal.md
index a07d67b..1d7473b 100644
--- a/docs/plans/files-terminal.md
+++ b/docs/plans/files-terminal.md
@@ -1,6 +1,7 @@
# Files terminal drawer plan
-Status: draft, 2026-10-16. Implementation starts with Phase 0 below.
+Status: implemented, 2026-10-17. Automated qualification and remaining manual
+checks are recorded below; see [support and limits](../files-terminal.md).
Add a terminal drawer beneath the file list, opened with F4 or a small
terminal icon at the bottom right. Embed libvterm in the Files process and
@@ -243,52 +244,52 @@ application and its shell session.
### Phase 0 Prove libvterm and shell coordination
-- [ ] Pin the library version and dependency delivery, compile a Files-only
+- [x] Pin the library version and dependency delivery, compile a Files-only
prototype, and record the tested shell and terminfo configuration.
-- [ ] Prove safe PTY launch, app-scope placement, Cairo rendering, keyboard
+- [x] Prove safe PTY launch, app-scope placement, Cairo rendering, keyboard
input, grid resize, alternate screen, Unicode, and shell exit.
-- [ ] Establish scrollback and reflow behaviour; measure continuous-output
+- [x] Establish scrollback and reflow behaviour; measure continuous-output
responsiveness and memory limits before choosing the final loop budgets.
-- [ ] Prove folder following with an empty prompt, partial input, a running
+- [x] Prove folder following with an empty prompt, partial input, a running
command, and rapid navigation. Qualify the shell integration transport.
-- [ ] Record capability limits and lifecycle decisions before UI polish.
+- [x] Record capability limits and lifecycle decisions before UI polish.
### Phase 1 Add terminal engine and process lifetime
-- [ ] Implement the libvterm wrapper, PTY session, bounded input/output work,
+- [x] Implement the libvterm wrapper, PTY session, bounded input/output work,
child tracking, app scopes, and cleanup.
-- [ ] Implement cell rendering, scrollback, selection, cursor, colours, and
+- [x] Implement cell rendering, scrollback, selection, cursor, colours, and
damage through the Files buffer pipeline.
-- [ ] Add terminal input encoding, compose/IME, clipboard, bracketed paste,
+- [x] Add terminal input encoding, compose/IME, clipboard, bracketed paste,
mouse reporting, and the supported escape-sequence policy.
### Phase 2 Build the Files drawer
-- [ ] Add controller state, F4, the status icon, header, and launch/exit/error
+- [x] Add controller state, F4, the status icon, header, and launch/exit/error
states using shared UI controls.
-- [ ] Extend the splitter, viewport geometry, scrollbars, hit testing, and
+- [x] Extend the splitter, viewport geometry, scrollbars, hit testing, and
height preference migration.
-- [ ] Add slide animation, reversal, reduced motion, compact layouts, and
+- [x] Add slide animation, reversal, reduced motion, compact layouts, and
correct focus restoration.
### Phase 3 Add directory following and lifecycle polish
-- [ ] Add the qualified shell integration and coalesced desired-directory
+- [x] Add the qualified shell integration and coalesced desired-directory
requests, acknowledgements, and actual-directory display.
-- [ ] Handle virtual locations, inaccessible paths, unsupported shells,
+- [x] Handle virtual locations, inaccessible paths, unsupported shells,
nested shells, remote sessions, and multiplexer behaviour explicitly.
-- [ ] Complete close-with-command/job, PTY hangup, shell exit/restart,
+- [x] Complete close-with-command/job, PTY hangup, shell exit/restart,
launch failure, and hidden-session behaviour.
-- [ ] Add Open external terminal with existing default-app resolution and
+- [x] Add Open external terminal with existing default-app resolution and
explicit independent-session behaviour.
### Phase 4 Validate and document support
-- [ ] Extend existing unit suites for geometry, preference migration,
+- [x] Extend existing unit suites for geometry, preference migration,
lifecycle, focus routing, and directory-request state where appropriate.
Add terminal fixtures for chunked escape sequences, Unicode cells,
scrollback bounds, partial writes, resize, and allocation failures.
-- [ ] Add a focused Files terminal headless suite with an isolated shell and
+- [x] Add a focused Files terminal headless suite with an isolated shell and
deterministic PTY fixtures. Test two Files windows for independent state.
- [ ] Exercise supported shells, copy/paste, dead keys, IME, selection,
scrolling, mouse modes, and full-screen tools such as `vim` and `top`.
@@ -298,7 +299,7 @@ application and its shell session.
- [ ] Check launch/close/crash races, shell jobs, capture, idle wakeups,
hidden-session continuity, and memory bounds under sustained output.
Verify Files navigation and normal compositor interactions remain responsive.
-- [ ] Build Debug and `-Doptimize=ReleaseSafe`; run `zig build test`,
+- [x] Build Debug and `-Doptimize=ReleaseSafe`; run `zig build test`,
`zig build test-files`, the terminal integration suite, and relevant Files
controls/decoration/browser and dead-key suites. Exercise normal focus,
workspace, and minimize behaviour with the drawer open. Review shared UI
@@ -311,3 +312,46 @@ directories, set `REDIWM_FILES_DEVICES=0`, and keep shell commands and test
files inside scratch directories. Document the supported libvterm version,
terminal capabilities, shell-integration matrix, and external-terminal action
with the completed feature.
+
+
+## Implementation and qualification record (2026-10-17)
+
+The complete drawer, terminal engine, Bash coordination, independent external
+terminal action and packaging are implemented. libvterm 0.3.3 is compiled from
+the source URL/content hash in `build.zig.zon`, so distro ABI/version differences
+do not affect Files. The session helper and Bash builtin install alongside the
+application. Shell support, terminal capabilities, physical-row resize behavior,
+scrollback/input bounds and lifecycle choices are in [the support document](../files-terminal.md).
+
+The Files unit suite now has 127 tests. New coverage includes chunked escape
+sequences and UTF-8, wide/combining cells, truecolour and reverse video, alternate
+screen, key/mouse/paste encoding, ignored OSC 52, history limits, allocator
+failures, preference migrations, viewport geometry, modifier/copy routing, modal
+priority and chooser isolation. Existing vertical splitters keep their default
+axis and the existing shared text API keeps its original defaults.
+
+`zig build test-files-terminal` exercises real PTYs and Bash 5.3.20/Readline
+8.3, including paths with spaces, quotes, newlines and Unicode; empty, partial
+and busy prompts; coalescing; removed directories; nested shells; background
+jobs; queued/partial writes; 200 kB pastes to a raw reader and Bash; vim/top;
+launch failure; shell exit; and Fish's initial-folder-only fallback. A private
+D-Bus service verifies scope placement, the exact owned PID and app.slice before
+exec. Its headless Files checks cover F4/repeat, hidden continuity, clipboard
+copy/paste and selection, configured external-terminal arguments/cwd, divider
+persistence, idle wakeups, independent windows and close/cancel. Fractional scale
+is exercised with `REDIWM_TEST_SCALE=1.5`. Workspace slides, tiled/canvas resize
+transitions and minimize/restore run with the drawer open. The complete terminal
+suite also runs against the ReleaseSafe installation.
+
+Debug and ReleaseSafe builds, `zig build test`, `zig build test-files`, the Files
+browser and decoration suites, the controls `--places-only` suite and dead-key
+suites pass. The full Files controls suite reaches its existing Git M/D/A badge
+timeout at `tests/files_controls.py:628`; the identical failure was reproduced
+in an isolated worktree of unchanged HEAD `3e68db4`. Its preference-version
+assertion was deliberately updated for the new v4 height format. App activation
+and session readiness checks cover the shared pure launch policy and child
+environment propagation.
+
+The remaining unchecked Phase 4 matrix is manual qualification, especially
+real fcitx5/IBus candidate UI, physical output moves and forced delayed-buffer
+release/crash races. No session survival across a Files crash is promised.
diff --git a/scripts/install-session-root.sh b/scripts/install-session-root.sh
index 5a9185a..097f3a5 100755
--- a/scripts/install-session-root.sh
+++ b/scripts/install-session-root.sh
@@ -12,12 +12,13 @@ umask 022
install -d /usr/local/bin
stage=$(mktemp -d /usr/local/bin/.rediwm-install.XXXXXX)
trap 'rm -rf -- "$stage"' EXIT HUP INT TERM
-for binary in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-images rediwm-editor rediwm-pdf rediwm-share-picker rediwm-session rediwm-dm rediwm-accounts-helper; do
+for binary in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-files-terminal rediwm-images rediwm-editor rediwm-pdf rediwm-share-picker rediwm-session rediwm-dm rediwm-accounts-helper; do
install -m755 "$release_dir/bin/$binary" "$stage/$binary"
done
install -Dm644 "$repo_dir/data/rediwm-theme.desktop" /usr/local/share/applications/rediwm-theme.desktop
install -Dm644 "$repo_dir/data/rediwm-theme.xml" /usr/local/share/mime/packages/rediwm-theme.xml
install -Dm644 "$repo_dir/data/rediwm-files.desktop" /usr/local/share/applications/rediwm-files.desktop
+install -Dm644 "$release_dir/share/licenses/rediwm/libvterm-LICENSE" /usr/local/share/licenses/rediwm/libvterm-LICENSE
install -Dm644 "$release_dir/share/icons/hicolor/256x256/apps/redi-fm-icon.png" /usr/local/share/icons/hicolor/256x256/apps/redi-fm-icon.png
install -Dm644 "$repo_dir/data/rediwm-images.desktop" /usr/local/share/applications/rediwm-images.desktop
install -Dm644 "$repo_dir/data/rediwm-editor.desktop" /usr/local/share/applications/rediwm-editor.desktop
@@ -70,7 +71,7 @@ for pack in "$release_dir"/share/rediwm/themes/*/; do
rm -rf "/usr/local/share/rediwm/themes/$name"
mv -T "/usr/local/share/rediwm/themes/.$name-new" "/usr/local/share/rediwm/themes/$name"
done
-for binary in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-images rediwm-editor rediwm-pdf rediwm-share-picker rediwm-session rediwm-dm rediwm-accounts-helper; do
+for binary in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-files-terminal rediwm-images rediwm-editor rediwm-pdf rediwm-share-picker rediwm-session rediwm-dm rediwm-accounts-helper; do
mv -fT "$stage/$binary" "/usr/local/bin/$binary"
done
# The compositor draws the desktop itself; the old client is retired.
diff --git a/scripts/install.sh b/scripts/install.sh
index ca6a194..a860378 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -215,7 +215,7 @@ case "$FAMILY" in
arch)
deps="wayland wayland-protocols pixman libxkbcommon \
freetype2 harfbuzz fontconfig librsvg cairo pango libinput poppler-glib libseccomp \
- libarchive libwebp libpng libjpeg-turbo libpulse pipewire pam mesa pkgconf git python \
+ libarchive libwebp libpng libjpeg-turbo libpulse pipewire pam mesa pkgconf git python readline \
xorg-xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk"
if [ "$PRIVATE_WLROOTS" = no ]; then
deps="wlroots0.20 $deps"
@@ -238,14 +238,14 @@ case "$FAMILY" in
libxcb-res0-dev libxcb-xfixes0-dev libxcb-dri3-dev libxcb-present-dev \
libxcb-render-util0-dev libxcb-shm0-dev libxcb-xinput-dev xwayland \
libfreetype-dev libharfbuzz-dev libfontconfig-dev librsvg2-dev libcairo2-dev libpango1.0-dev libgdk-pixbuf-2.0-dev \
- libglib2.0-dev libarchive-dev libwebp-dev libpng-dev libjpeg-dev libpulse-dev libpipewire-0.3-dev libpam0g-dev libpoppler-glib-dev libseccomp-dev \
+ libglib2.0-dev libarchive-dev libwebp-dev libpng-dev libjpeg-dev libpulse-dev libpipewire-0.3-dev libpam0g-dev libpoppler-glib-dev libseccomp-dev libreadline-dev \
xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk"
;;
fedora)
deps="wayland-devel wayland-protocols-devel pixman-devel libxkbcommon-devel \
freetype-devel harfbuzz-devel fontconfig-devel librsvg2-devel cairo-devel pango-devel libinput-devel \
libarchive-devel libwebp-devel libpng-devel libjpeg-turbo-devel pulseaudio-libs-devel pipewire-devel pam-devel poppler-glib-devel libseccomp-devel \
- mesa-libEGL-devel mesa-libGLES-devel glibc-devel \
+ mesa-libEGL-devel mesa-libGLES-devel glibc-devel readline-devel \
pkgconf-pkg-config git python3 \
xorg-x11-server-Xwayland \
xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk"
@@ -262,7 +262,7 @@ case "$FAMILY" in
deps="wlroots-devel wayland-devel wayland-protocols-devel libpixman-1-0-devel libxkbcommon-devel \
freetype2-devel harfbuzz-devel fontconfig-devel librsvg-devel cairo-devel pango-devel libinput-devel \
libarchive-devel libwebp-devel libpng16-devel libjpeg8-devel libpulse-devel pipewire-devel pam-devel libpoppler-glib-devel libseccomp-devel \
- Mesa-libEGL-devel Mesa-libGLESv2-devel glibc-devel \
+ Mesa-libEGL-devel Mesa-libGLESv2-devel glibc-devel readline-devel \
pkg-config git python3 \
xwayland \
xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk"
@@ -271,7 +271,7 @@ case "$FAMILY" in
deps="gui-libs/wlroots dev-libs/wayland dev-libs/wayland-protocols x11-libs/pixman x11-libs/libxkbcommon \
media-libs/freetype media-libs/harfbuzz media-libs/fontconfig gnome-base/librsvg x11-libs/cairo x11-libs/pango dev-libs/libinput \
app-arch/libarchive media-libs/libwebp media-libs/libpng media-libs/libjpeg-turbo media-libs/libpulse media-video/pipewire sys-libs/pam \
- media-libs/mesa \
+ media-libs/mesa sys-libs/readline \
virtual/pkgconfig dev-vcs/git dev-lang/python \
x11-base/xwayland \
sys-apps/xdg-desktop-portal gui-libs/xdg-desktop-portal-wlr sys-apps/xdg-desktop-portal-gtk"
diff --git a/scripts/release-verify.sh b/scripts/release-verify.sh
index 6f5afa7..3066c55 100644
--- a/scripts/release-verify.sh
+++ b/scripts/release-verify.sh
@@ -52,12 +52,14 @@ log "Checking the installed files"
for bin in /usr/local/bin/rediwm /usr/local/bin/rediwm-*; do
readelf -d "$bin" 2>/dev/null | grep -E 'RUNPATH|RPATH' | grep -q "/work/" && die "$bin carries a build path in its RUNPATH"
done
-for bin in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-images rediwm-editor rediwm-pdf rediwm-share-picker rediwm-session rediwm-dm rediwm-accounts-helper; do
+for bin in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-files-terminal rediwm-images rediwm-editor rediwm-pdf rediwm-share-picker rediwm-session rediwm-dm rediwm-accounts-helper; do
[ -x "/usr/local/bin/$bin" ] || die "/usr/local/bin/$bin is missing"
ldd "/usr/local/bin/$bin" 2>&1 | grep -q 'not found' && die "$bin has unresolved libraries"
done
[ -f /usr/share/wayland-sessions/rediwm-release-safe.desktop ] || die "the session entry is missing"
[ -d /usr/local/lib/rediwm ] || die "the bundled libraries are missing"
+runuser -u tester -- test -r /usr/local/lib/rediwm/files-bash.so || die "the Files Bash integration is missing or unreadable"
+runuser -u tester -- test -r /usr/local/share/licenses/rediwm/libvterm-LICENSE || die "the libvterm license is missing or unreadable"
for asset in theme.toml icons/folder.png icons/user-home.png icons/user-trash.png wallpapers/wallpaper-gold.png; do
runuser -u tester -- test -r "/usr/local/share/rediwm/themes/gold/$asset" || die "Gold theme asset is missing or unreadable: $asset"
done
diff --git a/src/Server.zig b/src/Server.zig
index 105ac63..842b38c 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -713,6 +713,7 @@ pub fn applyChildEnvWithToken(server: *Server, map: *child_env.Map, token: ?[]co
.qt_app_colors = !server.greeter_mode and server.qt_app_colors,
.region = server.config.region,
.input_method = server.config.input_method.env,
+ .app_scopes = server.app_scopes != null,
.wayland_display = server.wl_server_socket_name,
.ipc_socket = server.ipc_socket_path,
.x11_display = if (server.xwayland) |xw| xw.displayName() else null,
diff --git a/src/child_env.zig b/src/child_env.zig
index 5d0de03..3def10a 100644
--- a/src/child_env.zig
+++ b/src/child_env.zig
@@ -16,6 +16,10 @@ pub const Spec = struct {
qt_app_colors: bool = false,
region: @import("config").loader.RegionConfig = .{},
input_method: InputMethod = .none,
+ /// Resolved by the compositor before private supervisor fields are
+ /// stripped. App clients can scope their own children without guessing
+ /// whether their Wayland display belongs to a nested session.
+ app_scopes: ?bool = null,
wayland_display: ?[]const u8 = null,
ipc_socket: ?[]const u8 = null,
/// Owned Xwayland `DISPLAY` value (`:N`). Null means Xwayland is disabled
@@ -39,6 +43,7 @@ pub fn apply(map: *Map, spec: Spec) !void {
}
// Private supervisor authority must never escape to descendant launches.
inline for (.{ "REDIWM_SESSION_FD", "REDIWM_LOGIN_SESSION", "REDIWM_SESSION_PRIMARY", "REDIWM_LOGIN_STARTED_NS" }) |key| _ = map.swapRemove(key);
+ if (spec.app_scopes) |enabled| try map.put("REDIWM_APP_SCOPES", if (enabled) "1" else "0");
switch (spec.input_method) {
.none => {},
inline .fcitx, .ibus => |im| {
@@ -223,6 +228,11 @@ test "private session authority and stale activation tokens never reach children
inline for (.{ "REDIWM_SESSION_FD", "REDIWM_LOGIN_SESSION", "REDIWM_SESSION_PRIMARY", "REDIWM_LOGIN_STARTED_NS", "XDG_ACTIVATION_TOKEN", "DESKTOP_STARTUP_ID" }) |key| try map.put(key, "inherited");
try apply(&map, .{});
inline for (.{ "REDIWM_SESSION_FD", "REDIWM_LOGIN_SESSION", "REDIWM_SESSION_PRIMARY", "REDIWM_LOGIN_STARTED_NS", "XDG_ACTIVATION_TOKEN", "DESKTOP_STARTUP_ID" }) |key| try std.testing.expect(map.get(key) == null);
+ try map.put("REDIWM_APP_SCOPES", "1");
+ try apply(&map, .{ .app_scopes = false });
+ try std.testing.expectEqualStrings("0", map.get("REDIWM_APP_SCOPES").?);
+ try apply(&map, .{ .app_scopes = true });
+ try std.testing.expectEqualStrings("1", map.get("REDIWM_APP_SCOPES").?);
}
test "Qt app colors override inherited theming only after explicit opt in" {
diff --git a/src/files/AGENTS.md b/src/files/AGENTS.md
index 1081b6a..17d8f3a 100644
--- a/src/files/AGENTS.md
+++ b/src/files/AGENTS.md
@@ -19,6 +19,29 @@ records are in `app_model.zig`, drawing helpers in `app_draw.zig`, tests in
`app_tests.zig`. A new method goes in its group file plus an alias line in
`App`; a file that calls a sibling's non-method helper imports it directly.
+## Terminal drawer
+
+`app_terminal.zig` owns the per-window controller; `terminal/` owns libvterm,
+the PTY, shell integration, cells and text-input-v3. Support and limits are in
+`docs/files-terminal.md`; `zig build test-files-terminal` runs isolated PTY
+and headless fixtures. The pinned library is compiled only into Files/tests.
+
+* Poll slots 19–21 are PTY, integration socket and pidfd. Parsing/writes have a
+ 64 KiB budget per loop; POLLOUT is enabled only with queued work. Hidden
+ sessions drain without terminal damage or blink timers.
+* Following is a Bash Readline editing safepoint, never text sent through the
+ PTY. Keep its inherited socket private/CLOEXEC, check kernel credentials,
+ bound packets and coalesce requests/status under backpressure. A prompt,
+ title, foreground PID or quiet output alone never authorizes a directory
+ change. Unsupported and nested shells keep pending following suspended.
+* Spawn the fresh helper with `posix_spawn`, so PTY setup and scope placement
+ never run in a forked multithreaded Files child. Confirm every live session
+ on close; bound asynchronous cleanup and retain the session leader until
+ session members have been signaled through pidfds and it can be reaped.
+* Cell metrics use the exact shared mono advance. Paint non-ASCII/wide cells
+ separately so fallback shaping cannot move later cells. Preserve the
+ caller's Cairo damage clip. The test encoder drain exists only with FT_TEST.
+
## File types and associations
* **Types come from `src/mime_db.zig`, not GIO.** It reads shared-mime-info
diff --git a/src/files/app.zig b/src/files/app.zig
index c82cf02..890d5c0 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -37,6 +37,7 @@ const app_paint = @import("app_paint.zig");
const app_items = @import("app_items.zig");
const app_model = @import("app_model.zig");
const app_draw = @import("app_draw.zig");
+const app_terminal = @import("app_terminal.zig");
const DeviceOp = app_model.DeviceOp;
const MenuKind = app_model.MenuKind;
const Sort = app_model.Sort;
@@ -60,6 +61,8 @@ pub const FontMetrics = app_draw.FontMetrics;
pub const fontMetrics = app_draw.fontMetrics;
pub const measureText = app_draw.measureText;
pub const App = struct {
+ terminal: app_terminal.Drawer = .{},
+ closed: bool = false,
children: @import("../child_set.zig") = .{},
chooser: ?chooser_mod.Options = null,
filename: Editor = .{},
@@ -306,6 +309,7 @@ pub const App = struct {
self.list_view = prefs.list;
self.unpinned_places = prefs.unpinned_places;
self.git_view = prefs.git_view;
+ self.terminal.requested_height = @intCast(prefs.terminal_height);
self.sort_mode = @enumFromInt(prefs.sort);
}
self.pins_path = pins_mod.statePath(allocator, environ) catch null;
@@ -316,6 +320,7 @@ pub const App = struct {
}
pub fn deinit(self: *App) void {
+ self.terminal.deinit(self.allocator);
self.children.deinit(self.allocator);
self.closeExtractPicker();
self.extract_picker_bytes.deinit(self.allocator);
@@ -448,7 +453,7 @@ pub const App = struct {
pub fn savePreferences(self: *App) void {
const path = self.preferences_path orelse return;
- (Preferences{ .list = self.non_git_list_view orelse self.list_view, .sort = @intFromEnum(self.sort_mode), .unpinned_places = self.unpinned_places, .git_view = self.git_view }).save(self.allocator, self.io, path) catch {
+ (Preferences{ .list = self.non_git_list_view orelse self.list_view, .sort = @intFromEnum(self.sort_mode), .unpinned_places = self.unpinned_places, .git_view = self.git_view, .terminal_height = @intCast(self.terminal.requested_height) }).save(self.allocator, self.io, path) catch {
self.setStatusNotice("Could not save view preferences", true);
};
}
@@ -775,6 +780,36 @@ pub const App = struct {
// app_pointer.zig
pub const handleButton = app_pointer.handleButton;
+ // app_terminal.zig
+ pub const terminalHeight = app_terminal.terminalHeight;
+ pub const terminalMaximum = app_terminal.terminalMaximum;
+ pub const terminalRect = app_terminal.terminalRect;
+ pub const terminalBody = app_terminal.terminalBody;
+ pub const terminalControl = app_terminal.terminalControl;
+ pub const terminalHit = app_terminal.terminalHit;
+ pub const terminalRestartable = app_terminal.terminalRestartable;
+ pub const terminalDivider = app_terminal.terminalDivider;
+ pub const overTerminalDivider = app_terminal.overTerminalDivider;
+ pub const terminalScopes = app_terminal.terminalScopes;
+ pub const terminalHelper = app_terminal.terminalHelper;
+ pub const terminalStart = app_terminal.terminalStart;
+ pub const terminalToggle = app_terminal.terminalToggle;
+ pub const terminalStep = app_terminal.terminalStep;
+ pub const terminalDamage = app_terminal.terminalDamage;
+ pub const terminalScrollbar = app_terminal.terminalScrollbar;
+ pub const terminalKey = app_terminal.terminalKey;
+ pub const terminalModifiers = app_terminal.terminalModifiers;
+ pub const terminalCopy = app_terminal.terminalCopy;
+ pub const terminalMotion = app_terminal.terminalMotion;
+ pub const terminalButton = app_terminal.terminalButton;
+ pub const terminalCancelPointer = app_terminal.terminalCancelPointer;
+ pub const terminalWheel = app_terminal.terminalWheel;
+ pub const terminalRequestClose = app_terminal.terminalRequestClose;
+ pub const terminalConfirmClose = app_terminal.terminalConfirmClose;
+ pub const terminalFinishClose = app_terminal.terminalFinishClose;
+ pub const terminalExternal = app_terminal.terminalExternal;
+ pub const renderTerminal = app_terminal.renderTerminal;
+
// app_keyboard.zig
pub const keyRepeats = app_keyboard.keyRepeats;
pub const handleKey = app_keyboard.handleKey;
diff --git a/src/files/app_dialogs.zig b/src/files/app_dialogs.zig
index baeda2e..4d5a9e0 100644
--- a/src/files/app_dialogs.zig
+++ b/src/files/app_dialogs.zig
@@ -256,6 +256,7 @@ pub fn openConflictDialog(self: *App, conflict_name: []const u8) void {
pub fn confirmDialog(self: *App) void {
const dlg = self.dialog orelse return;
switch (dlg.kind) {
+ .terminal_close => self.terminalConfirmClose(),
.open_with => self.openWithAction(.open),
.properties => {},
.new_folder => {
@@ -376,5 +377,5 @@ pub fn handleDialogKey(self: *App, sym: u32, utf8: []const u8) void {
return;
}
- self.editKey(&dlg.edit, sym, utf8);
+ if (dlg.kind != .terminal_close) self.editKey(&dlg.edit, sym, utf8);
}
diff --git a/src/files/app_hover.zig b/src/files/app_hover.zig
index 081b6f7..fb0316f 100644
--- a/src/files/app_hover.zig
+++ b/src/files/app_hover.zig
@@ -12,6 +12,7 @@ const places = App.places;
const pin_base = App.pin_base;
pub fn hoverBounds(self: *App, key: usize) ?header.Rect {
+ if (key >= 900 and key < 904) return .{ .x = 0, .y = 0, .w = @floatFromInt(self.w), .h = @floatFromInt(self.h) };
if (key == 0) return .{ .x = 0, .y = 0, .w = 0, .h = 0 };
if (key >= 2_000_000) {
const index = key - 2_000_000;
diff --git a/src/files/app_keyboard.zig b/src/files/app_keyboard.zig
index 2adee8a..ae5e3d0 100644
--- a/src/files/app_keyboard.zig
+++ b/src/files/app_keyboard.zig
@@ -14,13 +14,15 @@ const Editor = @import("editor.zig").Editor;
/// and the file list. Delete, Return, Space and every shortcut fire once:
/// a held Delete must not trash file after file.
pub fn keyRepeats(self: *const App, sym: u32, utf8: []const u8) bool {
+ if (sym == c.XKB_KEY_F4 and !self.ctrl and !self.alt and !self.shift) return false;
+ if (self.dialog == null and self.menu == null and self.focus == .terminal) return !(self.ctrl and self.shift and (sym == c.XKB_KEY_c or sym == c.XKB_KEY_C or sym == c.XKB_KEY_v or sym == c.XKB_KEY_V));
if (self.ctrl or self.alt) return false;
const vertical = sym == c.XKB_KEY_Up or sym == c.XKB_KEY_Down;
const typing = shell_key_repeat.editingKey(switch (sym) {
c.XKB_KEY_BackSpace, c.XKB_KEY_Delete, c.XKB_KEY_Left, c.XKB_KEY_Right => true,
else => false,
}, utf8);
- if (self.dialog) |dlg| return if (dlg.kind == .open_with) vertical else dlg.kind != .properties and dlg.kind != .trash_confirm and dlg.kind != .conflict and typing;
+ if (self.dialog) |dlg| return if (dlg.kind == .open_with) vertical else dlg.kind != .properties and dlg.kind != .trash_confirm and dlg.kind != .conflict and dlg.kind != .terminal_close and typing;
if (self.menu != null) return vertical;
if (self.focus == .search or self.focus == .location_bar or self.focus == .filename) return typing;
return vertical or sym == c.XKB_KEY_Left or sym == c.XKB_KEY_Right or
@@ -40,6 +42,10 @@ pub fn handleKey(self: *App, sym: u32, utf8: []const u8) void {
self.handleDialogKey(sym, utf8);
return;
}
+ if (sym == c.XKB_KEY_F4 and !self.ctrl and !self.alt and !self.shift and self.chooser == null) {
+ self.terminalToggle();
+ return;
+ }
if (self.menu != null) {
const count = self.menuLabels().len;
@@ -48,6 +54,10 @@ pub fn handleKey(self: *App, sym: u32, utf8: []const u8) void {
return;
}
if (self.chooser != null and self.chooserKey(sym, utf8)) return;
+ if (self.focus == .terminal) {
+ self.terminalKey(sym, utf8);
+ return;
+ }
if (self.ctrl and (sym == c.XKB_KEY_f or sym == c.XKB_KEY_F)) {
self.search_visible = true;
self.focus = .search;
@@ -290,6 +300,14 @@ pub fn editKey(self: *App, edit: *Editor, sym: u32, utf8: []const u8) void {
}
pub fn pasteText(self: *App, bytes: []const u8) void {
+ if (self.dialog == null and self.focus == .terminal and self.terminal.visible) {
+ if (self.terminal.session) |session| {
+ if (!@import("terminal/model.zig").c.ft_paste(session, bytes.ptr, bytes.len)) self.setStatusNotice("Terminal paste exceeds the available input queue", true);
+ self.terminal.selection = null;
+ self.terminalDamage();
+ }
+ return;
+ }
const edit = self.activeEditor() orelse return;
if (self.focus == .filename) self.overwrite_pending = false;
edit.insert(self.allocator, bytes) catch {
diff --git a/src/files/app_model.zig b/src/files/app_model.zig
index f56cd8d..9640886 100644
--- a/src/files/app_model.zig
+++ b/src/files/app_model.zig
@@ -178,6 +178,7 @@ pub const ThumbRequest = struct {
};
pub const Focus = enum {
+ terminal,
file_view,
location_bar,
search,
@@ -189,6 +190,7 @@ pub const Focus = enum {
};
pub const DialogKind = enum {
+ terminal_close,
new_folder,
new_file,
new_branch,
diff --git a/src/files/app_paint.zig b/src/files/app_paint.zig
index 848bb79..d895028 100644
--- a/src/files/app_paint.zig
+++ b/src/files/app_paint.zig
@@ -158,6 +158,7 @@ pub fn render(self: *App, cr: *c.cairo_t) void {
// 5. Status Bar
if (self.chooser != null) self.renderChooser(cr) else self.renderStatusBar(cr, h_f);
+ self.renderTerminal(cr);
if (self.menu == null and self.dialog == null and self.selection_band == null) self.renderFilenameTip(cr);
if (self.menu != null) self.renderMenu(cr);
@@ -210,6 +211,11 @@ pub fn editorTextArea(self: *App) header.Rect {
}
pub fn pointerCursor(self: *App, x: f64, y: f64) [*:0]const u8 {
+ if (self.terminal.resize != null or self.overTerminalDivider(x, y)) return "row-resize";
+ if (self.dialog == null and self.menu == null) {
+ if (self.terminalHit(x, y) != null) return "pointer";
+ if (self.terminalHeight() > 0 and self.terminalBody().contains(x, y)) return "text";
+ }
if (self.sidebar_resize != null) return "col-resize";
if (self.text_dragging) return "text";
if (self.menu != null or self.selection_band != null or self.drag_origin != null or self.scroll_drag.active or self.sidebar_scroll_drag.active or self.horizontal_drag.active) return "default";
@@ -443,7 +449,7 @@ pub fn renderStatusBar(self: *App, cr: *c.cairo_t, h_f: f64) void {
}
}
- drawText(cr, status_text, x0 + 14, y + 17, shell_ui.statusSize(), false);
+ drawEllipsis(cr, status_text, x0 + 14, y + 17, @max(0, w_f - x0 - 52), shell_ui.statusSize(), false);
}
pub fn renderDialog(self: *App, cr: *c.cairo_t) void {
@@ -491,7 +497,11 @@ pub fn renderDialog(self: *App, cr: *c.cairo_t) void {
var buf: [256]u8 = undefined;
- if (dlg.kind == .conflict) {
+ if (dlg.kind == .terminal_close) {
+ drawEllipsis(cr, "Closing ends this shell and its running jobs.", dx + 16, dy + 56, dw - 32, shell_ui.textSize(), false);
+ self.renderButton(cr, dx + dw - 184, dy + 84, 80, 28, "Close", true);
+ self.renderButton(cr, dx + dw - 96, dy + 84, 80, 28, "Cancel", true);
+ } else if (dlg.kind == .conflict) {
const conflict_str = dlg.conflict_name orelse "";
const conflict_msg = std.fmt.bufPrint(&buf, "File '{s}' already exists in destination.", .{conflict_str}) catch "Conflict";
setSource(cr, t.fg);
diff --git a/src/files/app_pointer.zig b/src/files/app_pointer.zig
index 660edc7..7f1c544 100644
--- a/src/files/app_pointer.zig
+++ b/src/files/app_pointer.zig
@@ -40,6 +40,7 @@ pub fn hoverKey(self: *App) usize {
return 0;
}
if (self.menu != null) return 100 + (self.menuHit(x, y) orelse 99);
+ if (self.terminalHit(x, y)) |index| return 900 + index;
if (self.sidebar_resize != null or self.overSidebarDivider(x, y)) return 0;
if (self.chooser) |opts| {
if (y >= @as(f64, @floatFromInt(self.h - self.footerHeight()))) {
@@ -86,6 +87,12 @@ pub fn hoverKey(self: *App) usize {
}
pub fn handleMotion(self: *App, x: f64, y: f64) void {
+ if (self.terminalMotion(x, y)) {
+ self.mouse_x = x;
+ self.mouse_y = y;
+ return;
+ }
+ if (self.overTerminalDivider(self.mouse_x, self.mouse_y) != self.overTerminalDivider(x, y)) self.terminalDamage();
if (self.sidebar_resize) |drag| {
self.mouse_x = x;
self.mouse_y = y;
@@ -163,6 +170,10 @@ pub fn handleMotion(self: *App, x: f64, y: f64) void {
}
pub fn cancelDrag(self: *App) void {
+ self.terminalCancelPointer();
+ self.terminal.resize = null;
+ self.terminal.selecting = false;
+ self.terminal.scroll_drag.end();
if (self.dialog) |*dlg| {
dlg.deletion.placement.grab = null;
if (dlg.properties) |*props| props.placement.grab = null;
@@ -209,7 +220,7 @@ pub fn bandScrollDirection(self: *App) i32 {
const band = self.selection_band orelse return 0;
if (!band.active) return 0;
if (self.mouse_y < @as(f64, @floatFromInt(self.viewTop() + 20)) and self.scroll_y > 0) return -1;
- if (self.mouse_y > @as(f64, @floatFromInt(self.h - 46)) and self.scroll_y < self.maxScroll()) return 1;
+ if (self.mouse_y > @as(f64, @floatFromInt(self.contentBottom() - 20)) and self.scroll_y < self.maxScroll()) return 1;
return 0;
}
@@ -241,6 +252,11 @@ pub fn renderSelectionBand(self: *App, cr: *c.cairo_t) void {
}
pub fn handleButton(self: *App, button: u32, pressed: bool) void {
+ if (self.terminalButton(button, pressed)) return;
+ if (pressed and self.dialog == null and self.menu == null and self.focus == .terminal) {
+ self.focus = .file_view;
+ self.terminalDamage();
+ }
// Mice report side buttons either as SIDE/EXTRA or BACK/FORWARD.
if (button == 0x113 or button == 0x116 or button == 0x114 or button == 0x115) {
if (!pressed or self.dialog != null) return;
diff --git a/src/files/app_scroll.zig b/src/files/app_scroll.zig
index 7a0ed9d..5e75abd 100644
--- a/src/files/app_scroll.zig
+++ b/src/files/app_scroll.zig
@@ -23,7 +23,7 @@ pub fn horizontalOffset(self: *App) f64 {
}
pub fn contentBottom(self: *App) i32 {
- return self.h - self.footerHeight() - (if (self.maxHorizontalScroll() > 0) self.scrollbarGutter() else @as(i32, 0));
+ return self.h - self.footerHeight() - self.terminalHeight() - (if (self.maxHorizontalScroll() > 0) self.scrollbarGutter() else @as(i32, 0));
}
pub fn horizontalScrollbar(self: *App) ?scrollbar.Geometry {
@@ -77,6 +77,7 @@ pub fn wheelMax(self: *App) i32 {
}
pub fn handleWheel(self: *App, delta_px: f64, now: i64) void {
+ if (delta_px != 0 and self.terminalWheel(delta_px)) return;
if (self.shift and self.dialog == null and self.mouse_x >= @as(f64, @floatFromInt(self.sidebarWidth()))) {
self.handleHorizontalScroll(delta_px);
return;
@@ -123,6 +124,7 @@ pub fn stepWheel(self: *App, now: i64) void {
}
pub fn handleScroll(self: *App, delta_px: f64) void {
+ if (delta_px != 0 and self.terminalWheel(delta_px)) return;
if (self.shift and self.dialog == null and self.mouse_x >= @as(f64, @floatFromInt(self.sidebarWidth()))) {
self.handleHorizontalScroll(delta_px);
return;
@@ -146,6 +148,7 @@ pub fn handleScroll(self: *App, delta_px: f64) void {
}
pub fn handleHorizontalScroll(self: *App, delta_px: f64) void {
+ if (self.terminalHeight() > 0 and self.terminalRect().contains(self.mouse_x, self.mouse_y)) return;
if (delta_px == 0 or self.dialog != null or self.mouse_x < @as(f64, @floatFromInt(self.sidebarWidth()))) return;
self.cancelWheel();
self.menu = null;
diff --git a/src/files/app_terminal.zig b/src/files/app_terminal.zig
new file mode 100644
index 0000000..b8f4758
--- /dev/null
+++ b/src/files/app_terminal.zig
@@ -0,0 +1,461 @@
+//! Files terminal controller. All terminal state stays in this client process.
+const std = @import("std");
+const App = @import("app.zig").App;
+const model = @import("terminal/model.zig");
+const tc = model.c;
+const c = @import("c.zig").api;
+const ui = @import("ui");
+const Rect = @import("header.zig").Rect;
+const scrollbar = ui.widgets.scrollbar;
+const splitter = ui.widgets.splitter;
+const nowMs = @import("app_draw.zig").nowMs;
+pub const Drawer = model.Drawer;
+pub const header_height = 32;
+
+pub fn terminalHeight(self: *App) i32 {
+ if (self.chooser != null) return 0;
+ return @min(self.terminal.pixels, terminalMaximum(self));
+}
+pub fn terminalMaximum(self: *App) i32 {
+ const available = @max(0, self.h - self.footerHeight() - self.viewTop() - 48);
+ // Header, padding and two normal terminal rows. A smaller window keeps
+ // the session but gives input and all remaining space back to Files.
+ return if (available >= 96) available else 0;
+}
+pub fn terminalRect(self: *App) Rect {
+ const height = self.terminalHeight();
+ return .{ .x = @floatFromInt(self.sidebarWidth()), .y = @floatFromInt(self.h - self.footerHeight() - height), .w = @floatFromInt(self.w - self.sidebarWidth()), .h = @floatFromInt(height) };
+}
+pub fn terminalBody(self: *App) Rect {
+ const rect = self.terminalRect();
+ return .{ .x = rect.x + 8, .y = rect.y + header_height + 6, .w = @max(0, rect.w - 16 - @as(f64, @floatFromInt(self.scrollbarGutter()))), .h = @max(0, rect.h - header_height - 12) };
+}
+/// Button indices: status toggle, collapse, external terminal, restart.
+pub fn terminalControl(self: *App, index: usize) Rect {
+ const rect = self.terminalRect();
+ return switch (index) {
+ 0 => .{ .x = @floatFromInt(self.w - 32), .y = @floatFromInt(self.h - 25), .w = 28, .h = 24 },
+ 1 => .{ .x = rect.x + rect.w - 30, .y = rect.y + 3, .w = 26, .h = 26 },
+ 2 => .{ .x = rect.x + rect.w - 62, .y = rect.y + 3, .w = 26, .h = 26 },
+ else => .{ .x = rect.x + rect.w - 150, .y = rect.y + 3, .w = 84, .h = 26 },
+ };
+}
+pub fn terminalHit(self: *App, x: f64, y: f64) ?usize {
+ if (self.chooser != null) return null;
+ if (self.terminalControl(0).contains(x, y)) return 0;
+ const rect = self.terminalRect();
+ if (rect.h <= 0 or !rect.contains(x, y)) return null;
+ for (1..4) |index| {
+ if (index == 3 and !terminalRestartable(self)) continue;
+ if (self.terminalControl(index).contains(x, y)) return index;
+ }
+ return null;
+}
+pub fn terminalRestartable(self: *App) bool {
+ return if (self.terminal.session) |s| !tc.ft_running(s) and (tc.ft_exited(s) or tc.ft_error(s) != null) else self.terminal.error_message != null;
+}
+pub fn terminalDivider(self: *App) ?splitter.Geometry {
+ const rect = self.terminalRect();
+ if (rect.h <= 0) return null;
+ return .{ .x = rect.x, .y = rect.y, .w = rect.w, .h = 0, .axis = .horizontal };
+}
+pub fn overTerminalDivider(self: *App, x: f64, y: f64) bool {
+ if (self.dialog != null or self.menu != null or !self.terminal.visible) return false;
+ return if (self.terminalDivider()) |divider| divider.contains(x, y) else false;
+}
+
+fn rememberDirectory(self: *App) void {
+ if (self.terminal.navigation == self.navigation_count) return;
+ self.terminal.navigation = self.navigation_count;
+ if (self.isRecent() or self.history.archive_len != 0) return;
+ if (self.trash_dir) |trash| {
+ const current = self.history.current;
+ if (std.mem.eql(u8, current, trash) or (std.mem.startsWith(u8, current, trash) and current.len > trash.len and current[trash.len] == '/')) return;
+ }
+ const path_z = self.allocator.dupeZ(u8, self.history.current) catch return;
+ defer self.allocator.free(path_z);
+ var path_buf: [4096]u8 = undefined;
+ const real = c.realpath(path_z, &path_buf) orelse return;
+ var stat: c.struct_stat = undefined;
+ if (c.stat(real, &stat) != 0 or stat.st_mode & c.S_IFMT != c.S_IFDIR) return;
+ const resolved = std.mem.span(real);
+ if (self.terminal.directory) |old| if (std.mem.eql(u8, old, resolved)) return;
+ const owned = self.allocator.dupeZ(u8, resolved) catch return;
+ if (self.terminal.directory) |old| self.allocator.free(old);
+ self.terminal.directory = owned;
+ if (self.terminal.session) |session| _ = tc.ft_follow(session, owned);
+}
+
+/// Client processes necessarily have WAYLAND_DISPLAY. Only a native login
+/// (or an explicit override) places a scope; isolated/nested tests never do.
+pub fn terminalScopes(self: *App) bool {
+ const policy = @import("../session/launch_policy.zig");
+ const flag = self.environ.getPosix("REDIWM_APP_SCOPES");
+ if (policy.isTruthy(flag)) return true;
+ if (policy.isFalsy(flag)) return false;
+ var view = policy.viewFromEnviron(self.environ);
+ view.host_display = null;
+ return policy.isTruthy(view.login_session) and !policy.isNested(view);
+}
+pub fn terminalHelper(self: *App, name: []const u8, buffer: []u8) ![:0]u8 {
+ _ = self;
+ var executable: [4096]u8 = undefined;
+ const n = c.readlink("/proc/self/exe", &executable, executable.len);
+ if (n <= 0 or n >= executable.len) return error.NoExecutable;
+ const directory = std.fs.path.dirname(executable[0..@intCast(n)]) orelse return error.NoExecutable;
+ return std.fmt.bufPrintZ(buffer, "{s}/{s}", .{ directory, name });
+}
+pub fn terminalStart(self: *App) void {
+ if (self.chooser != null or self.terminal.close_at != null) return;
+ if (self.terminal.session) |old| {
+ if (tc.ft_running(old)) return;
+ tc.ft_free(old);
+ self.terminal.session = null;
+ }
+ self.terminal.error_message = null;
+ self.terminal.selection = null;
+ const session = tc.ft_new(12, 80) orelse {
+ self.terminal.error_message = "Could not allocate terminal";
+ self.invalidate();
+ return;
+ };
+ self.terminal.session = session;
+ self.terminal.generation = std.math.maxInt(u64);
+ rememberDirectory(self);
+ const directory = self.terminal.directory orelse self.allocator.dupeZ(u8, self.home_dir) catch {
+ self.terminal.error_message = "No terminal directory";
+ return;
+ };
+ defer if (self.terminal.directory == null) self.allocator.free(directory);
+ var helper_buf: [4096]u8 = undefined;
+ var plugin_buf: [4096]u8 = undefined;
+ const helper = self.terminalHelper("rediwm-files-terminal", &helper_buf) catch {
+ self.terminal.error_message = "Terminal helper is unavailable";
+ return;
+ };
+ const plugin = self.terminalHelper("../lib/rediwm/files-bash.so", &plugin_buf) catch "";
+ _ = tc.ft_start(session, helper, plugin, directory, self.terminalScopes());
+ self.invalidate();
+}
+pub fn terminalToggle(self: *App) void {
+ if (self.chooser != null or self.dialog != null or self.terminal.close_at != null) return;
+ if (!self.terminal.visible and self.terminalMaximum() == 0) {
+ self.setStatusNotice("Enlarge this window to show the terminal", false);
+ return;
+ }
+ self.cancelDrag();
+ self.menu = null;
+ self.terminal.visible = !self.terminal.visible;
+ self.focus = if (self.terminal.visible) .terminal else .file_view;
+ self.edit_revision += 1;
+ if (self.terminal.visible) {
+ if (self.terminal.requested_height == 0) self.terminal.requested_height = @max(100, @divTrunc(self.h - self.footerHeight() - self.contentTop(), 3));
+ if (self.terminal.session == null and self.terminal.error_message == null) self.terminalStart();
+ }
+ self.invalidate();
+ self.terminalStep(nowMs());
+}
+
+pub fn terminalStep(self: *App, now: i64) void {
+ if (self.chooser != null) return;
+ rememberDirectory(self);
+ const target = if (self.terminal.visible) @min(self.terminal.requested_height, self.terminalMaximum()) else 0;
+ if (target == 0 and self.focus == .terminal) self.focus = .file_view;
+ if (self.terminal.glide.to != @as(f32, @floatFromInt(target))) self.terminal.glide.retargetTo(now, @floatFromInt(target), ui.anim.curveFor(.panel_slide));
+ const pixels: i32 = if (self.terminal.glide.settled(now)) target else @intFromFloat(@round(self.terminal.glide.value(now)));
+ if (pixels != self.terminal.pixels) {
+ self.terminal.pixels = pixels;
+ self.clampScroll();
+ self.invalidate();
+ }
+ self.terminal.active = !self.terminal.glide.settled(now);
+ if (self.terminal.session) |session| {
+ const size = ui.cairo.textSize();
+ const scale: f32 = @floatFromInt(self.scale);
+ self.terminal.cell_w = @max(1, ui.text.measureWidthF("M", .mono, size, scale) catch 9);
+ const metrics = ui.text.verticalMetrics(.mono, size, scale) catch null;
+ self.terminal.ascent = if (metrics) |m| m.ascent else size;
+ self.terminal.cell_h = @ceil(if (metrics) |m| m.ascent + m.descent + 2 else size + 5);
+ const body = self.terminalBody();
+ // During a slide, use the final height and clip to the moving boundary;
+ // no intermediate 0-row PTYs and no sequence of reflowing prompts.
+ const final_height: f64 = @floatFromInt(@max(self.terminalHeight(), target));
+ const rows: i32 = @intFromFloat(@floor(@max(0, final_height - header_height - 12) / self.terminal.cell_h));
+ const cols: i32 = @intFromFloat(@floor(body.w / self.terminal.cell_w));
+ if (self.terminal.visible and rows > 0 and cols >= 2) {
+ const old_cols = tc.ft_cols(session);
+ tc.ft_resize(session, @min(512, rows), @min(512, cols));
+ if (old_cols != tc.ft_cols(session)) self.terminal.selection = null;
+ }
+ const focused = self.terminal.visible and self.focus == .terminal and self.dialog == null and self.menu == null and self.terminal.window_focused;
+ if (focused != self.terminal.focused) {
+ self.terminal.focused = focused;
+ tc.ft_focus(session, focused);
+ }
+ if (self.terminal.generation != self.theme_cfg.generation) {
+ @import("terminal/render.zig").applyPalette(session);
+ self.terminal.generation = self.theme_cfg.generation;
+ }
+ const bar = self.terminalScrollbar();
+ const hovered = if (bar) |b| self.dialog == null and b.overThumb(@floatCast(self.mouse_x), @floatCast(self.mouse_y)) else false;
+ if (self.terminal.bar.step(now, self.terminal.observed_offset != tc.ft_offset(session), hovered, self.terminal.scroll_drag.active, self.terminal.visible and bar != null)) self.terminalDamage();
+ self.terminal.observed_offset = tc.ft_offset(session);
+ if (tc.ft_changed(session)) self.terminalDamage();
+ }
+}
+pub fn terminalDamage(self: *App) void {
+ if (self.terminalHeight() > 0) {
+ var rect = self.terminalRect();
+ // The shared splitter paints just above the drawer's boundary.
+ rect.y -= 2;
+ rect.h += 2;
+ self.addDamage(rect);
+ }
+}
+pub fn terminalScrollbar(self: *App) ?scrollbar.Geometry {
+ const session = self.terminal.session orelse return null;
+ const body = self.terminalBody();
+ if (body.h <= 0) return null;
+ return scrollbar.Geometry.compute(.vertical, .{ .x = @floatCast(body.x + body.w + 4), .y = @floatCast(body.y), .w = @floatFromInt(self.scrollbarGutter()), .h = @floatCast(body.h) }, @floatFromInt(tc.ft_rows(session)), @floatFromInt(tc.ft_rows(session) + tc.ft_history(session)), @floatFromInt(tc.ft_history(session) - tc.ft_offset(session)));
+}
+pub fn terminalKey(self: *App, sym: u32, utf8: []const u8) void {
+ // Modifier presses carry no terminal input. In particular, Ctrl+Shift
+ // must preserve the selection until the following copy key arrives.
+ switch (sym) {
+ c.XKB_KEY_Shift_L,
+ c.XKB_KEY_Shift_R,
+ c.XKB_KEY_Control_L,
+ c.XKB_KEY_Control_R,
+ c.XKB_KEY_Alt_L,
+ c.XKB_KEY_Alt_R,
+ c.XKB_KEY_Meta_L,
+ c.XKB_KEY_Meta_R,
+ c.XKB_KEY_Super_L,
+ c.XKB_KEY_Super_R,
+ c.XKB_KEY_Hyper_L,
+ c.XKB_KEY_Hyper_R,
+ c.XKB_KEY_Caps_Lock,
+ c.XKB_KEY_Num_Lock,
+ c.XKB_KEY_Scroll_Lock,
+ c.XKB_KEY_ISO_Level3_Shift,
+ c.XKB_KEY_ISO_Level5_Shift,
+ c.XKB_KEY_Mode_switch,
+ => return,
+ else => {},
+ }
+ const session = self.terminal.session orelse return;
+ if (self.ctrl and self.shift and (sym == c.XKB_KEY_c or sym == c.XKB_KEY_C)) {
+ terminalCopy(self);
+ } else if (self.ctrl and self.shift and (sym == c.XKB_KEY_v or sym == c.XKB_KEY_V)) {
+ self.text_paste_requested = true;
+ } else if (self.shift and (sym == c.XKB_KEY_Page_Up or sym == c.XKB_KEY_Page_Down)) {
+ tc.ft_scroll(session, (if (sym == c.XKB_KEY_Page_Up) @as(i32, 1) else -1) * @max(1, tc.ft_rows(session) - 1));
+ } else {
+ self.terminal.selection = null;
+ tc.ft_key(session, sym, utf8.ptr, utf8.len, terminalModifiers(self));
+ }
+ self.terminalDamage();
+}
+pub fn terminalModifiers(self: *App) c_int {
+ return @as(c_int, if (self.shift) 1 else 0) | @as(c_int, if (self.alt) 2 else 0) | @as(c_int, if (self.ctrl) 4 else 0);
+}
+pub fn terminalCopy(self: *App) void {
+ const session = self.terminal.session orelse return;
+ const selection = self.terminal.selection orelse return;
+ const ends = selection.ordered();
+ var bytes: std.ArrayList(u8) = .empty;
+ defer bytes.deinit(self.allocator);
+ var line = @max(ends[0].line, tc.ft_line(session) - tc.ft_history(session));
+ const last_line = @min(ends[1].line, tc.ft_line(session) + tc.ft_rows(session) - 1);
+ while (line <= last_line) : (line += 1) {
+ const start = if (line == ends[0].line) ends[0].col else 0;
+ const end = if (line == ends[1].line) ends[1].col else tc.ft_cols(session);
+ const begin = bytes.items.len;
+ var col = start;
+ while (col < end) : (col += 1) {
+ var cell: tc.FT_Cell = undefined;
+ if (!tc.ft_cell_at(session, line, col, &cell) or cell.width == 0) continue;
+ if (cell.chars[0] == 0) bytes.append(self.allocator, ' ') catch return else for (cell.chars) |ch| {
+ if (ch == 0 or ch == std.math.maxInt(u32)) break;
+ var encoded: [4]u8 = undefined;
+ const len = std.unicode.utf8Encode(@intCast(ch), &encoded) catch continue;
+ bytes.appendSlice(self.allocator, encoded[0..len]) catch return;
+ }
+ if (bytes.items.len > 1024 * 1024 - 32) return;
+ }
+ if (!tc.ft_wrapped_at(session, line)) {
+ while (bytes.items.len > begin and bytes.items[bytes.items.len - 1] == ' ') _ = bytes.pop();
+ if (line < last_line) bytes.append(self.allocator, '\n') catch return;
+ }
+ }
+ self.clipboard_text.clearRetainingCapacity();
+ self.clipboard_text.appendSlice(self.allocator, bytes.items) catch return;
+ self.clearClipboard();
+ self.clipboard_cut = false;
+ self.clipboard_is_text = true;
+ self.clipboard_revision += 1;
+}
+
+fn pointAt(self: *App, x: f64, y: f64) model.Point {
+ const session = self.terminal.session.?;
+ const body = self.terminalBody();
+ return .{ .line = tc.ft_line(session) - tc.ft_offset(session) + @as(i32, @intFromFloat(std.math.clamp(@floor((y - body.y) / self.terminal.cell_h), 0, @as(f64, @floatFromInt(tc.ft_rows(session) - 1))))), .col = @intFromFloat(std.math.clamp(@floor((x - body.x) / self.terminal.cell_w), 0, @as(f64, @floatFromInt(tc.ft_cols(session))))) };
+}
+pub fn terminalMotion(self: *App, x: f64, y: f64) bool {
+ if (self.dialog != null or self.menu != null) return false;
+ if (self.terminal.resize) |drag| {
+ self.terminal.requested_height = drag.heightAt(y, @min(96, self.terminalMaximum()), self.terminalMaximum());
+ self.terminal.pixels = self.terminal.requested_height;
+ self.terminal.glide.cancel(@floatFromInt(self.terminal.pixels));
+ self.clampScroll();
+ self.invalidate();
+ return true;
+ }
+ const session = self.terminal.session orelse return false;
+ if (self.terminal.scroll_drag.active) {
+ if (self.terminalScrollbar()) |bar| {
+ const offset: i32 = @intFromFloat(@round(self.terminal.scroll_drag.offsetAt(bar, @floatCast(x), @floatCast(y))));
+ tc.ft_scroll(session, tc.ft_history(session) - offset - tc.ft_offset(session));
+ }
+ self.terminalDamage();
+ return true;
+ }
+ if (self.terminal.selecting) {
+ if (self.terminal.selection) |*selection| selection.end = pointAt(self, x, y);
+ self.terminalDamage();
+ return true;
+ }
+ if (self.terminal.mouse_buttons != 0 or (self.terminalHeight() > 0 and self.terminalBody().contains(x, y) and !self.shift and tc.ft_mouse_mode(session) != 0)) {
+ const p = pointAt(self, x, y);
+ tc.ft_mouse(session, @intCast(p.line - tc.ft_line(session) + tc.ft_offset(session)), p.col, 0, false, self.terminalModifiers());
+ if (self.terminal.mouse_buttons != 0) return true;
+ }
+ return false;
+}
+pub fn terminalButton(self: *App, button: u32, pressed: bool) bool {
+ if (self.chooser != null or self.dialog != null or self.menu != null) return false;
+ const x = self.mouse_x;
+ const y = self.mouse_y;
+ const mouse_button: c_int = switch (button) {
+ 0x110 => 1,
+ 0x112 => 2,
+ 0x111 => 3,
+ else => 0,
+ };
+ const mouse_bit: u8 = if (mouse_button > 0) @as(u8, 1) << @intCast(mouse_button - 1) else 0;
+ if (!pressed and self.terminal.mouse_buttons & mouse_bit != 0) {
+ if (self.terminal.session) |session| {
+ const p = pointAt(self, x, y);
+ tc.ft_mouse(session, @intCast(p.line - tc.ft_line(session) + tc.ft_offset(session)), p.col, mouse_button, false, self.terminalModifiers());
+ }
+ self.terminal.mouse_buttons &= ~mouse_bit;
+ return true;
+ }
+ if (!pressed and (self.terminal.resize != null or self.terminal.selecting or self.terminal.scroll_drag.active)) {
+ if (self.terminal.resize != null) self.savePreferences();
+ self.terminal.resize = null;
+ self.terminal.selecting = false;
+ self.terminal.scroll_drag.end();
+ self.terminalDamage();
+ return true;
+ }
+ if (button == 0x110 and pressed) {
+ if (self.terminalHit(x, y)) |index| {
+ self.edit_revision += 1;
+ switch (index) {
+ 0, 1 => self.terminalToggle(),
+ 2 => self.terminalExternal(),
+ else => self.terminalStart(),
+ }
+ return true;
+ }
+ if (self.overTerminalDivider(x, y)) {
+ self.terminal.resize = .{ .origin = y, .width = self.terminalHeight() };
+ return true;
+ }
+ }
+ if (self.terminalHeight() <= 0 or !self.terminalRect().contains(x, y)) return false;
+ if (pressed) {
+ self.focus = .terminal;
+ self.edit_revision += 1;
+ self.terminalDamage();
+ }
+ const session = self.terminal.session orelse return true;
+ if (!self.terminalBody().contains(x, y) and !self.terminal.selecting) {
+ if (self.terminalScrollbar()) |bar| {
+ if (pressed and button == 0x110) if (scrollbar.press(bar, @floatCast(x), @floatCast(y), @floatFromInt(tc.ft_history(session) - tc.ft_offset(session)))) |action| switch (action) {
+ .grab => self.terminal.scroll_drag.begin(bar, @floatCast(x), @floatCast(y), @floatFromInt(tc.ft_history(session) - tc.ft_offset(session))),
+ .page => |offset| tc.ft_scroll(session, tc.ft_history(session) - @as(i32, @intFromFloat(@round(offset))) - tc.ft_offset(session)),
+ };
+ }
+ return true;
+ }
+ const p = pointAt(self, x, y);
+ if (!self.shift and tc.ft_mouse_mode(session) != 0) {
+ tc.ft_mouse(session, @intCast(p.line - tc.ft_line(session) + tc.ft_offset(session)), p.col, mouse_button, pressed, self.terminalModifiers());
+ if (pressed) self.terminal.mouse_buttons |= mouse_bit;
+ } else if (button == 0x110 and pressed) {
+ self.terminal.selection = .{ .anchor = p, .end = p };
+ self.terminal.selecting = true;
+ }
+ return true;
+}
+pub fn terminalCancelPointer(self: *App) void {
+ if (self.terminal.mouse_buttons != 0) if (self.terminal.session) |session| {
+ const p = pointAt(self, self.mouse_x, self.mouse_y);
+ for (0..3) |index| {
+ if (self.terminal.mouse_buttons & (@as(u8, 1) << @intCast(index)) != 0) tc.ft_mouse(session, @intCast(p.line - tc.ft_line(session) + tc.ft_offset(session)), p.col, @intCast(index + 1), false, self.terminalModifiers());
+ }
+ };
+ self.terminal.mouse_buttons = 0;
+}
+pub fn terminalWheel(self: *App, delta: f64) bool {
+ if (self.dialog != null or self.menu != null or self.terminalHeight() <= 0 or !self.terminalRect().contains(self.mouse_x, self.mouse_y)) return false;
+ if (self.terminal.session) |session| {
+ const lines: i32 = @intFromFloat(@max(1, @ceil(@abs(delta) / 33)));
+ if (!self.shift and tc.ft_mouse_mode(session) != 0) {
+ const p = pointAt(self, self.mouse_x, self.mouse_y);
+ for (0..@intCast(@min(lines, 16))) |_| tc.ft_mouse(session, @intCast(p.line - tc.ft_line(session) + tc.ft_offset(session)), p.col, if (delta < 0) 4 else 5, true, self.terminalModifiers());
+ } else tc.ft_scroll(session, if (delta < 0) lines else -lines);
+ self.terminalDamage();
+ }
+ return true;
+}
+pub fn terminalRequestClose(self: *App) void {
+ if (self.terminal.close_at != null) return;
+ if (self.terminal.session) |session| if (tc.ft_running(session)) {
+ if (self.dialog != null) return;
+ // A snapshot cannot prove that no job began since it arrived. Confirm
+ // every live session, including hidden and unintegrated shells.
+ self.dialog = .{ .kind = .terminal_close, .title = "Close terminal session?" };
+ self.invalidate();
+ return;
+ };
+ self.closed = true;
+}
+pub fn terminalConfirmClose(self: *App) void {
+ self.closeDialog();
+ if (self.terminal.session) |session| if (tc.ft_running(session)) {
+ tc.ft_close(session, false);
+ self.terminal.close_at = nowMs() + 750;
+ return;
+ };
+ self.closed = true;
+}
+pub fn terminalFinishClose(self: *App, now: i64) void {
+ const at = self.terminal.close_at orelse return;
+ if (self.terminal.session) |session| {
+ if (tc.ft_running(session) and now < at) return;
+ if (tc.ft_running(session) and !self.terminal.close_forced) {
+ tc.ft_close(session, true);
+ self.terminal.close_forced = true;
+ self.terminal.close_at = now + 750;
+ return;
+ }
+ }
+ self.closed = true;
+}
+pub fn terminalExternal(self: *App) void {
+ @import("terminal/external.zig").launch(self) catch self.setStatusNotice("Could not open external terminal", true);
+}
+pub const renderTerminal = @import("terminal/render.zig").render;
diff --git a/src/files/app_tests.zig b/src/files/app_tests.zig
index 9e26744..20fe60e 100644
--- a/src/files/app_tests.zig
+++ b/src/files/app_tests.zig
@@ -165,6 +165,69 @@ fn testItems(app: *App, count: usize) !void {
}
}
+test "terminal drawer shares viewport geometry and preserves its preferred height" {
+ var app = try testApp();
+ defer app.deinit();
+ try testItems(&app, 60);
+ app.terminal.visible = true;
+ app.terminal.requested_height = 220;
+ app.terminal.pixels = 220;
+ const bottom = app.contentBottom();
+ try std.testing.expectEqual(app.h - app.footerHeight() - 220, bottom);
+ try std.testing.expectEqual(@as(?usize, null), app.itemAt(260, @floatFromInt(bottom + 1)));
+ try std.testing.expect(app.overTerminalDivider(300, @floatFromInt(bottom)));
+ try std.testing.expectEqualStrings("row-resize", std.mem.span(app.pointerCursor(300, @floatFromInt(bottom))));
+ app.list_view = true;
+ app.column_widths = .{ 1000, 120, 120, 160, 180 };
+ try std.testing.expectEqual(bottom - app.scrollbarGutter(), app.contentBottom());
+ try std.testing.expectEqual(@as(f32, @floatFromInt(app.contentBottom())), app.horizontalScrollbar().?.track.y);
+ app.resize(360, 240);
+ try std.testing.expectEqual(@as(i32, 220), app.terminal.requested_height);
+ try std.testing.expect(app.terminalHeight() <= app.terminalMaximum());
+ try std.testing.expectEqual(@as(i32, 0), app.terminalHeight());
+ try std.testing.expectEqual(app.h - app.footerHeight() - app.scrollbarGutter(), app.contentBottom());
+ app.resize(960, 540);
+ try std.testing.expectEqual(@as(i32, 220), app.terminalHeight());
+}
+
+test "terminal keys, modal priority and chooser isolation" {
+ const tc = @import("terminal/model.zig").c;
+ var app = try testApp();
+ defer app.deinit();
+ app.terminal.session = tc.ft_new(4, 20) orelse return error.OutOfMemory;
+ app.terminal.visible = true;
+ app.focus = .terminal;
+ app.ctrl = true;
+ app.handleKey(c.XKB_KEY_c, "\x03");
+ var bytes: [128]u8 = undefined;
+ try std.testing.expectEqualStrings("\x03", bytes[0..tc.ft_take_output(app.terminal.session.?, &bytes, bytes.len)]);
+ app.handleKey(c.XKB_KEY_l, "\x0c");
+ try std.testing.expect(app.focus == .terminal);
+ const sample = "copy";
+ tc.ft_feed(app.terminal.session.?, sample, sample.len);
+ app.terminal.selection = .{ .anchor = .{ .line = 0, .col = 0 }, .end = .{ .line = 0, .col = 4 } };
+ app.handleKey(c.XKB_KEY_Control_L, "");
+ app.shift = true;
+ app.handleKey(c.XKB_KEY_Shift_L, "");
+ app.handleKey(c.XKB_KEY_C, "\x03");
+ try std.testing.expectEqualStrings("copy", app.clipboard_text.items);
+ app.ctrl = false;
+ app.shift = false;
+ try std.testing.expect(!app.keyRepeats(c.XKB_KEY_F4, ""));
+ app.dialog = .{ .kind = .terminal_close, .title = "Close terminal?" };
+ app.handleKey(c.XKB_KEY_F4, "");
+ try std.testing.expect(app.terminal.visible);
+ app.handleKey(c.XKB_KEY_Escape, "");
+ try std.testing.expect(app.focus == .terminal);
+ app.handleKey(c.XKB_KEY_F4, "");
+ try std.testing.expect(!app.terminal.visible);
+ try std.testing.expect(app.focus == .file_view);
+ app.chooser = .{ .mode = .open };
+ app.handleKey(c.XKB_KEY_F4, "");
+ try std.testing.expect(!app.terminal.visible);
+ try std.testing.expectEqual(@as(?usize, null), app.terminalHit(940, 525));
+}
+
test "address search and dialog share selection editing without file shortcuts" {
var app = try testApp();
defer app.deinit();
diff --git a/src/files/main.zig b/src/files/main.zig
index 74293eb..10071d8 100644
--- a/src/files/main.zig
+++ b/src/files/main.zig
@@ -14,6 +14,7 @@ const clipboard_mod = @import("clipboard.zig");
const theme = @import("../icon_theme.zig");
const Allocator = std.mem.Allocator;
const a = std.heap.c_allocator;
+const terminal_c = @import("terminal/model.zig").c;
const Offer = struct {
proxy: *wl.DataOffer,
@@ -122,6 +123,7 @@ pub const Client = struct {
xkb_state: ?*c.xkb_state = null,
key_repeat: key_repeat.KeyRepeat = .{},
compose: @import("ui").compose.Compose = .{},
+ ime: @import("terminal/ime.zig").Ime = undefined,
/// LC_CTYPE of the session; picks the Compose table (´+c is ç in pt_BR).
locale: []const u8 = "",
app: app_mod.App,
@@ -131,6 +133,7 @@ pub const Client = struct {
.global => |g| {
const iface = std.mem.span(g.interface);
self.cursor_shape.bind(registry, g.name, iface, g.version);
+ if (std.mem.eql(u8, iface, "zwp_text_input_manager_v3")) self.ime.manager = registry.bind(g.name, @import("wayland").client.zwp.TextInputManagerV3, 1) catch null;
if (std.mem.eql(u8, iface, "wl_compositor")) {
self.compositor = registry.bind(g.name, wl.Compositor, @min(g.version, 5)) catch null;
} else if (std.mem.eql(u8, iface, "wl_shm")) {
@@ -182,10 +185,14 @@ pub const Client = struct {
/// the poll, including file-operation state changes. Only animation and
/// known deadlines need a timeout; an idle window sleeps.
fn pollTimeout(self: *Client) c_int {
- if (self.app.wheel_glide.active() or self.app.selectionNeedsScroll() or self.app.hover_active or self.app.layout_active or self.app.scroll_appearance.active or self.app.sidebar_scroll_appearance.active or self.app.horizontal_appearance.active) return 16;
+ if (self.app.wheel_glide.active() or self.app.selectionNeedsScroll() or self.app.hover_active or self.app.layout_active or self.app.scroll_appearance.active or self.app.sidebar_scroll_appearance.active or self.app.horizontal_appearance.active or self.app.terminal.active or self.app.terminal.bar.active) return 16;
if (self.app.hasRunningFolderSize()) return 33;
var deadline: ?i64 = null;
- if (self.app.status_notice != null) deadline = self.app.status_notice_until;
+ if (self.app.terminal.close_at) |at| deadline = earlier(deadline, at);
+ if (self.app.terminal.visible) if (self.app.terminal.bar.deadline) |at| {
+ deadline = earlier(deadline, at);
+ };
+ if (self.app.status_notice != null) deadline = earlier(deadline, self.app.status_notice_until);
if (self.app.scanNoticeDeadline()) |at| deadline = earlier(deadline, at);
if (self.app.scroll_appearance.deadline) |at| deadline = earlier(deadline, at);
if (self.app.horizontal_appearance.deadline) |at| deadline = earlier(deadline, at);
@@ -382,7 +389,7 @@ pub const Client = struct {
self.app.invalidate();
},
.close => {
- self.running = false;
+ self.app.terminalRequestClose();
},
}
}
@@ -536,7 +543,7 @@ pub const Client = struct {
fn handleTitlebarClick(self: *Client, w_f: f64, tbh_f: f64) void {
const close_w: f64 = @min(tbh_f, 32);
if (self.pointer_x >= w_f - close_w) {
- self.running = false;
+ self.app.terminalRequestClose();
return;
}
if (self.seat) |seat| self.xdg_toplevel.move(seat, self.input_serial);
@@ -578,8 +585,12 @@ pub const Client = struct {
fn keyboardEvent(_: *wl.Keyboard, event: wl.Keyboard.Event, self: *Client) void {
switch (event) {
- .enter => self.app.refreshPins(),
+ .enter => {
+ self.app.terminal.window_focused = true;
+ self.app.refreshPins();
+ },
.leave => {
+ self.app.terminal.window_focused = false;
self.key_repeat.stop();
self.compose.reset();
self.app.menu = null;
@@ -1282,6 +1293,8 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
.app = app,
.locale = @import("ui").compose.localeFromEnviron(init.minimal.environ),
};
+ self.ime = .{ .app = &self.app };
+ defer self.ime.deinit();
defer self.compose.deinit();
defer self.app.deinit();
if (chooser) |options| try self.app.configureChooser(options);
@@ -1303,6 +1316,7 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
registry.setListener(*Client, Client.registryEvent, &self);
if (display.roundtrip() != .SUCCESS) return error.DisplayFailed;
+ if (self.seat) |seat| try self.ime.setup(seat);
if (self.compositor == null or self.shm == null or self.wm_base == null) {
return error.MissingWaylandGlobals;
}
@@ -1357,7 +1371,7 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
// Initial commit to start xdg configuration sequence
self.surface.commit();
- while (self.running and !self.app.chooser_done) {
+ while (self.running and !self.app.closed and !self.app.chooser_done) {
self.openEditor();
try self.handleClipboard();
self.app.sync();
@@ -1365,6 +1379,9 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
self.app.stepWheel(app_mod.nowMs());
self.app.stepSelection(app_mod.nowMs());
self.app.stepLayout(app_mod.nowMs());
+ self.app.terminalStep(app_mod.nowMs());
+ self.app.terminalFinishClose(app_mod.nowMs());
+ self.ime.sync(self.titlebarHeight());
self.app.stepHover(app_mod.nowMs());
self.app.stepScrollbar(app_mod.nowMs());
self.app.stepScanNotice(app_mod.nowMs());
@@ -1381,7 +1398,7 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
if (display.dispatchPending() != .SUCCESS) return error.DisplayFailed;
}
- if (self.app.chooser_done) {
+ if (self.app.chooser_done or self.app.closed) {
display.cancelRead();
break;
}
@@ -1391,7 +1408,7 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
return error.DisplayFailed;
}
- var fds: [19]c.struct_pollfd = @splat(.{ .fd = -1, .events = c.POLLIN, .revents = 0 });
+ var fds: [22]c.struct_pollfd = @splat(.{ .fd = -1, .events = c.POLLIN, .revents = 0 });
fds[0] = .{ .fd = display.getFd(), .events = @intCast(c.POLLIN | @as(c_int, if (flushed == .AGAIN) c.POLLOUT else 0)), .revents = 0 };
fds[1].fd = self.app.preview_return_fd orelse -1;
fds[2].fd = if (self.receiving) |receive| receive.fd else -1;
@@ -1404,6 +1421,11 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
fds[16].fd = self.app.children.fd;
fds[17].fd = self.app.extract_picker_fd orelse -1;
fds[18].fd = if (self.app.job_runner) |runner| runner.wake_fd else -1;
+ if (self.app.terminal.session) |session| {
+ fds[19] = .{ .fd = terminal_c.ft_pty(session), .events = @intCast(c.POLLIN | @as(c_int, if (terminal_c.ft_wants_write(session)) c.POLLOUT else 0)), .revents = 0 };
+ fds[20] = .{ .fd = terminal_c.ft_channel(session), .events = @intCast(c.POLLIN | @as(c_int, if (terminal_c.ft_wants_request(session)) c.POLLOUT else 0)), .revents = 0 };
+ fds[21].fd = terminal_c.ft_pidfd(session);
+ }
const send_count = self.sends.items.len;
for (self.sends.items, 0..) |send, i| fds[i + 6] = .{ .fd = send.fd, .events = c.POLLOUT, .revents = 0 };
@@ -1415,6 +1437,7 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
}
if ((fds[0].revents & (c.POLLERR | c.POLLHUP)) != 0) return error.DisplayFailed;
+ if (self.app.terminal.session) |session| terminal_c.ft_io(session, fds[19].revents & (c.POLLIN | c.POLLHUP | c.POLLERR) != 0, fds[19].revents & c.POLLOUT != 0, fds[20].revents != 0, fds[21].revents != 0);
if (fds[3].revents & c.POLLIN != 0) self.app.worker.drainMain();
if (fds[4].revents & c.POLLIN != 0) {
if (self.app.dirsize_pool) |p| p.drainDone();
diff --git a/src/files/preferences.zig b/src/files/preferences.zig
index 8bf8134..1251f33 100644
--- a/src/files/preferences.zig
+++ b/src/files/preferences.zig
@@ -7,6 +7,8 @@ pub const Preferences = struct {
unpinned_places: u8 = 0,
/// Git status, branches and the changed-files list inside repositories.
git_view: bool = true,
+ /// Zero adopts one third of the available space on first opening.
+ terminal_height: u32 = 0,
pub fn path(a: std.mem.Allocator, env: std.process.Environ) ![]u8 {
if (env.getPosix("XDG_STATE_HOME")) |base| {
@@ -20,15 +22,19 @@ pub const Preferences = struct {
defer a.free(data);
const legacy = data.len == 4 and data[0] == '1';
const places = data.len == 5 and data[0] == '2';
- const current = data.len == 6 and data[0] == '3';
- if ((!legacy and !places and !current) or data[1] > 1 or data[2] > 7 or data[data.len - 1] != '\n') return .{};
- if ((places or current) and data[3] > 0x7f) return .{};
- if (current and data[4] > 1) return .{};
+ const v3 = data.len == 6 and data[0] == '3';
+ const current = data.len == 10 and data[0] == '4';
+ if ((!legacy and !places and !v3 and !current) or data[1] > 1 or data[2] > 7 or data[data.len - 1] != '\n') return .{};
+ if ((places or v3 or current) and data[3] > 0x7f) return .{};
+ if ((v3 or current) and data[4] > 1) return .{};
+ const height = if (current) std.mem.readInt(u32, data[5..9], .little) else 0;
+ if (height > 4096) return .{};
return .{
.list = data[1] == 1,
.sort = data[2],
- .unpinned_places = if (places or current) data[3] else 0,
- .git_view = if (current) data[4] == 1 else true,
+ .unpinned_places = if (places or v3 or current) data[3] else 0,
+ .git_view = if (v3 or current) data[4] == 1 else true,
+ .terminal_height = height,
};
}
pub fn save(self: Preferences, a: std.mem.Allocator, io: std.Io, file: []const u8) !void {
@@ -36,7 +42,8 @@ pub const Preferences = struct {
const temporary = try std.fmt.allocPrint(a, "{s}.{d}.tmp", .{ file, @import("c.zig").api.getpid() });
defer a.free(temporary);
defer std.Io.Dir.cwd().deleteFile(io, temporary) catch {};
- const data = [_]u8{ '3', @intFromBool(self.list), self.sort, self.unpinned_places, @intFromBool(self.git_view), '\n' };
+ var data = [_]u8{ '4', @intFromBool(self.list), self.sort, self.unpinned_places, @intFromBool(self.git_view), 0, 0, 0, 0, '\n' };
+ std.mem.writeInt(u32, data[5..9], @min(self.terminal_height, 4096), .little);
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = temporary, .data = &data });
try std.Io.Dir.rename(.cwd(), temporary, .cwd(), file, io);
}
diff --git a/src/files/settings.zig b/src/files/settings.zig
index 94cc69c..faaba6b 100644
--- a/src/files/settings.zig
+++ b/src/files/settings.zig
@@ -18,6 +18,7 @@ pub const ThemeUpdate = struct {
icon_theme: []const u8 = "",
io: std.Io,
single_click_open: bool = true,
+ terminal_opacity: ?f32 = null,
fn init(a: std.mem.Allocator, t: theme.Theme, prefs: config.RegionConfig, root: []const u8, icon_name: []const u8, io: std.Io) !ThemeUpdate {
var value = t;
@@ -127,6 +128,7 @@ pub const Settings = struct {
var root: []const u8 = "";
var prefs: config.RegionConfig = .{};
var single_click_open = true;
+ var terminal_opacity: ?f32 = null;
self.animations = .{};
self.region = .{};
for (paths, 0..) |path, i| {
@@ -144,6 +146,7 @@ pub const Settings = struct {
icon_name = arena.allocator().dupe(u8, icon_name) catch return null;
t = value.theme;
single_click_open = value.compositor.files_single_click_open;
+ terminal_opacity = value.compositor.terminal_opacity;
if (value.theme_pack) |pack| root = arena.allocator().dupe(u8, pack.root) catch return null;
inline for (.{ "font", "mono_font", "start_button_icon" }) |field| @field(t, field) = arena.allocator().dupe(u8, @field(t, field)) catch return null;
prefs = value.region;
@@ -161,6 +164,7 @@ pub const Settings = struct {
self.region.first_day_of_week = prefs.first_day_of_week;
var update = ThemeUpdate.init(a, t, prefs, root, icon_name, io) catch return null;
update.single_click_open = single_click_open;
+ update.terminal_opacity = terminal_opacity;
return update;
}
};
@@ -172,6 +176,10 @@ pub fn loadTheme(a: std.mem.Allocator, io: std.Io, env: std.process.Environ) voi
if (settings.poll(a, io)) |t| t.apply();
}
+pub fn terminalOpacity() ?f32 {
+ return if (applied_theme) |t| t.terminal_opacity else null;
+}
+
/// File timestamps use the same clock preference as the shell.
pub fn dateTime(timestamp: i64, buf: []u8) []const u8 {
return formatDateTime(timestamp, buf, region);
diff --git a/src/files/terminal/bash.c b/src/files/terminal/bash.c
new file mode 100644
index 0000000..7300992
--- /dev/null
+++ b/src/files/terminal/bash.c
@@ -0,0 +1,171 @@
+/* Session-only Bash loadable builtin. Uses Bash's installed public builtin
+ * ABI and Readline's getc hook, without timers, traps, synthetic keys, or
+ * replacing the user's prompt/startup hooks. Qualified on Bash 5.3/Readline 8.3.
+ */
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <stdbool.h>
+#include <sys/socket.h>
+#include <readline/readline.h>
+#include "protocol.h"
+#ifndef RL_STATE_READSTR
+#define RL_STATE_READSTR 0
+#endif
+
+/* Stable loadable-builtin ABI; no dependency on distro-private Bash headers. */
+typedef struct { char *word; int flags; } Word;
+typedef struct WordList { struct WordList *next; Word *word; } WordList;
+struct builtin {
+ char *name; int (*function)(WordList *); int flags;
+ char *const *long_doc; const char *short_doc; char *handle;
+};
+extern int cd_builtin(WordList *);
+extern int get_current_prompt_level(void);
+extern int count_all_jobs(void);
+extern int last_command_exit_value;
+extern int executing_builtin;
+extern char *get_string_value(const char *);
+extern char *decode_prompt_string(char *);
+extern void initialize_readline(void);
+extern void check_signals_and_traps(void);
+
+static int channel = -1;
+static pid_t owner;
+static rl_getc_func_t *previous_getc;
+static struct ft_request pending;
+static uint64_t applied;
+static int following_error;
+static struct ft_status last;
+static struct ft_status queued_status;
+static bool status_queued;
+
+static void flush_status(void) {
+ if (status_queued && send(channel,&queued_status,sizeof queued_status,MSG_DONTWAIT|MSG_NOSIGNAL)==sizeof queued_status) {
+ last=queued_status; status_queued=false;
+ }
+}
+
+static int safe_prompt(void) {
+ const unsigned long unsafe = RL_STATE_METANEXT | RL_STATE_MOREINPUT |
+ RL_STATE_ISEARCH | RL_STATE_NSEARCH | RL_STATE_SEARCH | RL_STATE_NUMERICARG |
+ RL_STATE_MACROINPUT | RL_STATE_MACRODEF | RL_STATE_COMPLETING |
+ RL_STATE_MULTIKEY | RL_STATE_VIMOTION | RL_STATE_CHARSEARCH | RL_STATE_READSTR;
+ return !executing_builtin && get_current_prompt_level() == 1 && rl_end == 0 &&
+ rl_pending_input == 0 && (rl_readline_state & RL_STATE_READCMD) &&
+ !(rl_readline_state & unsafe);
+}
+
+static void report(int flags, int error) {
+ struct ft_status s = { .magic = FT_MAGIC, .flags = flags | (following_error ? FT_ERROR : 0),
+ .serial = applied, .error = error ? error : following_error, .jobs = count_all_jobs() };
+ if (!getcwd(s.path, sizeof s.path)) s.path[0] = 0;
+ queued_status=s;
+ status_queued=memcmp(&s,&last,sizeof s)!=0;
+ flush_status();
+}
+
+static void apply_request(void) {
+ if (!pending.serial || !safe_prompt()) return;
+ /* Absolute path + explicit -- bypass CDPATH and option interpretation.
+ * cd_builtin validates access and maintains Bash's PWD/OLDPWD itself. */
+ Word path = { .word = pending.path, .flags = 0 };
+ Word option = { .word = "--", .flags = 0 };
+ WordList tail = { .next = NULL, .word = &path };
+ WordList args = { .next = &tail, .word = &option };
+ int saved_status = last_command_exit_value;
+ int result = cd_builtin(&args);
+ following_error=result;
+ last_command_exit_value = saved_status;
+ applied = pending.serial;
+ pending.serial = 0;
+ report(FT_READY | (result ? FT_ERROR : 0), result);
+ /* Re-expand the configured prompt, including \w, after a successful cd.
+ * No text from Files is ever parsed as shell code. */
+ if (!result) {
+ char *ps1 = get_string_value("PS1");
+ char *prompt = decode_prompt_string(ps1 ? ps1 : "");
+ if (prompt) { rl_set_prompt(prompt); free(prompt); }
+ rl_redisplay();
+ }
+}
+
+static int terminal_getc(FILE *stream) {
+ if (channel < 0 || getpid() != owner) return previous_getc(stream);
+ for (;;) {
+ apply_request();
+ report(safe_prompt() ? FT_READY : FT_EDITING, 0);
+ struct pollfd fds[2] = {{fileno(stream), POLLIN, 0}, {channel, POLLIN | (status_queued ? POLLOUT : 0), 0}};
+ int rc = poll(fds, 2, -1);
+ if (rc < 0) {
+ if (errno == EINTR) { rl_check_signals(); check_signals_and_traps(); continue; }
+ return previous_getc(stream);
+ }
+ if (fds[1].revents) {
+ if (fds[1].revents & POLLOUT) flush_status();
+ struct ft_request request;
+ ssize_t n;
+ /* At most the socket's bounded receive queue; keep only latest. */
+ while ((n = recv(channel, &request, sizeof request, MSG_DONTWAIT | MSG_TRUNC)) > 0) {
+ if (n == sizeof request && request.magic == FT_MAGIC && request.reserved == 0 &&
+ request.serial > applied && request.path[0] == '/' &&
+ memchr(request.path, 0, sizeof request.path)) pending = request;
+ }
+ if (n == 0 || (fds[1].revents & (POLLHUP | POLLERR | POLLNVAL))) {
+ close(channel); channel = -1;
+ return previous_getc(stream);
+ }
+ apply_request();
+ }
+ if (fds[0].revents) {
+ int ch = previous_getc(stream);
+ following_error=0;
+ /* Report ordinary accept-line/EOF keys once. Printable paste bytes
+ * must not alternate two 4 KiB status packets per character. The
+ * hook itself remains the authority even for custom bindings. */
+ if ((ch=='\r' || ch=='\n' || ch==4) &&
+ !(rl_readline_state & (RL_STATE_MOREINPUT | RL_STATE_SEARCH | RL_STATE_COMPLETING))) report(FT_BUSY, 0);
+ return ch;
+ }
+ }
+}
+
+static int terminal_builtin(WordList *args) {
+ if (args && args->word && !strcmp(args->word->word,"protect")) {
+ if (fcntl(3,F_SETFD,FD_CLOEXEC)<0) return 1;
+ const char *rc=getenv("REDIWM_FILES_RC_FD");
+ if (rc) { int fd=atoi(rc); if (fd>=4) (void)fcntl(fd,F_SETFD,FD_CLOEXEC); }
+ return 0;
+ }
+ if (channel >= 0) return 0;
+ struct ucred peer;
+ socklen_t len = sizeof peer;
+ if (getsockopt(3, SOL_SOCKET, SO_PEERCRED, &peer, &len) ||
+ peer.uid != getuid() || peer.pid != getppid()) return 1;
+ channel = fcntl(3, F_DUPFD_CLOEXEC, 10);
+ close(3);
+ if (channel < 0) return 1;
+ owner = getpid();
+ initialize_readline();
+ previous_getc = rl_getc_function ? rl_getc_function : rl_getc;
+ rl_getc_function = terminal_getc;
+ return 0;
+}
+
+static char *const doc[] = { "Private Files directory coordination.", NULL };
+struct builtin rediwm_terminal_struct = {
+ "rediwm_terminal", terminal_builtin, 1, doc, "rediwm_terminal", NULL
+};
+
+/* Refuse unloading while Readline still points into this library. */
+void rediwm_terminal_builtin_unload(char *name) {
+ (void)name;
+ if (rl_getc_function == terminal_getc) rl_getc_function = previous_getc;
+ if (channel >= 0) close(channel);
+ channel = -1;
+}
diff --git a/src/files/terminal/child.c b/src/files/terminal/child.c
new file mode 100644
index 0000000..247f8b2
--- /dev/null
+++ b/src/files/terminal/child.c
@@ -0,0 +1,86 @@
+/* Executed by posix_spawn: PTY setup runs in a fresh, single-threaded process.
+ * Never run libc/GIO between fork and exec in the multithreaded Files client. */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <gio/gio.h>
+
+static void place_scope(void) {
+ /* Parent resolved the same nested/headless policy as app_scope.place.
+ * Finish placement before executing startup files or any shell children. */
+ GError *error = NULL;
+ GDBusConnection *bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
+ if (!bus) { g_clear_error(&error); return; }
+ char name[96];
+ snprintf(name, sizeof name, "app-rediwm-files-terminal-%ld.scope", (long)getpid());
+ GVariantBuilder props, aux, pids;
+ g_variant_builder_init(&props, G_VARIANT_TYPE("a(sv)"));
+ g_variant_builder_init(&pids, G_VARIANT_TYPE("au"));
+ g_variant_builder_add(&pids, "u", (guint32)getpid());
+ g_variant_builder_add(&props, "(sv)", "PIDs", g_variant_builder_end(&pids));
+ g_variant_builder_add(&props, "(sv)", "Slice", g_variant_new_string("app.slice"));
+ g_variant_builder_add(&props, "(sv)", "CollectMode", g_variant_new_string("inactive-or-failed"));
+ g_variant_builder_init(&aux, G_VARIANT_TYPE("a(sa(sv))"));
+ GVariant *reply = g_dbus_connection_call_sync(bus, "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StartTransientUnit",
+ g_variant_new("(ssa(sv)a(sa(sv)))", name, "fail", &props, &aux), NULL,
+ G_DBUS_CALL_FLAGS_NO_AUTO_START, 1500, NULL, &error);
+ if (reply) g_variant_unref(reply);
+ g_clear_error(&error);
+ g_object_unref(bus);
+}
+
+int main(int argc, char **argv) {
+ if (argc < 5) return 125;
+ /* scope, directory, shell/plugin (or --external + command argv) */
+ int external = !strcmp(argv[3], "--external");
+ if (!strcmp(argv[1], "1")) place_scope();
+ if (chdir(argv[2])) { perror("Terminal directory"); return 125; }
+ if (external) { execvp(argv[4], argv + 4); perror("External terminal"); return 127; }
+ if (setsid() < 0 || ioctl(STDIN_FILENO, TIOCSCTTY, 0) < 0) {
+ perror("Terminal session"); return 125;
+ }
+ signal(SIGINT, SIG_DFL); signal(SIGQUIT, SIG_DFL); signal(SIGHUP, SIG_DFL);
+ signal(SIGPIPE, SIG_DFL); signal(SIGCHLD, SIG_DFL); signal(SIGTSTP, SIG_DFL);
+ signal(SIGTTIN, SIG_DFL); signal(SIGTTOU, SIG_DFL);
+ setenv("TERM", "xterm-256color", 1);
+ setenv("COLORTERM", "truecolor", 1);
+ /* No inherited multiplexer identity, activation token, or stale dimensions. */
+ unsetenv("TMUX"); unsetenv("STY"); unsetenv("COLUMNS"); unsetenv("LINES");
+ unsetenv("XDG_ACTIVATION_TOKEN"); unsetenv("DESKTOP_STARTUP_ID");
+ const char *shell = argv[3];
+ setenv("SHELL",shell,1);
+ const char *base = strrchr(shell, '/'); base = base ? base + 1 : shell;
+ if (!strcmp(base, "bash") && argv[4][0]) {
+ /* Anonymous rcfile: startup config remains on disk untouched. fd 3 is
+ * private until the builtin duplicates it with CLOEXEC. */
+ int rc = memfd_create("files-terminal-rc", 0);
+ static const char script[] =
+ "if builtin enable -f \"$REDIWM_FILES_BASH_PLUGIN\" rediwm_terminal; then\n"
+ " builtin rediwm_terminal protect\n"
+ "else\n"
+ " exec 3<&-\n"
+ "fi\n"
+ "unset REDIWM_FILES_RC_FD\n"
+ "[[ -r $HOME/.bashrc ]] && source \"$HOME/.bashrc\"\n"
+ "builtin rediwm_terminal 2>/dev/null || exec 3<&-\n"
+ "unset REDIWM_FILES_BASH_PLUGIN\n";
+ if (rc < 0 || write(rc, script, sizeof script - 1) != sizeof script - 1 || lseek(rc, 0, SEEK_SET) < 0) return 125;
+ setenv("REDIWM_FILES_BASH_PLUGIN", argv[4], 1);
+ char rc_env[32]; snprintf(rc_env,sizeof rc_env,"%d",rc);
+ setenv("REDIWM_FILES_RC_FD",rc_env,1);
+ char file[64]; snprintf(file, sizeof file, "/proc/self/fd/%d", rc);
+ execl(shell, base, "--rcfile", file, "-i", (char *)NULL);
+ } else {
+ close(3);
+ execl(shell, base, "-i", (char *)NULL);
+ }
+ perror("Terminal shell"); return 127;
+}
diff --git a/src/files/terminal/engine.c b/src/files/terminal/engine.c
new file mode 100644
index 0000000..3320ae5
--- /dev/null
+++ b/src/files/terminal/engine.c
@@ -0,0 +1,520 @@
+#define _GNU_SOURCE
+#include "engine.h"
+#include <vterm.h>
+#include <xkbcommon/xkbcommon.h>
+#include <xkbcommon/xkbcommon-keysyms.h>
+#include <errno.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <poll.h>
+#include <pty.h>
+#include <pwd.h>
+#include <signal.h>
+#include <spawn.h>
+#include <setjmp.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/wait.h>
+
+#if VTERM_VERSION_MAJOR != 0 || VTERM_VERSION_MINOR != 3 || VTERM_VERSION_PATCH < 3
+#error Files requires libvterm 0.3.3 (0.3 ABI)
+#endif
+
+extern char **environ;
+enum { HISTORY_LINES=4096, HISTORY_BYTES=8*1024*1024, OUTPUT_BYTES=1024*1024,
+ READ_BUDGET=64*1024, GRID_MAX=512 };
+struct line { VTermScreenCell *cells; int cols; bool wrapped; };
+struct allocation {
+ struct allocation *next, *previous;
+ union { long double value; void *pointer; } alignment;
+};
+struct ft_terminal {
+ FT_Allocator allocator;
+ struct allocation *allocations;
+ jmp_buf allocation_failure;
+ VTerm *vt;
+ VTermScreen *screen;
+ VTermState *state;
+ int master, channel, pidfd;
+ pid_t pid;
+ bool exited, eof, changed, cursor_visible, reverse, alternate;
+ int exit_status, rows, cols, mouse, cursor_shape;
+ VTermPos cursor;
+ struct line history[HISTORY_LINES];
+ int first, count, offset;
+ int64_t line;
+ size_t history_bytes;
+ char output[OUTPUT_BYTES];
+ size_t out_start, out_len;
+ struct ft_request request;
+ bool request_queued;
+ uint64_t serial;
+ struct ft_status status;
+ const char *error;
+};
+
+static int damage(VTermRect rect, void *user) { (void)rect; ((FT *)user)->changed=true; return 1; }
+static int cursor(VTermPos pos, VTermPos old, int visible, void *user) {
+ (void)old; FT *t=user; t->cursor=pos; t->cursor_visible=visible; t->changed=true; return 1;
+}
+static int property(VTermProp prop, VTermValue *val, void *user) {
+ FT *t=user;
+ switch (prop) {
+ case VTERM_PROP_CURSORVISIBLE: t->cursor_visible=val->boolean; break;
+ case VTERM_PROP_CURSORSHAPE: t->cursor_shape=val->number; break;
+ case VTERM_PROP_REVERSE: t->reverse=val->boolean; break;
+ case VTERM_PROP_ALTSCREEN: t->alternate=val->boolean; t->offset=0; break;
+ case VTERM_PROP_MOUSE: t->mouse=val->number; break;
+ default: break; /* Titles, OSC 7/8/52: no desktop side effects. */
+ }
+ t->changed=true; return 1;
+}
+static void drop_oldest(FT *t) {
+ struct line *line=&t->history[t->first];
+ t->history_bytes-=(size_t)line->cols*sizeof *line->cells;
+ free(line->cells); *line=(struct line){0};
+ t->first=(t->first+1)%HISTORY_LINES; t->count--;
+}
+static int pushline(int cols, const VTermScreenCell *cells, void *user) {
+ FT *t=user;
+ size_t bytes=(size_t)cols*sizeof *cells;
+ if (bytes>HISTORY_BYTES) return 0;
+ VTermScreenCell *copy=malloc(bytes);
+ if (!copy) return 0; /* Output continues; old history remains valid. */
+ memcpy(copy,cells,bytes);
+ for (int col=0;col<cols;col++) copy[col].attrs.reverse^=t->reverse;
+ while (t->count==HISTORY_LINES || t->history_bytes+bytes>HISTORY_BYTES) drop_oldest(t);
+ const VTermLineInfo *next=t->rows>1 ? vterm_state_get_lineinfo(t->state,1) : NULL;
+ t->history[(t->first+t->count)%HISTORY_LINES]=(struct line){copy,cols,next && next->continuation};
+ t->count++; t->history_bytes+=bytes;
+ t->line++;
+ if (t->offset) t->offset=t->offset<t->count ? t->offset+1 : t->count;
+ t->changed=true; return 1;
+}
+static int popline(int cols, VTermScreenCell *cells, void *user) {
+ FT *t=user;
+ if (!t->count) return 0;
+ struct line *line=&t->history[(t->first+t->count-1)%HISTORY_LINES];
+ memset(cells,0,(size_t)cols*sizeof *cells);
+ VTermColor fg,bg;
+ vterm_state_get_default_colors(t->state,&fg,&bg);
+ for (int col=0;col<cols;col++) { cells[col].width=1; cells[col].fg=fg; cells[col].bg=bg; }
+ memcpy(cells,line->cells,(size_t)(cols<line->cols ? cols : line->cols)*sizeof *cells);
+ for (int col=0;col<cols;col++) cells[col].attrs.reverse^=t->reverse;
+ t->history_bytes-=(size_t)line->cols*sizeof *line->cells;
+ free(line->cells); *line=(struct line){0}; t->count--;
+ t->line--;
+ if (t->offset>t->count) t->offset=t->count;
+ t->changed=true; return 1;
+}
+static int clear_history(void *user) {
+ FT *t=user; while(t->count) drop_oldest(t); t->offset=0; t->changed=true; return 1;
+}
+static const VTermScreenCallbacks callbacks={
+ .damage=damage, .movecursor=cursor, .settermprop=property,
+ .sb_pushline=pushline, .sb_popline=popline, .sb_clear=clear_history,
+};
+static void *system_alloc(void *owner, size_t bytes) { (void)owner; return malloc(bytes); }
+static void system_free(void *owner, void *pointer) { (void)owner; free(pointer); }
+static void *terminal_alloc(size_t bytes, void *owner) {
+ FT *t=owner;
+ if (bytes>SIZE_MAX-sizeof(struct allocation)) longjmp(t->allocation_failure,1);
+ struct allocation *allocation=t->allocator.alloc(t->allocator.owner,sizeof *allocation+bytes);
+ if (!allocation) longjmp(t->allocation_failure,1);
+ allocation->previous=NULL; allocation->next=t->allocations;
+ if (allocation->next) allocation->next->previous=allocation;
+ t->allocations=allocation;
+ memset(allocation+1,0,bytes);
+ return allocation+1;
+}
+static void terminal_free(void *pointer, void *owner) {
+ if (!pointer) return;
+ FT *t=owner;
+ struct allocation *allocation=(struct allocation *)pointer-1;
+ if (allocation->previous) allocation->previous->next=allocation->next;
+ else t->allocations=allocation->next;
+ if (allocation->next) allocation->next->previous=allocation->previous;
+ t->allocator.free(t->allocator.owner,allocation);
+}
+static const VTermAllocatorFunctions terminal_allocator={terminal_alloc,terminal_free};
+static void allocation_failed(FT *t) {
+ /* An interrupted libvterm mutation is no longer safe to inspect or free
+ * through its own object graph. Our allocation ledger owns every block. */
+ while (t->allocations) terminal_free(t->allocations+1,t);
+ t->vt=NULL; t->state=NULL; t->screen=NULL;
+ t->error="Terminal ran out of memory"; t->changed=true;
+ ft_close(t,true);
+}
+static bool enqueue(FT *t, const char *bytes, size_t len) {
+ if (len>OUTPUT_BYTES-t->out_len) { t->error="Terminal input queue is full"; return false; }
+ if (t->out_start+t->out_len+len>OUTPUT_BYTES) {
+ memmove(t->output,t->output+t->out_start,t->out_len); t->out_start=0;
+ }
+ memcpy(t->output+t->out_start+t->out_len,bytes,len); t->out_len+=len; return true;
+}
+static void output(const char *bytes, size_t len, void *user) { (void)enqueue(user,bytes,len); }
+
+FT *ft_new(int rows, int cols) {
+ return ft_new_alloc(rows,cols,NULL);
+}
+FT *ft_new_alloc(int rows, int cols, const FT_Allocator *allocator) {
+ if (rows<1 || rows>GRID_MAX || cols<2 || cols>GRID_MAX) return NULL;
+ FT_Allocator a=allocator ? *allocator : (FT_Allocator){NULL,system_alloc,system_free};
+ if (!a.alloc || !a.free) return NULL;
+ FT *t=a.alloc(a.owner,sizeof *t);
+ if (!t) return NULL;
+ memset(t,0,sizeof *t); t->allocator=a;
+ t->master=t->channel=t->pidfd=-1;
+ t->rows=rows; t->cols=cols; t->cursor_visible=true; t->cursor_shape=1;
+ if (setjmp(t->allocation_failure)) { allocation_failed(t); ft_free(t); return NULL; }
+ t->vt=vterm_new_with_allocator(rows,cols,(VTermAllocatorFunctions *)&terminal_allocator,t);
+ vterm_set_utf8(t->vt,1);
+ t->state=vterm_obtain_state(t->vt);
+ t->screen=vterm_obtain_screen(t->vt);
+ vterm_output_set_callback(t->vt,output,t);
+ vterm_screen_set_callbacks(t->screen,&callbacks,t);
+ vterm_screen_enable_altscreen(t->screen,1);
+ /* Physical rows remain stable in history. Screen/history resize clips and
+ * pads, never silently reflows selections or joins unrelated commands. */
+ vterm_screen_enable_reflow(t->screen,false);
+ vterm_screen_set_damage_merge(t->screen,VTERM_DAMAGE_SCREEN);
+ vterm_screen_reset(t->screen,1);
+ return t;
+}
+
+static bool valid_shell(const char *path) {
+ struct stat st;
+ return path && path[0]=='/' && !stat(path,&st) && S_ISREG(st.st_mode) && !access(path,X_OK);
+}
+int ft_start(FT *t, const char *helper, const char *plugin, const char *directory, bool scope) {
+ if (t->pid) return -1;
+ const char *shell=getenv("SHELL");
+ char account_buf[16384]; struct passwd account, *found=NULL;
+ if (!valid_shell(shell)) {
+ if (!getpwuid_r(getuid(),&account,account_buf,sizeof account_buf,&found) && found && valid_shell(found->pw_shell)) shell=found->pw_shell;
+ else shell="/bin/sh";
+ }
+ int master=-1, slave=-1, pair[2]={-1,-1};
+ struct winsize size={.ws_row=(unsigned short)t->rows,.ws_col=(unsigned short)t->cols};
+ if (openpty(&master,&slave,NULL,NULL,&size)) goto failed;
+ if (fcntl(master,F_SETFD,FD_CLOEXEC) || fcntl(slave,F_SETFD,FD_CLOEXEC) ||
+ fcntl(master,F_SETFL,O_NONBLOCK) || socketpair(AF_UNIX,SOCK_SEQPACKET|SOCK_CLOEXEC|SOCK_NONBLOCK,0,pair)) goto failed;
+ int one=1;
+ if (setsockopt(pair[0],SOL_SOCKET,SO_PASSCRED,&one,sizeof one)) goto failed;
+ posix_spawn_file_actions_t actions;
+ if (posix_spawn_file_actions_init(&actions)) goto failed;
+ int rc=0;
+ for (int fd=0;fd<3;fd++) if (posix_spawn_file_actions_adddup2(&actions,slave,fd)) rc=1;
+ if (posix_spawn_file_actions_adddup2(&actions,pair[1],3) ||
+ posix_spawn_file_actions_addclosefrom_np(&actions,4)) rc=1;
+ char *const args[]={(char *)helper,scope ? "1" : "0",(char *)directory,(char *)shell,(char *)plugin,NULL};
+ if (!rc) rc=posix_spawn(&t->pid,helper,&actions,NULL,args,environ);
+ posix_spawn_file_actions_destroy(&actions);
+ if (rc) { errno=rc; goto failed; }
+ close(slave); close(pair[1]); t->master=master; t->channel=pair[0];
+ t->pidfd=(int)syscall(SYS_pidfd_open,t->pid,0);
+ if (t->pidfd<0) { ft_close(t,true); t->error="Could not watch terminal process"; return -1; }
+ t->changed=true; return 0;
+failed:
+ if (master>=0) close(master);
+ if (slave>=0) close(slave);
+ if (pair[0]>=0) close(pair[0]);
+ if (pair[1]>=0) close(pair[1]);
+ t->pid=0; t->error="Could not launch terminal"; return -1;
+}
+void ft_resize(FT *t, int rows, int cols) {
+ if (!t->vt) return;
+ if (rows<1 || rows>GRID_MAX || cols<2 || cols>GRID_MAX || (rows==t->rows && cols==t->cols)) return;
+ if (setjmp(t->allocation_failure)) { allocation_failed(t); return; }
+ t->rows=rows; t->cols=cols;
+ vterm_set_size(t->vt,rows,cols); vterm_screen_flush_damage(t->screen);
+ if (t->master>=0) {
+ struct winsize size={.ws_row=(unsigned short)rows,.ws_col=(unsigned short)cols};
+ (void)ioctl(t->master,TIOCSWINSZ,&size);
+ }
+ t->changed=true;
+}
+void ft_feed(FT *t, const char *bytes, size_t len) {
+ if (!t->vt) return;
+ if (setjmp(t->allocation_failure)) { allocation_failed(t); return; }
+ vterm_input_write(t->vt,bytes,len); vterm_screen_flush_damage(t->screen);
+}
+int ft_pty(const FT *t) { return t->master; }
+int ft_channel(const FT *t) { return t->channel; }
+int ft_pidfd(const FT *t) { return t->exited ? -1 : t->pidfd; }
+bool ft_wants_write(const FT *t) { return t->out_len>0 && !t->eof; }
+bool ft_wants_request(const FT *t) { return t->channel>=0 && t->request_queued; }
+
+static void flush_output(FT *t) {
+ if (t->master<0 || !t->out_len) return;
+ size_t n=t->out_len<READ_BUDGET ? t->out_len : READ_BUDGET;
+ ssize_t written=write(t->master,t->output+t->out_start,n);
+ if (written>0) { t->out_start+=(size_t)written; t->out_len-=(size_t)written; if (!t->out_len) t->out_start=0; }
+ else if (written<0 && errno!=EINTR && errno!=EAGAIN) t->out_len=0;
+}
+static void integration(FT *t) {
+ for (int i=0;i<32 && t->channel>=0;i++) {
+ struct ft_status status;
+ struct iovec iov={&status,sizeof status};
+ char control[CMSG_SPACE(sizeof(struct ucred))];
+ struct msghdr msg={.msg_iov=&iov,.msg_iovlen=1,.msg_control=control,.msg_controllen=sizeof control};
+ ssize_t n=recvmsg(t->channel,&msg,MSG_DONTWAIT|MSG_TRUNC);
+ if (n<0 && (errno==EAGAIN || errno==EINTR)) break;
+ if (n<=0) { close(t->channel); t->channel=-1; t->status.flags=0; t->changed=true; break; }
+ bool authenticated=false;
+ for (struct cmsghdr *cm=CMSG_FIRSTHDR(&msg);cm;cm=CMSG_NXTHDR(&msg,cm)) {
+ if (cm->cmsg_level==SOL_SOCKET && cm->cmsg_type==SCM_CREDENTIALS && cm->cmsg_len>=CMSG_LEN(sizeof(struct ucred))) {
+ struct ucred peer; memcpy(&peer,CMSG_DATA(cm),sizeof peer);
+ authenticated=peer.uid==getuid() && peer.pid==t->pid;
+ }
+ }
+ if (authenticated && n==sizeof status && !(msg.msg_flags&(MSG_TRUNC|MSG_CTRUNC)) &&
+ status.magic==FT_MAGIC && status.serial<=t->serial && memchr(status.path,0,sizeof status.path)) {
+ t->status=status; t->changed=true;
+ }
+ }
+ if (t->request_queued && t->channel>=0 &&
+ send(t->channel,&t->request,sizeof t->request,MSG_DONTWAIT|MSG_NOSIGNAL)==sizeof t->request) t->request_queued=false;
+}
+/* A still-owned (possibly zombie) session leader reserves the session id, so
+ * these signals cannot hit a reused pid. Detached setsid jobs are independent.
+ * Runs only during session teardown, never on an idle or output path. */
+static void signal_session(FT *t, int sig) {
+ if (t->pid<=0 || t->exited || getsid(t->pid)!=t->pid) return;
+ DIR *proc=opendir("/proc");
+ if (!proc) return;
+ struct dirent *entry;
+ while ((entry=readdir(proc))) {
+ char *end; long value=strtol(entry->d_name,&end,10);
+ if (!*entry->d_name || *end || value<=0 || value>INT_MAX || value==t->pid) continue;
+ pid_t pid=(pid_t)value;
+ int fd=(int)syscall(SYS_pidfd_open,pid,0);
+ if (fd<0) continue;
+ if (getsid(pid)==t->pid) (void)syscall(SYS_pidfd_send_signal,fd,sig,NULL,0);
+ close(fd);
+ }
+ closedir(proc);
+}
+void ft_io(FT *t, bool read_pty, bool write_pty, bool channel, bool exited) {
+ if (read_pty && t->master>=0) {
+ char bytes[8192];
+ for (size_t used=0;used<READ_BUDGET;) {
+ ssize_t n=read(t->master,bytes,sizeof bytes);
+ if (n<0 && errno==EINTR) continue;
+ if (n<0 && errno==EAGAIN) break;
+ if (n<=0) { close(t->master); t->master=-1; t->eof=true; t->out_len=0; t->changed=true; break; }
+ used+=(size_t)n; ft_feed(t,bytes,(size_t)n);
+ }
+ }
+ if (write_pty) flush_output(t);
+ if (channel) integration(t);
+ if (exited && t->pid>0 && !t->exited) {
+ int status=0;
+ /* pidfd readiness proves exit; retain the zombie until all remaining
+ * members of this terminal's session have received their final signal. */
+ signal_session(t,SIGKILL);
+ pid_t rc=waitpid(t->pid,&status,WNOHANG);
+ if (rc==t->pid || (rc<0 && errno==ECHILD)) {
+ t->exited=true; t->exit_status=WIFEXITED(status) ? WEXITSTATUS(status) : 128+WTERMSIG(status);
+ t->changed=true;
+ }
+ }
+}
+bool ft_changed(FT *t) { bool changed=t->changed; t->changed=false; return changed; }
+bool ft_running(const FT *t) { return t->pid>0 && !t->exited; }
+bool ft_exited(const FT *t) { return t->exited; }
+int ft_exit_status(const FT *t) { return t->exit_status; }
+const char *ft_error(const FT *t) { return t->error; }
+void ft_close(FT *t, bool force) {
+ if (t->pid>0 && !t->exited) {
+ int signal=force ? SIGKILL : SIGHUP;
+ signal_session(t,signal);
+ if (t->pidfd>=0) (void)syscall(SYS_pidfd_send_signal,t->pidfd,signal,NULL,0);
+ else (void)kill(t->pid,signal);
+ }
+}
+void ft_free(FT *t) {
+ if (!t) return;
+ ft_close(t,true);
+ if (t->pid>0 && !t->exited) (void)waitpid(t->pid,NULL,WNOHANG);
+ if (t->master>=0) close(t->master);
+ if (t->channel>=0) close(t->channel);
+ if (t->pidfd>=0) close(t->pidfd);
+ while(t->count) drop_oldest(t);
+ if (t->vt) vterm_free(t->vt);
+ while (t->allocations) terminal_free(t->allocations+1,t);
+ t->allocator.free(t->allocator.owner,t);
+}
+int ft_follow(FT *t, const char *directory) {
+ if (!directory || directory[0]!='/' || strlen(directory)>=FT_PATH || t->channel<0) return -1;
+ t->request=(struct ft_request){.magic=FT_MAGIC,.serial=++t->serial};
+ strcpy(t->request.path,directory); t->request_queued=true;
+ integration(t); t->changed=true; return 0;
+}
+const struct ft_status *ft_status(const FT *t) { return &t->status; }
+bool ft_pending(const FT *t) { return t->serial>t->status.serial; }
+void ft_palette(FT *t, int index, uint8_t r, uint8_t g, uint8_t b) {
+ if (!t->vt) return;
+ VTermColor color; vterm_color_rgb(&color,r,g,b);
+ if (index>=0 && index<16) vterm_state_set_palette_color(t->state,index,&color);
+ else {
+ VTermColor fg,bg; vterm_state_get_default_colors(t->state,&fg,&bg);
+ if (index==-1) fg=color; else bg=color;
+ vterm_state_set_default_colors(t->state,&fg,&bg);
+ }
+}
+bool ft_cell(FT *t, int row, int col, FT_Cell *cell) {
+ if (row<0 || row>=t->rows || col<0 || col>=t->cols) return false;
+ return ft_cell_at(t,t->line-t->offset+row,col,cell);
+}
+int64_t ft_line(const FT *t) { return t->line; }
+bool ft_cell_at(FT *t, int64_t line_number, int col, FT_Cell *cell) {
+ if (!t->vt) return false;
+ if (line_number<t->line-t->count || line_number>=t->line+t->rows || col<0 || col>=t->cols) return false;
+ VTermScreenCell source={0};
+ int pos=t->count+(int)(line_number-t->line);
+ if (pos<t->count) {
+ const struct line *line=&t->history[(t->first+pos)%HISTORY_LINES];
+ if (col<line->cols) source=line->cells[col];
+ else {
+ source.width=1;
+ vterm_state_get_default_colors(t->state,&source.fg,&source.bg);
+ }
+ source.attrs.reverse^=t->reverse;
+ } else if (!vterm_screen_get_cell(t->screen,(VTermPos){pos-t->count,col},&source)) return false;
+ memset(cell,0,sizeof *cell);
+ memcpy(cell->chars,source.chars,sizeof cell->chars);
+ cell->width=source.width;
+ if (source.chars[0]==UINT32_MAX) cell->width=0;
+ cell->attrs=(source.attrs.bold ? FT_BOLD : 0) | (source.attrs.italic ? FT_ITALIC : 0) |
+ (source.attrs.underline ? FT_UNDERLINE : 0) | (source.attrs.strike ? FT_STRIKE : 0) |
+ (source.attrs.reverse ? FT_REVERSE : 0) | (source.attrs.conceal ? FT_CONCEAL : 0);
+ VTermColor default_fg,default_bg;
+ vterm_state_get_default_colors(t->state,&default_fg,&default_bg);
+ if (VTERM_COLOR_IS_DEFAULT_FG(&source.fg)) source.fg=default_fg;
+ if (VTERM_COLOR_IS_DEFAULT_BG(&source.bg)) source.bg=default_bg;
+ vterm_screen_convert_color_to_rgb(t->screen,&source.fg);
+ vterm_screen_convert_color_to_rgb(t->screen,&source.bg);
+ cell->fg[0]=source.fg.rgb.red; cell->fg[1]=source.fg.rgb.green; cell->fg[2]=source.fg.rgb.blue;
+ cell->bg[0]=source.bg.rgb.red; cell->bg[1]=source.bg.rgb.green; cell->bg[2]=source.bg.rgb.blue;
+ return true;
+}
+bool ft_wrapped(FT *t, int row) {
+ return ft_wrapped_at(t,t->line-t->offset+row);
+}
+bool ft_wrapped_at(FT *t, int64_t line_number) {
+ if (!t->vt) return false;
+ if (line_number<t->line-t->count || line_number>=t->line+t->rows) return false;
+ int pos=t->count+(int)(line_number-t->line);
+ if (pos<t->count) return t->history[(t->first+pos)%HISTORY_LINES].wrapped;
+ int next=pos-t->count+1;
+ const VTermLineInfo *info=next<t->rows ? vterm_state_get_lineinfo(t->state,next) : NULL;
+ return info && info->continuation;
+}
+int ft_history(const FT *t) { return t->count; }
+size_t ft_history_bytes(const FT *t) { return t->history_bytes; }
+int ft_offset(const FT *t) { return t->offset; }
+void ft_scroll(FT *t, int lines) {
+ if (t->alternate) return;
+ int offset=t->offset+lines;
+ if (offset<0) offset=0;
+ if (offset>t->count) offset=t->count;
+ if (offset!=t->offset) { t->offset=offset; t->changed=true; }
+}
+void ft_key(FT *t, uint32_t sym, const char *text, size_t len, int modifiers) {
+ if (!t->vt) return;
+ if (t->offset) { t->offset=0; t->changed=true; }
+ VTermKey key=VTERM_KEY_NONE;
+ switch (sym) {
+ case XKB_KEY_Return: case XKB_KEY_KP_Enter: key=VTERM_KEY_ENTER; break;
+ case XKB_KEY_Tab: case XKB_KEY_ISO_Left_Tab: key=VTERM_KEY_TAB; break;
+ case XKB_KEY_BackSpace: key=VTERM_KEY_BACKSPACE; break;
+ case XKB_KEY_Escape: key=VTERM_KEY_ESCAPE; break;
+ case XKB_KEY_Up: key=VTERM_KEY_UP; break;
+ case XKB_KEY_Down: key=VTERM_KEY_DOWN; break;
+ case XKB_KEY_Left: key=VTERM_KEY_LEFT; break;
+ case XKB_KEY_Right: key=VTERM_KEY_RIGHT; break;
+ case XKB_KEY_Insert: key=VTERM_KEY_INS; break;
+ case XKB_KEY_Delete: key=VTERM_KEY_DEL; break;
+ case XKB_KEY_Home: key=VTERM_KEY_HOME; break;
+ case XKB_KEY_End: key=VTERM_KEY_END; break;
+ case XKB_KEY_Page_Up: key=VTERM_KEY_PAGEUP; break;
+ case XKB_KEY_Page_Down: key=VTERM_KEY_PAGEDOWN; break;
+ default:
+ if (sym>=XKB_KEY_F1 && sym<=XKB_KEY_F35) key=VTERM_KEY_FUNCTION(sym-XKB_KEY_F1+1);
+ break;
+ }
+ if (key!=VTERM_KEY_NONE) vterm_keyboard_key(t->vt,key,modifiers);
+ else if (modifiers&(VTERM_MOD_CTRL|VTERM_MOD_ALT)) {
+ uint32_t ch=xkb_keysym_to_utf32(sym);
+ if (ch) vterm_keyboard_unichar(t->vt,ch,modifiers);
+ } else {
+ /* XKB/compose and IME commits are valid UTF-8. Decode with an explicit
+ * bound; malformed input is replaced, never read beyond the slice. */
+ for (size_t i=0;i<len;) {
+ unsigned char ch=(unsigned char)text[i++]; uint32_t cp=ch; int more=0;
+ if (ch>=0xc2 && ch<=0xdf) { cp=ch&31; more=1; }
+ else if (ch>=0xe0 && ch<=0xef) { cp=ch&15; more=2; }
+ else if (ch>=0xf0 && ch<=0xf4) { cp=ch&7; more=3; }
+ else if (ch>=0x80) cp=0xfffd;
+ if (i+(size_t)more>len) { cp=0xfffd; more=0; }
+ for (int j=0;j<more;j++) {
+ unsigned char c=(unsigned char)text[i];
+ if ((c&0xc0)!=0x80) { cp=0xfffd; break; }
+ cp=(cp<<6)|(c&63); i++;
+ }
+ if (cp>0x10ffff || (cp>=0xd800 && cp<=0xdfff)) cp=0xfffd;
+ vterm_keyboard_unichar(t->vt,cp,0);
+ }
+ }
+}
+bool ft_paste(FT *t, const char *bytes, size_t len) {
+ if (!t->vt) return false;
+ if (len>OUTPUT_BYTES-t->out_len-((OUTPUT_BYTES-t->out_len)>=16 ? 16 : 0) || OUTPUT_BYTES-t->out_len<16) return false;
+ t->offset=0; t->changed=true;
+ vterm_keyboard_start_paste(t->vt);
+ /* Drop ESC and other control bytes so pasted text cannot close bracketed
+ * paste or inject terminal replies. Keep tabs and convert LF to CR. */
+ for (size_t i=0;i<len;i++) {
+ unsigned char ch=(unsigned char)bytes[i];
+ if (ch=='\n') ch='\r';
+ if ((ch>=32 && ch!=127) || ch=='\r' || ch=='\t') (void)enqueue(t,(char *)&ch,1);
+ }
+ vterm_keyboard_end_paste(t->vt); return true;
+}
+void ft_mouse(FT *t, int row, int col, int button, bool pressed, int modifiers) {
+ if (!t->vt) return;
+ if (row<0) row=0;
+ if (row>=t->rows) row=t->rows-1;
+ if (col<0) col=0;
+ if (col>=t->cols) col=t->cols-1;
+ vterm_mouse_move(t->vt,row,col,modifiers);
+ if (button) vterm_mouse_button(t->vt,button,pressed,modifiers);
+}
+int ft_mouse_mode(const FT *t) { return t->mouse; }
+void ft_focus(FT *t, bool focused) {
+ if (!t->vt) return;
+ if (focused) vterm_state_focus_in(t->state); else vterm_state_focus_out(t->state);
+ t->changed=true;
+}
+bool ft_cursor(const FT *t, int *row, int *col, int *shape) {
+ *row=t->cursor.row; *col=t->cursor.col; *shape=t->cursor_shape;
+ return t->cursor_visible && !t->offset;
+}
+int ft_rows(const FT *t) { return t->rows; }
+int ft_cols(const FT *t) { return t->cols; }
+#ifdef FT_TEST
+size_t ft_take_output(FT *t, char *bytes, size_t capacity) {
+ size_t n=capacity<t->out_len ? capacity : t->out_len;
+ memcpy(bytes,t->output+t->out_start,n); t->out_start+=n; t->out_len-=n;
+ if (!t->out_len) t->out_start=0;
+ return n;
+}
+#endif
diff --git a/src/files/terminal/engine.h b/src/files/terminal/engine.h
new file mode 100644
index 0000000..23a4a49
--- /dev/null
+++ b/src/files/terminal/engine.h
@@ -0,0 +1,65 @@
+#ifndef REDIWM_FILES_TERMINAL_ENGINE_H
+#define REDIWM_FILES_TERMINAL_ENGINE_H
+#include <stddef.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include "protocol.h"
+typedef struct ft_terminal FT;
+typedef struct {
+ uint32_t chars[6];
+ uint8_t fg[3], bg[3], width;
+ uint16_t attrs;
+} FT_Cell;
+enum { FT_BOLD=1, FT_ITALIC=2, FT_UNDERLINE=4, FT_STRIKE=8, FT_REVERSE=16, FT_CONCEAL=32 };
+FT *ft_new(int rows, int cols);
+/* Optional allocator for the engine and libvterm, with max_align_t alignment.
+ * Library allocation failure tears down the emulator and reports a failed
+ * session instead of letting libvterm dereference NULL in the Files process. */
+typedef struct {
+ void *owner;
+ void *(*alloc)(void *owner, size_t bytes);
+ void (*free)(void *owner, void *pointer);
+} FT_Allocator;
+FT *ft_new_alloc(int rows, int cols, const FT_Allocator *allocator);
+void ft_free(FT *t);
+int ft_start(FT *t, const char *helper, const char *plugin, const char *directory, bool scope);
+void ft_resize(FT *t, int rows, int cols);
+void ft_feed(FT *t, const char *bytes, size_t len);
+int ft_pty(const FT *t);
+int ft_channel(const FT *t);
+int ft_pidfd(const FT *t);
+bool ft_wants_write(const FT *t);
+bool ft_wants_request(const FT *t);
+void ft_io(FT *t, bool read_pty, bool write_pty, bool channel, bool exited);
+bool ft_changed(FT *t);
+bool ft_running(const FT *t);
+bool ft_exited(const FT *t);
+int ft_exit_status(const FT *t);
+const char *ft_error(const FT *t);
+void ft_close(FT *t, bool force);
+int ft_follow(FT *t, const char *directory);
+const struct ft_status *ft_status(const FT *t);
+bool ft_pending(const FT *t);
+void ft_palette(FT *t, int index, uint8_t r, uint8_t g, uint8_t b);
+bool ft_cell(FT *t, int row, int col, FT_Cell *cell);
+int64_t ft_line(const FT *t);
+bool ft_cell_at(FT *t, int64_t line, int col, FT_Cell *cell);
+bool ft_wrapped_at(FT *t, int64_t line);
+bool ft_wrapped(FT *t, int row);
+int ft_history(const FT *t);
+size_t ft_history_bytes(const FT *t);
+int ft_offset(const FT *t);
+void ft_scroll(FT *t, int lines);
+void ft_key(FT *t, uint32_t sym, const char *text, size_t len, int modifiers);
+bool ft_paste(FT *t, const char *bytes, size_t len);
+void ft_mouse(FT *t, int row, int col, int button, bool pressed, int modifiers);
+int ft_mouse_mode(const FT *t);
+void ft_focus(FT *t, bool focused);
+bool ft_cursor(const FT *t, int *row, int *col, int *shape);
+int ft_rows(const FT *t);
+int ft_cols(const FT *t);
+#ifdef FT_TEST
+/* Noninstalled unit fixture access to queued encoder output. */
+size_t ft_take_output(FT *t, char *bytes, size_t capacity);
+#endif
+#endif
diff --git a/src/files/terminal/external.zig b/src/files/terminal/external.zig
new file mode 100644
index 0000000..6e528d5
--- /dev/null
+++ b/src/files/terminal/external.zig
@@ -0,0 +1,32 @@
+//! Launches an independent configured terminal in a real directory.
+const std = @import("std");
+const App = @import("../app.zig").App;
+const defaults = @import("../../config_runtime/default_apps.zig");
+const apps = @import("../../start_menu/applications.zig");
+const launcher = @import("../../start_menu/launch.zig");
+
+pub fn launch(self: *App) !void {
+ var arena = std.heap.ArenaAllocator.init(self.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const prefs = defaults.load(a, self.io, self.environ);
+ const catalogue = try apps.scanAll(a, self.io, self.environ);
+ const entry = defaults.find(catalogue.entries, prefs.terminal);
+ const args = if (entry) |e| try launcher.parseExec(a, e.exec, e) else try launcher.parseExec(a, self.environ.getPosix("TERMINAL") orelse "foot", null);
+ if (args.len == 0) return error.EmptyCommand;
+ // Theme flags use the same helper as compositor terminal launches.
+ const wrapped = try @import("config").terminal_theme.wrap(a, self.io, args, @import("ui").theme.global, @import("../settings.zig").terminalOpacity());
+ var helper_buf: [4096]u8 = undefined;
+ const helper = try self.terminalHelper("rediwm-files-terminal", &helper_buf);
+ const argv = try a.alloc([]const u8, wrapped.len + 4);
+ argv[0] = helper;
+ argv[1] = if (self.terminalScopes()) "1" else "0";
+ argv[2] = self.terminal.directory orelse self.home_dir;
+ argv[3] = "--external";
+ @memcpy(argv[4..], wrapped);
+ var child = try std.process.spawn(self.io, .{ .argv = argv });
+ self.children.add(self.allocator, child.id.?) catch |err| {
+ child.kill(self.io);
+ return err;
+ };
+}
diff --git a/src/files/terminal/ime.zig b/src/files/terminal/ime.zig
new file mode 100644
index 0000000..304cbfa
--- /dev/null
+++ b/src/files/terminal/ime.zig
@@ -0,0 +1,118 @@
+//! text-input-v3 for terminal input. Terminal output is never surrounding
+//! editable text: commits go to the PTY and preedit stays local until done.
+const std = @import("std");
+const wl = @import("wayland").client.wl;
+const zwp = @import("wayland").client.zwp;
+const App = @import("../app.zig").App;
+const tc = @import("model.zig").c;
+pub const Ime = struct {
+ app: *App,
+ manager: ?*zwp.TextInputManagerV3 = null,
+ input: ?*zwp.TextInputV3 = null,
+ entered: bool = false,
+ enabled: bool = false,
+ serial: u32 = 0,
+ revision: usize = 0,
+ session: ?*tc.FT = null,
+ rectangle: [4]i32 = @splat(0),
+ commit_text: std.ArrayList(u8) = .empty,
+ preedit_text: std.ArrayList(u8) = .empty,
+ has_preedit: bool = false,
+ invalid: bool = false,
+
+ pub fn setup(self: *Ime, seat: *wl.Seat) !void {
+ if (self.manager) |manager| {
+ self.input = try manager.getTextInput(seat);
+ self.input.?.setListener(*Ime, event, self);
+ }
+ }
+ pub fn deinit(self: *Ime) void {
+ if (self.input) |input| input.destroy();
+ if (self.manager) |manager| manager.destroy();
+ self.commit_text.deinit(self.app.allocator);
+ self.preedit_text.deinit(self.app.allocator);
+ }
+ fn clear(self: *Ime) void {
+ self.commit_text.clearRetainingCapacity();
+ self.preedit_text.clearRetainingCapacity();
+ self.has_preedit = false;
+ self.invalid = false;
+ }
+ fn event(_: *zwp.TextInputV3, ev: zwp.TextInputV3.Event, self: *Ime) void {
+ switch (ev) {
+ .enter => self.entered = true,
+ .leave => {
+ self.entered = false;
+ self.enabled = false;
+ self.clear();
+ self.app.terminal.preedit.clearRetainingCapacity();
+ self.app.terminalDamage();
+ },
+ .preedit_string => |e| {
+ self.preedit_text.clearRetainingCapacity();
+ self.has_preedit = true;
+ if (e.text) |s| {
+ const bytes = std.mem.span(s);
+ if (bytes.len <= 4096 and std.unicode.utf8ValidateSlice(bytes)) self.preedit_text.appendSlice(self.app.allocator, bytes) catch {} else self.invalid = true;
+ }
+ },
+ .commit_string => |e| {
+ if (e.text) |s| {
+ const bytes = std.mem.span(s);
+ if (bytes.len + self.commit_text.items.len <= 4096 and std.unicode.utf8ValidateSlice(bytes)) self.commit_text.appendSlice(self.app.allocator, bytes) catch {} else self.invalid = true;
+ }
+ },
+ .delete_surrounding_text => |e| {
+ if (e.before_length != 0 or e.after_length != 0) self.invalid = true;
+ },
+ .done => |e| {
+ defer self.clear();
+ if (self.invalid or e.serial != self.serial or !self.enabled or self.app.dialog != null or self.app.menu != null or self.app.focus != .terminal or !self.app.terminal.visible or self.session != self.app.terminal.session or self.revision != self.app.edit_revision) return;
+ if (self.commit_text.items.len > 0) {
+ // An IME commit is typed text, never paste or shell syntax.
+ if (self.session) |session| tc.ft_key(session, 0, self.commit_text.items.ptr, self.commit_text.items.len, 0);
+ }
+ self.app.terminal.preedit.clearRetainingCapacity();
+ if (self.has_preedit) self.app.terminal.preedit.appendSlice(self.app.allocator, self.preedit_text.items) catch {};
+ self.app.terminalDamage();
+ },
+ }
+ }
+ pub fn sync(self: *Ime, titlebar: i32) void {
+ const input = self.input orelse return;
+ const enabled = self.entered and self.app.focus == .terminal and self.app.terminal.visible and self.app.dialog == null and self.app.menu == null and self.app.terminal.session != null;
+ if (!enabled) {
+ if (self.enabled) {
+ input.disable();
+ input.commit();
+ self.serial +%= 1;
+ self.clear();
+ self.app.terminal.preedit.clearRetainingCapacity();
+ self.app.terminalDamage();
+ }
+ self.enabled = false;
+ return;
+ }
+ const session = self.app.terminal.session.?;
+ var row: c_int = 0;
+ var col: c_int = 0;
+ var shape: c_int = 0;
+ _ = tc.ft_cursor(session, &row, &col, &shape);
+ const body = self.app.terminalBody();
+ const rect: [4]i32 = .{ @intFromFloat(body.x + @as(f64, @floatFromInt(col)) * self.app.terminal.cell_w), @as(i32, @intFromFloat(body.y + @as(f64, @floatFromInt(row)) * self.app.terminal.cell_h)) + titlebar, @intFromFloat(self.app.terminal.cell_w), @intFromFloat(self.app.terminal.cell_h) };
+ if (self.enabled and self.session == session and self.revision == self.app.edit_revision and std.meta.eql(rect, self.rectangle)) return;
+ if (!self.enabled or self.session != session) {
+ input.enable();
+ self.clear();
+ }
+ self.enabled = true;
+ self.revision = self.app.edit_revision;
+ self.session = session;
+ self.rectangle = rect;
+ input.setSurroundingText("", 0, 0);
+ input.setContentType(.{ .multiline = true }, .terminal);
+ input.setCursorRectangle(rect[0], rect[1], @max(1, rect[2]), @max(1, rect[3]));
+ input.commit();
+ self.serial +%= 1;
+ }
+};
diff --git a/src/files/terminal/model.zig b/src/files/terminal/model.zig
new file mode 100644
index 0000000..83a4bf0
--- /dev/null
+++ b/src/files/terminal/model.zig
@@ -0,0 +1,58 @@
+//! Session and drawer state, owned by one Files window.
+const std = @import("std");
+const ui = @import("ui");
+pub const c = @cImport({
+ @cUndef("_FORTIFY_SOURCE");
+ if (@import("builtin").is_test) @cDefine("FT_TEST", "1");
+ @cInclude("engine.h");
+});
+pub const Point = struct { line: i64, col: i32 };
+pub const Selection = struct {
+ anchor: Point,
+ end: Point,
+ pub fn ordered(self: Selection) [2]Point {
+ return if (self.anchor.line < self.end.line or (self.anchor.line == self.end.line and self.anchor.col <= self.end.col))
+ .{ self.anchor, self.end }
+ else
+ .{ self.end, self.anchor };
+ }
+ pub fn contains(self: Selection, line: i64, col: i32) bool {
+ const p = self.ordered();
+ return (line > p[0].line or (line == p[0].line and col >= p[0].col)) and
+ (line < p[1].line or (line == p[1].line and col < p[1].col));
+ }
+};
+pub const Drawer = struct {
+ session: ?*c.FT = null,
+ visible: bool = false,
+ requested_height: i32 = 0,
+ pixels: i32 = 0,
+ glide: ui.anim.Anim = .{},
+ active: bool = false,
+ resize: ?ui.widgets.splitter.Drag = null,
+ directory: ?[:0]u8 = null,
+ navigation: ?u32 = null,
+ focused: bool = false,
+ window_focused: bool = false,
+ generation: u64 = std.math.maxInt(u64),
+ cell_w: f64 = 9,
+ cell_h: f64 = 20,
+ ascent: f64 = 15,
+ error_message: ?[]const u8 = null,
+ selection: ?Selection = null,
+ selecting: bool = false,
+ mouse_buttons: u8 = 0,
+ scroll_drag: ui.widgets.scrollbar.Drag = .{},
+ bar: ui.widgets.scrollbar.Appearance = .{},
+ observed_offset: i32 = 0,
+ close_at: ?i64 = null,
+ close_forced: bool = false,
+ preedit: std.ArrayList(u8) = .empty,
+
+ pub fn deinit(self: *Drawer, a: std.mem.Allocator) void {
+ if (self.session) |session| c.ft_free(session);
+ if (self.directory) |path| a.free(path);
+ self.preedit.deinit(a);
+ self.* = .{};
+ }
+};
diff --git a/src/files/terminal/protocol.h b/src/files/terminal/protocol.h
new file mode 100644
index 0000000..e855c8e
--- /dev/null
+++ b/src/files/terminal/protocol.h
@@ -0,0 +1,17 @@
+#ifndef REDIWM_FILES_TERMINAL_PROTOCOL_H
+#define REDIWM_FILES_TERMINAL_PROTOCOL_H
+#include <stdint.h>
+
+/* Private inherited SOCK_SEQPACKET, never a terminal escape sequence. Paths
+ * are data. Fixed, bounded packets simplify validation on both ends. */
+#define FT_MAGIC 0x46543031u
+#define FT_PATH 4096
+enum { FT_READY = 1, FT_EDITING = 2, FT_BUSY = 4, FT_ERROR = 8 };
+struct ft_request { uint32_t magic; uint32_t reserved; uint64_t serial; char path[FT_PATH]; };
+struct ft_status {
+ uint32_t magic, flags;
+ uint64_t serial;
+ int32_t error, jobs;
+ char path[FT_PATH];
+};
+#endif
diff --git a/src/files/terminal/render.zig b/src/files/terminal/render.zig
new file mode 100644
index 0000000..669e696
--- /dev/null
+++ b/src/files/terminal/render.zig
@@ -0,0 +1,218 @@
+//! Cairo terminal rendering through the shared text rasterizer/font fallback.
+const std = @import("std");
+const ui = @import("ui");
+const theme = ui.theme;
+const shell = ui.cairo;
+const c = @import("../c.zig").api;
+const tc = @import("model.zig").c;
+const App = @import("../app.zig").App;
+const draw = @import("../app_draw.zig");
+const button = ui.widgets.button;
+
+pub fn applyPalette(session: *tc.FT) void {
+ const t = theme.global;
+ setColor(session, -1, t.terminal_fg orelse t.window_fg);
+ setColor(session, -2, t.terminal_bg orelse t.app_bg);
+ const names = .{ "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "bright_black", "bright_red", "bright_green", "bright_yellow", "bright_blue", "bright_magenta", "bright_cyan", "bright_white" };
+ const defaults = [_][3]u8{
+ .{ 24, 24, 24 }, .{ 205, 49, 49 }, .{ 13, 188, 121 }, .{ 229, 190, 11 },
+ .{ 36, 114, 200 }, .{ 188, 63, 188 }, .{ 17, 168, 205 }, .{ 229, 229, 229 },
+ .{ 102, 102, 102 }, .{ 241, 76, 76 }, .{ 35, 209, 139 }, .{ 245, 245, 67 },
+ .{ 59, 142, 234 }, .{ 214, 112, 214 }, .{ 41, 184, 219 }, .{ 255, 255, 255 },
+ };
+ inline for (names, 0..) |name, i| {
+ if (@field(t, "terminal_" ++ name)) |color| setColor(session, i, color) else {
+ const color = defaults[i];
+ tc.ft_palette(session, i, color[0], color[1], color[2]);
+ }
+ }
+}
+fn setColor(session: *tc.FT, index: c_int, color: [4]f32) void {
+ tc.ft_palette(session, index, @intFromFloat(std.math.clamp(color[0], 0, 1) * 255), @intFromFloat(std.math.clamp(color[1], 0, 1) * 255), @intFromFloat(std.math.clamp(color[2], 0, 1) * 255));
+}
+fn rgb(color: [3]u8) [4]f32 {
+ return .{ @as(f32, @floatFromInt(color[0])) / 255, @as(f32, @floatFromInt(color[1])) / 255, @as(f32, @floatFromInt(color[2])) / 255, 1 };
+}
+fn control(self: *App, cr: *c.cairo_t, index: usize, icon: ?ui.layout.IconId, label: []const u8) void {
+ const rect = self.terminalControl(index);
+ var layer = shell.Layer.begin(cr, .{ .x = @floatCast(rect.x), .y = @floatCast(rect.y), .w = @floatCast(rect.w), .h = @floatCast(rect.h) }) orelse return;
+ button.paint(&layer.renderer, layer.local(), .{ .variant = .ghost, .icon = icon, .label = label, .icon_scale = 0.65 }, .{ .pointer = if (self.dialog == null and self.menu == null and rect.contains(self.mouse_x, self.mouse_y)) .hover else .idle, .selected = index == 0 and self.terminal.visible });
+ layer.finish();
+}
+pub fn render(self: *App, cr: *c.cairo_t) void {
+ if (self.chooser != null) return;
+ control(self, cr, 0, .terminal, "Terminal · F4");
+ const rect = self.terminalRect();
+ if (rect.h > 0) {
+ c.cairo_save(cr);
+ c.cairo_rectangle(cr, rect.x, rect.y, rect.w, rect.h);
+ c.cairo_clip(cr);
+ shell.setSource(cr, theme.global.terminal_bg orelse theme.global.app_bg);
+ c.cairo_paint(cr);
+ shell.setSource(cr, theme.global.app_bar);
+ c.cairo_rectangle(cr, rect.x, rect.y, rect.w, 32);
+ c.cairo_fill(cr);
+ var status_buf: [4608]u8 = undefined;
+ const message = terminalLabel(self, &status_buf);
+ if (shell.Layer.begin(cr, .{ .x = @floatCast(rect.x + 12), .y = @floatCast(rect.y + 8), .w = 16, .h = 16 })) |value| {
+ var layer = value;
+ layer.renderer.drawIcon(0, 0, 16, 16, .{ .id = .terminal, .color = theme.global.window_fg });
+ layer.finish();
+ }
+ shell.setSource(cr, theme.global.window_fg);
+ draw.drawEllipsis(cr, message, rect.x + 38, rect.y + 22, @max(0, rect.w - if (self.terminalRestartable()) @as(f64, 200) else 110), shell.statusSize(), false);
+ control(self, cr, 1, .chevron_down, "Hide terminal");
+ control(self, cr, 2, .open, "Open external terminal");
+ if (self.terminalRestartable()) control(self, cr, 3, null, "Restart");
+ if (self.terminal.session) |session| paintCells(self, cr, session);
+ c.cairo_restore(cr);
+ if (self.terminalDivider()) |divider| shell.drawSplitter(cr, divider, self.terminal.resize != null or self.overTerminalDivider(self.mouse_x, self.mouse_y));
+ }
+ if (self.dialog == null and self.menu == null) if (self.terminalHit(self.mouse_x, self.mouse_y)) |index| {
+ const label: []const u8 = switch (index) {
+ 0 => "Terminal · F4",
+ 1 => "Hide terminal · F4",
+ 2 => "Open external terminal",
+ else => "Restart terminal",
+ };
+ const w = shell.measureText(cr, label, shell.statusSize(), false) + 16;
+ const control_rect = self.terminalControl(index);
+ const x = @max(4, @min(control_rect.x, @as(f64, @floatFromInt(self.w)) - w - 4));
+ const y = @max(4, control_rect.y - 28);
+ draw.roundedRect(cr, x, y, w, 24, 4);
+ shell.setSource(cr, theme.global.app_divider);
+ c.cairo_fill(cr);
+ shell.setSource(cr, theme.global.window_fg);
+ shell.drawText(cr, label, x + 8, y + 17, shell.statusSize(), false);
+ };
+}
+fn terminalLabel(self: *App, buffer: []u8) []const u8 {
+ if (self.terminal.error_message) |message| return message;
+ const s = self.terminal.session orelse return "Terminal";
+ if (tc.ft_error(s)) |message| return std.mem.span(message);
+ if (tc.ft_exited(s)) return std.fmt.bufPrint(buffer, "Terminal · Exited ({d})", .{tc.ft_exit_status(s)}) catch "Terminal exited";
+ const status = tc.ft_status(s).*;
+ const known = std.mem.sliceTo(&status.path, 0);
+ const path = if (known.len > 0) known else self.terminal.directory orelse self.home_dir;
+ // Paths may contain literal newlines/control bytes, but the header is one line.
+ var clean: [4096]u8 = undefined;
+ const len = @min(path.len, clean.len);
+ for (path[0..len], clean[0..len]) |ch, *out| out.* = if (ch < 32 or ch == 127) ' ' else ch;
+ const label = if (std.unicode.utf8ValidateSlice(clean[0..len])) clean[0..len] else "Directory";
+ const suffix: []const u8 = if (tc.ft_channel(s) < 0) " · Following unavailable" else if (status.magic == 0) " · Starting…" else if (status.flags & tc.FT_ERROR != 0) " · Folder unavailable" else if (tc.ft_pending(s)) " · Following pending" else "";
+ return std.fmt.bufPrint(buffer, "Terminal · {s}{s}", .{ label, suffix }) catch "Terminal";
+}
+fn cellBytes(cell: tc.FT_Cell, buffer: []u8) []const u8 {
+ var len: usize = 0;
+ for (cell.chars) |ch| {
+ if (ch == 0 or ch > 0x10ffff) break;
+ var bytes: [4]u8 = undefined;
+ const n = std.unicode.utf8Encode(@intCast(ch), &bytes) catch continue;
+ if (len + n > buffer.len) break;
+ @memcpy(buffer[len..][0..n], bytes[0..n]);
+ len += n;
+ }
+ if (len == 0 and buffer.len > 0) {
+ buffer[0] = ' ';
+ len = 1;
+ }
+ return buffer[0..len];
+}
+fn paintCells(self: *App, cr: *c.cairo_t, session: *tc.FT) void {
+ const body = self.terminalBody();
+ if (body.h <= 0 or body.w <= 0) return;
+ c.cairo_save(cr);
+ c.cairo_rectangle(cr, body.x, body.y, body.w, body.h);
+ c.cairo_clip(cr);
+ const drawer = &self.terminal;
+ const cw = drawer.cell_w;
+ const ch = drawer.cell_h;
+ const rows = @min(tc.ft_rows(session), @as(i32, @intFromFloat(@ceil(body.h / ch))));
+ var row: i32 = 0;
+ while (row < rows) : (row += 1) {
+ var col: i32 = 0;
+ while (col < tc.ft_cols(session)) {
+ var cell: tc.FT_Cell = undefined;
+ if (!tc.ft_cell(session, row, col, &cell)) break;
+ if (cell.width == 0) {
+ col += 1;
+ continue;
+ }
+ const selected = if (drawer.selection) |selection| selection.contains(tc.ft_line(session) - tc.ft_offset(session) + row, col) else false;
+ const reverse = cell.attrs & tc.FT_REVERSE != 0;
+ const fg = if (reverse) cell.bg else cell.fg;
+ const bg = if (reverse) cell.fg else cell.bg;
+ const first_col = col;
+ var bytes: [16384]u8 = undefined;
+ var len: usize = 0;
+ const ascii_run = cell.width == 1 and cell.chars[0] >= 32 and cell.chars[0] < 127 and cell.chars[1] == 0;
+ while (col < tc.ft_cols(session)) {
+ var next: tc.FT_Cell = undefined;
+ if (!tc.ft_cell(session, row, col, &next)) break;
+ if (next.width == 0) {
+ col += 1;
+ continue;
+ }
+ const next_selected = if (drawer.selection) |selection| selection.contains(tc.ft_line(session) - tc.ft_offset(session) + row, col) else false;
+ if (next.attrs != cell.attrs or !std.mem.eql(u8, &next.fg, &cell.fg) or !std.mem.eql(u8, &next.bg, &cell.bg) or selected != next_selected) break;
+ if (col != first_col and (!ascii_run or next.width != 1 or next.chars[0] < 32 or next.chars[0] >= 127 or next.chars[1] != 0)) break;
+ const chunk = cellBytes(next, bytes[len..]);
+ len += chunk.len;
+ col += @max(1, next.width);
+ if (!ascii_run) break;
+ }
+ const x = body.x + @as(f64, @floatFromInt(first_col)) * cw;
+ const y = body.y + @as(f64, @floatFromInt(row)) * ch;
+ const width = @as(f64, @floatFromInt(col - first_col)) * cw;
+ shell.setSource(cr, rgb(bg));
+ c.cairo_rectangle(cr, x, y, width, ch);
+ c.cairo_fill(cr);
+ if (selected) {
+ shell.setSource(cr, theme.shellPalette().selectionColor());
+ c.cairo_rectangle(cr, x, y, width, ch);
+ c.cairo_fill(cr);
+ }
+ if (cell.attrs & tc.FT_CONCEAL == 0) {
+ shell.setSource(cr, rgb(fg));
+ c.cairo_save(cr);
+ c.cairo_rectangle(cr, x, y, width, ch);
+ c.cairo_clip(cr);
+ shell.drawStyledText(cr, bytes[0..len], x, y + drawer.ascent, shell.textSize(), if (cell.attrs & tc.FT_BOLD != 0) .mono_bold else .mono, cell.attrs & tc.FT_ITALIC != 0);
+ c.cairo_restore(cr);
+ if (cell.attrs & tc.FT_UNDERLINE != 0) {
+ c.cairo_rectangle(cr, x, y + drawer.ascent + 1, width, 1);
+ c.cairo_fill(cr);
+ }
+ if (cell.attrs & tc.FT_STRIKE != 0) {
+ c.cairo_rectangle(cr, x, y + drawer.ascent * 0.6, width, 1);
+ c.cairo_fill(cr);
+ }
+ }
+ }
+ }
+ var cursor_row: c_int = 0;
+ var cursor_col: c_int = 0;
+ var shape: c_int = 0;
+ if (tc.ft_cursor(session, &cursor_row, &cursor_col, &shape) and drawer.focused) {
+ const x = body.x + @as(f64, @floatFromInt(cursor_col)) * cw;
+ const y = body.y + @as(f64, @floatFromInt(cursor_row)) * ch;
+ const cursor_color = theme.global.terminal_cursor orelse theme.shellPalette().caretColor();
+ shell.setSource(cr, cursor_color);
+ c.cairo_rectangle(cr, x, y + if (shape == 2) ch - 2 else 0, if (shape == 3) 2 else cw, if (shape == 2) 2 else ch);
+ c.cairo_fill(cr);
+ if (shape == 1) {
+ var cell: tc.FT_Cell = undefined;
+ if (tc.ft_cell(session, cursor_row, cursor_col, &cell)) {
+ var text: [24]u8 = undefined;
+ shell.setSource(cr, theme.global.terminal_bg orelse theme.global.app_bg);
+ shell.drawTextFont(cr, cellBytes(cell, &text), x, y + drawer.ascent, shell.textSize(), .mono);
+ }
+ }
+ if (drawer.preedit.items.len > 0) {
+ shell.setSource(cr, theme.global.terminal_fg orelse theme.global.window_fg);
+ shell.drawTextFont(cr, drawer.preedit.items, x, y + drawer.ascent, shell.textSize(), .mono);
+ }
+ }
+ c.cairo_restore(cr);
+ if (self.terminalScrollbar()) |bar| shell.drawScrollbar(cr, ui.widgets.scrollbar.look(bar, drawer.bar, self.scrollbar_width, theme.shellPalette()));
+}
diff --git a/src/files/terminal/tests.zig b/src/files/terminal/tests.zig
new file mode 100644
index 0000000..e13d0ea
--- /dev/null
+++ b/src/files/terminal/tests.zig
@@ -0,0 +1,128 @@
+const std = @import("std");
+const tc = @import("model.zig").c;
+const c = @import("../c.zig").api;
+
+fn feed(t: *tc.FT, bytes: []const u8) void {
+ tc.ft_feed(t, bytes.ptr, bytes.len);
+}
+fn cell(t: *tc.FT, row: i32, col: i32) !tc.FT_Cell {
+ var result: tc.FT_Cell = undefined;
+ try std.testing.expect(tc.ft_cell(t, row, col, &result));
+ return result;
+}
+test "terminal accepts chunked Unicode and escape sequences, attributes and alternate screen" {
+ const t = tc.ft_new(4, 20) orelse return error.OutOfMemory;
+ defer tc.ft_free(t);
+ for ("Aé界e\xcc\x81\x1b[31;1mZ") |byte| feed(t, &.{byte});
+ try std.testing.expectEqual(@as(u32, 'A'), (try cell(t, 0, 0)).chars[0]);
+ try std.testing.expectEqual(@as(u32, 'é'), (try cell(t, 0, 1)).chars[0]);
+ try std.testing.expectEqual(@as(u8, 2), (try cell(t, 0, 2)).width);
+ try std.testing.expectEqual(@as(u8, 0), (try cell(t, 0, 3)).width);
+ try std.testing.expectEqual(@as(u32, 0x301), (try cell(t, 0, 4)).chars[1]);
+ try std.testing.expect((try cell(t, 0, 5)).attrs & tc.FT_BOLD != 0);
+ feed(t, "\x1b[38;2;12;34;56mQ");
+ try std.testing.expectEqualSlices(u8, &.{ 12, 34, 56 }, &(try cell(t, 0, 6)).fg);
+ feed(t, "\x1b[?5h");
+ try std.testing.expect((try cell(t, 0, 0)).attrs & tc.FT_REVERSE != 0);
+ feed(t, "\x1b[?5l");
+ try std.testing.expect((try cell(t, 0, 0)).attrs & tc.FT_REVERSE == 0);
+ feed(t, "\x1b[?1049h\x1b[Halternate");
+ try std.testing.expectEqual(@as(u32, 'a'), (try cell(t, 0, 0)).chars[0]);
+ feed(t, "\x1b[?1049l");
+ try std.testing.expectEqual(@as(u32, 'A'), (try cell(t, 0, 0)).chars[0]);
+ tc.ft_resize(t, 8, 30);
+ try std.testing.expectEqual(@as(i32, 8), tc.ft_rows(t));
+ try std.testing.expectEqual(@as(u32, 'A'), (try cell(t, 0, 0)).chars[0]);
+ tc.ft_resize(t, 0, 0);
+ try std.testing.expectEqual(@as(i32, 30), tc.ft_cols(t));
+}
+test "terminal history stays bounded and preserves a reader's position" {
+ const t = tc.ft_new(3, 80) orelse return error.OutOfMemory;
+ defer tc.ft_free(t);
+ for (0..100) |_| feed(t, "line\r\n");
+ tc.ft_scroll(t, 30);
+ const top = tc.ft_line(t) - tc.ft_offset(t);
+ feed(t, "new\r\n");
+ try std.testing.expectEqual(top, tc.ft_line(t) - tc.ft_offset(t));
+ for (0..10000) |_| feed(t, "bounded\r\n");
+ try std.testing.expect(tc.ft_history(t) <= 4096);
+ try std.testing.expect(tc.ft_history_bytes(t) <= 8 * 1024 * 1024);
+ tc.ft_scroll(t, -100000);
+ try std.testing.expectEqual(@as(i32, 0), tc.ft_offset(t));
+ feed(t, "\x1b[3J");
+ try std.testing.expectEqual(@as(i32, 0), tc.ft_history(t));
+}
+test "terminal encodes controls, application cursors, bracketed paste and mouse modes" {
+ const t = tc.ft_new(4, 20) orelse return error.OutOfMemory;
+ defer tc.ft_free(t);
+ var bytes: [128]u8 = undefined;
+ tc.ft_key(t, c.XKB_KEY_c, "\x03", 1, 4);
+ try std.testing.expectEqualStrings("\x03", bytes[0..tc.ft_take_output(t, &bytes, bytes.len)]);
+ feed(t, "\x1b[?1h");
+ tc.ft_key(t, c.XKB_KEY_Up, "", 0, 0);
+ try std.testing.expectEqualStrings("\x1bOA", bytes[0..tc.ft_take_output(t, &bytes, bytes.len)]);
+ feed(t, "\x1b[?2004h");
+ try std.testing.expect(tc.ft_paste(t, "hi\n\x1btext", 8));
+ try std.testing.expectEqualStrings("\x1b[200~hi\rtext\x1b[201~", bytes[0..tc.ft_take_output(t, &bytes, bytes.len)]);
+ feed(t, "\x1b[?1000h\x1b[?1006h");
+ try std.testing.expect(tc.ft_mouse_mode(t) != 0);
+ tc.ft_mouse(t, 1, 2, 1, true, 0);
+ try std.testing.expectEqualStrings("\x1b[<0;3;2M", bytes[0..tc.ft_take_output(t, &bytes, bytes.len)]);
+ // OSC 52 cannot touch the Wayland clipboard or emit a clipboard response.
+ feed(t, "\x1b]52;c;?\x07\x1b]52;c;YmFk\x07");
+ try std.testing.expectEqual(@as(usize, 0), tc.ft_take_output(t, &bytes, bytes.len));
+ const large = try std.testing.allocator.alloc(u8, 1024 * 1024);
+ defer std.testing.allocator.free(large);
+ @memset(large, 'x');
+ try std.testing.expect(!tc.ft_paste(t, large.ptr, large.len));
+ try std.testing.expectEqual(@as(usize, 0), tc.ft_take_output(t, &bytes, bytes.len));
+}
+test "terminal sessions and palette defaults remain independent" {
+ const t = tc.ft_new(3, 10) orelse return error.OutOfMemory;
+ defer tc.ft_free(t);
+ const other = tc.ft_new(3, 10) orelse return error.OutOfMemory;
+ defer tc.ft_free(other);
+ feed(t, "hello");
+ tc.ft_palette(t, -1, 12, 34, 56);
+ try std.testing.expectEqualSlices(u8, &.{ 12, 34, 56 }, &(try cell(t, 0, 0)).fg);
+ try std.testing.expectEqual(@as(u32, 0), (try cell(other, 0, 0)).chars[0]);
+}
+
+const FailingAllocator = struct {
+ calls: usize = 0,
+ fail_at: usize,
+ active: usize = 0,
+ fn alloc(owner: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque {
+ const self: *FailingAllocator = @ptrCast(@alignCast(owner.?));
+ self.calls += 1;
+ if (self.calls == self.fail_at) return null;
+ const pointer = c.malloc(size) orelse return null;
+ self.active += 1;
+ return pointer;
+ }
+ fn free(owner: ?*anyopaque, pointer: ?*anyopaque) callconv(.c) void {
+ const self: *FailingAllocator = @ptrCast(@alignCast(owner.?));
+ if (pointer != null) self.active -= 1;
+ c.free(pointer);
+ }
+};
+test "libvterm allocation failures release partial construction and fail resize safely" {
+ var reached_success = false;
+ for (1..40) |fail_at| {
+ var state: FailingAllocator = .{ .fail_at = fail_at };
+ const allocator: tc.FT_Allocator = .{ .owner = &state, .alloc = FailingAllocator.alloc, .free = FailingAllocator.free };
+ if (tc.ft_new_alloc(4, 20, &allocator)) |t| {
+ state.calls = 0;
+ state.fail_at = 1;
+ tc.ft_resize(t, 24, 120);
+ try std.testing.expect(tc.ft_error(t) != null);
+ var result: tc.FT_Cell = undefined;
+ try std.testing.expect(!tc.ft_cell(t, 0, 0, &result));
+ tc.ft_free(t);
+ reached_success = true;
+ }
+ try std.testing.expectEqual(@as(usize, 0), state.active);
+ if (reached_success) break;
+ }
+ try std.testing.expect(reached_success);
+}
diff --git a/src/files_tests.zig b/src/files_tests.zig
index f6fe1c2..c2d4a2e 100644
--- a/src/files_tests.zig
+++ b/src/files_tests.zig
@@ -599,11 +599,15 @@ test "view preferences survive restart and reject malformed state" {
defer ops_mod.deleteRecursive(a, tmp) catch {};
const path = try std.fmt.allocPrint(a, "{s}/state/files", .{tmp});
defer a.free(path);
- const pref: Preferences = .{ .list = true, .sort = 7, .unpinned_places = 0b0101010 };
+ const pref: Preferences = .{ .list = true, .sort = 7, .unpinned_places = 0b0101010, .terminal_height = 286 };
try pref.save(a, std.testing.io, path);
try std.testing.expectEqual(pref, Preferences.load(a, std.testing.io, path));
try writeTestFile(path, &.{ '1', 1, 7, '\n' });
try std.testing.expectEqual(Preferences{ .list = true, .sort = 7 }, Preferences.load(a, std.testing.io, path));
+ try writeTestFile(path, &.{ '3', 1, 2, 3, 0, '\n' });
+ try std.testing.expectEqual(Preferences{ .list = true, .sort = 2, .unpinned_places = 3, .git_view = false }, Preferences.load(a, std.testing.io, path));
+ try writeTestFile(path, &.{ '4', 0, 0, 0, 1, 0xff, 0xff, 0xff, 0xff, '\n' });
+ try std.testing.expectEqual(Preferences{}, Preferences.load(a, std.testing.io, path));
try writeTestFile(path, &.{ '2', 1, 7, 0x80, '\n' });
try std.testing.expectEqual(Preferences{}, Preferences.load(a, std.testing.io, path));
try writeTestFile(path, "invalid");
@@ -1095,6 +1099,7 @@ test {
_ = @import("files/thumbs.zig");
_ = @import("files/volumes.zig");
_ = @import("files/pins.zig");
+ _ = @import("files/terminal/tests.zig");
}
test {
diff --git a/src/session/activation.zig b/src/session/activation.zig
index 31986e8..5bb1d7c 100644
--- a/src/session/activation.zig
+++ b/src/session/activation.zig
@@ -9,48 +9,12 @@ const wire = dbus.wire;
const log = std.log.scoped(.activation);
-pub const EnvView = struct {
- nested_flag: ?[]const u8 = null,
- backends: ?[]const u8 = null,
- import_flag: ?[]const u8 = null,
- config_home: ?[]const u8 = null,
- home: ?[]const u8 = null,
- login_session: ?[]const u8 = null,
- primary: ?[]const u8 = null,
- host_display: ?[]const u8 = null,
-};
-
-pub fn viewFromEnviron(environ: std.process.Environ) EnvView {
- return .{
- .nested_flag = environ.getPosix("REDIWM_NESTED"),
- .backends = environ.getPosix("WLR_BACKENDS"),
- .import_flag = environ.getPosix("REDIWM_IMPORT_ACTIVATION_ENV"),
- .config_home = environ.getPosix("XDG_CONFIG_HOME"),
- .home = environ.getPosix("HOME"),
- .login_session = environ.getPosix("REDIWM_LOGIN_SESSION"),
- .primary = environ.getPosix("REDIWM_SESSION_PRIMARY"),
- .host_display = environ.getPosix("WAYLAND_DISPLAY"),
- };
-}
-
-pub fn isTruthy(text: ?[]const u8) bool {
- const value = text orelse return false;
- return value.len > 0 and !std.mem.eql(u8, value, "0") and !std.mem.eql(u8, value, "false");
-}
-
-pub fn isFalsy(text: ?[]const u8) bool {
- const value = text orelse return false;
- return std.mem.eql(u8, value, "0") or std.mem.eql(u8, value, "false");
-}
-
-/// Nested Wayland, headless test backends, or an explicit REDIWM_NESTED flag.
-/// A DRM login typically leaves WLR_BACKENDS unset (or "drm") — not nested.
-pub fn isNested(view: EnvView) bool {
- if (isTruthy(view.nested_flag)) return true;
- const backends = view.backends orelse return view.host_display != null;
- return std.mem.indexOf(u8, backends, "wayland") != null or
- std.mem.indexOf(u8, backends, "headless") != null;
-}
+const policy = @import("launch_policy.zig");
+pub const EnvView = policy.EnvView;
+pub const viewFromEnviron = policy.viewFromEnviron;
+pub const isTruthy = policy.isTruthy;
+pub const isFalsy = policy.isFalsy;
+pub const isNested = policy.isNested;
/// Publish only on a real login. REDIWM_IMPORT_ACTIVATION_ENV=0 skips even
/// then; there is no force-import override for nested sessions (that would
diff --git a/src/session/launch_policy.zig b/src/session/launch_policy.zig
new file mode 100644
index 0000000..9bad513
--- /dev/null
+++ b/src/session/launch_policy.zig
@@ -0,0 +1,45 @@
+//! Pure launch/session environment policy, shared with poll-based app clients.
+const std = @import("std");
+
+pub const EnvView = struct {
+ nested_flag: ?[]const u8 = null,
+ backends: ?[]const u8 = null,
+ import_flag: ?[]const u8 = null,
+ config_home: ?[]const u8 = null,
+ home: ?[]const u8 = null,
+ login_session: ?[]const u8 = null,
+ primary: ?[]const u8 = null,
+ host_display: ?[]const u8 = null,
+};
+
+pub fn viewFromEnviron(environ: std.process.Environ) EnvView {
+ return .{
+ .nested_flag = environ.getPosix("REDIWM_NESTED"),
+ .backends = environ.getPosix("WLR_BACKENDS"),
+ .import_flag = environ.getPosix("REDIWM_IMPORT_ACTIVATION_ENV"),
+ .config_home = environ.getPosix("XDG_CONFIG_HOME"),
+ .home = environ.getPosix("HOME"),
+ .login_session = environ.getPosix("REDIWM_LOGIN_SESSION"),
+ .primary = environ.getPosix("REDIWM_SESSION_PRIMARY"),
+ .host_display = environ.getPosix("WAYLAND_DISPLAY"),
+ };
+}
+
+pub fn isTruthy(text: ?[]const u8) bool {
+ const value = text orelse return false;
+ return value.len > 0 and !std.mem.eql(u8, value, "0") and !std.mem.eql(u8, value, "false");
+}
+
+pub fn isFalsy(text: ?[]const u8) bool {
+ const value = text orelse return false;
+ return std.mem.eql(u8, value, "0") or std.mem.eql(u8, value, "false");
+}
+
+/// Nested Wayland, headless test backends, or an explicit REDIWM_NESTED flag.
+/// A DRM login typically leaves WLR_BACKENDS unset (or "drm") — not nested.
+pub fn isNested(view: EnvView) bool {
+ if (isTruthy(view.nested_flag)) return true;
+ const backends = view.backends orelse return view.host_display != null;
+ return std.mem.indexOf(u8, backends, "wayland") != null or
+ std.mem.indexOf(u8, backends, "headless") != null;
+}
diff --git a/src/ui/cairo.zig b/src/ui/cairo.zig
index 42345a5..bff43c3 100644
--- a/src/ui/cairo.zig
+++ b/src/ui/cairo.zig
@@ -178,10 +178,19 @@ pub fn drawScrollbar(cr_any: *anyopaque, look: scrollbar.Look) void {
/// Draws `str` with its pen at `x` and baseline at `y`, like
/// `cairo_show_text`, in the context's current (solid) source colour.
pub fn drawText(cr_any: *anyopaque, str: []const u8, x: f64, y: f64, size: f64, bold: bool) void {
+ drawTextFont(cr_any, str, x, y, size, fontOf(bold));
+}
+
+/// Explicit face for terminal cells; uses the same shaping/fallback and
+/// device-pixel placement as ordinary client text.
+pub fn drawTextFont(cr_any: *anyopaque, str: []const u8, x: f64, y: f64, size: f64, font: text.Font) void {
+ drawStyledText(cr_any, str, x, y, size, font, false);
+}
+
+pub fn drawStyledText(cr_any: *anyopaque, str: []const u8, x: f64, y: f64, size: f64, font: text.Font, italic: bool) void {
if (str.len == 0) return;
const cr: *c.cairo_t = @ptrCast(cr_any);
const s = scaleOf(cr);
- const font = fontOf(bold);
const size_f: f32 = @floatCast(size);
const m = text.verticalMetrics(font, size_f, s) catch return;
const advance = text.measureWidthF(str, font, size_f, s) catch return;
@@ -208,6 +217,7 @@ pub fn drawText(cr_any: *anyopaque, str: []const u8, x: f64, y: f64, size: f64,
.clip = .{ .x = 0, .y = 0, .w = w_logical, .h = h_logical },
.ellipsize = false,
.baseline = baseline,
+ .italic = italic,
}) catch return;
// Pen and baseline onto whole device pixels, so the raster lands 1:1.
diff --git a/src/ui/shell_icons.zig b/src/ui/shell_icons.zig
index 76b9a65..2486c3a 100644
--- a/src/ui/shell_icons.zig
+++ b/src/ui/shell_icons.zig
@@ -57,6 +57,7 @@ pub fn configure(io: std.Io, root: []const u8) void {
.{ IconId.git_branch, "git-branch" },
.{ IconId.home, "home" },
.{ IconId.folder, "folder" },
+ .{ IconId.terminal, "terminal" },
.{ IconId.edit, "edit" },
.{ IconId.keyboard, "keyboard" },
.{ IconId.settings, "settings" },
@@ -147,6 +148,7 @@ fn builtinSource(id: IconId) ?[]const u8 {
.git_branch => @embedFile("shell-icon-git-branch"),
.home => @embedFile("shell-icon-home"),
.folder => @embedFile("shell-icon-folder"),
+ .terminal => @embedFile("shell-icon-terminal"),
.edit => @embedFile("shell-icon-edit"),
.keyboard => @embedFile("shell-icon-keyboard"),
.settings => @embedFile("shell-icon-settings"),
diff --git a/src/ui/widgets/splitter.zig b/src/ui/widgets/splitter.zig
index ca99b60..5297c57 100644
--- a/src/ui/widgets/splitter.zig
+++ b/src/ui/widgets/splitter.zig
@@ -1,4 +1,4 @@
-//! A vertical pane divider with a wider pointer target than its painted line.
+//! Pane dividers with a wider pointer target than their painted line.
const theme = @import("../theme.zig");
pub const Rect = @import("field.zig").Rect;
@@ -6,13 +6,19 @@ pub const Geometry = struct {
x: f64,
y: f64,
h: f64,
+ w: f64 = 0,
+ axis: enum { vertical, horizontal } = .vertical,
pub fn contains(self: Geometry, x: f64, y: f64) bool {
- return @abs(x - self.x) <= 4 and y >= self.y and y < self.y + self.h;
+ return if (self.axis == .horizontal)
+ @abs(y - self.y) <= 4 and x >= self.x and x < self.x + self.w
+ else
+ @abs(x - self.x) <= 4 and y >= self.y and y < self.y + self.h;
}
pub fn line(self: Geometry, engaged: bool) Rect {
const width: f32 = if (engaged) 2 else 1;
+ if (self.axis == .horizontal) return .{ .x = @floatCast(self.x), .y = @as(f32, @floatCast(self.y)) - width, .w = @floatCast(self.w), .h = width };
return .{ .x = @as(f32, @floatCast(self.x)) - width, .y = @floatCast(self.y), .w = width, .h = @floatCast(self.h) };
}
};
@@ -29,4 +35,9 @@ pub const Drag = struct {
const value = @as(f64, @floatFromInt(self.width)) + x - self.origin;
return @intFromFloat(@round(@min(@max(value, @as(f64, @floatFromInt(minimum))), @as(f64, @floatFromInt(maximum)))));
}
+
+ /// A bottom pane grows as its top edge moves upward.
+ pub fn heightAt(self: Drag, y: f64, minimum: i32, maximum: i32) i32 {
+ return self.widthAt(2 * self.origin - y, minimum, maximum);
+ }
};
diff --git a/tests/files_controls.py b/tests/files_controls.py
index 3e54605..5816c22 100644
--- a/tests/files_controls.py
+++ b/tests/files_controls.py
@@ -496,7 +496,7 @@ def run():
title("Documents") # Unpin does not navigate or delete the folder.
assert (home / "Documents").is_dir()
saved = (tmp / "state/rediwm/files-view").read_bytes()
- assert saved[0] == ord("3") and saved[3] & 2 and saved[4] == 1, saved
+ assert len(saved) == 10 and saved[0] == ord("4") and saved[3] & 2 and saved[4] == 1, saved
click(70, 305) # Downloads now occupies Documents' old row.
title("Downloads")
click(70, 140, 273) # Home has Open, Open in New Window and Properties.
diff --git a/tests/files_terminal.py b/tests/files_terminal.py
new file mode 100644
index 0000000..d1f704f
--- /dev/null
+++ b/tests/files_terminal.py
@@ -0,0 +1,506 @@
+#!/usr/bin/env python3
+"""Isolated PTY/shell coordination and the real Files terminal drawer.
+
+No production test hooks: the engine fixture calls the same C API as Files,
+and the UI suite uses normal Wayland input, screenshots and /proc evidence.
+"""
+import ctypes as C
+import os
+from pathlib import Path
+import select
+import shlex
+import shutil
+import subprocess
+import tempfile
+import time
+
+from ipc_client import IPCClient, ROOT, spawn_compositor, stop_process
+from files_browser import wait_for
+
+MAGIC = 0x46543031
+VTERM_HASH = 'N-V-__8AAFwIBQAS1j3S14ozuJ18ebNtLQ-c5Kl6W4J7PoJt'
+BIN = Path(os.environ.get('REDIWM_TEST_BIN', ROOT / 'zig-out/bin')).resolve()
+
+
+class Status(C.Structure):
+ _fields_ = [('magic', C.c_uint32), ('flags', C.c_uint32),
+ ('serial', C.c_uint64), ('error', C.c_int32),
+ ('jobs', C.c_int32), ('path', C.c_char * 4096)]
+
+
+def build_engine(tmp):
+ vterm = ROOT / 'zig-pkg' / VTERM_HASH
+ out = tmp / 'engine.so'
+ subprocess.run(['cc', '-shared', '-fPIC', '-O2', '-std=c99',
+ '-I' + str(vterm / 'include'), '-I' + str(vterm / 'src'),
+ str(ROOT / 'src/files/terminal/engine.c'),
+ *[str(p) for p in sorted((vterm / 'src').glob('*.c'))],
+ '-lxkbcommon', '-lutil', '-o', str(out)], check=True)
+ lib = C.CDLL(str(out))
+ signatures = {
+ 'ft_new': ([C.c_int, C.c_int], C.c_void_p),
+ 'ft_free': ([C.c_void_p], None),
+ 'ft_start': ([C.c_void_p, C.c_char_p, C.c_char_p, C.c_char_p, C.c_bool], C.c_int),
+ 'ft_pty': ([C.c_void_p], C.c_int), 'ft_channel': ([C.c_void_p], C.c_int),
+ 'ft_pidfd': ([C.c_void_p], C.c_int),
+ 'ft_wants_write': ([C.c_void_p], C.c_bool),
+ 'ft_wants_request': ([C.c_void_p], C.c_bool),
+ 'ft_io': ([C.c_void_p, C.c_bool, C.c_bool, C.c_bool, C.c_bool], None),
+ 'ft_follow': ([C.c_void_p, C.c_char_p], C.c_int),
+ 'ft_status': ([C.c_void_p], C.POINTER(Status)),
+ 'ft_close': ([C.c_void_p, C.c_bool], None),
+ 'ft_running': ([C.c_void_p], C.c_bool),
+ 'ft_exited': ([C.c_void_p], C.c_bool),
+ 'ft_exit_status': ([C.c_void_p], C.c_int),
+ 'ft_history_bytes': ([C.c_void_p], C.c_size_t),
+ 'ft_paste': ([C.c_void_p, C.c_char_p, C.c_size_t], C.c_bool),
+ }
+ for name, (args, result) in signatures.items():
+ fn = getattr(lib, name)
+ fn.argtypes, fn.restype = args, result
+ return lib
+
+
+class Engine:
+ def __init__(self, lib, directory):
+ self.lib, self.handle = lib, lib.ft_new(12, 80)
+ assert self.handle
+ helper = BIN / 'rediwm-files-terminal'
+ plugin = BIN.parent / 'lib/rediwm/files-bash.so'
+ assert lib.ft_start(self.handle, os.fsencode(helper), os.fsencode(plugin),
+ os.fsencode(directory), False) == 0
+
+ def pump(self, timeout=.05):
+ poll = select.poll()
+ fds = [self.lib.ft_pty(self.handle), self.lib.ft_channel(self.handle),
+ self.lib.ft_pidfd(self.handle)]
+ for i, fd in enumerate(fds):
+ if fd >= 0:
+ output = (i == 0 and self.lib.ft_wants_write(self.handle)) or (
+ i == 1 and self.lib.ft_wants_request(self.handle))
+ poll.register(fd, select.POLLIN | (select.POLLOUT if output else 0))
+ events = dict(poll.poll(round(timeout * 1000)))
+ self.lib.ft_io(self.handle, bool(events.get(fds[0], 0) & (
+ select.POLLIN | select.POLLHUP | select.POLLERR)),
+ bool(events.get(fds[0], 0) & select.POLLOUT),
+ fds[1] in events, fds[2] in events)
+
+ def wait(self, pred, description, timeout=5):
+ end = time.monotonic() + timeout
+ while time.monotonic() < end:
+ self.pump()
+ if pred():
+ return
+ s = self.status()
+ raise AssertionError((description, s.magic, s.flags, s.serial, s.path))
+
+ def status(self):
+ return self.lib.ft_status(self.handle).contents
+
+ def send(self, text):
+ os.write(self.lib.ft_pty(self.handle), text if isinstance(text, bytes) else text.encode())
+
+ def follow(self, path):
+ assert self.lib.ft_follow(self.handle, os.fsencode(path)) == 0
+
+ def free(self):
+ self.lib.ft_close(self.handle, False)
+ try:
+ self.wait(lambda: self.lib.ft_exited(self.handle), 'owned shell reaped', timeout=1)
+ except AssertionError:
+ self.lib.ft_close(self.handle, True)
+ self.wait(lambda: self.lib.ft_exited(self.handle), 'owned shell killed and reaped')
+ finally:
+ self.lib.ft_free(self.handle)
+
+
+def engine_tests(tmp, home):
+ lib = build_engine(tmp)
+ weird = home / "spaces ' quotes \" $()\n新"
+ weird.mkdir()
+ another = home / 'latest'
+ another.mkdir()
+ e = Engine(lib, home)
+ try:
+ e.wait(lambda: e.status().magic == MAGIC and e.status().flags == 1, 'empty Bash prompt')
+ e.follow(weird)
+ e.wait(lambda: e.status().serial == 1 and e.status().path == os.fsencode(weird), 'path transported as data')
+ e.send('printf partial')
+ e.wait(lambda: e.status().flags == 2, 'partly typed command')
+ e.follow(home)
+ for _ in range(4):
+ e.pump()
+ assert e.status().serial == 1 and e.status().path == os.fsencode(weird)
+ e.send(b'\x15') # Ctrl+U clears the line without executing it.
+ e.wait(lambda: e.status().serial == 2, 'following after line cleared')
+ e.send('sleep .4\n')
+ e.wait(lambda: e.status().flags == 4, 'running command')
+ e.follow(weird)
+ e.follow(home)
+ e.follow(another)
+ e.wait(lambda: e.status().serial == 5 and e.status().path == os.fsencode(another), 'latest request wins after command')
+ e.send('printf keep')
+ e.wait(lambda: e.status().flags == 2, 'partial input before inaccessible folder')
+ gone = home / 'gone'
+ gone.mkdir()
+ e.follow(gone)
+ gone.rmdir()
+ e.send(b'\x15')
+ e.wait(lambda: e.status().serial == 6 and e.status().flags & 8, 'failed cd acknowledged')
+ assert e.status().path == os.fsencode(another)
+ e.send('bash --noprofile --norc\n')
+ e.wait(lambda: e.status().flags == 4, 'nested shell suspends following')
+ e.follow(home)
+ for _ in range(4):
+ e.pump()
+ assert e.status().serial == 6
+ e.send('exit\n')
+ e.wait(lambda: e.status().serial == 7 and e.status().path == os.fsencode(home), 'following resumes in owned shell')
+ e.send('sleep 30 &\n')
+ e.wait(lambda: e.status().jobs > 0 and e.status().flags == 1, 'background jobs reported')
+ # A raw reader exercises queued writes, EAGAIN and partial PTY writes.
+ ready, pasted = home / 'paste-ready', home / 'pasted'
+ script = ('import os,termios,tty; old=termios.tcgetattr(0); tty.setraw(0); '
+ f'open({str(ready)!r},"w").close(); '
+ f'f=open({str(pasted)!r},"wb"); '
+ 'left=200000\ntry:\n while left:\n b=os.read(0,min(left,8192)); f.write(b); left-=len(b)\n'
+ 'finally:\n f.close(); termios.tcsetattr(0,termios.TCSANOW,old)')
+ e.send('python3 -c ' + shlex.quote(script) + '\n')
+ e.wait(lambda: ready.exists(), 'raw reader ready')
+ payload = b'x' * 200000
+ assert lib.ft_paste(e.handle, payload, len(payload))
+ e.wait(lambda: pasted.exists() and pasted.stat().st_size == len(payload), 'partial writes preserve paste', timeout=10)
+ assert pasted.read_bytes() == payload
+ e.wait(lambda: e.status().flags == 1, 'prompt after raw reader')
+ bash_paste = b'true # ' + b'x' * 200000
+ assert lib.ft_paste(e.handle, bash_paste, len(bash_paste))
+ e.wait(lambda: not lib.ft_wants_write(e.handle), 'large Bash paste drains', timeout=10)
+ e.send('\n')
+ e.wait(lambda: e.status().flags == 1, 'large paste preserves Readline responsiveness', timeout=10)
+ if Path('/usr/bin/vim').exists():
+ vim_file, vim_ready = home / 'vim.txt', home / 'vim-ready'
+ e.send('vim -Nu NONE -i NONE -n -c ' + shlex.quote(
+ 'call writefile(["ready"], "' + str(vim_ready) + '")') + ' ' + shlex.quote(str(vim_file)) + '\n')
+ e.wait(lambda: vim_ready.exists(), 'vim alternate screen')
+ e.send(b'ihello terminal\x1b:wq\n')
+ e.wait(lambda: vim_file.exists(), 'vim accepts keyboard input')
+ e.wait(lambda: e.status().flags == 1, 'vim restores shell screen')
+ assert vim_file.read_text() == 'hello terminal\n'
+ if Path('/usr/bin/top').exists():
+ e.send('top -d .1 -n 2\n')
+ e.wait(lambda: e.status().flags == 4, 'top fullscreen')
+ e.wait(lambda: e.status().flags == 1, 'top completes fullscreen updates')
+ e.send("printf '\\033]52;c;YmFk\\007'; seq 1 100000\n")
+ e.wait(lambda: e.status().flags == 4, 'continuous output starts')
+ e.wait(lambda: e.status().flags == 1, 'continuous output finishes', timeout=10)
+ assert lib.ft_history_bytes(e.handle) <= 8 * 1024 * 1024
+ e.send('exit 7\n')
+ e.wait(lambda: lib.ft_exited(e.handle), 'shell exit')
+ assert lib.ft_exit_status(e.handle) == 7
+ finally:
+ e.free()
+ before = len(list(Path('/proc/self/fd').iterdir()))
+ failed = lib.ft_new(4, 20)
+ assert failed
+ assert lib.ft_start(failed, b'/nonexistent-files-terminal-helper', b'', os.fsencode(home), False) == -1
+ lib.ft_free(failed)
+ assert len(list(Path('/proc/self/fd').iterdir())) == before, 'failed launch leaked descriptors'
+ if shutil.which('fish'):
+ selected = os.environ['SHELL']
+ os.environ['SHELL'] = shutil.which('fish')
+ unsupported = Engine(lib, home)
+ os.environ['SHELL'] = selected
+ try:
+ unsupported.wait(lambda: lib.ft_channel(unsupported.handle) < 0, 'unsupported integration closes its channel')
+ fish_dir = home / 'fish-dir'
+ unsupported.send('pwd > ' + shlex.quote(str(fish_dir)) + '\n')
+ unsupported.wait(lambda: fish_dir.exists(), 'Fish starts and accepts input')
+ assert fish_dir.read_text().strip() == str(home)
+ finally:
+ unsupported.free()
+ print('PTY: Unicode paths, partial/busy prompts, coalescing, failed cd, nested shells, jobs, paste writes, vim/top, bounds, launch failure, Fish and exit', flush=True)
+
+
+def task_switches(pid):
+ total = 0
+ for task in Path(f'/proc/{pid}/task').glob('*/status'):
+ for line in task.read_text().splitlines():
+ if line.startswith(('voluntary_ctxt_switches:', 'nonvoluntary_ctxt_switches:')):
+ total += int(line.split()[-1])
+ return total
+
+
+def scope_test(home, env):
+ # The helper's native placement path talks only to this private fake user
+ # manager. Assert scope placement completes before any app code executes.
+ script = r'''
+import os, subprocess, sys, warnings
+warnings.simplefilter('ignore', DeprecationWarning)
+from gi.repository import Gio, GLib
+helper, home = sys.argv[1:]
+loop = GLib.MainLoop()
+conn = Gio.bus_get_sync(Gio.BusType.SESSION)
+conn.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus', 'RequestName',
+ GLib.Variant('(su)', ('org.freedesktop.systemd1', 0)), None, Gio.DBusCallFlags.NONE, 3000, None)
+xml = """<node><interface name='org.freedesktop.systemd1.Manager'>
+<method name='StartTransientUnit'><arg type='s' direction='in'/><arg type='s' direction='in'/>
+<arg type='a(sv)' direction='in'/><arg type='a(sa(sv))' direction='in'/>
+<arg type='o' direction='out'/></method></interface></node>"""
+node = Gio.DBusNodeInfo.new_for_xml(xml)
+seen = []
+def called(conn, sender, path, interface, method, parameters, invocation):
+ name, mode, values, aux = parameters.unpack()
+ props = dict(values)
+ assert name == f'app-rediwm-files-terminal-{proc.pid}.scope', name
+ assert mode == 'fail' and props['PIDs'] == [proc.pid], props
+ assert props['Slice'] == 'app.slice' and props['CollectMode'] == 'inactive-or-failed', props
+ open(home + '/scope-placed', 'w').close()
+ seen.append(name)
+ invocation.return_value(GLib.Variant('(o)', ('/org/freedesktop/systemd1/job/1',)))
+conn.register_object('/org/freedesktop/systemd1', node.interfaces[0], called, None, None)
+program = 'import os; assert os.path.exists("scope-placed"); open("scoped-cwd","w").write(os.getcwd())'
+proc = subprocess.Popen([helper, '1', home, '--external', sys.executable, '-c', program])
+def exited(pid, status):
+ proc.returncode = os.waitstatus_to_exitcode(status)
+ loop.quit()
+GLib.child_watch_add(proc.pid, exited)
+GLib.timeout_add_seconds(5, lambda: (loop.quit(), False)[1])
+try:
+ loop.run()
+ assert proc.returncode == 0 and seen, (proc.returncode, seen)
+finally:
+ if proc.returncode is None:
+ proc.kill(); proc.wait()
+'''
+ subprocess.run(['dbus-run-session', '--', 'python3', '-c', script,
+ str(BIN / 'rediwm-files-terminal'), str(home)],
+ env=env, check=True, timeout=10)
+ assert (home / 'scoped-cwd').read_text() == str(home)
+ print('Scope: private manager receives owned PID/app.slice before exec', flush=True)
+
+
+def ui_tests(tmp, home, env):
+ external_cwd, external_args = home / 'external-cwd', home / 'external-args'
+ external = tmp / 'external-terminal'
+ external.write_text('#!/bin/sh\npwd > "$HOME/external-cwd"\nprintf "%s\\0" "$@" > "$HOME/external-args"\n')
+ external.chmod(0o755)
+ applications = tmp / 'data/applications'
+ applications.mkdir(parents=True, exist_ok=True)
+ (applications / 'files-terminal-fixture.desktop').write_text(
+ '[Desktop Entry]\nType=Application\nName=Terminal fixture\nCategories=TerminalEmulator;\n'
+ f'Exec={external} --flag "two words"\n')
+ comp, log = spawn_compositor(tmp, binary=BIN / 'rediwm', config_content='[compositor]\nxwayland = false\ndefault_terminal = "files-terminal-fixture.desktop"\n',
+ scale=os.environ.get('REDIWM_TEST_SCALE', '1'), env_extra=env)
+ procs = []
+ logs = []
+ try:
+ sock = wait_for(lambda: next(tmp.glob('rediwm-*.sock'), None), 'compositor socket')
+ display = next(p.name for p in tmp.glob('wayland-*') if not p.name.endswith('.lock'))
+ def start():
+ output = (tmp / f'files-{len(procs)}.log').open('w')
+ logs.append(output)
+ p = subprocess.Popen([str(BIN / 'rediwm-files'), str(home)],
+ env=dict(env, WAYLAND_DISPLAY=display), stdout=output, stderr=output)
+ procs.append(p)
+ return p
+ with IPCClient(sock) as ipc:
+ first = start()
+ window = wait_for(lambda: next((w for w in ipc.get_windows() if w['app_id'] == 'rediwm-files'), None), 'Files window')
+ ident = window['id']
+ ipc.focus_window(ident)
+ ipc.wait_for('window_geometry_settled', window_id=ident)
+ def key(code, modifiers=()):
+ for modifier in modifiers:
+ ipc.key(modifier, True)
+ ipc.key_down_up(code)
+ for modifier in reversed(modifiers):
+ ipc.key(modifier, False)
+ def command(text):
+ ipc.type_text(text)
+ key(28)
+ def click(x, y, pressed=None):
+ box = ipc.get_window_debug(ident)['client_box']
+ ipc.move_cursor(round(box['x'] + x), round(box['y'] + y))
+ if pressed is None:
+ ipc.pointer_button(272, True)
+ ipc.pointer_button(272, False)
+ else:
+ ipc.pointer_button(272, pressed)
+ # A held F4 must open once, even after the repeat delay expires.
+ ipc.key(62, True)
+ time.sleep(.65)
+ ipc.key(62, False)
+ pidfile = home / 'bash-pid'
+ shell = wait_for(lambda: int(pidfile.read_text()) if pidfile.exists() else None, 'lazy shell startup')
+ marker = home / 'gui-output'
+ command('printf GUI > ' + shlex.quote(str(marker)))
+ wait_for(lambda: marker.exists(), 'terminal receives keys after held F4')
+ ipc.screenshot(path=str(tmp / 'drawer.png'))
+ # F4 hides without stopping a running command; reopening retains it.
+ hidden = home / 'hidden-output'
+ command('sleep .2; printf survived > ' + shlex.quote(str(hidden)))
+ key(62)
+ wait_for(lambda: hidden.exists(), 'hidden command survives')
+ key(62)
+ assert Path(f'/proc/{shell}').exists()
+ target = home / "folder with ' quotes"
+ target.mkdir()
+ # Terminal keeps Ctrl+L; explicitly focus the file list first.
+ click(350, 160)
+ key(38, (29,))
+ ipc.type_text(str(target))
+ key(28)
+ wait_for(lambda: Path(f'/proc/{shell}/cwd').resolve() == target, 'Files navigation follows empty prompt')
+ # Focus the terminal body and prove shell Ctrl+C reaches a command.
+ box = ipc.get_window_debug(ident)['client_box']
+ click(350, box['height'] - 55)
+ command('sleep 30')
+ key(46, (29,))
+ interrupted = home / 'interrupted'
+ command('printf done > ' + shlex.quote(str(interrupted)))
+ wait_for(lambda: interrupted.exists(), 'Ctrl+C interrupts foreground command')
+ # The external action preserves desktop-entry argv and Files' cwd.
+ default_height = max(100, int((box['height'] - 26 - 112) / 3))
+ top = box['height'] - 26 - default_height
+ click(box['width'] - 49, top + 16)
+ wait_for(lambda: external_args.exists(), 'configured external terminal')
+ assert external_cwd.read_text().strip() == str(target)
+ assert external_args.read_bytes() == b'--flag\0two words\0'
+ assert Path(f'/proc/{shell}').exists()
+ if shutil.which('wl-copy') and shutil.which('wl-paste'):
+ clipboard_env = dict(env, WAYLAND_DISPLAY=display)
+ pasted = home / 'clipboard-pasted'
+ copy = subprocess.Popen(['wl-copy', '--foreground', '--paste-once'], stdin=subprocess.PIPE, env=clipboard_env)
+ procs.append(copy)
+ copy.stdin.write(('printf pasted > ' + shlex.quote(str(pasted))).encode())
+ copy.stdin.close()
+ # The terminal header action leaves keyboard focus in Files;
+ # take the terminal again before pasting.
+ click(350, box['height'] - 55)
+ time.sleep(.1) # Wayland selection offer follows wl-copy startup.
+ key(47, (29, 42)) # Ctrl+Shift+V.
+ copy.wait(timeout=5)
+ key(28)
+ wait_for(lambda: pasted.exists(), 'Wayland clipboard pasted into PTY')
+ selected = home / 'selection-ready'
+ command("clear; printf 'SELECTABLE\\n'; printf ready > " + shlex.quote(str(selected)))
+ wait_for(lambda: selected.exists(), 'selection output ready')
+ ipc.wait_for_frame()
+ time.sleep(.1)
+ # Default mono metrics: use stty columns if theme size changes.
+ click(216.2, top + 48, True)
+ click(216.2 + 80, top + 48, False)
+ key(46, (29, 42))
+ def has_selection():
+ return subprocess.run(['wl-paste', '--list-types'], env=clipboard_env,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ timeout=3).returncode == 0
+ wait_for(has_selection, 'terminal publishes selected text')
+ copied = subprocess.run(['wl-paste', '--no-newline'], env=clipboard_env, stdout=subprocess.PIPE, timeout=5, check=True).stdout
+ assert copied == b'SELECTABLE', ('terminal selection', copied)
+ # Resizing the shared divider changes the preferred height and persists it.
+ click(400, top, True)
+ click(400, top - 50, False)
+ key(62)
+ state = tmp / 'state/rediwm/files-view'
+ wait_for(lambda: state.exists(), 'drawer height saved')
+ assert state.read_bytes()[0:1] == b'4'
+ # Hidden drawer is idle. Check all Files and shell threads together.
+ time.sleep(.8)
+ before = task_switches(first.pid) + task_switches(shell)
+ time.sleep(1.1)
+ after = task_switches(first.pid) + task_switches(shell)
+ assert after - before < 20, ('terminal idle wakeups', after - before)
+ key(62)
+ ipc.minimize(ident)
+ ipc.restore(ident)
+ ipc.focus_window(ident)
+ ipc.wait_for('window_geometry_settled', window_id=ident)
+ assert Path(f'/proc/{shell}').exists(), 'minimize/restore replaced the session'
+ # Switching workspaces keeps an open drawer's session alive through
+ # the slide and the size changes on entering/leaving tiled mode.
+ ipc.action('set_desktop_mode', {'mode': 'workspaces', 'persist': False})
+ ipc.wait_for('window_geometry_settled', window_id=ident)
+ current_workspace = next(w['id'] for w in ipc.get_workspaces() if w['is_focused'])
+ switched = home / 'workspace-output'
+ command('sleep .2; printf survived > ' + shlex.quote(str(switched)))
+ ipc.action('switch_workspace', {'workspace': 9})
+ wait_for(lambda: switched.exists(), 'terminal command survives workspace slide')
+ ipc.action('switch_workspace', {'workspace': current_workspace})
+ ipc.focus_window(ident)
+ ipc.action('set_desktop_mode', {'mode': 'canvas', 'persist': False})
+ ipc.wait_for('window_geometry_settled', window_id=ident)
+ assert Path(f'/proc/{shell}').exists()
+ # New window starts hidden and creates its own shell only on F4.
+ second = start()
+ wait_for(lambda: len([w for w in ipc.get_windows() if w['app_id'] == 'rediwm-files']) == 2, 'second Files window')
+ second_window = next(w for w in ipc.get_windows() if w['app_id'] == 'rediwm-files' and w['id'] != ident)
+ ipc.focus_window(second_window['id'])
+ ipc.wait_for('window_geometry_settled', window_id=second_window['id'])
+ assert not Path(f'/proc/{second.pid}/task/{second.pid}/children').read_text().strip()
+ key(62)
+ other_shell = wait_for(lambda: int(pidfile.read_text()) if pidfile.read_text() != str(shell) else None, 'independent terminal')
+ assert other_shell != shell
+ ipc.focus_window(ident)
+ # Close confirmation also covers the hidden terminal; cancellation preserves it.
+ ipc.action('close_window', {'id': ident})
+ time.sleep(.15)
+ assert first.poll() is None
+ key(1)
+ assert first.poll() is None and Path(f'/proc/{shell}').exists()
+ ipc.action('close_window', {'id': ident})
+ time.sleep(.15)
+ key(28)
+ first.wait(timeout=4)
+ assert not Path(f'/proc/{shell}').exists(), 'shell reaped on close'
+ assert second.poll() is None and Path(f'/proc/{other_shell}').exists()
+ print('Files: F4/repeat, input, copy/paste, selection, external launch, following, divider/resize, idle, workspaces, minimize, independent windows and close/cancel', flush=True)
+ except Exception:
+ for path in tmp.glob('*.log'):
+ print(path.name, path.read_text()[-6000:])
+ keep = Path('/tmp/rediwm-files-terminal-failure.png')
+ if (tmp / 'drawer.png').exists():
+ keep.write_bytes((tmp / 'drawer.png').read_bytes())
+ raise
+ finally:
+ for p in reversed(procs):
+ if p.poll() is None:
+ stop_process(p)
+ for output in logs:
+ output.close()
+ stop_process(comp)
+ log.close()
+
+
+def run():
+ os.umask(0o077)
+ with tempfile.TemporaryDirectory(prefix='rediwm-files-terminal-') as directory:
+ tmp = Path(directory)
+ home = tmp / 'Home'
+ home.mkdir()
+ (home / '.bashrc').write_text("PS1='files-test:\\w$ '\nHISTFILE=/dev/null\nprintf '%s' \"$BASHPID\" > \"$HOME/bash-pid\"\n")
+ env = dict(os.environ, HOME=str(home), SHELL='/bin/bash', XDG_RUNTIME_DIR=directory,
+ XDG_CONFIG_HOME=str(tmp / 'config'), XDG_STATE_HOME=str(tmp / 'state'),
+ XDG_DATA_HOME=str(tmp / 'data'), XDG_CACHE_HOME=str(tmp / 'cache'),
+ WLR_BACKENDS='headless', REDIWM_FILES_DEVICES='0', REDIWM_APP_SCOPES='0',
+ DBUS_SESSION_BUS_ADDRESS='unix:path=/nonexistent-files-test-session-bus',
+ DBUS_SYSTEM_BUS_ADDRESS='unix:path=/nonexistent-files-test-system-bus')
+ env.pop('WAYLAND_DISPLAY', None)
+ env.pop('REDIWM_SOCKET', None)
+ original = dict(os.environ)
+ os.environ.clear()
+ os.environ.update(env)
+ try:
+ engine_tests(tmp, home)
+ scope_test(home, env)
+ (home / 'bash-pid').unlink(missing_ok=True)
+ # Use one configuration for the compositor and Files.
+ env['REDIWM_CONFIG'] = str(tmp / 'rediwm-config.toml')
+ ui_tests(tmp, home, env)
+ finally:
+ os.environ.clear()
+ os.environ.update(original)
+
+
+if __name__ == '__main__':
+ run()