Skip to content

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

calculator and text editor updates

oxydizer657cc382ea67
diff --git a/TESTING.md b/TESTING.md
index 0515f56..ef0eae1 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -1,555 +1,59 @@
# Testing
-## Ground rules
-
-Every test runs in its own headless compositor, temporary `XDG_RUNTIME_DIR`
-and, where D-Bus is involved, a private `dbus-run-session` bus reached through
-`DBUS_SYSTEM_BUS_ADDRESS`. Tests never touch the host display, session bus,
-audio, backlight or power state, never submit real passwords, and never
-request a real reboot or shutdown. Keep new tests that way. For visual
-debugging on the host, see AGENTS.md, "Rendering".
-
-## Layers
-
-| Command | What it checks |
-| --- | --- |
-| `zig build test` | In-process unit tests: rasterizers vs. full rasters, UI, config, IPC parser/serializer fixtures, glass damage, projection damage, restack and visibility cuts, hit tests and surface feedback from its typed graph (paint order, unrounded edges, list lifetime), a tree's dim (inheritance, the popup barrier, damage), lifecycle/allocation failures, Files/desktop logic. No compositor or bus. |
-| `zig build test-glass` | The glass registry and an effect's geometry in the graph at every zoom (no GPU). Glass pixels are gated in `test-scene-pass` (stage 5b) and by `tests/glass_reblur.py`. |
-| `zig build test-pass-spike` | The owned-pass spike of `docs/plans/scene-graph-stage1.md`: rounded clip, border, shadow, external-OES texture, backdrop blur, buffer-age damage and cost on headless GLES2 (needs a render node; `-Doptimize=ReleaseSafe` for cost). |
-| `zig build test-scene-pass` | Stage 3's owned GLES2 drawing backend against wlroots: transforms, crops, filters, premultiplied alpha, damage, external-OES (an RGB EGLImage and a linear NV12 dmabuf; needs gbm), GL/EGL state and acquire/release timelines. Needs a compatible render node (`WLR_RENDER_DRM_DEVICE` on multi-GPU machines); also run with `-Doptimize=ReleaseSafe`. The unavailable-acquire test intentionally logs `drmSyncobjTransfer failed`. Stage 4b's rounded-shape gates are in the same fixture: clip against a supersampled reference, piece joins, border/body, premultiplied edges, the opaque cover, shadow, and partial repaint across a clip edge; the 128 parity cases also run through the shaped programs. Stage 4d's shadow gate compares every pixel with the CPU chrome's shadow formula. The dim gates (`rediwm_scene_pass_set_dim`, inactive window dimming) compare a dimmed pass's rects, shapes, rings, translucent texels and glass composite with a C reference of the grade, and check that shadows are not graded, that a pass starts undimmed and that a bad fraction fails the pass. |
-| `zig build test-lock` | Lock/greeter painter, password editing, PAM transitions (PAM is replaced at link time in test binaries only), greeter↔rediwm-dm conversation, saved login appearance and account-switch fallback, bounded wallpaper rasters and hostile snapshot files. |
-| `zig build test-dm` | rediwm-dm relay state machine and framing. |
-| `zig build test-dbus`, `test-polkit`, `test-polkit-ui`, `test-notifications`, `test-settings-portal`, `test-power`, `test-power-profiles`, `test-tray`, `test-app-activation`, `test-rediwm-session`, `test-layout-autosave`, `test-files`, `test-images` | Subsystem suites; the D-Bus ones re-exec under `dbus-run-session`. |
-| `python3 tests/<name>.py` | Integration tests against the real `zig-out/bin/rediwm` on `WLR_BACKENDS=headless`. |
-
-`zig build test` includes direct test targets for the `ui`, `config` and
-`dbus` modules; Zig does not collect dependency-module tests through an
-executable's test root.
-
-Build first (`zig build`). Integration tests need Python 3 with Pillow, a C
-compiler, `wayland-scanner` and wayland-protocols; D-Bus suites need PyGObject,
-`dbus-run-session` and `busctl`. Some need extra tools, listed below.
-
-`zig build test-printers` runs the printing unit suite and
-`tests/printers.py` against the real headless Settings page. It needs the regular
-integration dependencies above, `wl-paste` (`wl-clipboard`), PyGObject/Gio/GLib,
-`dbus-daemon`, and a C compiler capable of a small shared `LD_PRELOAD` fixture.
-It needs libcups and its development headers, but does not require a running
-CUPS server, cups-pk-helper or a printer. `tests/printers_direct.py` also exercises
-the native backend against private schedulers: queue operations, PPD editing,
-rename, authentication retry, password cancellation and page teardown.
-
```sh
-zig build test-printers
-REDIWM_TEST_SCALE=1.5 zig build test-printers
-zig build test-printers -Doptimize=ReleaseSafe
+umask 077
+zig build
+zig build -Doptimize=ReleaseSafe --prefix zig-out/release-safe
+zig build test
+python3 tests/<name>.py
```
-The unit suite covers bounded IPP/HTTP, full identities, URI validation and
-matching, sysfs/node evidence, ladder/report privacy, PPD options/dimensions,
-PDFs and language samples, resolution suggestions, preserving defaults/private
-observations, socket-directory watches, notifier credentials and active DNS
-cancellation. Temporary loopback sockets and fixture trees never use a host
-scheduler or USB node.
-
-The integration uses private Unix/TCP schedulers, a private D-Bus helper/service
-manager, and temporary home/XDG directories. For administrative tests a
-noninstalled connect shim redirects only `/run/cups/cups.sock` and its `/var/run`
-alias to the private scheduler; this exercises the production canonical-server
-gate without a compositor test hook. All confirmed PDF/raw/ruler documents end
-in fixture memory. Coverage includes listing/jobs and denial, stopped/empty
-queues, malformed replies and deadlines, responsive IPC/cancel-on-hide, reports,
-remote-read/local-admin isolation, forged notifier rejection, setup/driver
-choices, options/defaults, named rename/removal confirmations, collision/job
-guards, preference migration and idle/hidden/closed lifetime.
-
-The independent [CUPS qualification matrix](docs/plans/printers-qualification.md)
-records actual helper ABI, subscription leases/cancellation and raw bytes through
-synthetic PPD queues in four disposable distro containers. It also records real
-helper rename and option semantics, including IPP/PPD discrepancies that the
-synthetic UI fixture cannot establish. Those commands are separate from the
-normal test target. Real USB/backend printing, physical ruler measurements,
-stock desktop polkit/notifier behavior, application/portal visibility and
-openSUSE qualification remain acceptance gates in the
-[Printers plan](docs/plans/printers.md). No automated test may contact the host
-scheduler, change a host queue/service or print to real hardware.
-
-### Common knobs
-
-- Run from a shell with `umask 077`: suites that create their own runtime
- directory otherwise get a world-readable one, and the compositor refuses to
- open its IPC socket there (`RuntimeDirNotPrivate`).
-- Export a scratch `XDG_STATE_HOME`, or tests read and overwrite your real
- layout autosave and saved window sizes.
-- Files lists the host's removable and external disks from UDisks2, so every
- Files-launching suite sets `REDIWM_FILES_DEVICES=0`. Do the same in new ones.
-- Files records opened files in shared recent history; set a scratch
- `XDG_DATA_HOME` in suites that open files so they never update the host's history.
-- The compositor requires GLES2 (the owned output pass, stage 4e of
- `docs/plans/scene-graph-stage4.md`), so every suite runs on a render node:
- `ipc_client.py` sets `WLR_RENDER_DRM_DEVICE=/dev/dri/renderD128` when it is
- unset; suites that start the compositor without it need it in the environment
- on multi-GPU machines. Without a GPU use Mesa's llvmpipe
- (`WLR_RENDERER_ALLOW_SOFTWARE=1`). GLES2 frees CPU scene buffers after
- upload, so `DumpBuffer` reads only what the compositor still holds; compare
- output screenshots for pixels.
-- `REDIWM_TEST_SCALE=1.5` (or a `1.5` / `--scale 1.5` argument, per script):
- fractional scale. `REDIWM_TEST_OUTPUTS=2`: two outputs.
-- `python3 tests/scene_baseline.py --out /tmp/scene-cost.json`: clean and stats
- sessions per scale (`--configs`), instructions, frame timers, RSS and power
- conditions; compare with `--report new.json --against old.json`. Use a
- ReleaseSafe build and a render node, keep other builds/tests stopped and AC
- power on. `--report` still reads the stages 3 and 4 "paired" results.
-- `zig build -Ddamage-audit=true` (Debug): after every frame the compositor
- redraws the same entries whole into a private buffer and logs `damage audit`
- errors for any pixel the frame's damage missed, with the entries over it. It
- reads two frames back each time, so timing-sensitive suites (`glass_hold`,
- `glass_reblur`, `desktop_damage`, `window_urgency`) fail on that build; read
- the logs of the others. `REDIWM_TEST_LOG_DIR=/dir` makes
- `ipc_client.spawn_compositor` keep each compositor log there
- (`grep -h "damage audit" /dir/*.log`). A hit means a change reached the graph
- without damaging itself (`docs/plans/scene-graph-stage6.md`, 6b); the
- `capture` suite is known to show a few corner pixels (unsubmitted isolated
- renders upset buffer age, which predates the graph damage). The same build self-checks the projection's per-group resolve: after every gated sync it
- resolves everything again and logs `gate audit: leaf N was stale` for any item the
- gate left behind (a change path that never marked its group).
-- `REDIWM_*_PREVIEW=/tmp/...` (lock, greeter, OSD, settings, switcher, tray,
- notification): keep the compositor's own screenshots.
-- GLES2 at a fractional scale can differ by one level depending on render
- history. Compare integer scales exactly, or allow one level.
-
-## The IPC socket is the test harness
-
-`tests/ipc_client.py` (`IPCClient`, `spawn_compositor`, `stop_process`) and the
-helpers in `tests/xwayland_support.py`, re-exported by `tests/xwayland.py`
-(`start_compositor`, `wayland_display_name`, `wait_for`) start compositors and talk to `$XDG_RUNTIME_DIR/rediwm-*.sock`.
-Importing `ipc_client` sets `REDIWM_IPC_AUTOMATION=1`; launchers that build
-their own environment must set it, or synthetic input and pixel reads return
-`AutomationDisabled` (`tests/ipc_automation.py` checks that gate). `spawn_compositor` also points `XDG_STATE_HOME` into the test
-directory: otherwise the layout autosave restore (2–37 s after start) moves
-test windows to wherever the last run, or the host session, left them.
-
-- Synthetic input (`MoveCursor`, `PointerButton`, `Key`, `TypeText`, `Drag`, …)
- goes through the normal input path; no libinput device or host is involved.
-- Prefer exact state (`GetCamera`, `Windows`, `GetInputState`,
- `GetShellState`, `GetPerformanceStats`, `wait_for` conditions) over pixels.
- Use `Screenshot`/`SamplePixels` plus Pillow only for what IPC cannot report.
-- `src/ipc/protocol.zig` is the source of truth for calls and events.
-
-Real Wayland peers are small C fixtures compiled at test time
-(`tests/*_client.c` with `wayland-scanner` + `cc`); `desktop_zoom.build_client`
-builds the generic xdg toplevel (`zoom_client.c`, `--app-id`, `--title`).
-LD_PRELOAD hooks (`*_hook.c`) model hardware the headless backend lacks:
-output unplug, gamma LUTs, mode lists, polkit input, short writes.
-
-## Integration tests by area
-
-**Shell and windows**: `focus_zoom.py` (Alt+Tab/taskbar reveal easing, temporary
-full-size boosts, camera depth focus, geometry, pixels, input and reduced
-motion; supports the renderer/scale knobs), `desktop_zoom.py` (camera, window zoom, input at every
-zoom, needs a render node for gles2 runs), `popup_constraint.py` (xdg popups
-slide to the visible screen for windows panned or zoomed away from the world
-origin), `zoom_osd.py` (shared zoom OSD,
-100% camera cap, pixels, timeout and input), `decorations.py`, `kde_decorations.py`, `window_corners.py`
-(border antialiasing and filled side edges on dark/light backgrounds at
-integer/fractional scales, plus workspace focus outlines on server/client
-decorations, mode transitions, fullscreen and default/explicit gaps, transparent
-client corners and that a click on a clipped corner reaches the window below),
-`switcher.py`,
-`switcher_live.py`, `workspaces.py` (floating rules, Settings/IPC layout controls,
-versioned restart/named-save restoration, duplicate app occurrences, restored tab groups,
-saved canvas state and multi-window layout undo, both sides of tiled/floating
-output transfers, dialog transfers, closed-member reconciliation, late configure
-replies, keyboard/IPC tiling controls, drag previews and Escape, live
-split resizing, unmap/remap, placeholder replacement, automatic split geometry,
-new windows splitting the focused tile, hidden input while a workspace slides out,
-constraints/overflow, stable focus,
-minimize/maximize/fullscreen reinsertion, manual placement, workspace membership,
-hidden input, dialog transfers, Settings, workspace protocol activation,
-canvas restore and shortcut overrides; supports `REDIWM_TEST_OUTPUTS=2`,
-`REDIWM_TEST_SCALE=1.5`, `REDIWM_TEST_NEGATIVE=1`, and `REDIWM_TEST_XWAYLAND=1` for real GTK click delivery;
-GLES requires a render node; `--persistence-only` runs the restart/control checks), `window_snapping.py`, `initial_window_state.py` (startup
-maximize/fullscreen placement, restore, window rules and depth), `taskbar_peek.py`,
-`taskbar_title_repaint.py`, `window_urgency.py`, `start_menu.py`,
-`start_menu.py --launcher-only` (Super+Space in canvas and workspace modes, centered placement on a second output, fractional scale, live theme changes, keyboard/card launches, pin persistence and dismissal),
-`power_menu.py` (only ever activates Log Out), `control_center.py`,
-`control_center.py --services-only` (private systemd and polkit fixture: availability, in-table loading, unlock/lock and prompt cancellation, startup settings, Notify service types and isolated drop-in edits, runtime actions, authorization refusal, analysis, in-place state updates and coalesced reloads, signal-flood resistance, nothing read until the page is shown or while it is hidden, no RefUnit or unloaded-unit reads, the IPC lease, and lifetime),
-`calendar_popup.py`, `bluetooth.py` (private BlueZ service; Settings device search,
-radio, discovery cleanup, battery updates, PIN/passkey/confirmation pairing,
-connect/disconnect, trust, removal, permissions and service restarts), `wifi_popup.py` (private NetworkManager service; popup and
-Network settings, password/hidden forms, saved and open joins, radio, wired
-details, connect/disconnect and permission errors, service restart and scrolling;
-`--settings-only` runs just the settings checks), `battery_popup.py` (fake sysfs and private power-profile
-service; charge states, missing details, selection and dismissal),
-`keyboard_shortcuts.py`, `dock.py` (opt-in Appearance toggle, four-edge position selector, bounded size and hover-zoom sliders, opacity and corner-radius sliders, the off-by-default active-app rectangle, live placement/resizing and persistence, vertical icon/indicator layout, inward tooltips (after their 1.5 s delay) and menus, launcher/input, dragging pinned icons into a new order (marker, Escape, drop in place), shared shortcut icons and running pills, hover zoom anchored toward the desktop (painted edges and overflow input on all four edges), pill animation/reversals, reduced motion and idle scheduling, preferred apps and terminal fallback, running windows, fullscreen, scale, live radius, context menu and remembered removal; `--positions-only` isolates placement),
-`panel_damage.py`, `glass_hold.py` (holds and
-mixed-scale idle), `glass_reblur.py` (glass re-blurs for changes below it,
-never for its own client), `animations.py`, `hotspots.py`, `launch_feedback.py`,
-`launch_placeholder.py`, `appearance_*.py`, `desktop_canvas.py`,
-`layout_autosave.py`, `mini_map.py` (settings, pixels, timeout and dragging),
-`mini_map_lifecycle.py` (focus, multiple outputs, cancellation and idle wakeups),
-`mini_map_windows.py` (window outline pixels, size, movement, zoom and lifetime),
-`mini_map_canvas.py` (live canvas growth/shrink with open windows, minimap fit
-and off-canvas reachability).
-
-`taskbar_sections.py` checks left/center/right defaults, live section controls,
-ordering and visibility, window groups defaulting left, nonoverlapping input bounds,
-the moved Start menu, the opt-in Power widget and its menu, capture visibility
-and its warning, legacy item lists
-and restart persistence. It supports
-`REDIWM_TEST_SCALE=1.5` and `REDIWM_TEST_OUTPUTS=2`.
-
-`wifi_popup.py --popup-only --gold --top 1.5` and
-`battery_popup.py --gold --top --scale 1.5` also check Gold's cream cards,
-control contrast and popup interactions with a top taskbar at fractional scale.
-Omit `--top` to exercise bottom placement, or `--gold` for the default palette.
-`--popup-only` skips the separate tray-blink and Settings-page checks.
-
-`window_tabs.py` covers the Appearance checkbox list, opt-in persistence, explicit
-+ launches, independent groups, tab focus, shared geometry, overflow, closing and
-disabling without closing clients, close-confirmation dialogs, fullscreen and
-failed launches. It supports `REDIWM_TEST_SCALE`,
-`REDIWM_TEST_RENDERER`, and `REDIWM_TABS_PREVIEW`.
-`REDIWM_TEST_WORKSPACES=1` also checks group layout undo, selected-tab closure
-and remapping into the surviving group.
-
-`appearance_settings.py --app-colors-only` exercises the GTK/Qt apply buttons,
-configuration preservation and backups, failure reporting, and the persisted
-launch environment. When development packages are available it also compiles
-small GTK3, GTK4, libadwaita, Qt5 and Qt6 clients to check the actual loaded
-colors. All configuration, clients and displays stay in temporary directories.
-
-`kde_decorations.py` covers KDE decoration startup ordering, mode changes,
-window rules, fullscreen/remapping, lifetime and titlebar controls. To also
-check the installed Ghostty in a private D-Bus session, run
-`python3 tests/kde_decorations.py --ghostty`.
-
-**Wayland protocols**: `security_context.py` (wp-security-context-v1
-registry hiding, guess-bind rejection, nested context forbidden, IPC window
-attribution, sandbox allowances, sandboxed IPC caller detection via `bwrap`
-and Flatpak info), `wlr_protocols.py` (wlr-output-management via
-wlr-randr, wlr-foreign-toplevel via wlrctl, wlr-screencopy, virtual-pointer,
-ext-session-lock via a fixture and real swaylock; workspace enumeration, tags,
-content/tearing hints and renderer colour negotiation via the same fixture), `input_protocols.py`
-(data-control with wl-clipboard, xdg-activation, text-input/IME,
-virtual-keyboard), `dead_keys.py` (a virtual `latam` keyboard types dead-key
-sequences into the start menu and Files' rename field under `pt_BR` and
-`es_MX`; acute then c must give ç and ć), `pointer_constraints.py`, `shortcuts_inhibit.py`, `cursor_shape.py`,
-`single_pixel.py`, `xdg_output.py` (`--xwayland` adds RandR via `xrandr`),
-`presentation_time.py`, `explicit_sync.py` (gles2; vkcube), `direct_scanout.py` (gles2;
-an opaque fullscreen client, XRGB or ARGB with an opaque region, is scanned out, a
-translucent one is not), `layer_lifecycle.py`,
-`idle.py`, `layout_ipc.py`, `clipboard_gtk_client.py`/`dnd_gtk_client.py`
-(fixtures used by `xwayland.py`).
-
-`window_titles.py` checks malformed initial and updated titles and valid Unicode.
-It requires the patched private wlroots build
-described in `patches/wlroots/README.md`.
-
-**Displays**: `output_scale.py`, `output_destroy.py` (hook unplugs an output),
-`display_arrangement.py` (Settings' arrangement: drag, snap, 0,0 normalization,
-saved positions, windows carried along, main display, hidden with one output),
-`night_light.py` (gamma hook: reject/accept modes, schedules via
-`SetNightLightClock`).
-
-**Capture**: `capture.py` (ext-image-copy-capture for outputs and windows over
-shm and, with a render node, dmabuf; occlusion, camera, resize, destroy,
-minimize, idle blank, unplug, `get_capture_state`; under `owned` a captured
-server-decorated window has transparent bottom corners), `screencast.py` (portal
-config packaging, `rediwm-share-picker --xdpw-dmenu` contract, Stop sharing
-indicator, independent taskbar placement and saved visibility without stopping
-capture), `screenshot_tool.py`, `screenshot_regressions.py` (save hook
-injects write failures).
-
-**Lock, login, authentication**: `lock_screen.py`, `greeter.py`, `dm.py`
-(real daemon unprivileged with `--test` and `pam_start_confdir` stacks),
-`polkit_dialog.py`, `polkit.py`.
-
-**Session**: `session_restart.py` (uses `zig-out/release-safe`),
-`rediwm_session.py`, `session_services.py`, `session_bus.py`,
-`session_readiness.py`, `notification_services.py`, `app_activation.py`,
-`settings_portal.py`, `power.py`, `power_profiles.py`, `notifications.py`,
-`tray.py`, `hardware_keys.py` and `audio_balance.py` (private PipeWire; need
-`pipewire`, `pipewire-pulse`, `pactl`, `pw-metadata`), `startup.py`,
-`startup_warmup.py`. `audio_balance.py --scale 1.5` also checks fractional-scale
-settings; it covers balance, volume keys, silence/mute and stereo/surround/mono
-channel maps without accessing host audio. `audio_mute_fade.py` (also needs
-WirePlumber's smart filters, `dbus-run-session`, `pw-record`, `pw-link`,
-`paplay`) records the bass filter's output: mute fades out before the device
-mutes, unmute fades in, a quick re-press turns the fade around, quitting
-mid-fade still mutes.
-
-`python3 tests/workspaces.py --controls-only` isolates tiling controls and lifecycle
-checks; `--automatic-only` skips the older workspace-mode suite.
-`--acceptance-only` runs live scale/origin reloads, tile-grab cancellation,
-actual Wayland click delivery, per-thread idle wakeups, configure stability and
-workspace IPC/protocol lock guards, including lock-client death. It uses
-per-output scaling (`REDIWM_SCALE=auto`) and also supports two outputs.
-The split engine also has pure unit tests in `src/auto_layout.zig`, included in
-`zig build test`.
-
-The [optional tiling qualification record](docs/plans/optional-tiling-qualification.md)
-contains the renderer-specific GLES results, HEAD failure comparisons and the
-pending physical-display checklist. Workspace GTK/Xwayland routing honors
-`REDIWM_TEST_RENDERER` too. Select `WLR_RENDER_DRM_DEVICE` explicitly on multi-GPU
-machines: headless multi-output idle and glass results can differ by driver.
-
-`REDIWM_TEST_WORKSPACES=1 python3 tests/output_destroy.py` repeats hot-unplug
-and reconnects the same connector, checking visible/hidden workspace ownership,
-activation after migration and undo of transfers to the reconnected output. Use the same
-flag with `keyboard_shortcuts.py` to exercise workspace preset editing and
-disabling through Settings, or `window_tabs.py` for tab groups in automatically
-tiled workspaces. `shortcuts_inhibit.py` also supports this flag for tiled/floating
-bindings, Alt+Tab, number/wheel navigation, Super-drag and Super+Escape revocation.
-
-**Xwayland**: `xwayland.py` (runs `xwayland_core.py`, `xwayland_gtk.py` and
-`xwayland_selection.py`; needs Xwayland, libxcb, `xdpyinfo`, PyGObject/GTK 3;
-never uses the host `DISPLAY`), `xwayland_fractional.py`,
-`xwayland_hardening.py` (extreme/invalid client size hints and recovery; needs
-Xwayland and libxcb).
-
-`xwayland.py` checks actual GTK click delivery on negative-origin outputs and
-after panning beyond the physical display in either direction, including 1.5x
-X11 rendering and clicking an already-open menu after another pan. X11 root
-coordinates follow the camera viewport; scene and native Wayland coordinates
-remain in world space.
-
-**File dialogs**: `zig build test-file-chooser` (private D-Bus; OpenFile,
-SaveFile, SaveFiles, filters, multiple selection, breadcrumbs, overwrite
-confirmation, cancellation and Settings portal preferences). The chooser can
-also be launched with `rediwm-files --open`, `--save` or `--folder`; it returns
-a JSON result on stdout.
-
-**System Monitor**: `zig build test-monitor` covers proc parsing, CPU and memory
-accounting, PID reuse, filtering/sorting, stable selection, history, real pidfd
-actions against disposable children, and worker pause/resume/cancellation.
-`python3 tests/system_monitor.py` covers shortcut launch and restore in both
-desktop modes, search, keyboard actions, named force-quit confirmation,
-disappearing targets, resize, live theme updates while paused, focus loss,
-minimize/restore, Files-style row hover/selection, pointer leave and idle worker
-lifetime. Repeat with `REDIWM_TEST_SCALE=1.5`.
-The noninstalled preload fixture uses seccomp user notifications to permit
-signals only to recorded disposable child identities, and verifies that gate
-against an unlisted disposable child before exercising UI actions. These tests
-require Linux seccomp user notifications; production builds contain no hooks.
-
-**Desktop, Files, Images**: `desktop_icons.py`, `desktop_damage.py`,
-`zig build test-files-torrents` builds the applications, then runs a real
-libtorrent seed/tracker/selected download on loopback, persistence and collision
-checks, and a headless Files/tray flow. Requires Python's libtorrent bindings,
-PyGObject, a C compiler and the ordinary headless dependencies. The noninstalled
-`tests/torrent_network.c` confines the helper's networking to loopback. All
-state and the session bus are private. The UI screenshots are written to
-`/tmp/rediwm-transfers-list.png`, `/tmp/rediwm-transfers-files.png` and
-`/tmp/rediwm-transfers-folder.png` (folder controls and hover details) for inspection.
-
-`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
-controls from the Git checks; `--single-click-only` checks icon-only opening in
-both views, hand cursors, selection/drag cancellation and the live Settings toggle.
-`files_thumbnails.py` (draws real pictures and reads thumbnail pixels back: shape,
-colour, EXIF rotation, the shared freedesktop cache read and write, a 240-picture
-folder, the `REDIWM_FILES_THUMBNAILS=0` switch and idle wakeups; it sets a scratch
-`XDG_CACHE_HOME`), `files_fixes.py` (wl-clipboard), `files_associations.py` (private MIME/app
-databases and AppImage registration/browser callbacks; needs update-mime-database,
-update-desktop-database, gio and squashfs-tools; `--appimage-only` isolates the
-AppImage context action, metadata, defaults and real URL launches), `files_drag.py` (GTK 3; `--browser` tests
-real Brave uploads with an isolated profile; `--select` selects by dragging
-from empty space, `--list` exercises list view, and `--pin` drags folders and a
-file onto PLACES: insertion line, order, refused drops, open and remove;
-`--transfer` moves/copies into folders and between Files windows in grid/list), `files_drag_dodge.py`
-(Files slides aside while a file is dragged out onto a window it covers, and
-back on drop or Escape; also camera zoom, the setting off and nothing to uncover;
-`browser` runs the real Brave upload and is not in the default set), `images_viewer.py`, `client_cursor.py` (grim;
-themed cursor pixels, live theme reload and client cursor serials).
-
-**Text editor**: `zig build test-editor` (document history, Unicode boundaries,
-line segmentation and folding, the scrolling view, file classification, loading
-and safe saving), `python3 tests/editor.py` (Files Space, tab reuse and
-activation, typing, undo/redo, clipboard, Save As, unsaved-close prompts,
-external-change protection, and a 46 MiB file opened, edited at its end and
-saved exactly). `python3 tests/editor_visuals.py` checks
-caret blinking and idle wakeups, and title glyph dimensions across resizes
-(`REDIWM_EDITOR_DRAG=1` exercises pointer resizing). Supports `REDIWM_TEST_SCALE`,
-`REDIWM_TEST_RENDERER`, and `REDIWM_EDITOR_PREVIEW=/tmp/editor.png`.
-
-**PDF viewer**: `zig build test-pdf`, `pdf_viewer.py` (rendering, navigation,
-text selection/copying, tiled fit width, and print dismissal/failure through a
-fake Print portal on a private bus; run
-it with `REDIWM_SCALE=2` too, where tiles split differently), `pdf_sandbox.py`
-(a test-only parser hook checks file, syscall, inherited-FD, environment and
-Wayland restrictions, that the print helper's socket cannot pass descriptors,
-plus failure to install the sandbox). Requires Poppler GLib, libseccomp, Linux
-Landlock ABI 3+, Python Cairo, `wl-paste`, and `dbus-daemon`.
-
-**Browsers**: `brave_input.py` (optional; `REDIWM_TEST_BRAVE=/path`), a smoke
-test of focus, clipboard, navigation and scrolling in a fresh profile.
-
-**CLI**: `msg.py` runs `rediwm-msg` against a fake socket using the captured
-cases in `tests/msg_v1.json`.
-
-### Known limitations pinned by tests
-
-These assertions are expected to start failing when wlroots fixes them; that
-is the signal to revisit, not a regression.
-
-- X11 → Wayland clipboard requires an Xwayland window focused at paste time
- (`test_x11_to_wayland_clipboard_focus_limitation`); PRIMARY behaves the same.
-- X11 → Wayland drag-and-drop never starts (`test_x11_source_drag_to_wayland_limitation`).
-- Synthetic pointer input over a GTK window on a second output does not reach
- the client, although hit-testing and RandR geometry are right.
-- wlrctl 0.2.2 cannot match `state:maximized` (enum value 0); `wlr_protocols.py`
- checks maximize through IPC instead.
-
-### Timing rules learned the hard way
-
-- Allow ~150 ms after `SetZoom`/`SetCamera` before clicking: IPC reflects the
- camera at once, but projection settles on the next frame.
-- Two clicks at the same surface-local pixel send no `wl_pointer.motion`, and
- Xwayland ignores the second; vary the offset.
-- Give each drag-and-drop combination its own compositor; a second drag in one
- session is unreliable. Native → X11 DnD still flakes about 1 in 8.
-- Synchronize on protocol acknowledgements, IPC events and `wait_for_frame`,
- not sleeps, wherever possible.
+Run affected integration suites after building. Find suites and flags in
+[tests/](tests/) and build targets in [build/tests.zig](build/tests.zig).
+Compare failures with a clean HEAD worktree before calling them regressions.
+Integration dependencies: Python 3 + Pillow, C compiler, `wayland-scanner`,
+wayland-protocols and GLES2; D-Bus suites also need PyGObject,
+`dbus-run-session` and `busctl`. Check each suite for extra dependencies.
+App checks include [calculator](tests/calculator.py), [editor](tests/editor.py)
+and [editor visuals](tests/editor_visuals.py).
+
+## Isolation and harness
+
+- Use a private headless compositor, temporary home/XDG directories and private
+ D-Bus services (`DBUS_SYSTEM_BUS_ADDRESS` points to the fixture bus). Never
+ touch host displays, buses, audio, power, printers or real credentials.
+- Keep runtime directories private (`umask 077`); isolate `XDG_STATE_HOME`
+ (layout autosave), `XDG_DATA_HOME` (recent files) and `XDG_CACHE_HOME`.
+ Files suites set `REDIWM_FILES_DEVICES=0` to avoid host disks.
+- Reuse [ipc_client.py](tests/ipc_client.py): `IPCClient`, `spawn_compositor`,
+ `stop_process`. Custom launch environments need `REDIWM_IPC_AUTOMATION=1`.
+ Prefer IPC state/events and `wait_for_frame` over pixels or sleeps; wait for
+ `window_geometry_settled` before pointer input or geometry checks.
+- Select `WLR_RENDER_DRM_DEVICE` on multi-GPU machines; without hardware use
+ Mesa llvmpipe (`WLR_RENDERER_ALLOW_SOFTWARE=1`). Use output screenshots for
+ pixels: GLES2 can release CPU buffers after upload.
+- Repeat UI checks at `REDIWM_TEST_SCALE=1.5`; supporting suites also accept
+ `REDIWM_TEST_OUTPUTS=2`. Check script-specific arguments. Fractional GLES2
+ pixels may differ by one level.
+- `zig build -Ddamage-audit=true` checks missed damage and stale resolve groups;
+ keep logs with `REDIWM_TEST_LOG_DIR`. It disrupts timing-sensitive tests.
+- Update IPC expectations explicitly in `src/ipc_serializers.jsonl` and
+ `tests/msg_v1.json`; never derive expected results from the implementation.
## Languages and locale correctness
-`zig build i18n-check` checks source/catalog drift, placeholder sets, plural
-forms and French spacing. `zig build i18n-lint` checks converted UI files listed
-in `po/lint-files`; `zig build test-i18n` covers compiled lookup, fallback,
-formatting and plural rules. PO parser/compiler tests also run in `zig build
-test`. Run `zig build i18n-extract` after changing source messages and merge the
-updated template into every catalog. Fuzzy entries are excluded from the UI
-and generated desktop/polkit metadata. Every PO and the POT are explicit build
-inputs, so edits and review flags invalidate generated catalogs and metadata.
-
-A local ReleaseSafe microbenchmark (20 million calls, three `perf stat` runs on
-one pinned core) measured about 0.031 s for English lookup versus 0.022 s for a
-literal loop, and 0.324 s for qps. These are lookup measurements, not complete
-frame timings. The 1,879-message qps catalog has 3,759 64-byte slots and about
-83 KiB of translated text, plus source IDs and form slices. Fuzzy catalogs
-have empty lookup tables; reviewed catalogs will increase binary size.
-
-`python3 tests/i18n.py` checks explicit-language precedence, localized desktop
-names and live catalog/cache invalidation, stable widget names, and expanded
-power-menu labels. `python3 tests/calendar_popup.py --locale-only` uses a
-private German locale generated by `localedef`, checks localized calendar
-names and reloads formats. The full calendar test also checks picker/child
-locale persistence. `tests/input_protocols.py` covers ru/ua-only shortcuts;
-`tests/dead_keys.py` covers Portuguese/Spanish compose and German/French layouts.
-`zig build test-polkit` covers language re-registration, including active
-requests that must finish before registration changes.
-
-Files collation tests run C and, when available, de_DE.UTF-8 and ru_RU.UTF-8.
-To avoid host changes, generate private locales and pass their directory as
-`LOCPATH`; missing locales are reported as skips. The directory worker owns
-LC_COLLATE and computes keys once per listing. A 100,000-file ReleaseSafe
-benchmark on the development machine measured about 135 ms German / 134 ms
-Russian for enumeration, keys and both sorts, versus about 221 ms for direct
-strcoll comparisons. C remained around 95–96 ms. These are local measurements,
-not performance thresholds.
-
-`python3 scripts/i18n-screens.py qps --out /tmp/rediwm-qps-review` captures the
-shell, every available Settings section and app/dialog fixtures into an
-isolated directory. Repeat for each reviewed language and `--scale 1.5`.
-`review.json` records measured overflow, skipped/unavailable surfaces and the
-manual security-screen checklist. Icon-only controls carry accessible labels
-but have zero painted text width; synthetic IPC hit targets may not have a
-text measurement. `--allow-overflow` only keeps the report-producing walk from
-failing; it does not approve a language. Review every recorded ellipsis/overflow
-before changing its native-review header. Lock/greeter/polkit screenshots use
-their existing isolated fixtures; production locked IPC stays denied.
-
-## Fixtures that must stay stable
-
-`src/ipc_serializers.jsonl` pins response serialization. `src/ipc_tests.zig`
-checks every canonical v1 command and rejection of legacy envelopes/names.
-`tests/msg_v1.json` specifies CLI requests in the v1 format; `tests/msg.py`
-checks them against an owned fake socket. Update expected contracts explicitly
-when the protocol changes; never regenerate expectations from the implementation.
-
-## Performance
-
-Measure with ReleaseSafe (`zig build -Doptimize=ReleaseSafe`); keep renderer,
-scale, input rate and compiler backend identical across comparisons.
-
-- `perf.py` checks metric invariants on empty commits, full damage and menus.
- `perf.py --socket $REDIWM_SOCKET --seconds 10` observes a running desktop
- (resets its counters).
-- `motion_perf.py` measures idle, pointer motion, selection, hover, drags and
- panning (`--rate 1000` for high-rate mice); it asserts that motion over
- unchanged desktop content repaints nothing.
-- `scene_baseline.py` is the fixed workload for `docs/plans/scene-graph.md`:
- three glass windows, 60 fps damage, drag, resize, fullscreen and camera
- zoom on GLES2 at scale 1, 1.5 and mixed. A "clean" session records process
- cost (CPU, `perf stat` instructions:u, context switches, RSS) and a "stats"
- session the frame timers; `--out`/`--report --against` diff two builds,
- `--capture`/`--compare` keep and check golden screenshots. See
- `docs/plans/scene-graph-baseline.md`.
-- `spawn_latency.py` times spawn → map → first presented frame.
-- `startup_perf.py --binary zig-out/release-safe/bin/rediwm --runs 7`
- measures process entry → first scene commit, responsive IPC, catalogue and
- wallpaper in isolated headless sessions. `--native-scaling` includes X11
- native scaling; `--publication-delay-ms 1000` models slow login environment
- publication. `--cold-cache` disables reuse of the app catalogue between runs
- without flushing OS caches. Compare the same renderer, scale and build mode.
- The `startup` IPC counters distinguish `first_presented_ns` (successful
- scene submission) from `first_visible_ns` (the backend's presentation
- acknowledgement for a scene buffer, excluding the initial empty modeset).
- `backend_start_ns`/`backend_ready_ns` bracket display backend startup;
- `input_ready_ns` marks completed input enumeration. `services_started_ns`
- means optional service initialization has been issued, not that every
- external service has replied. Native unlocked sessions enumerate input
- after presentation; greeter/lock recovery initialize input immediately.
- Optional services start one per event-loop turn before autostart. A one-shot
- 250 ms fallback handles missing presentation feedback, and an inactive seat
- resumes pending input on its activation event. `reveal_done_ns` marks the
- end of the fade in from black (`reveal.zig`); it stays zero headless, where
- outputs carry no veil, so judge the fade nested or on a real login.
- `rediwm-dm` carries the accepted handoff's monotonic timestamp through PAM
- and the login shell: `login_to_compositor_ns` includes greeter shutdown,
- PAM session opening, shell profiles and supervisor setup;
- `login_to_visible_ns` includes those plus the compositor's first presented
- scene acknowledgement. These are zero without a supplied login timestamp;
- unlike the other offsets their origin is the accepted login, including
- across a compositor restart in that login. Physical login/VT timings still
- need a real greeter login; headless runs do not enumerate native devices.
- `startup.py` also checks startup and shutdown with stalled audio;
- `session_readiness.py` withholds the supervisor's acknowledgement while
- exercising frames, input, IPC and exec restart.
-- `GetPerformanceStats.frame_time_ms` is the interval between commits, not
- frame cost. `frame_work` has per-stage wall times over the last 512 samples
- (`cpu_frame`, `taskbar_cpu`, `chrome_cpu`, `panels_cpu`, `projection_cpu`,
- `glass_cpu`, `scene_commit_cpu`, `gpu_elapsed`; `glass_cpu` stays empty since
- the output pass draws glass, which `scene_commit_cpu` now includes, and
- `glass_reblurs` counts the blurs it re-took). CPU and GPU overlap; don't
- add them or invert them into FPS.
-- The GPU timer starts on the first stats request and stops after five idle
- minutes; it costs CPU per frame (about 0.9 % of a core with a 60 Hz client).
- The per-stage wall timers (`taskbar_cpu`, `chrome_cpu`, `panels_cpu`,
- `projection_cpu`, `anim_cpu`) run in the same window: they stay empty until a
- stats request or `reset_performance_stats`, so reset first, then measure. For
- CPU A/B runs, make no stats requests and read process CPU time (per-thread
- schedstat) or `perf stat -e instructions:u` instead.
-
-## Still manual
-
-Not covered by any automated test: a real login through rediwm-dm (logind, VT
-hand-off, keyring), real-account PAM unlock, real polkit helper/pkexec
-authentication, xdg-desktop-portal-wlr with a browser or OBS, DRM modesetting
-and EDID scale on physical panels, physical backlight permissions, and IME
-behaviour across real toolkits (fcitx5/IBus with GTK, Qt, foot, Firefox).
+Run `zig build i18n-check`, `zig build i18n-lint`, `zig build test-i18n` and
+`python3 tests/i18n.py`. Follow [translation review](po/README.md); generate
+private locales with `localedef` + `LOCPATH`, never change host locales.
-During the 2026-10-02 review the user confirmed real password login through
-rediwm-dm, unlock and native polkit authentication on the development machine.
-Keyring unlock and browser/OBS sharing remain unverified. See
-[desktop readiness](desktop-readiness.md) for review results and known baseline
-failures, and [screen sharing](docs/screen-sharing.md#remaining-qualification)
-for the remaining capture acceptance checks.
+## Further checks
-`python3 tests/taskbar_shape.py` covers the floating taskbar: the Appearance sliders for gap from the edge, length and corner radius, the same geometry from the theme file on both edges, the strip a maximized window leaves, and the pixels of the rounded ends.
+Measure performance with ReleaseSafe and identical renderer/scale/input settings;
+see [scene_baseline.py](tests/scene_baseline.py), [motion_perf.py](tests/motion_perf.py)
+and [startup_perf.py](tests/startup_perf.py). Stats requests enable timers and
+add overhead; keep CPU comparisons free of them. `frame_time_ms` is the commit
+interval; CPU and GPU work overlap, so do not add their timings.
-`python3 tests/theme_packs.py` covers theme ZIP installation, refusal of unsafe paths/links/special files/bombs, Xcursor headers/data bounds and per-size frame limits (including sizes other than the selected one), pack discovery, base plus overrides, live wallpaper and folder icons, reset, cursors and removal in isolated data/config/state directories.
+Hardware, login, browser/OBS sharing and toolkit IME checks remain manual. See
+[rendering](docs/agent-notes/rendering.md), [tiling qualification](docs/plans/optional-tiling-qualification.md)
+and [printer qualification](docs/plans/printers-qualification.md).
diff --git a/po/de.po b/po/de.po
index d92501a..c879b22 100644
--- a/po/de.po
+++ b/po/de.po
@@ -1144,7 +1144,7 @@ msgstr "Klassisch (überlappend)"
msgid "Clear search"
msgstr "Suche leeren"
-#: src/editor/app_input.zig
+#: src/editor/app_edit.zig
msgid "Clipboard selections are limited to 1 MiB."
msgstr "Zwischenablageauswahlen sind auf 1 MiB begrenzt."
@@ -2260,10 +2260,6 @@ msgstr "Prozess beenden"
msgid "Enlarge this window to show the terminal"
msgstr "Vergrößere dieses Fenster, um das Terminal anzuzeigen"
-#: src/calculator/app.zig
-msgid "Enter = Esc clear F9 ± % = ÷100"
-msgstr "Eingabe = Esc leeren F9 ± % = ÷100"
-
#: src/polkit/dialog.zig
msgid "Enter Password"
msgstr "Passwort eingeben"
@@ -2516,7 +2512,7 @@ msgstr "Im Dokument suchen…"
msgid "Find ▲"
msgstr "Suchen ▲"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Find…"
msgstr "Suchen…"
@@ -3324,7 +3320,7 @@ msgstr "Mittel"
msgid "Memory (resident)"
msgstr "Speicher (resident)"
-#: src/editor/client_render.zig
+#: src/editor/app_paint.zig
msgid "Menu"
msgstr "Menü"
@@ -3604,7 +3600,7 @@ msgstr "Neuer Tab"
msgid "Newest first"
msgstr "Neueste zuerst"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Next"
msgstr "Weiter"
@@ -4724,7 +4720,7 @@ msgstr "Wiederholverzögerung"
msgid "Repeat rate"
msgstr "Wiederholrate"
-#: src/files/app_chooser.zig
+#: src/editor/app.zig
msgid "Replace"
msgstr "Ersetzen"
@@ -5744,7 +5740,7 @@ msgstr "Textdatei"
msgid "Text files are limited to 4 GiB."
msgstr "Textdateien sind auf 4 GiB begrenzt."
-#: src/editor/app_input.zig
+#: src/editor/app_search.zig
msgid "Text not found"
msgstr "Text nicht gefunden"
@@ -7444,7 +7440,7 @@ msgctxt "desktop:Comment"
msgid "Edit text files in tabs"
msgstr "Textdateien in Tabs bearbeiten"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Comment"
msgid "RediWM Wayland compositor"
msgstr "RediWM-Wayland-Compositor"
@@ -7519,7 +7515,7 @@ msgctxt "desktop:Name"
msgid "PDF Viewer"
msgstr "PDF-Betrachter"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Name"
msgid "RediWM"
msgstr "RediWM"
@@ -7575,3 +7571,23 @@ msgstr "Einstellungen;Steuerung;Bedienfeld;Voreinstellungen;Bildschirm;Erscheinu
#: src/control_center/sections/region.zig
msgid "English"
msgstr "Englisch"
+
+#: src/battery_popup.zig
+msgid "No power profile service is running."
+msgstr ""
+
+#: src/battery_popup.zig
+msgid "Power profiles unavailable"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace All"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace with…"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Matches replaced: {count}"
+msgstr ""
diff --git a/po/es.po b/po/es.po
index f68fe50..ff08bd9 100644
--- a/po/es.po
+++ b/po/es.po
@@ -1141,7 +1141,7 @@ msgstr "Clásico (apilado)"
msgid "Clear search"
msgstr "Limpiar búsqueda"
-#: src/editor/app_input.zig
+#: src/editor/app_edit.zig
msgid "Clipboard selections are limited to 1 MiB."
msgstr "Las selecciones del portapapeles tienen un límite de 1 MiB."
@@ -2257,10 +2257,6 @@ msgstr "Terminar proceso"
msgid "Enlarge this window to show the terminal"
msgstr "Amplía esta ventana para mostrar el terminal"
-#: src/calculator/app.zig
-msgid "Enter = Esc clear F9 ± % = ÷100"
-msgstr "Intro = Esc borrar F9 ± % = ÷100"
-
#: src/polkit/dialog.zig
msgid "Enter Password"
msgstr "Introducir contraseña"
@@ -2513,7 +2509,7 @@ msgstr "Buscar en el documento..."
msgid "Find ▲"
msgstr "Buscar ▲"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Find…"
msgstr "Buscar…"
@@ -3321,7 +3317,7 @@ msgstr "Medio"
msgid "Memory (resident)"
msgstr "Memoria (residente)"
-#: src/editor/client_render.zig
+#: src/editor/app_paint.zig
msgid "Menu"
msgstr "Menú"
@@ -3601,7 +3597,7 @@ msgstr "Pestaña nueva"
msgid "Newest first"
msgstr "Más reciente primero"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Next"
msgstr "Siguiente"
@@ -4721,7 +4717,7 @@ msgstr "Retardo de repetición"
msgid "Repeat rate"
msgstr "Frecuencia de repetición"
-#: src/files/app_chooser.zig
+#: src/editor/app.zig
msgid "Replace"
msgstr "Reemplazar"
@@ -5741,7 +5737,7 @@ msgstr "Archivo de texto"
msgid "Text files are limited to 4 GiB."
msgstr "Los archivos de texto tienen un límite de 4 GiB."
-#: src/editor/app_input.zig
+#: src/editor/app_search.zig
msgid "Text not found"
msgstr "No se encontró el texto"
@@ -7441,7 +7437,7 @@ msgctxt "desktop:Comment"
msgid "Edit text files in tabs"
msgstr "Edita archivos de texto en pestañas"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Comment"
msgid "RediWM Wayland compositor"
msgstr "Compositor Wayland RediWM"
@@ -7516,7 +7512,7 @@ msgctxt "desktop:Name"
msgid "PDF Viewer"
msgstr "Visor de PDF"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Name"
msgid "RediWM"
msgstr "RediWM"
@@ -7572,3 +7568,23 @@ msgstr "configuración;control;panel;preferencias;pantalla;apariencia;ratón;tec
#: src/control_center/sections/region.zig
msgid "English"
msgstr "Inglés"
+
+#: src/battery_popup.zig
+msgid "No power profile service is running."
+msgstr ""
+
+#: src/battery_popup.zig
+msgid "Power profiles unavailable"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace All"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace with…"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Matches replaced: {count}"
+msgstr ""
diff --git a/po/fr.po b/po/fr.po
index 72f4033..0fa0a4c 100644
--- a/po/fr.po
+++ b/po/fr.po
@@ -1144,7 +1144,7 @@ msgstr "Classique (superposition)"
msgid "Clear search"
msgstr "Effacer la recherche"
-#: src/editor/app_input.zig
+#: src/editor/app_edit.zig
msgid "Clipboard selections are limited to 1 MiB."
msgstr "Les sélections du presse-papiers sont limitées à 1 Mio."
@@ -2260,10 +2260,6 @@ msgstr "Terminer le processus"
msgid "Enlarge this window to show the terminal"
msgstr "Agrandissez cette fenêtre pour afficher le terminal"
-#: src/calculator/app.zig
-msgid "Enter = Esc clear F9 ± % = ÷100"
-msgstr "Entrée = Échap effacer F9 ± % = ÷100"
-
#: src/polkit/dialog.zig
msgid "Enter Password"
msgstr "Saisir le mot de passe"
@@ -2516,7 +2512,7 @@ msgstr "Rechercher dans le document…"
msgid "Find ▲"
msgstr "Rechercher ▲"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Find…"
msgstr "Rechercher…"
@@ -3324,7 +3320,7 @@ msgstr "Moyen"
msgid "Memory (resident)"
msgstr "Mémoire (résidente)"
-#: src/editor/client_render.zig
+#: src/editor/app_paint.zig
msgid "Menu"
msgstr "Menu"
@@ -3604,7 +3600,7 @@ msgstr "Nouvel onglet"
msgid "Newest first"
msgstr "Plus récents d'abord"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Next"
msgstr "Suivant"
@@ -4724,7 +4720,7 @@ msgstr "Délai de répétition"
msgid "Repeat rate"
msgstr "Fréquence de répétition"
-#: src/files/app_chooser.zig
+#: src/editor/app.zig
msgid "Replace"
msgstr "Remplacer"
@@ -5744,7 +5740,7 @@ msgstr "Fichier texte"
msgid "Text files are limited to 4 GiB."
msgstr "Les fichiers texte sont limités à 4 Gio."
-#: src/editor/app_input.zig
+#: src/editor/app_search.zig
msgid "Text not found"
msgstr "Texte introuvable"
@@ -7444,7 +7440,7 @@ msgctxt "desktop:Comment"
msgid "Edit text files in tabs"
msgstr "Modifier des fichiers texte dans des onglets"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Comment"
msgid "RediWM Wayland compositor"
msgstr "Compositeur Wayland RediWM"
@@ -7519,7 +7515,7 @@ msgctxt "desktop:Name"
msgid "PDF Viewer"
msgstr "Visionneuse PDF"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Name"
msgid "RediWM"
msgstr "RediWM"
@@ -7575,3 +7571,23 @@ msgstr "paramètres;contrôle;panneau;préférences;affichage;apparence;souris;c
#: src/control_center/sections/region.zig
msgid "English"
msgstr "Anglais"
+
+#: src/battery_popup.zig
+msgid "No power profile service is running."
+msgstr ""
+
+#: src/battery_popup.zig
+msgid "Power profiles unavailable"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace All"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace with…"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Matches replaced: {count}"
+msgstr ""
diff --git a/po/lint-files b/po/lint-files
index e565afd..5b43b29 100644
--- a/po/lint-files
+++ b/po/lint-files
@@ -141,3 +141,6 @@ src/system_monitor_main.zig
src/taskbar/battery.zig
src/taskbar/window_menu.zig
src/toplevel/info.zig
+src/editor/app_controls.zig
+src/editor/app_search.zig
+src/editor/app_edit.zig
diff --git a/po/pt_BR.po b/po/pt_BR.po
index b4540eb..c14e4aa 100644
--- a/po/pt_BR.po
+++ b/po/pt_BR.po
@@ -1141,7 +1141,7 @@ msgstr "Clássico (empilhamento)"
msgid "Clear search"
msgstr "Limpar busca"
-#: src/editor/app_input.zig
+#: src/editor/app_edit.zig
msgid "Clipboard selections are limited to 1 MiB."
msgstr "As seleções da área de transferência são limitadas a 1 MiB."
@@ -2257,10 +2257,6 @@ msgstr "Encerrar processo"
msgid "Enlarge this window to show the terminal"
msgstr "Amplie esta janela para mostrar o terminal"
-#: src/calculator/app.zig
-msgid "Enter = Esc clear F9 ± % = ÷100"
-msgstr "Enter = Esc limpar F9 ± % = ÷100"
-
#: src/polkit/dialog.zig
msgid "Enter Password"
msgstr "Digitar senha"
@@ -2513,7 +2509,7 @@ msgstr "Localizar no documento..."
msgid "Find ▲"
msgstr "Localizar ▲"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Find…"
msgstr "Localizar…"
@@ -3321,7 +3317,7 @@ msgstr "Médio"
msgid "Memory (resident)"
msgstr "Memória (residente)"
-#: src/editor/client_render.zig
+#: src/editor/app_paint.zig
msgid "Menu"
msgstr "Menu"
@@ -3601,7 +3597,7 @@ msgstr "Nova aba"
msgid "Newest first"
msgstr "Mais recente primeiro"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Next"
msgstr "Próximo"
@@ -4721,7 +4717,7 @@ msgstr "Atraso de repetição"
msgid "Repeat rate"
msgstr "Taxa de repetição"
-#: src/files/app_chooser.zig
+#: src/editor/app.zig
msgid "Replace"
msgstr "Substituir"
@@ -5741,7 +5737,7 @@ msgstr "Arquivo de texto"
msgid "Text files are limited to 4 GiB."
msgstr "Os arquivos de texto são limitados a 4 GiB."
-#: src/editor/app_input.zig
+#: src/editor/app_search.zig
msgid "Text not found"
msgstr "Texto não encontrado"
@@ -7441,7 +7437,7 @@ msgctxt "desktop:Comment"
msgid "Edit text files in tabs"
msgstr "Edite arquivos de texto em abas"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Comment"
msgid "RediWM Wayland compositor"
msgstr "Compositor Wayland RediWM"
@@ -7516,7 +7512,7 @@ msgctxt "desktop:Name"
msgid "PDF Viewer"
msgstr "Visualizador de PDF"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Name"
msgid "RediWM"
msgstr "RediWM"
@@ -7572,3 +7568,23 @@ msgstr "configurações;controle;painel;preferências;tela;aparência;mouse;tecl
#: src/control_center/sections/region.zig
msgid "English"
msgstr "Inglês"
+
+#: src/battery_popup.zig
+msgid "No power profile service is running."
+msgstr ""
+
+#: src/battery_popup.zig
+msgid "Power profiles unavailable"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace All"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace with…"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Matches replaced: {count}"
+msgstr ""
diff --git a/po/rediwm.pot b/po/rediwm.pot
index 6fc0c17..a5dee5d 100644
--- a/po/rediwm.pot
+++ b/po/rediwm.pot
@@ -1135,7 +1135,7 @@ msgstr ""
msgid "Clear search"
msgstr ""
-#: src/editor/app_input.zig
+#: src/editor/app_edit.zig
msgid "Clipboard selections are limited to 1 MiB."
msgstr ""
@@ -2255,10 +2255,6 @@ msgstr ""
msgid "Enlarge this window to show the terminal"
msgstr ""
-#: src/calculator/app.zig
-msgid "Enter = Esc clear F9 ± % = ÷100"
-msgstr ""
-
#: src/polkit/dialog.zig
msgid "Enter Password"
msgstr ""
@@ -2515,7 +2511,7 @@ msgstr ""
msgid "Find ▲"
msgstr ""
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Find…"
msgstr ""
@@ -3291,6 +3287,10 @@ msgstr ""
msgid "Master volume"
msgstr ""
+#: src/editor/app_search.zig
+msgid "Matches replaced: {count}"
+msgstr ""
+
#: src/control_center/sections/shortcuts.zig
msgid "Maximize or restore the focused window."
msgstr ""
@@ -3327,7 +3327,7 @@ msgstr ""
msgid "Memory (resident)"
msgstr ""
-#: src/editor/client_render.zig
+#: src/editor/app_paint.zig
msgid "Menu"
msgstr ""
@@ -3607,7 +3607,7 @@ msgstr ""
msgid "Newest first"
msgstr ""
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Next"
msgstr ""
@@ -4739,14 +4739,22 @@ msgstr ""
msgid "Repeat rate"
msgstr ""
-#: src/files/app_chooser.zig
+#: src/editor/app.zig
msgid "Replace"
msgstr ""
+#: src/editor/app_search.zig
+msgid "Replace All"
+msgstr ""
+
#: src/control_center/sections/appearance_sections.zig
msgid "Replace installed theme"
msgstr ""
+#: src/editor/app_search.zig
+msgid "Replace with…"
+msgstr ""
+
#: src/control_center/sections/printers_details.zig
msgid "Report copied"
msgstr ""
@@ -5767,7 +5775,7 @@ msgstr ""
msgid "Text files are limited to 4 GiB."
msgstr ""
-#: src/editor/app_input.zig
+#: src/editor/app_search.zig
msgid "Text not found"
msgstr ""
@@ -7471,7 +7479,7 @@ msgctxt "desktop:Comment"
msgid "Edit text files in tabs"
msgstr ""
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Comment"
msgid "RediWM Wayland compositor"
msgstr ""
@@ -7546,7 +7554,7 @@ msgctxt "desktop:Name"
msgid "PDF Viewer"
msgstr ""
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Name"
msgid "RediWM"
msgstr ""
diff --git a/po/ru.po b/po/ru.po
index 283deed..6016063 100644
--- a/po/ru.po
+++ b/po/ru.po
@@ -1144,7 +1144,7 @@ msgstr "Классическое (с перекрытием)"
msgid "Clear search"
msgstr "Очистить поиск"
-#: src/editor/app_input.zig
+#: src/editor/app_edit.zig
msgid "Clipboard selections are limited to 1 MiB."
msgstr "Размер выделения буфера обмена ограничен 1 МиБ."
@@ -2262,10 +2262,6 @@ msgstr "Завершить процесс"
msgid "Enlarge this window to show the terminal"
msgstr "Увеличьте окно, чтобы показать терминал"
-#: src/calculator/app.zig
-msgid "Enter = Esc clear F9 ± % = ÷100"
-msgstr "Enter = Esc: очистить F9 ± % = ÷100"
-
#: src/polkit/dialog.zig
msgid "Enter Password"
msgstr "Введите пароль"
@@ -2518,7 +2514,7 @@ msgstr "Найти в документе…"
msgid "Find ▲"
msgstr "Найти ▲"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Find…"
msgstr "Найти…"
@@ -3326,7 +3322,7 @@ msgstr "Средний"
msgid "Memory (resident)"
msgstr "Память (резидентная)"
-#: src/editor/client_render.zig
+#: src/editor/app_paint.zig
msgid "Menu"
msgstr "Меню"
@@ -3606,7 +3602,7 @@ msgstr "Новая вкладка"
msgid "Newest first"
msgstr "Сначала новые"
-#: src/editor/app_paint.zig
+#: src/editor/app_search.zig
msgid "Next"
msgstr "Далее"
@@ -4726,7 +4722,7 @@ msgstr "Задержка повтора"
msgid "Repeat rate"
msgstr "Частота повтора"
-#: src/files/app_chooser.zig
+#: src/editor/app.zig
msgid "Replace"
msgstr "Заменить"
@@ -5746,7 +5742,7 @@ msgstr "Текстовый файл"
msgid "Text files are limited to 4 GiB."
msgstr "Размер текстового файла ограничен 4 ГиБ."
-#: src/editor/app_input.zig
+#: src/editor/app_search.zig
msgid "Text not found"
msgstr "Текст не найден"
@@ -7456,7 +7452,7 @@ msgctxt "desktop:Comment"
msgid "Edit text files in tabs"
msgstr "Редактирование текстовых файлов во вкладках"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Comment"
msgid "RediWM Wayland compositor"
msgstr "Композитор Wayland RediWM"
@@ -7531,7 +7527,7 @@ msgctxt "desktop:Name"
msgid "PDF Viewer"
msgstr "Просмотр PDF"
-#: data/rediwm.desktop
+#: data/rediwm-release-safe.desktop
msgctxt "desktop:Name"
msgid "RediWM"
msgstr "RediWM"
@@ -7587,3 +7583,23 @@ msgstr "настройки;управление;панель;параметры;
#: src/control_center/sections/region.zig
msgid "English"
msgstr "Английский"
+
+#: src/battery_popup.zig
+msgid "No power profile service is running."
+msgstr ""
+
+#: src/battery_popup.zig
+msgid "Power profiles unavailable"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace All"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Replace with…"
+msgstr ""
+
+#: src/editor/app_search.zig
+msgid "Matches replaced: {count}"
+msgstr ""
diff --git a/src/calculator/app.zig b/src/calculator/app.zig
index 033d746..1f8f002 100644
--- a/src/calculator/app.zig
+++ b/src/calculator/app.zig
@@ -6,9 +6,9 @@ const W = ui.layout.Widget;
const c = @import("../files/c.zig").api;
const Model = @import("model.zig").Model;
-/// The entry line is set in the keypad's own label size.
+/// Give the entry twice the usual large-button label size.
fn entrySize() f32 {
- return ui.widgets.button.metrics(.lg, theme.global).font_size;
+ return ui.widgets.button.metrics(.lg, theme.global).font_size * 2;
}
const labels = [_][]const u8{
@@ -90,7 +90,7 @@ pub const App = struct {
const height: f32 = @floatFromInt(self.h);
const gap: f32 = 8;
const cell_w = (width - 32 - gap * 3) / 4;
- const top: f32 = @max(112, entrySize() + cairo.statusSize() * 3 + 56);
+ const top: f32 = @max(112, entrySize() + cairo.statusSize() + 56);
const cell_h = @max(24, (height - top - 16 - gap * 5) / 6);
self.root.computed_width = width;
self.root.computed_height = height;
@@ -209,14 +209,17 @@ pub const App = struct {
c.cairo_paint(cr);
const status = cairo.statusSize();
const heading = entrySize();
- if (self.model.history_len > 0) self.textRight(cr, self.model.history[0..self.model.history_len], 16 + status, status, false);
+ const history = if (self.model.notice.len > 0) self.model.notice else self.model.history[0..self.model.history_len];
+ if (history.len > 0) self.textRight(cr, history, 16 + status, status, false);
const expression = self.model.display();
self.textRight(cr, if (expression.len == 0) "0" else expression, 28 + status + heading, heading, true);
- self.textRight(cr, if (self.model.notice.len > 0) self.model.notice else @import("i18n").tr("Enter = Esc clear F9 ± % = ÷100"), 40 + status * 2 + heading, status, false);
ui.input.active_dispatcher = &self.dispatcher;
defer ui.input.active_dispatcher = null;
if (cairo.Layer.begin(cr, .{ .x = 0, .y = 0, .w = @floatFromInt(self.w), .h = @floatFromInt(self.h) })) |value| {
var layer = value;
+ var keypad_theme = theme.shellPalette();
+ keypad_theme.button_font_size *= 1.5;
+ layer.renderer.palette = keypad_theme;
ui.paint.paint(&self.root, &layer.renderer);
layer.finish();
}
diff --git a/src/calculator/model.zig b/src/calculator/model.zig
index 6715b00..64662f0 100644
--- a/src/calculator/model.zig
+++ b/src/calculator/model.zig
@@ -55,23 +55,32 @@ pub const Model = struct {
self.notice = @import("i18n").tr("Expression is full");
}
- /// Toggle the trailing number (including a scientific-notation result).
+ /// Toggle the trailing operand, including a percentage or grouped result.
pub fn negate(self: *Model) void {
self.notice = "";
self.evaluated = false;
var start = self.len;
- while (start > 0 and (std.ascii.isDigit(self.buffer[start - 1]) or self.buffer[start - 1] == '.')) start -= 1;
- if (start > 0) {
- var exponent = start;
- if (self.buffer[exponent - 1] == '+' or self.buffer[exponent - 1] == '-') exponent -= 1;
- if (exponent > 0 and (self.buffer[exponent - 1] == 'e' or self.buffer[exponent - 1] == 'E')) {
- start = exponent - 1;
- while (start > 0 and (std.ascii.isDigit(self.buffer[start - 1]) or self.buffer[start - 1] == '.')) start -= 1;
+ while (start > 0 and self.buffer[start - 1] == '%') start -= 1;
+ if (start > 0 and self.buffer[start - 1] == ')') {
+ var depth: usize = 1;
+ start -= 1;
+ while (start > 0 and depth > 0) {
+ start -= 1;
+ if (self.buffer[start] == ')') depth += 1;
+ if (self.buffer[start] == '(') depth -= 1;
+ }
+ if (depth != 0) return;
+ } else {
+ while (start > 0 and (std.ascii.isDigit(self.buffer[start - 1]) or self.buffer[start - 1] == '.')) start -= 1;
+ if (start > 0) {
+ var exponent = start;
+ if (self.buffer[exponent - 1] == '+' or self.buffer[exponent - 1] == '-') exponent -= 1;
+ if (exponent > 0 and (self.buffer[exponent - 1] == 'e' or self.buffer[exponent - 1] == 'E')) {
+ start = exponent - 1;
+ while (start > 0 and (std.ascii.isDigit(self.buffer[start - 1]) or self.buffer[start - 1] == '.')) start -= 1;
+ }
}
}
- // After an operator, ± starts a negative entry; on a closed group or
- // percentage it leaves the completed operand alone.
- if (start == self.len and self.len > 0 and (self.buffer[self.len - 1] == ')' or self.buffer[self.len - 1] == '%')) return;
if (start > 0 and self.buffer[start - 1] == '-' and
(start == 1 or std.mem.indexOfScalar(u8, "+-*/(", self.buffer[start - 2]) != null))
{
@@ -132,10 +141,17 @@ const Parser = struct {
pos: usize = 0,
depth: usize = 0,
+ const Value = struct {
+ number: f64,
+ /// A percentage operand keeps its meaning through signs and grouping.
+ /// Products and sums produce ordinary numbers.
+ percent: bool = false,
+ };
+
fn evaluate(self: *Parser) EvalError!f64 {
const value = try self.sum();
if (self.pos != self.text.len) return error.InvalidExpression;
- return value;
+ return value.number;
}
fn take(self: *Parser, char: u8) bool {
@@ -149,33 +165,34 @@ const Parser = struct {
return value;
}
- fn sum(self: *Parser) EvalError!f64 {
+ fn sum(self: *Parser) EvalError!Value {
var value = try self.product();
while (self.pos < self.text.len) {
- if (self.take('+')) {
- value = try finite(value + try self.product());
- } else if (self.take('-')) {
- value = try finite(value - try self.product());
- } else break;
+ const subtract = if (self.take('+')) false else if (self.take('-')) true else break;
+ const rhs = try self.product();
+ // Calculator-style increases/discounts: 200 + 10% = 220.
+ // Resolve multiplication/division first, using fractional rates.
+ const amount = if (rhs.percent) try finite(value.number * rhs.number) else rhs.number;
+ value = .{ .number = try finite(if (subtract) value.number - amount else value.number + amount) };
}
return value;
}
- fn product(self: *Parser) EvalError!f64 {
+ fn product(self: *Parser) EvalError!Value {
var value = try self.operand();
while (self.pos < self.text.len) {
if (self.take('*')) {
- value = try finite(value * try self.operand());
+ value = .{ .number = try finite(value.number * (try self.operand()).number) };
} else if (self.take('/')) {
- const divisor = try self.operand();
+ const divisor = (try self.operand()).number;
if (divisor == 0) return error.DivisionByZero;
- value = try finite(value / divisor);
+ value = .{ .number = try finite(value.number / divisor) };
} else break;
}
return value;
}
- fn operand(self: *Parser) EvalError!f64 {
+ fn operand(self: *Parser) EvalError!Value {
if (self.depth >= 32) return error.InvalidExpression;
self.depth += 1;
defer self.depth -= 1;
@@ -183,7 +200,7 @@ const Parser = struct {
while (self.pos < self.text.len) {
if (self.take('-')) negative = !negative else if (!self.take('+')) break;
}
- var value: f64 = undefined;
+ var value: Value = undefined;
if (self.take('(')) {
value = try self.sum();
if (!self.take(')')) return error.InvalidExpression;
@@ -194,9 +211,17 @@ const Parser = struct {
_ = self.take('+') or self.take('-');
while (self.pos < self.text.len and std.ascii.isDigit(self.text[self.pos])) self.pos += 1;
}
- value = std.fmt.parseFloat(f64, self.text[start..self.pos]) catch return error.InvalidExpression;
+ value = .{ .number = std.fmt.parseFloat(f64, self.text[start..self.pos]) catch return error.InvalidExpression };
}
- while (self.take('%')) value /= 100;
- return finite(if (negative) -value else value);
+ while (self.take('%')) {
+ value.number /= 100;
+ value.percent = true;
+ }
+ value.number = try finite(if (negative) -value.number else value.number);
+ return value;
}
};
+
+test {
+ _ = @import("model_tests.zig");
+}
diff --git a/src/calculator/model_tests.zig b/src/calculator/model_tests.zig
new file mode 100644
index 0000000..32f0461
--- /dev/null
+++ b/src/calculator/model_tests.zig
@@ -0,0 +1,143 @@
+const std = @import("std");
+const Model = @import("model.zig").Model;
+
+fn enter(model: *Model, expression: []const u8) void {
+ for (expression) |char| model.input(char);
+}
+
+fn expectResult(model: *Model, expected: []const u8) !void {
+ model.equals();
+ try std.testing.expectEqualStrings("", model.notice);
+ try std.testing.expect(model.evaluated);
+ try std.testing.expectEqualStrings(expected, model.display());
+}
+
+test "calculator percentages follow the arithmetic operator and grouping" {
+ const cases = [_][2][]const u8{
+ .{ "100+5%", "105" },
+ .{ "200+10%", "220" },
+ .{ "200-10%", "180" },
+ .{ "200*10%", "20" },
+ .{ "200/10%", "2000" },
+ .{ "10%*200", "20" },
+ .{ "10%/200", "0.0005" },
+ .{ "5%", "0.05" },
+ .{ "200+10%+5%", "231" },
+ .{ "200-10%-5%", "171" },
+ .{ "200+10%-10%", "198" },
+ .{ "200+0%", "200" },
+ .{ "200-100%", "0" },
+ .{ "200+150%", "500" },
+ .{ "0+5%", "0" },
+ .{ "-200+10%", "-220" },
+ .{ "200+-10%", "180" },
+ .{ "200--10%", "220" },
+ .{ "200+2.5%", "205" },
+ .{ "200+(5+5)%", "220" },
+ .{ "200+(10%)", "220" },
+ .{ "200+(-(10%))", "180" },
+ .{ "(100+5)%", "1.05" },
+ .{ "(200+10%)*2", "440" },
+ .{ "100+200*5%", "110" },
+ .{ "100+5%*200", "110" },
+ .{ "100+200/5%", "4100" },
+ .{ "100*2+5%", "210" },
+ .{ "50%%", "0.005" },
+ };
+ for (cases) |case| {
+ var model: Model = .{};
+ enter(&model, case[0]);
+ errdefer std.debug.print("expression: {s}\n", .{case[0]});
+ try expectResult(&model, case[1]);
+ try std.testing.expectEqualStrings(case[0], model.history[0..model.history_len]);
+ }
+}
+
+test "calculator preserves precedence, associativity and readable decimals" {
+ const cases = [_][2][]const u8{
+ .{ "2+3*4", "14" }, .{ "(2+3)*4", "20" },
+ .{ "20/5*2", "8" }, .{ "20-5-2", "13" },
+ .{ "2*-3", "-6" }, .{ "-(2+3)", "-5" },
+ .{ ".5+.25", "0.75" }, .{ "0.1+0.2", "0.3" },
+ .{ "-0", "0" }, .{ "1/10000000000", "1e-10" },
+ };
+ for (cases) |case| {
+ var model: Model = .{};
+ enter(&model, case[0]);
+ try expectResult(&model, case[1]);
+ }
+}
+
+test "calculator continues from results and starts fresh on numeric entry" {
+ var model: Model = .{};
+ enter(&model, "200+10%");
+ try expectResult(&model, "220");
+ try expectResult(&model, "220"); // A repeated equals keeps the result.
+ enter(&model, "-5%");
+ try expectResult(&model, "209");
+ enter(&model, "1/10000000000");
+ try expectResult(&model, "1e-10");
+ enter(&model, "*10000000000");
+ try expectResult(&model, "1");
+ enter(&model, "0.1+0.2");
+ try expectResult(&model, "0.3");
+ enter(&model, "*10");
+ try expectResult(&model, "3");
+}
+
+test "calculator sign toggle handles numbers, percentages and groups" {
+ const cases = [_][2][]const u8{
+ .{ "200+10%", "180" }, .{ "200+(5+5)%", "180" },
+ .{ "2*(3+4)", "-14" }, .{ "2+3", "-1" },
+ };
+ for (cases) |case| {
+ var model: Model = .{};
+ enter(&model, case[0]);
+ model.negate();
+ model.negate();
+ try std.testing.expectEqualStrings(case[0], model.expression());
+ model.negate();
+ try expectResult(&model, case[1]);
+ }
+ var model: Model = .{};
+ enter(&model, "1/10000000000");
+ try expectResult(&model, "1e-10");
+ model.negate();
+ try expectResult(&model, "-1e-10");
+}
+
+test "calculator rejects invalid expressions and allows correction" {
+ for ([_][]const u8{ "1/0", "100/0%", "1/(2-2)", "1+", "(1+2", "1+2)", "2(3)", "%" }) |expression| {
+ var model: Model = .{};
+ enter(&model, expression);
+ model.equals();
+ try std.testing.expect(!model.evaluated);
+ try std.testing.expect(model.notice.len > 0);
+ try std.testing.expectEqualStrings(expression, model.expression());
+ }
+ var model: Model = .{};
+ enter(&model, "100/0%");
+ model.equals();
+ model.backspace();
+ model.backspace();
+ enter(&model, "5%");
+ try expectResult(&model, "2000");
+ model.clear();
+ try std.testing.expectEqualStrings("", model.display());
+ try std.testing.expectEqual(@as(usize, 0), model.history_len);
+}
+
+test "calculator bounds entry and rejects overflowing arithmetic" {
+ var model: Model = .{};
+ for (0..256) |_| model.input('9');
+ model.input('9');
+ try std.testing.expectEqual(@as(usize, 256), model.len);
+ try std.testing.expect(model.notice.len > 0);
+ model.equals();
+ try std.testing.expect(model.evaluated);
+ model.input('*');
+ for (0..100) |_| model.input('9');
+ model.equals();
+ try std.testing.expect(!model.evaluated);
+ try std.testing.expect(model.notice.len > 0);
+}
diff --git a/src/calculator_main.zig b/src/calculator_main.zig
index c700691..591acca 100644
--- a/src/calculator_main.zig
+++ b/src/calculator_main.zig
@@ -10,7 +10,7 @@ pub fn main(init: std.process.Init) !void {
if (args.len > 1) {
const arg = std.mem.span(args[1]);
if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
- std.debug.print("Usage: rediwm-calculator\n\nCalculator for RediWM.\nType arithmetic and parentheses, then Enter or =.\nBackspace: undo digit Escape/Delete: clear F9: change sign\nPercent divides by 100. Ctrl+Q: close.\n", .{});
+ std.debug.print("Usage: rediwm-calculator\n\nCalculator for RediWM.\nType arithmetic and parentheses, then Enter or =.\nBackspace: undo digit Escape/Delete: clear F9: change sign\nAdd/subtract a percentage of the preceding amount: 100+5% = 105.\nMultiply/divide by a fractional rate: 100*5% = 5; 100/5% = 2000.\nCtrl+Q: close.\n", .{});
return;
}
return error.UnexpectedArgument;
diff --git a/src/editor/app.zig b/src/editor/app.zig
index 22d04f2..8846efb 100644
--- a/src/editor/app.zig
+++ b/src/editor/app.zig
@@ -20,6 +20,9 @@ const app_files = @import("app_files.zig");
const app_view = @import("app_view.zig");
const app_input = @import("app_input.zig");
const app_paint = @import("app_paint.zig");
+const app_search = @import("app_search.zig");
+const app_edit = @import("app_edit.zig");
+const app_controls = @import("app_controls.zig");
const a = std.heap.c_allocator;
pub const top: f64 = 40;
pub const status_h: f64 = 26;
@@ -32,8 +35,8 @@ const Status = struct {
};
/// Stand-in for the position of a cursor too far from the view to measure.
pub const far: c_int = 1_000_000 * 1024;
-pub const Action = enum { new, open, save, save_as, find, wrap };
-pub const labels = [_]i18n.Message{ i18n.msg("New"), i18n.msg("Open"), i18n.msg("Save"), i18n.msg("Save As"), i18n.msg("Find"), i18n.msg("Word Wrap") };
+pub const Action = enum { new, open, save, save_as, find, replace, wrap };
+pub const labels = [_]i18n.Message{ i18n.msg("New"), i18n.msg("Open"), i18n.msg("Save"), i18n.msg("Save As"), i18n.msg("Find"), i18n.msg("Replace"), i18n.msg("Word Wrap") };
pub const Tab = struct {
id: usize,
doc: Document = .{},
@@ -87,8 +90,8 @@ pub const App = struct {
/// the same tab shows feedback, not switching to a tab scrolled elsewhere.
bar_observed: f64 = 0,
bar_tab: ?*Tab = null,
- px: f64 = 0,
- py: f64 = 0,
+ px: f64 = -1,
+ py: f64 = -1,
wrap: bool = true,
io: std.Io,
operation: ?*op.Operation = null,
@@ -100,7 +103,10 @@ pub const App = struct {
notice_len: usize = 0,
title: [1024:0]u8 = @splat(0),
find_open: bool = false,
+ replace_open: bool = false,
+ search_focus: app_search.Control = .query,
query: @import("../files/editor.zig").Editor = .{},
+ replacement: @import("../files/editor.zig").Editor = .{},
clipboard: std.ArrayList(u8) = .empty,
clipboard_revision: usize = 0,
paste_requested: bool = false,
@@ -120,6 +126,7 @@ pub const App = struct {
for (self.queue.items) |path| a.free(path);
self.queue.deinit(a);
self.query.deinit(a);
+ self.replacement.deinit(a);
self.clipboard.deinit(a);
self.preedit.deinit(a);
self.rows.deinit(a);
@@ -183,6 +190,11 @@ pub const App = struct {
pub const menuHit = app_paint.menuHit;
pub const paintMenu = app_paint.paintMenu;
pub const paintButton = app_paint.paintButton;
+ pub const paintIcon = app_controls.paintIcon;
+ pub const tabCloseBox = app_controls.tabCloseBox;
+ pub const newButtonBox = app_controls.newButtonBox;
+ pub const menuButtonBox = app_controls.menuButtonBox;
+ pub const hoverTarget = app_controls.hoverTarget;
pub const render = app_paint.render;
pub const paintLine = app_paint.paintLine;
pub const paintClose = app_paint.paintClose;
@@ -223,9 +235,18 @@ pub const App = struct {
pub const handleMotion = app_input.handleMotion;
pub const handleButton = app_input.handleButton;
pub const pasteText = app_input.pasteText;
- pub const findNext = app_input.findNext;
+ pub const findNext = app_search.findNext;
+ pub const openSearch = app_search.openSearch;
+ pub const searchEditor = app_search.searchEditor;
+ pub const searchBox = app_search.searchBox;
+ pub const searchHit = app_search.searchHit;
+ pub const searchKey = app_search.searchKey;
+ pub const searchActivate = app_search.searchActivate;
+ pub const paintSearch = app_search.paintSearch;
+ pub const searchCaret = app_search.searchCaret;
pub const keyRepeats = app_input.keyRepeats;
pub const handleKey = app_input.handleKey;
+ pub const editKey = app_edit.editKey;
};
pub fn fill(cr: *c.cairo_t, x: f64, y: f64, w: f64, h: f64, color: [4]f32) void {
ui.setSource(cr, color);
diff --git a/src/editor/app_controls.zig b/src/editor/app_controls.zig
new file mode 100644
index 0000000..2557fbc
--- /dev/null
+++ b/src/editor/app_controls.zig
@@ -0,0 +1,56 @@
+//! Shared geometry for the tab controls and their hover feedback.
+const c = @import("../files/c.zig").api;
+const ui = @import("ui").cairo;
+const theme = @import("ui").theme;
+const button = @import("ui").widgets.button;
+const Rect = @import("ui").context_menu.Rect;
+const app = @import("app.zig");
+const App = app.App;
+const SearchControl = @import("app_search.zig").Control;
+
+pub fn tabCloseBox(_: *const App, index: usize) Rect {
+ return .{ .x = @as(f64, @floatFromInt(index)) * app.tab_w + app.tab_w - 36, .y = 2, .w = 34, .h = 34 };
+}
+
+pub fn newButtonBox(self: *const App) Rect {
+ return .{ .x = self.tabRight(), .y = 2, .w = 36, .h = 34 };
+}
+
+pub fn menuButtonBox(self: *const App) Rect {
+ return .{ .x = @as(f64, @floatFromInt(self.w)) - 38, .y = 2, .w = 36, .h = 34 };
+}
+
+const Hover = union(enum) { none, close: usize, new, menu, search: SearchControl, dialog: usize };
+
+pub fn hoverTarget(self: *App) Hover {
+ if (self.close_tab != null) {
+ const x = (@as(f64, @floatFromInt(self.w)) - 420) / 2;
+ const y = (@as(f64, @floatFromInt(self.h)) - 170) / 2;
+ for ([_]Rect{
+ .{ .x = x + 20, .y = y + 112, .w = 115, .h = 38 },
+ .{ .x = x + 145, .y = y + 112, .w = 125, .h = 38 },
+ .{ .x = x + 280, .y = y + 112, .w = 120, .h = 38 },
+ }, 0..) |box, i| if (box.contains(self.px, self.py)) return .{ .dialog = i };
+ return .none;
+ }
+ if (self.menu_open) return .none;
+ if (self.find_open) if (self.searchHit(self.px, self.py)) |hit| return .{ .search = hit };
+ if (self.newButtonBox().contains(self.px, self.py)) return .new;
+ if (!self.has_titlebar and self.menuButtonBox().contains(self.px, self.py)) return .menu;
+ for (self.first_tab..self.tabs.items.len) |i| {
+ const index = i - self.first_tab;
+ if (@as(f64, @floatFromInt(index + 1)) * app.tab_w > self.tabRight()) break;
+ if (self.tabCloseBox(index).contains(self.px, self.py)) return .{ .close = i };
+ }
+ return .none;
+}
+
+pub fn paintIcon(self: *App, cr: *c.cairo_t, box: Rect, icon: @import("ui").layout.IconId, label: []const u8, selected: bool) void {
+ var layer = ui.Layer.begin(cr, .{ .x = @floatCast(box.x), .y = @floatCast(box.y), .w = @floatCast(box.w), .h = @floatCast(box.h) }) orelse return;
+ defer layer.finish();
+ layer.renderer.palette = theme.shellPalette();
+ button.paint(&layer.renderer, layer.local(), .{ .label = label, .icon = icon, .icon_scale = 1, .variant = .ghost, .size = .sm }, .{
+ .selected = selected,
+ .pointer = if (!self.menu_open and self.close_tab == null and box.contains(self.px, self.py)) .hover else .idle,
+ });
+}
diff --git a/src/editor/app_edit.zig b/src/editor/app_edit.zig
new file mode 100644
index 0000000..b211566
--- /dev/null
+++ b/src/editor/app_edit.zig
@@ -0,0 +1,73 @@
+//! Document keyboard edits and clipboard shortcuts.
+const std = @import("std");
+const c = @import("../files/c.zig").api;
+const tr = @import("i18n").tr;
+const App = @import("app.zig").App;
+const a = std.heap.c_allocator;
+
+pub fn editKey(self: *App, sym: u32, utf8: []const u8) void {
+ const d = self.document();
+ const sel = d.selection();
+ if (self.ctrl) switch (sym) {
+ c.XKB_KEY_a, c.XKB_KEY_A => {
+ d.anchor = 0;
+ d.cursor = d.text.items.len;
+ self.reveal();
+ return;
+ },
+ c.XKB_KEY_c, c.XKB_KEY_C, c.XKB_KEY_x, c.XKB_KEY_X => {
+ if (sel[0] == sel[1]) return;
+ if (sel[1] - sel[0] > @import("../files/transfer.zig").limit) {
+ self.message(tr("Clipboard selections are limited to 1 MiB."));
+ return;
+ }
+ self.clipboard.clearRetainingCapacity();
+ self.clipboard.appendSlice(a, d.text.items[sel[0]..sel[1]]) catch return;
+ self.clipboard_revision += 1;
+ if (sym == c.XKB_KEY_x or sym == c.XKB_KEY_X) {
+ d.insert("") catch |err| self.failure(err);
+ self.reveal();
+ }
+ return;
+ },
+ c.XKB_KEY_v, c.XKB_KEY_V => {
+ self.paste_requested = true;
+ return;
+ },
+ c.XKB_KEY_z, c.XKB_KEY_Z, c.XKB_KEY_y, c.XKB_KEY_Y => {
+ d.undo(self.shift or sym == c.XKB_KEY_y or sym == c.XKB_KEY_Y) catch |err| self.failure(err);
+ self.reveal();
+ return;
+ },
+ else => {},
+ };
+ switch (sym) {
+ c.XKB_KEY_Left, c.XKB_KEY_Right => {
+ const right = sym == c.XKB_KEY_Right;
+ d.move(if (!self.shift and !self.ctrl and sel[0] != sel[1]) (if (right) sel[1] else sel[0]) else d.boundary(right, self.ctrl), self.shift);
+ },
+ c.XKB_KEY_Home => d.move(if (self.ctrl) 0 else d.lineStart(d.cursor), self.shift),
+ c.XKB_KEY_End => d.move(if (self.ctrl) d.text.items.len else d.lineEnd(d.cursor), self.shift),
+ c.XKB_KEY_Up, c.XKB_KEY_Down, c.XKB_KEY_Page_Up, c.XKB_KEY_Page_Down => {
+ const r = self.caretRectNear();
+ const down = sym == c.XKB_KEY_Down or sym == c.XKB_KEY_Page_Down;
+ const distance = if (sym == c.XKB_KEY_Page_Up or sym == c.XKB_KEY_Page_Down) self.viewHeight() else @as(f64, @floatFromInt(r.height)) / 1024;
+ d.move(self.indexAt(@as(f64, @floatFromInt(r.x)) / 1024, @as(f64, @floatFromInt(r.y)) / 1024 + @as(f64, @floatFromInt(r.height)) / 2048 + (if (down) distance else -distance)), self.shift);
+ },
+ c.XKB_KEY_BackSpace, c.XKB_KEY_Delete => {
+ if (sel[0] == sel[1]) d.anchor = d.boundary(sym == c.XKB_KEY_Delete, self.ctrl);
+ d.insert("") catch |err| self.failure(err);
+ },
+ c.XKB_KEY_Return, c.XKB_KEY_KP_Enter => {
+ if (!self.ctrl and !self.alt) d.insert(if (d.crlf) "\r\n" else "\n") catch |err| self.failure(err);
+ },
+ c.XKB_KEY_Tab => {
+ if (!self.ctrl and !self.alt) d.insert("\t") catch |err| self.failure(err);
+ },
+ c.XKB_KEY_F3 => self.findNext(self.shift),
+ else => {
+ if (!self.ctrl and !self.alt and utf8.len > 0 and utf8[0] >= 32) d.insert(utf8) catch |err| self.failure(err);
+ },
+ }
+ self.reveal();
+}
diff --git a/src/editor/app_files.zig b/src/editor/app_files.zig
index 8dd40db..fea98f4 100644
--- a/src/editor/app_files.zig
+++ b/src/editor/app_files.zig
@@ -182,9 +182,9 @@ pub fn act(self: *App, action: Action) void {
.save => self.save(false),
.save_as => self.save(true),
.find => {
- self.find_open = !self.find_open;
- self.query.select_all = true;
+ if (self.find_open) self.find_open = false else self.openSearch(false);
},
+ .replace => self.openSearch(true),
.wrap => {
self.wrap = !self.wrap;
self.current().scroll_x = 0;
diff --git a/src/editor/app_input.zig b/src/editor/app_input.zig
index 7a84084..2a6c9c8 100644
--- a/src/editor/app_input.zig
+++ b/src/editor/app_input.zig
@@ -21,7 +21,7 @@ pub fn indexAt(self: *App, x: f64, y: f64) usize {
}
pub fn handleMotion(self: *App, x: f64, y: f64) void {
- const changed_hover = ((self.py < top or y < top) and @divFloor(self.px, 76) != @divFloor(x, 76)) or (self.py < top) != (y < top);
+ const previous_hover = self.hoverTarget();
self.px = x;
self.py = y;
if (self.menu_open) {
@@ -48,7 +48,7 @@ pub fn handleMotion(self: *App, x: f64, y: f64) void {
if (self.scrollbarGeometry()) |bar| self.seekScroll(self.scroll_drag.offsetAt(bar, @floatCast(x), @floatCast(y)));
self.dirty = true;
}
- if (changed_hover) self.dirty = true;
+ if (!std.meta.eql(previous_hover, self.hoverTarget())) self.dirty = true;
}
pub fn handleButton(self: *App, code: u32, pressed: bool) void {
@@ -81,22 +81,23 @@ pub fn handleButton(self: *App, code: u32, pressed: bool) void {
}
if (self.py < 0) return;
if (self.py < top) {
- if (!self.has_titlebar and self.px >= @as(f64, @floatFromInt(self.w)) - 34) {
+ if (!self.has_titlebar and self.menuButtonBox().contains(self.px, self.py)) {
self.toggleMenu(@as(f64, @floatFromInt(self.w)) - 8);
return;
}
- if (self.px >= self.tabRight()) {
+ if (self.newButtonBox().contains(self.px, self.py)) {
self.act(.new);
return;
}
+ if (self.px < 0 or self.px >= self.tabRight()) return;
const i = self.first_tab + @as(usize, @intFromFloat(@max(0, self.px) / tab_w));
if (i < self.tabs.items.len) {
self.selected = i;
self.changed();
- if (@mod(self.px, tab_w) > tab_w - 28) self.closeSelected();
+ if (self.tabCloseBox(i - self.first_tab).contains(self.px, self.py)) self.closeSelected();
}
} else if (self.find_open and self.py < self.viewTop()) {
- if (self.px > @as(f64, @floatFromInt(self.w)) - 90) self.findNext(self.shift);
+ if (self.searchHit(self.px, self.py)) |control| self.searchActivate(control);
} else if (self.py < @as(f64, @floatFromInt(self.h)) - status_h) {
if (self.px > @as(f64, @floatFromInt(self.w)) - scrollbar.gutter(theme.global.scrollbar_width)) {
if (self.scrollbarGeometry()) |bar| {
@@ -111,14 +112,15 @@ pub fn handleButton(self: *App, code: u32, pressed: bool) void {
}
return;
}
+ const text_y = self.py - self.viewTop();
self.find_open = false;
const t = self.current();
- const pos = self.indexAt(self.px - 16 + t.scroll_x, self.py - self.viewTop());
+ const pos = self.indexAt(self.px - 16 + t.scroll_x, text_y);
const now = @import("ui").key_repeat.nowMs();
const double = if (last_click) |last| last.tab == t.id and now - last.time <= input.multi_click_ms and
@abs(self.px - last.x) <= input.multi_click_slop and @abs(self.py - last.y) <= input.multi_click_slop else false;
if (double and !self.shift) {
- const range = t.doc.wordRange(self.port().characterAt(self.px - 16 + t.scroll_x, self.py - self.viewTop()));
+ const range = t.doc.wordRange(self.port().characterAt(self.px - 16 + t.scroll_x, text_y));
t.doc.anchor = range[0];
t.doc.cursor = range[1];
self.drag_word = range;
@@ -135,7 +137,7 @@ pub fn pasteText(self: *App, bytes: []const u8) void {
self.caret_activity +%= 1;
if (self.close_tab != null or self.menu_open) return;
if (self.find_open) {
- self.query.insert(a, bytes) catch |err| self.failure(err);
+ if (self.searchEditor()) |editor| editor.insert(a, bytes) catch |err| self.failure(err);
self.dirty = true;
return;
}
@@ -147,19 +149,6 @@ pub fn pasteText(self: *App, bytes: []const u8) void {
self.reveal();
}
-pub fn findNext(self: *App, backwards: bool) void {
- const q = self.query.text.items;
- if (q.len == 0) return;
- const d = self.document();
- const sel = d.selection();
- const found = if (backwards) std.mem.lastIndexOf(u8, d.text.items[0..sel[0]], q) orelse std.mem.lastIndexOf(u8, d.text.items, q) else std.mem.indexOfPos(u8, d.text.items, sel[1], q) orelse std.mem.indexOf(u8, d.text.items, q);
- if (found) |pos| {
- d.anchor = pos;
- d.cursor = pos + q.len;
- self.reveal();
- } else self.message(tr("Text not found"));
-}
-
pub fn keyRepeats(self: *App, sym: u32, utf8: []const u8) bool {
if (self.close_tab != null or self.menu_open or self.alt) return false;
if (self.ctrl) return switch (sym) {
@@ -245,9 +234,11 @@ pub fn handleKey(self: *App, sym: u32, utf8: []const u8) void {
return;
},
c.XKB_KEY_f, c.XKB_KEY_F => {
- self.find_open = true;
- self.query.select_all = true;
- self.dirty = true;
+ self.openSearch(false);
+ return;
+ },
+ c.XKB_KEY_h, c.XKB_KEY_H => {
+ self.openSearch(true);
return;
},
c.XKB_KEY_Tab, c.XKB_KEY_ISO_Left_Tab, c.XKB_KEY_Page_Up, c.XKB_KEY_Page_Down => {
@@ -264,72 +255,8 @@ pub fn handleKey(self: *App, sym: u32, utf8: []const u8) void {
return;
}
if (self.find_open) {
- if (sym == c.XKB_KEY_Return) self.findNext(self.shift) else if (self.ctrl and (sym == c.XKB_KEY_v or sym == c.XKB_KEY_V)) self.paste_requested = true else self.query.key(a, sym, utf8, self.ctrl, self.shift, self.alt);
- self.dirty = true;
+ self.searchKey(sym, utf8);
return;
}
- const d = self.document();
- const sel = d.selection();
- if (self.ctrl) switch (sym) {
- c.XKB_KEY_a, c.XKB_KEY_A => {
- d.anchor = 0;
- d.cursor = d.text.items.len;
- self.reveal();
- return;
- },
- c.XKB_KEY_c, c.XKB_KEY_C, c.XKB_KEY_x, c.XKB_KEY_X => {
- if (sel[0] == sel[1]) return;
- if (sel[1] - sel[0] > @import("../files/transfer.zig").limit) {
- self.message(tr("Clipboard selections are limited to 1 MiB."));
- return;
- }
- self.clipboard.clearRetainingCapacity();
- self.clipboard.appendSlice(a, d.text.items[sel[0]..sel[1]]) catch return;
- self.clipboard_revision += 1;
- if (sym == c.XKB_KEY_x or sym == c.XKB_KEY_X) {
- d.insert("") catch |err| self.failure(err);
- self.reveal();
- }
- return;
- },
- c.XKB_KEY_v, c.XKB_KEY_V => {
- self.paste_requested = true;
- return;
- },
- c.XKB_KEY_z, c.XKB_KEY_Z, c.XKB_KEY_y, c.XKB_KEY_Y => {
- d.undo(self.shift or sym == c.XKB_KEY_y or sym == c.XKB_KEY_Y) catch |err| self.failure(err);
- self.reveal();
- return;
- },
- else => {},
- };
- switch (sym) {
- c.XKB_KEY_Left, c.XKB_KEY_Right => {
- const right = sym == c.XKB_KEY_Right;
- d.move(if (!self.shift and !self.ctrl and sel[0] != sel[1]) (if (right) sel[1] else sel[0]) else d.boundary(right, self.ctrl), self.shift);
- },
- c.XKB_KEY_Home => d.move(if (self.ctrl) 0 else d.lineStart(d.cursor), self.shift),
- c.XKB_KEY_End => d.move(if (self.ctrl) d.text.items.len else d.lineEnd(d.cursor), self.shift),
- c.XKB_KEY_Up, c.XKB_KEY_Down, c.XKB_KEY_Page_Up, c.XKB_KEY_Page_Down => {
- const r = self.caretRectNear();
- const down = sym == c.XKB_KEY_Down or sym == c.XKB_KEY_Page_Down;
- const distance = if (sym == c.XKB_KEY_Page_Up or sym == c.XKB_KEY_Page_Down) self.viewHeight() else @as(f64, @floatFromInt(r.height)) / 1024;
- d.move(self.indexAt(@as(f64, @floatFromInt(r.x)) / 1024, @as(f64, @floatFromInt(r.y)) / 1024 + @as(f64, @floatFromInt(r.height)) / 2048 + (if (down) distance else -distance)), self.shift);
- },
- c.XKB_KEY_BackSpace, c.XKB_KEY_Delete => {
- if (sel[0] == sel[1]) d.anchor = d.boundary(sym == c.XKB_KEY_Delete, self.ctrl);
- d.insert("") catch |err| self.failure(err);
- },
- c.XKB_KEY_Return, c.XKB_KEY_KP_Enter => {
- if (!self.ctrl and !self.alt) d.insert(if (d.crlf) "\r\n" else "\n") catch |err| self.failure(err);
- },
- c.XKB_KEY_Tab => {
- if (!self.ctrl and !self.alt) d.insert("\t") catch |err| self.failure(err);
- },
- c.XKB_KEY_F3 => self.findNext(self.shift),
- else => {
- if (!self.ctrl and !self.alt and utf8.len > 0 and utf8[0] >= 32) d.insert(utf8) catch |err| self.failure(err);
- },
- }
- self.reveal();
+ self.editKey(sym, utf8);
}
diff --git a/src/editor/app_paint.zig b/src/editor/app_paint.zig
index 95ebd5b..08c0878 100644
--- a/src/editor/app_paint.zig
+++ b/src/editor/app_paint.zig
@@ -31,6 +31,7 @@ pub const CaretState = struct {
cursor: usize,
anchor: usize,
find: bool,
+ search_focus: @import("app_search.zig").Control,
query_hash: u64,
activity: usize,
top: usize,
@@ -44,14 +45,16 @@ pub const CaretState = struct {
pub fn caretState(self: *App) CaretState {
const d = self.document();
const r = self.inputRectangle();
+ const editor = self.searchEditor();
const in_view = @as(f64, @floatFromInt(r.y + r.height)) > self.viewTop() and @as(f64, @floatFromInt(r.y)) < self.viewTop() + self.viewHeight();
return .{
- .active = self.focused and !self.menu_open and self.close_tab == null and self.preedit.items.len == 0 and (self.find_open or (d.cursor == d.anchor and in_view)),
+ .active = self.focused and !self.menu_open and self.close_tab == null and self.preedit.items.len == 0 and (editor != null or (!self.find_open and d.cursor == d.anchor and in_view)),
.tab = self.tabId(),
.revision = d.revision,
- .cursor = if (self.find_open) self.query.cursor else d.cursor,
- .anchor = if (self.find_open) self.query.anchor else d.anchor,
+ .cursor = if (editor) |e| e.cursor else d.cursor,
+ .anchor = if (editor) |e| e.anchor else d.anchor,
.find = self.find_open,
+ .search_focus = self.search_focus,
.activity = self.caret_activity,
.top = d.top,
.dy = self.current().dy,
@@ -59,7 +62,7 @@ pub fn caretState(self: *App) CaretState {
.width = self.w,
.height = self.h,
.scale = self.scale,
- .query_hash = if (self.find_open) std.hash.Wyhash.hash(0, self.query.text.items) else 0,
+ .query_hash = if (editor) |e| std.hash.Wyhash.hash(0, e.text.items) else 0,
};
}
@@ -71,12 +74,7 @@ pub fn stepCaret(self: *App, now: i64, active: bool, restart: bool, snap: bool)
.h = @as(f32, @floatFromInt(r.height)) / 1024,
};
if (self.find_open) {
- if (self.layouts.cr) |cr| target = .{
- .x = @floatCast(22 + ui.measureText(cr, self.query.text.items[0..@min(self.query.cursor, self.query.text.items.len)], ui.textSize(), false)),
- .y = 48,
- .w = 1,
- .h = 18,
- };
+ if (self.layouts.cr) |cr| target = self.searchCaret(cr);
}
if (self.caret.update(now, active, restart, target, snap or self.caret_snap)) self.caret_dirty = true;
self.caret_snap = false;
@@ -102,7 +100,7 @@ pub fn paintCaret(self: *App, cr: *c.cairo_t) void {
}
pub fn tabRight(self: *const App) f64 {
- return @as(f64, @floatFromInt(self.w)) - @as(f64, if (self.has_titlebar) 34 else 70);
+ return @as(f64, @floatFromInt(self.w)) - @as(f64, if (self.has_titlebar) 40 else 80);
}
pub fn dismissMenu(self: *App) void {
@@ -144,8 +142,8 @@ pub fn menuHit(self: *const App, x: f64, y: f64) ?usize {
pub fn paintMenu(self: *App, cr: *c.cairo_t) void {
menu.frame(cr, self.menuBox(), true);
const IconId = @import("ui").layout.IconId;
- const icons = [_]?IconId{ .plus, .open, .save, .save, .search, if (self.wrap) .checkmark else null };
- const hints = [_]?[]const u8{ "CTRL+N", "CTRL+O", "CTRL+S", "CTRL+SHIFT+S", "CTRL+F", null };
+ const icons = [_]?IconId{ .plus, .open, .save, .save, .search, .search, if (self.wrap) .checkmark else null };
+ const hints = [_]?[]const u8{ "CTRL+N", "CTRL+O", "CTRL+S", "CTRL+SHIFT+S", "CTRL+F", "CTRL+H", null };
for (labels, 0..) |label, i| menu.row(cr, self.menuRow(i), .{
.label = label.get(),
.hint = hints[i],
@@ -178,40 +176,16 @@ pub fn render(self: *App, cr: *c.cairo_t) void {
var buf: [512]u8 = undefined;
const label = std.fmt.bufPrint(&buf, "{s}{s}", .{ tab.name(), if (tab.doc.modified()) " •" else "" }) catch tr("Text file");
c.cairo_save(cr);
- c.cairo_rectangle(cr, x + 12, 2, tab_w - 42, 32);
+ c.cairo_rectangle(cr, x + 12, 2, tab_w - 52, 32);
c.cairo_clip(cr);
ui.setSource(cr, t.window_fg);
ui.drawText(cr, label, x + 12, 24, ui.textSize(), false);
c.cairo_restore(cr);
- self.paintButton(cr, .{ .x = @floatCast(x + tab_w - 28), .y = 5, .w = 24, .h = 26 }, "×", false);
- }
- self.paintButton(cr, .{ .x = @floatCast(self.tabRight() + 2), .y = 5, .w = 28, .h = 26 }, "+", false);
- if (!self.has_titlebar) self.paintButton(cr, .{ .x = @floatFromInt(self.w - 32), .y = 5, .w = 28, .h = 26 }, "…", self.menu_open);
- if (self.find_open) {
- const box: field.Rect = .{ .x = 12, .y = 43, .w = @floatFromInt(self.w - 110), .h = 30 };
- if (ui.Layer.begin(cr, box)) |l| {
- var layer = l;
- _ = field.paintFrame(&layer.renderer, layer.local(), .{}, .{ .focused = true });
- layer.finish();
- }
- c.cairo_save(cr);
- c.cairo_rectangle(cr, 22, 43, @floatFromInt(self.w - 130), 30);
- c.cairo_clip(cr);
- const bytes = self.query.text.items;
- const selected = self.query.selection();
- if (selected[0] != selected[1]) {
- const x = 22 + ui.measureText(cr, bytes[0..selected[0]], ui.textSize(), false);
- const width = ui.measureText(cr, bytes[selected[0]..selected[1]], ui.textSize(), false);
- fill(cr, x, 46, width, 24, t.app_item_selected);
- }
- var ink = t.window_fg;
- if (bytes.len == 0) ink[3] *= 0.5;
- ui.setSource(cr, ink);
- ui.drawText(cr, if (bytes.len == 0) tr("Find…") else bytes, 22, 64, ui.textSize(), false);
- self.paintCaret(cr);
- c.cairo_restore(cr);
- self.paintButton(cr, .{ .x = @floatFromInt(self.w - 90), .y = 43, .w = 78, .h = 30 }, tr("Next"), false);
+ self.paintIcon(cr, self.tabCloseBox(i - self.first_tab), .close, tr("Close tab"), false);
}
+ self.paintIcon(cr, self.newButtonBox(), .plus, tr("New tab"), false);
+ if (!self.has_titlebar) self.paintIcon(cr, self.menuButtonBox(), .more, tr("Menu"), self.menu_open);
+ if (self.find_open) self.paintSearch(cr);
self.layouts.beginFrame();
const pt = self.port();
pt.clamp();
diff --git a/src/editor/app_search.zig b/src/editor/app_search.zig
new file mode 100644
index 0000000..8635141
--- /dev/null
+++ b/src/editor/app_search.zig
@@ -0,0 +1,240 @@
+//! Find/replace controls, field focus, navigation and undoable replacements.
+const std = @import("std");
+const i18n = @import("i18n");
+const tr = i18n.tr;
+const c = @import("../files/c.zig").api;
+const ui = @import("ui").cairo;
+const theme = @import("ui").theme;
+const field = @import("ui").widgets.field;
+const button = @import("ui").widgets.button;
+const Rect = @import("ui").context_menu.Rect;
+const Editor = @import("../files/editor.zig").Editor;
+const App = @import("app.zig").App;
+const fill = @import("app.zig").fill;
+const a = std.heap.c_allocator;
+
+pub const Control = enum { query, next, toggle, close, replacement, replace, replace_all };
+const order = [_]Control{ .query, .replacement, .next, .replace, .replace_all, .toggle, .close };
+
+pub fn openSearch(self: *App, replace: bool) void {
+ self.cancelDrag();
+ self.find_open = true;
+ self.replace_open = replace;
+ self.search_focus = .query;
+ self.query.select_all = true;
+ self.caret_snap = true;
+ self.dirty = true;
+}
+
+pub fn searchEditor(self: *App) ?*Editor {
+ if (!self.find_open) return null;
+ return switch (self.search_focus) {
+ .query => &self.query,
+ .replacement => &self.replacement,
+ else => null,
+ };
+}
+
+fn visible(self: *App, control: Control) bool {
+ return switch (control) {
+ .replacement, .replace, .replace_all => self.replace_open,
+ else => true,
+ };
+}
+
+pub fn searchBox(self: *App, control: Control) Rect {
+ const w: f64 = @floatFromInt(self.w);
+ return switch (control) {
+ .query => .{ .x = 12, .y = 43, .w = w - 282, .h = 32 },
+ .next => .{ .x = w - 262, .y = 43, .w = 86, .h = 32 },
+ .toggle => .{ .x = w - 170, .y = 43, .w = 116, .h = 32 },
+ .close => .{ .x = w - 46, .y = 43, .w = 34, .h = 32 },
+ .replacement => .{ .x = 12, .y = 83, .w = w - 282, .h = 32 },
+ .replace => .{ .x = w - 262, .y = 83, .w = 116, .h = 32 },
+ .replace_all => .{ .x = w - 140, .y = 83, .w = 128, .h = 32 },
+ };
+}
+
+pub fn searchHit(self: *App, x: f64, y: f64) ?Control {
+ for (order) |control| if (visible(self, control) and self.searchBox(control).contains(x, y)) return control;
+ return null;
+}
+
+pub fn findNext(self: *App, backwards: bool) void {
+ const q = self.query.text.items;
+ if (q.len == 0) return;
+ const d = self.document();
+ const sel = d.selection();
+ const found = if (backwards) std.mem.lastIndexOf(u8, d.text.items[0..sel[0]], q) orelse std.mem.lastIndexOf(u8, d.text.items, q) else std.mem.indexOfPos(u8, d.text.items, sel[1], q) orelse std.mem.indexOf(u8, d.text.items, q);
+ if (found) |pos| {
+ d.anchor = pos;
+ d.cursor = pos + q.len;
+ self.notice_len = 0;
+ self.reveal();
+ } else self.message(tr("Text not found"));
+}
+
+fn replaceOne(self: *App) void {
+ const q = self.query.text.items;
+ if (q.len == 0) return;
+ const d = self.document();
+ var sel = d.selection();
+ if (!std.mem.eql(u8, d.text.items[sel[0]..sel[1]], q)) {
+ self.findNext(false);
+ sel = d.selection();
+ if (!std.mem.eql(u8, d.text.items[sel[0]..sel[1]], q)) return;
+ }
+ d.insert(self.replacement.text.items) catch |err| {
+ self.failure(err);
+ return;
+ };
+ self.reveal();
+ self.findNext(false);
+}
+
+fn replaceAll(self: *App) void {
+ if (self.query.text.items.len == 0) return;
+ const count = self.document().replaceAll(self.query.text.items, self.replacement.text.items) catch |err| {
+ self.failure(err);
+ return;
+ };
+ if (count == 0) {
+ self.message(tr("Text not found"));
+ return;
+ }
+ self.reveal();
+ var buf: [128]u8 = undefined;
+ self.message(i18n.fmt(&buf, tr("Matches replaced: {count}"), .{ .count = count }) catch "");
+}
+
+pub fn searchActivate(self: *App, control: Control) void {
+ if ((control == .replace or control == .replace_all) and (self.query.text.items.len == 0 or self.document().locked)) return;
+ switch (control) {
+ .query, .replacement => self.search_focus = control,
+ .next => self.findNext(self.shift),
+ .toggle => {
+ self.replace_open = !self.replace_open;
+ self.search_focus = if (self.replace_open) .replacement else .query;
+ },
+ .close => self.find_open = false,
+ .replace => replaceOne(self),
+ .replace_all => replaceAll(self),
+ }
+ self.caret_snap = true;
+ self.dirty = true;
+}
+
+pub fn searchKey(self: *App, sym: u32, utf8: []const u8) void {
+ if (self.ctrl and (sym == c.XKB_KEY_z or sym == c.XKB_KEY_Z or sym == c.XKB_KEY_y or sym == c.XKB_KEY_Y)) {
+ self.document().undo(self.shift or sym == c.XKB_KEY_y or sym == c.XKB_KEY_Y) catch |err| self.failure(err);
+ self.notice_len = 0;
+ self.reveal();
+ } else if (sym == c.XKB_KEY_Tab or sym == c.XKB_KEY_ISO_Left_Tab) {
+ var index = std.mem.indexOfScalar(Control, &order, self.search_focus) orelse 0;
+ const backwards = self.shift or sym == c.XKB_KEY_ISO_Left_Tab;
+ while (true) {
+ index = (index + if (backwards) order.len - 1 else @as(usize, 1)) % order.len;
+ if (visible(self, order[index])) break;
+ }
+ self.search_focus = order[index];
+ if (self.searchEditor()) |editor| editor.select_all = true;
+ self.caret_snap = true;
+ } else if (sym == c.XKB_KEY_F3) {
+ self.findNext(self.shift);
+ } else if (sym == c.XKB_KEY_Return or sym == c.XKB_KEY_KP_Enter) {
+ self.searchActivate(switch (self.search_focus) {
+ .query => .next,
+ .replacement => if (self.ctrl) .replace_all else .replace,
+ else => self.search_focus,
+ });
+ } else if (self.searchEditor()) |editor| {
+ if (self.ctrl and (sym == c.XKB_KEY_v or sym == c.XKB_KEY_V)) {
+ self.paste_requested = true;
+ } else if (self.ctrl and (sym == c.XKB_KEY_c or sym == c.XKB_KEY_C or sym == c.XKB_KEY_x or sym == c.XKB_KEY_X)) {
+ const sel = editor.selection();
+ if (sel[0] == sel[1]) return;
+ self.clipboard.clearRetainingCapacity();
+ self.clipboard.appendSlice(a, editor.text.items[sel[0]..sel[1]]) catch return;
+ self.clipboard_revision += 1;
+ if (sym == c.XKB_KEY_x or sym == c.XKB_KEY_X) editor.insert(a, "") catch |err| self.failure(err);
+ } else editor.key(a, sym, utf8, self.ctrl, self.shift, self.alt);
+ } else if (sym == c.XKB_KEY_space) self.searchActivate(self.search_focus);
+ self.dirty = true;
+}
+
+fn textBox(self: *App, control: Control) field.Rect {
+ const box = self.searchBox(control);
+ return field.arrange(.{ .x = @floatCast(box.x), .y = @floatCast(box.y), .w = @floatCast(box.w), .h = @floatCast(box.h) }, .{}, theme.global).text;
+}
+
+fn scrollField(cr: *c.cairo_t, editor: *Editor, width: f64) f64 {
+ editor.normalize();
+ const x = ui.measureText(cr, editor.text.items[0..editor.cursor], ui.textSize(), false);
+ editor.scroll = @max(0, @max(x - width + 2, @min(editor.scroll, x)));
+ return x - editor.scroll;
+}
+
+pub fn searchCaret(self: *App, cr: *c.cairo_t) @import("caret.zig").Rect {
+ const editor = self.searchEditor() orelse return .{};
+ const box = textBox(self, self.search_focus);
+ return .{ .x = @floatCast(box.x + scrollField(cr, editor, box.w)), .y = box.y + 6, .w = 1, .h = @floatCast(ui.textSize() + 3) };
+}
+
+fn paintField(self: *App, cr: *c.cairo_t, control: Control, editor: *Editor, placeholder: []const u8) void {
+ const box = self.searchBox(control);
+ const focused = self.search_focus == control;
+ if (ui.Layer.begin(cr, .{ .x = @floatCast(box.x), .y = @floatCast(box.y), .w = @floatCast(box.w), .h = @floatCast(box.h) })) |l| {
+ var layer = l;
+ _ = field.paintFrame(&layer.renderer, layer.local(), .{}, .{ .focused = focused });
+ layer.finish();
+ }
+ const text = textBox(self, control);
+ _ = scrollField(cr, editor, text.w);
+ c.cairo_save(cr);
+ defer c.cairo_restore(cr);
+ c.cairo_rectangle(cr, text.x, text.y, text.w, text.h);
+ c.cairo_clip(cr);
+ const bytes = editor.text.items;
+ const selected = editor.selection();
+ const origin = text.x - editor.scroll;
+ if (selected[0] != selected[1]) {
+ const x = origin + ui.measureText(cr, bytes[0..selected[0]], ui.textSize(), false);
+ const width = ui.measureText(cr, bytes[selected[0]..selected[1]], ui.textSize(), false);
+ fill(cr, x, text.y + 3, width, text.h - 6, theme.global.app_item_selected);
+ }
+ var ink = theme.global.window_fg;
+ if (bytes.len == 0) ink[3] *= 0.5;
+ ui.setSource(cr, ink);
+ ui.drawText(cr, if (bytes.len == 0) placeholder else bytes, origin, text.y + 21, ui.textSize(), false);
+ if (focused) self.paintCaret(cr);
+}
+
+pub fn paintSearch(self: *App, cr: *c.cairo_t) void {
+ paintField(self, cr, .query, &self.query, tr("Find…"));
+ if (self.replace_open) paintField(self, cr, .replacement, &self.replacement, tr("Replace with…"));
+ for (order) |control| {
+ if (!visible(self, control) or control == .query or control == .replacement) continue;
+ const box = self.searchBox(control);
+ var layer = ui.Layer.begin(cr, .{ .x = @floatCast(box.x), .y = @floatCast(box.y), .w = @floatCast(box.w), .h = @floatCast(box.h) }) orelse continue;
+ const disabled = (control == .next or control == .replace or control == .replace_all) and (self.query.text.items.len == 0 or (control != .next and self.document().locked));
+ layer.renderer.palette = theme.shellPalette();
+ button.paint(&layer.renderer, layer.local(), .{
+ .label = switch (control) {
+ .next => tr("Next"),
+ .toggle, .replace => tr("Replace"),
+ .replace_all => tr("Replace All"),
+ .close => tr("Close"),
+ else => unreachable,
+ },
+ .icon = if (control == .close) .close else null,
+ .leading_icon = if (control == .toggle) (if (self.replace_open) .chevron_up else .chevron_down) else null,
+ .variant = .ghost,
+ .size = .sm,
+ }, .{
+ .selected = control == .toggle and self.replace_open,
+ .focused = self.search_focus == control,
+ .pointer = if (disabled) .disabled else if (self.close_tab == null and !self.menu_open and box.contains(self.px, self.py)) .hover else .idle,
+ });
+ layer.finish();
+ }
+}
diff --git a/src/editor/app_view.zig b/src/editor/app_view.zig
index df21b0b..184e902 100644
--- a/src/editor/app_view.zig
+++ b/src/editor/app_view.zig
@@ -20,7 +20,7 @@ pub fn resize(self: *App, w: i32, h: i32) void {
}
pub fn viewTop(self: *App) f64 {
- return top + if (self.find_open) @as(f64, 40) else 0;
+ return top + if (self.find_open) @as(f64, if (self.replace_open) 80 else 40) else 0;
}
pub fn viewHeight(self: *App) f64 {
@@ -34,7 +34,11 @@ pub fn cancelDrag(self: *App) void {
}
pub fn cursorName(self: *App) [*:0]const u8 {
- return if (!self.menu_open and self.py >= self.viewTop() and self.py < @as(f64, @floatFromInt(self.h)) - status_h and self.px < @as(f64, @floatFromInt(self.w)) - 16) "text" else "default";
+ if (self.close_tab != null or self.menu_open) return "default";
+ if (self.find_open) if (self.searchHit(self.px, self.py)) |control| {
+ return if (control == .query or control == .replacement) "text" else "default";
+ };
+ return if (self.px >= 0 and self.py >= self.viewTop() and self.py < @as(f64, @floatFromInt(self.h)) - status_h and self.px < @as(f64, @floatFromInt(self.w)) - 16) "text" else "default";
}
/// The current tab's bar, along the right edge of the text view; null
diff --git a/src/editor/client_input.zig b/src/editor/client_input.zig
index a9f775d..c05357c 100644
--- a/src/editor/client_input.zig
+++ b/src/editor/client_input.zig
@@ -27,6 +27,7 @@ pub fn pointerEvent(_: *wl.Pointer, event: wl.Pointer.Event, self: *Client) void
.leave => {
self.inside = false;
self.app.cancelDrag();
+ self.app.handleMotion(-1, -1);
self.app.dirty = true;
},
.motion => |ev| {
diff --git a/src/editor/client_render.zig b/src/editor/client_render.zig
index 9268866..d4bc026 100644
--- a/src/editor/client_render.zig
+++ b/src/editor/client_render.zig
@@ -140,6 +140,7 @@ pub fn renderTitlebar(self: *Client, cr: *c.cairo_t, w: i32, h: i32) void {
},
.variant = if (control == .close) .chrome else .ghost,
.size = .sm,
+ .icon_scale = if (control == .menu) 1.25 else 0.5,
}, .{
.pointer = if (self.overHeaderButton(control)) .hover else .idle,
.selected = control == .menu and self.app.menu_open,
diff --git a/src/editor/clipboard.zig b/src/editor/clipboard.zig
index 2512244..72f5716 100644
--- a/src/editor/clipboard.zig
+++ b/src/editor/clipboard.zig
@@ -22,6 +22,7 @@ pub const Clipboard = struct {
cursor: usize = 0,
anchor: usize = 0,
find: bool = false,
+ search_activity: usize = 0,
pub fn deinit(self: *Clipboard) void {
if (self.receive) |*r| r.deinit();
for (self.sends.items) |*s| s.deinit();
@@ -168,6 +169,7 @@ pub const Clipboard = struct {
self.cursor = self.app.document().cursor;
self.anchor = self.app.document().anchor;
self.find = self.app.find_open;
+ self.search_activity = self.app.caret_activity;
offer.proxy.receive(mime, fds[1]);
}
pub fn addPoll(self: *Clipboard, fds: []c.struct_pollfd) usize {
@@ -202,7 +204,7 @@ pub const Clipboard = struct {
break :blk true;
};
if (done) {
- if (!expired and !failed and self.app.tabId() == self.tab_id and self.app.editRevision() == r.revision and self.app.document().cursor == self.cursor and self.app.document().anchor == self.anchor and self.app.find_open == self.find) self.app.pasteText(r.bytes.items);
+ if (!expired and !failed and self.app.tabId() == self.tab_id and self.app.editRevision() == r.revision and self.app.document().cursor == self.cursor and self.app.document().anchor == self.anchor and self.app.find_open == self.find and (!self.find or self.app.caret_activity == self.search_activity)) self.app.pasteText(r.bytes.items);
r.deinit();
self.receive = null;
}
diff --git a/src/editor/document.zig b/src/editor/document.zig
index ecf699b..5b9ebc7 100644
--- a/src/editor/document.zig
+++ b/src/editor/document.zig
@@ -197,6 +197,7 @@ pub const Document = struct {
}
}
}
+ pub const replaceAll = @import("document_search.zig").replaceAll;
pub fn undo(d: *Document, redo: bool) !void {
if (d.locked) return error.Busy;
if (redo) {
diff --git a/src/editor/document_search.zig b/src/editor/document_search.zig
new file mode 100644
index 0000000..8df67c7
--- /dev/null
+++ b/src/editor/document_search.zig
@@ -0,0 +1,50 @@
+//! Replace nonoverlapping literal matches in one history entry. Build the
+//! changed span once, so repeated matches never memmove the document's tail.
+const std = @import("std");
+const document = @import("document.zig");
+const Document = document.Document;
+const a = std.heap.c_allocator;
+
+pub fn replaceAll(d: *Document, query: []const u8, replacement: []const u8) !usize {
+ if (d.locked) return error.Busy;
+ if (query.len == 0) return 0;
+ try Document.validate(query);
+ try Document.validate(replacement);
+ const text = d.text.items;
+ const first = std.mem.indexOf(u8, text, query) orelse return 0;
+ var end = first;
+ var count: usize = 0;
+ while (std.mem.indexOfPos(u8, text, end, query)) |at| {
+ count += 1;
+ end = at + query.len;
+ }
+ if (std.mem.eql(u8, query, replacement)) return count;
+ const added = std.math.mul(usize, count, replacement.len) catch return error.FileTooLarge;
+ const size = std.math.add(usize, text.len - count * query.len, added) catch return error.FileTooLarge;
+ if (size > document.limit) return error.FileTooLarge;
+ const result = try a.alloc(u8, end - first - count * query.len + added);
+ defer a.free(result);
+ var from = first;
+ var to: usize = 0;
+ while (std.mem.indexOfPos(u8, text[0..end], from, query)) |at| {
+ @memcpy(result[to..][0 .. at - from], text[from..at]);
+ to += at - from;
+ @memcpy(result[to..][0..replacement.len], replacement);
+ to += replacement.len;
+ from = at + query.len;
+ }
+ const cursor = d.cursor;
+ const anchor = d.anchor;
+ d.anchor = first;
+ d.cursor = end;
+ errdefer {
+ d.cursor = cursor;
+ d.anchor = anchor;
+ }
+ try d.insert(result);
+ return count;
+}
+
+test {
+ _ = @import("document_search_tests.zig");
+}
diff --git a/src/editor/document_search_tests.zig b/src/editor/document_search_tests.zig
new file mode 100644
index 0000000..3f8637f
--- /dev/null
+++ b/src/editor/document_search_tests.zig
@@ -0,0 +1,39 @@
+const std = @import("std");
+const Document = @import("document.zig").Document;
+
+test "replace all is literal, UTF-8 safe and one undoable edit" {
+ var d = try Document.init("\xef\xbb\xbf雪 cat\r\ncat 雪\r\ncat");
+ defer d.deinit();
+ try std.testing.expectEqual(@as(usize, 3), try d.replaceAll("cat", "猫cat"));
+ try std.testing.expectEqualStrings("雪 猫cat\r\n猫cat 雪\r\n猫cat", d.text.items);
+ try std.testing.expect(d.bom and d.crlf and d.modified());
+ try d.undo(false);
+ try std.testing.expectEqualStrings("雪 cat\r\ncat 雪\r\ncat", d.text.items);
+ try std.testing.expect(!d.modified());
+ try d.undo(true);
+ try std.testing.expectEqualStrings("雪 猫cat\r\n猫cat 雪\r\n猫cat", d.text.items);
+}
+
+test "replace all handles empty, unchanged, absent and overlapping matches" {
+ var d = try Document.init("aaaaa");
+ defer d.deinit();
+ try std.testing.expectEqual(@as(usize, 0), try d.replaceAll("", "x"));
+ try std.testing.expectEqual(@as(usize, 0), try d.replaceAll("missing", "x"));
+ try std.testing.expectEqual(@as(usize, 2), try d.replaceAll("aa", "aa"));
+ try std.testing.expect(!d.modified());
+ try std.testing.expectEqual(@as(usize, 2), try d.replaceAll("aa", ""));
+ try std.testing.expectEqualStrings("a", d.text.items);
+ try d.undo(false);
+ try std.testing.expectEqualStrings("aaaaa", d.text.items);
+}
+
+test "replace all refuses a borrowed save buffer without changing state" {
+ var d = try Document.init("keep keep");
+ defer d.deinit();
+ d.move(2, false);
+ d.locked = true;
+ try std.testing.expectError(error.Busy, d.replaceAll("keep", "gone"));
+ try std.testing.expectEqualStrings("keep keep", d.text.items);
+ try std.testing.expectEqual(@as(usize, 2), d.cursor);
+ try std.testing.expect(!d.modified());
+}
diff --git a/src/editor_tests.zig b/src/editor_tests.zig
index 7a62c62..5ccfef5 100644
--- a/src/editor_tests.zig
+++ b/src/editor_tests.zig
@@ -2,6 +2,7 @@ test {
_ = @import("editor/caret.zig");
_ = @import("editor/formats.zig");
_ = @import("editor/document.zig");
+ _ = @import("editor/document_search.zig");
_ = @import("editor/lines.zig");
_ = @import("editor/view.zig");
_ = @import("editor/operation.zig");
diff --git a/src/ui_tests.zig b/src/ui_tests.zig
index 779136d..64518cb 100644
--- a/src/ui_tests.zig
+++ b/src/ui_tests.zig
@@ -1,6 +1,7 @@
// Compositor integration/unit-test root. Shared modules have separate test
// targets in build.zig; their roots cannot import compositor code.
test {
+ _ = @import("calculator/model.zig");
_ = @import("control_center/search_index.zig");
_ = @import("auto_layout.zig");
_ = @import("desktop/app.zig");
diff --git a/tests/calculator.py b/tests/calculator.py
new file mode 100644
index 0000000..7825d00
--- /dev/null
+++ b/tests/calculator.py
@@ -0,0 +1,145 @@
+#!/usr/bin/env python3
+"""Calculator keyboard/keypad arithmetic and layout in a private compositor."""
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+
+from PIL import Image, ImageChops
+from ipc_client import IPCClient, ROOT, spawn_compositor, stop_process
+from xwayland_support import wait_for
+
+
+def run(scale):
+ with tempfile.TemporaryDirectory(prefix="rediwm-calculator-") as directory:
+ tmp = Path(directory)
+ env = dict(HOME=directory, XDG_CONFIG_HOME=str(tmp / "config"),
+ XDG_DATA_HOME=str(tmp / "data"), XDG_CACHE_HOME=str(tmp / "cache"),
+ XDG_STATE_HOME=str(tmp / "state"), DBUS_SESSION_BUS_ADDRESS="",
+ DBUS_SYSTEM_BUS_ADDRESS="unix:path=/nonexistent-rediwm-test-system-bus",
+ WLR_RENDERER_ALLOW_SOFTWARE="1", LANG="C", LC_ALL="C")
+ compositor, log = spawn_compositor(
+ tmp, scale=str(scale), env_extra=env,
+ config_content='[compositor]\nxwayland = false\nfocus_zoom = "keep"\n[animations]\nenabled = false\n',
+ binary=os.environ.get("REDIWM_TEST_BINARY"))
+ app = None
+ try:
+ with IPCClient(tmp, timeout=20) as ipc:
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ app_env = dict(os.environ, **env, XDG_RUNTIME_DIR=directory,
+ WAYLAND_DISPLAY=display, REDIWM_CONFIG=str(tmp / "rediwm-config.toml"))
+ app_env.pop("REDIWM_THEME", None)
+ with (tmp / "calculator.log").open("w") as app_log:
+ app = subprocess.Popen([os.environ.get("REDIWM_TEST_CALCULATOR",
+ str(ROOT / "zig-out/bin/rediwm-calculator"))],
+ env=app_env, stdout=app_log, stderr=app_log)
+ ipc.wait_for("window_mapped", app_id="rediwm-calculator")
+ win = next(w for w in ipc.get_windows() if w["app_id"] == "rediwm-calculator")
+ ipc.focus_window(win["id"])
+ ipc.wait_for("window_geometry_settled", window_id=win["id"])
+ ipc.move_cursor(0, 0)
+
+ def box():
+ return ipc.get_window_debug(win["id"])["client_box"]
+
+ def capture(region=None):
+ ipc.wait_for_frame()
+ path = tmp / "screen.png"
+ path.unlink(missing_ok=True)
+ ipc.screenshot(path=str(path))
+ with Image.open(path) as image:
+ b = box()
+ factor = image.width / ipc.get_outputs()[0]["logical_width"]
+ x1, y1, x2, y2 = region or (0, 0, b["width"], b["height"])
+ return image.convert("RGB").crop(tuple(round(v * factor) for v in
+ (b["x"] + x1, b["y"] + y1, b["x"] + x2, b["y"] + y2)))
+
+ def readout():
+ return capture((16, 36, box()["width"] - 16, 96))
+
+ def same(left, right):
+ return ImageChops.difference(left, right).getbbox() is None
+
+ zero = readout()
+
+ def clear():
+ ipc.key_down_up(1) # Escape
+ wait_for(lambda: same(zero, readout()), "clear did not reset the readout")
+
+ # Compare rendered results against directly entered reference
+ # values: no OCR, test-only app API or font-specific goldens.
+ cases = [
+ ("100+5%", "105"), ("200-10%", "180"),
+ ("200*10%", "20"), ("200/10%", "2000"),
+ ("200+10%+5%", "231"), ("200+(5+5)%", "220"),
+ ("100+200*5%", "110"), ("2+3*4", "14"),
+ ("(2+3)*4", "20"), ("0.1+0.2", "0.3"),
+ ]
+ references = {"0": zero}
+ for expected in dict.fromkeys(value for _, value in cases):
+ clear()
+ ipc.type_text(expected)
+ wait_for(lambda: not same(zero, readout()), "numeric entry was not painted")
+ references[expected] = readout()
+ for expression, expected in cases:
+ clear()
+ ipc.type_text(expression)
+ ipc.key_down_up(28) # Enter
+ wait_for(lambda: same(references[expected], readout()),
+ f"{expression} did not display {expected}")
+
+ def click_button(row, column):
+ b = box()
+ cell_w = (b["width"] - 56) / 4
+ cell_h = (b["height"] - 112 - 56) / 6
+ ipc.click_at(round(b["x"] + 16 + column * (cell_w + 8) + cell_w / 2),
+ round(b["y"] + 112 + row * (cell_h + 8) + cell_h / 2))
+
+ clear()
+ for row, column in [(4, 0), (5, 0), (5, 0), (3, 3), (3, 1), (1, 1), (4, 3)]:
+ click_button(row, column) # 100+5%=
+ ipc.move_cursor(0, 0)
+ wait_for(lambda: same(references["105"], readout()), "keypad percentage failed")
+
+ clear()
+ ipc.type_text("200+10%")
+ ipc.key_down_up(67) # F9 / ±
+ ipc.key_down_up(28)
+ wait_for(lambda: same(references["180"], readout()), "percentage sign toggle failed")
+
+ clear()
+ ipc.type_text("200/0%")
+ ipc.key_down_up(28)
+ wait_for(lambda: any(low != high for low, high in
+ capture((16, 8, box()["width"] - 16, 34)).getextrema()),
+ "division-by-zero notice was not painted")
+ ipc.key_down_up(14)
+ ipc.key_down_up(14)
+ ipc.type_text("10%")
+ ipc.key_down_up(28)
+ wait_for(lambda: same(references["2000"], readout()), "error correction failed")
+
+ # The removed shortcut line stays blank below the larger entry.
+ strip = capture((16, 96, box()["width"] - 16, 110))
+ assert all(low == high for low, high in strip.getextrema()), "shortcut line remains"
+ destination = os.environ.get("REDIWM_TEST_CAPTURE")
+ if destination:
+ capture().save(destination)
+ ipc.close_window(win["id"])
+ ipc.wait_for("window_closed", window_id=win["id"])
+ assert app.wait(timeout=5) == 0
+ print(f"Calculator: arithmetic, keyboard, keypad and layout passed at scale {scale}")
+ finally:
+ if app is not None and app.poll() is None:
+ stop_process(app)
+ stop_process(compositor)
+ log.close()
+ for path in (tmp / "compositor.log", tmp / "calculator.log"):
+ if path.exists():
+ errors = path.read_text()
+ assert "panic" not in errors and "error(gpa)" not in errors, errors[-6000:]
+
+
+if __name__ == "__main__":
+ os.umask(0o077)
+ run(float(os.environ.get("REDIWM_TEST_SCALE", "1")))
diff --git a/tests/editor.py b/tests/editor.py
index 31d4ad7..b66e3bd 100644
--- a/tests/editor.py
+++ b/tests/editor.py
@@ -201,6 +201,53 @@ def run():
title("beta.txt")
print("find, selection replacement and undo", flush=True)
+ # Replace one and all through the real fields and buttons. A
+ # replacement containing its query must not be searched again.
+ key(30, ctrl=True)
+ ipc.type_text("cat cat cafe cat")
+ key(31, ctrl=True)
+ wait_for(lambda: second.read_text() == "cat cat cafe cat", "replacement fixture saved")
+ key(35, ctrl=True) # Ctrl+H
+ ipc.type_text("cat")
+ key(15) # Tab focuses replacement
+ ipc.type_text("catfish")
+ if output := os.environ.get("REDIWM_EDITOR_REPLACE_PREVIEW"):
+ ipc.screenshot(path=output)
+ key(28) # Replace current/next match
+ key(31, ctrl=True)
+ wait_for(lambda: second.read_text() == "catfish cat cafe cat", "replace one")
+ key(44, ctrl=True) # Undo while the replacement field has focus
+ key(31, ctrl=True)
+ wait_for(lambda: second.read_text() == "cat cat cafe cat", "replace-one undo")
+ box = ipc.get_window_debug(editor()["id"])["client_box"]
+ click(editor(), box["width"] - 76, header + 99) # Replace All
+ key(31, ctrl=True)
+ wait_for(lambda: second.read_text() == "catfish catfish cafe catfish", "replace all without rescanning replacements")
+ key(44, ctrl=True)
+ key(31, ctrl=True)
+ wait_for(lambda: second.read_text() == "cat cat cafe cat", "replace-all single undo")
+ key(21, ctrl=True)
+ key(31, ctrl=True)
+ wait_for(lambda: second.read_text() == "catfish catfish cafe catfish", "replace-all redo")
+ key(1)
+ menu_action(5) # Replace is also discoverable in the menu
+ ipc.type_text("catfish")
+ key(15)
+ key(14) # Empty replacement deletes every match
+ key(28, ctrl=True)
+ key(31, ctrl=True)
+ wait_for(lambda: second.read_text() == " cafe ", "replace all with empty text")
+ key(35, ctrl=True)
+ ipc.type_text("missing")
+ key(15)
+ ipc.type_text("unused")
+ key(28, ctrl=True)
+ key(31, ctrl=True)
+ title("beta.txt")
+ assert second.read_text() == " cafe ", "no-match replace changed text"
+ key(1)
+ print("replace one/all, empty replacement, no match and atomic undo/redo", flush=True)
+
# Drive the actual text-input-v3 client with the existing IM peer.
im_log = tmp / "ime.log"
with im_log.open("w") as log:
diff --git a/tests/editor_visuals.py b/tests/editor_visuals.py
index 457cb1b..97e7a1f 100644
--- a/tests/editor_visuals.py
+++ b/tests/editor_visuals.py
@@ -126,6 +126,47 @@ def run():
thread.join(timeout=5)
ipc.action('pointer_button',{'button':272,'pressed':False})
time.sleep(.3)
+ # Cross the close button boundary within the old coarse hover
+ # bucket, then leave the client entirely: both must repaint.
+ box=ipc.get_window_debug(win['id'])['client_box']
+ header=46 if csd else 0
+ def hover_image(x, y):
+ ipc.move_cursor(round(box['x']+x), round(box['y']+y))
+ time.sleep(.15)
+ shot=capture()
+ factor=shot.width/ipc.get_outputs()[0]['logical_width']
+ return shot.crop(tuple(round(v*factor) for v in (
+ box['x']+140, box['y']+header+2,
+ box['x']+174, box['y']+header+36)))
+ idle_close=hover_image(130, header+19)
+ hover_close=hover_image(145, header+19)
+ assert ImageChops.difference(idle_close, hover_close).getbbox(), 'close-tab hover did not repaint'
+ left_close=hover_image(-30, -30)
+ assert not ImageChops.difference(idle_close, left_close).getbbox(), 'close-tab hover stuck after pointer leave'
+ print('close-tab hover appears and clears on pointer leave',flush=True)
+
+ # Opening the unsaved-close prompt must update a stationary
+ # I-beam, and dismissing it must restore the text cursor.
+ import re
+ def cursor_shape(expected):
+ def latest():
+ shapes=re.findall(r'wp_cursor_shape_device_v1#\d+\.set_shape\(\d+, (\d+)\)', (tmp/'rediwm-editor.log').read_text())
+ return shapes and int(shapes[-1]) == expected
+ wait_for(latest, f'editor cursor shape {expected}')
+ ipc.move_cursor(round(box['x']+200), round(box['y']+header+150))
+ cursor_shape(9)
+ ipc.type_text('x')
+ ipc.key(29,True)
+ ipc.key_down_up(17)
+ ipc.key(29,False)
+ cursor_shape(1)
+ ipc.key_down_up(1)
+ cursor_shape(9)
+ ipc.key(29,True)
+ ipc.key_down_up(44)
+ ipc.key(29,False)
+ print('save prompt resets the stationary cursor and restores it on dismissal',flush=True)
+
# The application menu lives in the tab bar with shared chrome.
box=ipc.get_window_debug(win['id'])['client_box']
ipc.move_cursor(round(box['x']+box['width']-(132 if csd else 18)),round(box['y']+23))