Skip to content

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

network settings enhancements

oxydizer14872379887c
diff --git a/build/apps.zig b/build/apps.zig
index 314655c..53c0313 100644
--- a/build/apps.zig
+++ b/build/apps.zig
@@ -180,7 +180,7 @@ pub fn add(ctx: Context) Apps {
.use_lld = use_llvm,
});
editor.root_module.addImport("wayland", wayland);
- inline for (.{ "wayland-client", "wayland-cursor", "xkbcommon", "pangocairo" }) |lib| editor.root_module.linkSystemLibrary(lib, .{});
+ inline for (.{ "wayland-client", "wayland-cursor", "xkbcommon", "pangocairo", "glib-2.0" }) |lib| editor.root_module.linkSystemLibrary(lib, .{});
const install_editor = b.addInstallArtifact(editor, .{});
const editor_entry = b.addInstallFileWithDir(localizedData(b, i18n_tool, ctx.layout.prefix, "data/rediwm-editor.desktop"), .prefix, "share/applications/rediwm-editor.desktop");
b.getInstallStep().dependOn(&install_editor.step);
diff --git a/build/tests.zig b/build/tests.zig
index 316ad4f..1d0ffd5 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -145,6 +145,16 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
printing_tests.root_module.addCSourceFile(.{ .file = b.path("src/printing/direct.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-deprecated-declarations" } });
const run_printing_tests = b.addRunArtifact(printing_tests);
test_step.dependOn(&run_printing_tests.step);
+ // NetworkManager parsing that needs no compositor: addresses, profile read/write.
+ const network_tests = b.addTest(.{ .root_module = b.createModule(.{
+ .root_source_file = b.path("src/network_tests.zig"),
+ .target = target,
+ .optimize = optimize,
+ }) });
+ network_tests.root_module.addImport("dbus", dbus_mod);
+ const run_network_tests = b.addRunArtifact(network_tests);
+ test_step.dependOn(&run_network_tests.step);
+ b.step("test-network", "Test NetworkManager address and profile parsing").dependOn(&run_network_tests.step);
const printers_integration = b.addSystemCommand(&.{"python3"});
printers_integration.addFileArg(b.path("tests/printers.py"));
printers_integration.step.dependOn(b.getInstallStep());
diff --git a/docs/plans/network.md b/docs/plans/network.md
new file mode 100644
index 0000000..b715035
--- /dev/null
+++ b/docs/plans/network.md
@@ -0,0 +1,48 @@
+# Network settings plan
+
+Settings → Network showed IPv4/gateway/DNS/MAC for Ethernet only and offered no
+way to change anything but joining a network. Scope agreed 2026-11-08 (hotspot
+left out for now).
+
+## Decisions
+
+* **Data comes from NetworkManager's `GetManagedObjects` snapshot** that the
+ page already fetches: IP4Config, IP6Config, ActiveConnection, wireless
+ Bitrate and AccessPoint Frequency/HwAddress are in it. No new polling.
+* **Profiles are edited as read-modify-write** (`GetSettings`, replace only the
+ keys we own, `Update` with interactive authorization), like the Wi-Fi
+ password update. Verified on a throwaway profile: an `Update` without
+ `psk` keeps the stored secret, and `GetSettings` never returns it.
+* **Unlock follows Services** (`systemd/actions.zig`): polkit
+ `CheckAuthorization` for `org.freedesktop.NetworkManager.settings.modify.system`.
+ The check runs without interaction when the page opens; where policy already
+ allows (the default for an active local session) the page is simply unlocked
+ and no button shows, otherwise an Unlock button asks with interaction.
+ Proxy is per-user and never needs it.
+* **Proxy** is not a NetworkManager concept (only a per-connection PAC URL).
+ RediWM writes GSettings `org.gnome.system.proxy` (what GTK/GIO apps and
+ Firefox's "system proxy" read; hand-declared GIO ABI) and exports
+ `http_proxy`-style variables to apps it launches.
+
+## Phases
+
+1. Read-only details: Wi-Fi details card (SSID, security, signal, band/channel,
+ link speed, BSSID, MAC), IPv6 and search domains for both, DHCP/manual.
+2. Actions and editor: Forget, Disconnect, auto-connect; IP editor (IPv4/IPv6
+ Automatic/Manual/Link-local/Disabled, DNS, MTU, metered); unlock.
+3. Proxy page.
+4. VPN (list, connect/disconnect, NM VPN + WireGuard) and airplane mode.
+
+## Status
+
+All four phases are built (2026-11-08). Airplane mode is an rfkill soft block
+(`platform/rfkill.zig`) rather than an NM property so Bluetooth follows too; it
+is not integration-tested because a test must never write the host's
+`/dev/rfkill` (unit tests cover the event encoding). Hotspot, importing VPN
+configurations, per-protocol proxy credentials and a NetworkManager secret
+agent are left for later.
+
+Tests: `zig build test-network` (parsing, profile round trip, proxy
+environment), `tests/network_settings.py` (details, editing, forget, unlock,
+VPN, proxy; against `tests/nm_fake.py`, with GSettings on a keyfile backend in
+a scratch directory), and `tests/wifi_popup.py` for the older Wi-Fi paths.
diff --git a/docs/wiki/Apps-and-Services.md b/docs/wiki/Apps-and-Services.md
index 1feb833..5221a59 100644
--- a/docs/wiki/Apps-and-Services.md
+++ b/docs/wiki/Apps-and-Services.md
@@ -44,6 +44,13 @@ costs a few milliseconds per 100 MB per keystroke.
| Ctrl+PageUp/Down | switch tabs |
| Ctrl+W | close tab |
| Ctrl+F, F3 | find |
+| F10 | menu (Open Recent is a submenu: Right opens it) |
+
+**Open Recent** (in the menu) lists the last ten text files that still exist,
+newest first, from the same freedesktop history (`recently-used.xbel`) that
+Files' Recent view uses, so files opened from Files or saved with Save As appear
+too. **Clear Recent** forgets the text files in that history, which also removes
+them from Files' Recent; other kinds of files stay.
## Images (`rediwm-images`) and PDF (`rediwm-pdf FILE`)
@@ -58,6 +65,42 @@ Print (toolbar button or Ctrl+P) opens the print dialog of xdg-desktop-portal
(GTK's, by default). A helper started before the sandbox hands the portal the
file you opened; the sandboxed parser can only ask it to print.
+## Network settings
+
+Settings → Network talks to NetworkManager over D-Bus; nothing here runs `nmcli`.
+
+- **Details:** the wired adapter and the connected Wi-Fi network list IPv4 and
+ IPv6 addresses, gateway, DNS servers, search domains, MAC, whether the
+ profile is automatic or manual, and for Wi-Fi the security, signal, band and
+ channel, link speed and access point. Address rows have a copy button.
+- **Saved connections:** Wi-Fi and Ethernet have **Edit settings…**. It sets
+ connect-automatically, IPv4 and IPv6 (Automatic, Manual with address,
+ prefix and gateway, Link-local only, or Disabled), DNS (automatic or your own
+ servers), MTU and metered, and writes them back to the profile. Only those
+ keys change; secrets and everything else in the profile are left as they were.
+ Saving reapplies the connection if it is in use. **Forget** (two clicks)
+ deletes the profile, and the Wi-Fi row also has **Disconnect**.
+- **Unlock:** changing a saved connection needs the polkit action
+ `org.freedesktop.NetworkManager.settings.modify.system`. The page asks once
+ without interaction when it opens. Where policy already allows it (the usual
+ default for a local session) nothing shows; otherwise the page offers
+ **Unlock**, like Services, which asks through your polkit agent.
+- **VPN:** NetworkManager VPN and WireGuard connections are listed with
+ Connect, Disconnect and Remove. Add one with your VPN's NetworkManager plugin
+ or `nmcli connection import`. RediWM has no secret agent, so a VPN that asks
+ for a password at connect time needs its credentials saved in the profile.
+- **Proxy:** Off, Manual (HTTP, HTTPS, SOCKS and a bypass list) or Automatic (a
+ script address). It is stored in GSettings `org.gnome.system.proxy`, which GTK
+ and GIO apps and Firefox's "system proxy" read, so it needs the
+ gsettings-desktop-schemas package. A manual proxy is also exported as
+ `http_proxy`, `https_proxy`, `all_proxy` and `no_proxy` (both cases) to apps
+ RediWM starts afterwards; Off and Automatic export nothing and leave your own
+ login environment alone. Proxy credentials are not stored here.
+- **Airplane mode** soft-blocks every radio through `/dev/rfkill`, so
+ NetworkManager and BlueZ both follow. Turning it off puts each radio back as
+ it was before. It is hidden where there is no rfkill, and disabled while a
+ hardware switch is blocking a radio.
+
## Desktop
Icons and wallpaper from `~/Desktop`, on by default (`[desktop] enabled`). A
diff --git a/docs/wiki/Theme.md b/docs/wiki/Theme.md
index 20994b7..03e21f8 100644
--- a/docs/wiki/Theme.md
+++ b/docs/wiki/Theme.md
@@ -2,502 +2,349 @@
Put these keys in `[theme]` in `$XDG_CONFIG_HOME/rediwm/config.toml`.
`REDIWM_CONFIG` selects another config file; `REDIWM_THEME` overlays another
-file's `[theme]` section. Omitted keys use the built-in defaults below.
+file's `[theme]` section. Omitted keys use the built-in defaults below, and
Appearance saves custom tokens along with its sliders and selectors.
-The bundled picker includes RediWM Dark, RediWM Light, Redi Blue and Redi-Mocha.
-Redi Blue uses navy surfaces, cyan accents, 98% chrome opacity and a 30% selection tint.
-RediWM Light uses 75% window chrome opacity and teal selection accents.
-Redi-Mocha uses the [Catppuccin Mocha palette](https://catppuccin.com/palette/#mocha),
-mauve accents and the bundled `wallpaper-mocha.png` Auckland skyline.
-`start_button_logo_color` optionally tints the bundled R logo; Light uses a
-dark tint for contrast. Custom start-button icons retain their own colours.
-
-Appearance also has a **Taskbar theme** picker under Theme, with the same
-presets plus "Same as theme". It gives the taskbar the preset's colours and
-leaves every other surface on the theme above. It is saved as a
-`[taskbar_theme]` section holding only these keys: `clock_bold`, `clock_italic`, `taskbar_bg`,
-`taskbar_surface`, `taskbar_hover`, `taskbar_border`, `taskbar_outline`, `border_soft`,
-`surface_hover`, `window_fg`, `window_dim`, `danger`, `window_close_hover`,
+
+## Theme packs and the picker
+
+The picker offers RediWM Dark, RediWM Light and Redi Blue (navy surfaces, cyan
+accents, 98% chrome opacity, 30% selection tint). Light uses 75% window chrome
+opacity and teal selection accents.
+
+Redi-Mocha (Catppuccin Mocha palette, mauve accents, `wallpaper-mocha.png`) and
+Gold are installed but hidden from the picker (`picker_hidden` in
+`src/config/theme_pack.zig`). A config with `base = "redi-mocha"` or `"gold"`
+loads as before, keeps its overrides, and still shows as selected; switching
+away removes it from the list. `chamfer-blue` (`assets/themes/chamfer-blue.toml`)
+is likewise not offered. Gold's clock is bold, not italic.
+
+`start_button_logo_color` optionally tints the bundled R logo (Light uses a dark
+tint); custom start-button icons keep their own colours.
+
+**Taskbar theme** (Appearance, under Theme) takes the same presets plus "Same as
+theme" and recolours only the taskbar; every other surface stays on the main
+theme. It is saved as a `[taskbar_theme]` section that reads only these keys:
+`clock_bold`, `clock_italic`, `taskbar_bg`, `taskbar_surface`, `taskbar_hover`,
+`taskbar_border`, `taskbar_outline`, `border_soft`, `surface_hover`,
+`window_fg`, `window_dim`, `danger`, `window_close_hover`,
`start_button_hover`, `start_button_indicator`, `start_button_logo_color` and
-the `battery_*` colours. Unlisted keys are ignored, so a whole theme file's
-body can be pasted under that header; keys it leaves out take the built-in
-defaults, not the main theme's. The section's presence selects the taskbar
-theme (an empty one is the built-in colours); without it the taskbar follows
-`[theme]`. Sizes, gaps and radii always come from `[theme]`.
-Under **Appearance → Taskbar**, **Bold clock text** and **Italic clock text**
-independently style both time and date. They save into the selected taskbar
-theme, or the main theme when the taskbar follows it. Both default to false;
-Gold uses bold with italics off. Clock widths and digit spacing update live.
+the `battery_*` colours. Other keys are ignored, so a whole theme file's body can
+be pasted under the header; keys it omits take the built-in defaults, not the
+main theme's. An empty section is the built-in colours; no section means the
+taskbar follows `[theme]`. Sizes, gaps and radii always come from `[theme]`.
+
+**Bold clock text** and **Italic clock text** (Appearance → Taskbar) style both
+time and date, save into the taskbar theme (or the main theme when the taskbar
+follows it), and default to false.
## GTK and Qt app colors
-In **Settings → Appearance**, **Apply GTK colors** and **Apply Qt colors**
-sit below the Theme and Taskbar theme selectors. They export the current
-main theme's app backgrounds, toolbar, sidebar, text and shell accent.
-The taskbar override does not affect app colors. Exports are snapshots:
-apply again after selecting or editing a theme, then restart the apps.
-
-GTK colors are written to `gtk-3.0/rediwm-colors.css` and
-`gtk-4.0/rediwm-colors.css` under `$XDG_CONFIG_HOME` (otherwise `~/.config`).
-A marked import is added at the *end* of each `gtk.css`, so it wins over palettes
-imported there by other generators (matugen, DMS) while the rest of the file is
-preserved. Applying again moves an older block that sits first. GTK3 includes common widget color overrides; GTK4 also
-gets the CSS variables used by recent libadwaita. No theme package is patched
-and the dark-mode preference is never briefly flipped to force a refresh.
-
-Qt colors require **qt5ct** for Qt 5 apps and **qt6ct** for Qt 6 apps. The
-installed toolkit configurations select native `colors/rediwm.conf` palettes
-and the palette-aware Fusion style. Other preferences are preserved.
-RediWM launches receive the selected platform theme and style immediately;
-sign in again to update the environment for apps activated by D-Bus or
-launched elsewhere. This opt-in is recorded in `rediwm/app-colors.conf`.
-KDE apps such as Dolphin read `kdeglobals` rather than the qt6ct palette, so
-the Qt export also rewrites the `[Colors:*]` groups there (Window, View,
-Button, Selection, Tooltip, Complementary, Header). Other keys are kept, and
-the first copy is saved as `kdeglobals.rediwm-backup`. The file is shared with
-any Plasma session, which will see the same palette.
-Bundled Qt runtimes, sandboxed apps, and apps with their own styles may need
+**Apply GTK colors** and **Apply Qt colors** (Settings → Appearance, below the
+theme selectors) export the main theme's app backgrounds, toolbar, sidebar, text
+and shell accent; the taskbar override is not used. Exports are snapshots: apply
+again after changing a theme, then restart the apps.
+
+**GTK:** written to `gtk-3.0/rediwm-colors.css` and `gtk-4.0/rediwm-colors.css`
+under `$XDG_CONFIG_HOME` (else `~/.config`), with a marked import added at the
+*end* of each `gtk.css` so it wins over other generators (matugen, DMS); the rest
+of the file is kept, and an older block that sits first is moved. GTK3 gets
+common widget overrides, GTK4 also the CSS variables recent libadwaita uses. No
+theme package is patched and the dark-mode preference is never flipped.
+
+**Qt:** needs **qt5ct** (Qt 5) or **qt6ct** (Qt 6). The toolkit configs select
+native `colors/rediwm.conf` palettes and the palette-aware Fusion style; other
+preferences are kept. RediWM launches get the platform theme at once; sign in
+again for apps activated by D-Bus or launched elsewhere. The opt-in is recorded
+in `rediwm/app-colors.conf`. KDE apps such as Dolphin read `kdeglobals`, so the
+export also rewrites its `[Colors:*]` groups (Window, View, Button, Selection,
+Tooltip, Complementary, Header), keeps other keys, and saves the first copy as
+`kdeglobals.rediwm-backup`. That file is shared with any Plasma session.
+Bundled Qt runtimes, sandboxed apps and apps with their own styles may need
their own configuration.
-The first existing user configuration is backed up beside its original as
-`<filename>.rediwm-backup`; later applications keep that first backup.
-A `gtk.css` (or Qt config) that is a symlink, for example one generated by
-another theming tool, is replaced by a regular file holding its current
-contents plus the RediWM block; the link target is not modified. A config
-*folder* that is a symlink is refused and reported in Settings. To undo GTK colors,
-remove the marked RediWM import blocks from both `gtk.css` files (or restore
-their backups). To undo Qt colors, restore the qt5ct/qt6ct configuration
-and `kdeglobals` backups (or delete configurations created by the export if no backup exists),
-remove `rediwm/app-colors.conf`, and sign in again.
-
-## Color tokens
-
-Colors accept `"#rrggbb"`, `"#rrggbbaa"`, or `"rgba(r,g,b,a)"` with RGB
-channels from 0 to 255 and alpha from 0 to 1. Numbers must be finite and
-nonnegative. Sizes are logical pixels. The tables describe appearance tokens;
-window placement, animation timing, cursor themes and sizes, blur, inactive
-opacity and frame radius also have settings in the other config sections.
+**Backups and undo:** the first existing config is backed up beside the original
+as `<filename>.rediwm-backup`, and later applications keep that first backup. A
+symlinked `gtk.css` or Qt config (e.g. from another theming tool) is replaced by
+a regular file with its current contents plus the RediWM block; the target is not
+modified. A symlinked config *folder* is refused and reported in Settings. To
+undo GTK, remove the marked import blocks from both `gtk.css` files (or restore
+the backups). To undo Qt, restore the qt5ct/qt6ct and `kdeglobals` backups (or
+delete configs the export created if none exists), remove
+`rediwm/app-colors.conf`, and sign in again.
+
+## Token syntax
+
+Colors accept `"#rrggbb"`, `"#rrggbbaa"` or `"rgba(r,g,b,a)"` (RGB 0–255, alpha
+0–1). Numbers must be finite and nonnegative; sizes are logical pixels. Window
+placement, animation timing, cursor theme and size, blur, inactive opacity and
+frame radius have settings in the other config sections.
```toml
[theme]
shell_accent = "#86bfff"
-control_thumb = "#ffffff"
toggle_track = "rgba(120,140,170,0.25)"
slider_track_height = 6
app_text_size = 14
-app_heading_size = 13
-app_status_size = 12
-desktop_selection = "rgba(80,140,220,0.2)"
-desktop_selection_border = "#508cdc"
-battery_full = "#40dca0"
-image_checker_size = 16
pdf_search_match = "rgba(100,180,255,0.4)"
```
-## Palettes and reload
-
-Shell surfaces use `window_fg` and `window_dim`. Their accent normally follows
-`start_menu_selected_marker`; `shell_accent`, `shell_on_accent` and
-`shell_border_focus` override that palette and its control/field focus rings. Settings uses `settings_radius` for
-controls. Text fields, carets and text selection have optional overrides that
-otherwise follow the accent of the surface displaying them.
-
-Files' New, Sort and Filter buttons share the secondary-button palette:
-`surface` sets the background, `surface_hover` the hover fill, and `border_soft`
-the border. Their text and icons use `window_fg`. Active Filter and view-mode
-buttons use `shell_accent` (or `start_menu_selected_marker` when unset), tinted
-by `button_selected_alpha`. All of these values can be set in `[theme]`;
-Files follows edits while running.
-
-Files' dialog bodies and context menus share `app_toolbar` as their background
-color. Changing it in `[theme]` updates both.
-
-The compositor reloads the theme when the config changes. Files and Images
-follow saved colors and sizes; PDF and Editor load them when starting. The
-compositor's frame radius is the numeric `[theme].radius_lg`. The legacy
-`[compositor].border_radius` is used only when the theme omits `radius_lg`.
-Appearance's Radius presets write all numeric radius tokens: Default restores
-the current built-in radii, Sharp caps them at 4 px (the minimap's default),
-and Round uses 1.3 times the defaults. Individual theme radii remain editable.
-Cursor styling is `[input].cursor_theme` and `[input].cursor_size`; animation behavior belongs in `[animations]`.
-
-Set `[theme].chrome_round_buttons = true` for circular window controls and
-pill-shaped window tabs. Tab close, new-tab and overflow controls follow the
-same setting. It defaults to `false`, preserving the existing corner radii,
-and reloads live from the main config or the `REDIWM_THEME` file. Button sizes
-and hit targets stay the same; `radius_lg` still controls the window frame.
-
-`[theme].window_shape` replaces the rounded rectangle of server-decorated
-windows with a polygon: up to 16 points, `"x y"` pairs separated by commas.
-A coordinate is logical px from the left or top edge, a negative one (`-0`
-included) px from the right or bottom edge, and `N%` a fraction of the window,
-so one outline fits any size. For example
+## Behavior
+
+**Accent and focus.** Shell surfaces use `window_fg` and `window_dim`. Their
+accent follows `start_menu_selected_marker` unless `shell_accent`,
+`shell_on_accent` or `shell_border_focus` override it (and the control/field
+focus rings). Text fields, carets and selections have optional overrides that
+otherwise follow the accent of the surface showing them. Settings controls use
+`settings_radius`.
+
+**Files.** The New, Sort and Filter buttons share the secondary-button palette:
+`surface` (background), `surface_hover` (hover) and `border_soft` (border), with
+`window_fg` text and icons. Active Filter and view-mode buttons use
+`shell_accent` (else `start_menu_selected_marker`), tinted by
+`button_selected_alpha`. Dialog bodies and context menus use `app_toolbar` as
+their background. Files follows edits while running.
+
+**Reload.** The compositor reloads the theme when the config changes. Files and
+Images follow saved colors and sizes; PDF and Editor load them at start.
+
+**Radius.** The frame radius is the numeric `radius_lg`; the legacy
+`[compositor].border_radius` applies only when the theme omits it. Appearance's
+Radius presets write every numeric radius token: Default restores the built-in
+radii, Sharp caps them at 4 px, Round uses 1.3 times the defaults. Individual
+radii stay editable and the presets leave `taskbar_radius` alone. Cursor styling
+is `[input].cursor_theme` and `cursor_size`; animation belongs in `[animations]`.
+
+**Round window controls.** `chrome_round_buttons = true` makes window controls
+circular and window tabs pill-shaped (tab close, new-tab and overflow follow).
+Default `false`; reloads live; sizes and hit targets are unchanged.
+
+**Window shape.** `window_shape` replaces the rounded rectangle of
+server-decorated windows with a polygon of up to 16 `"x y"` points separated by
+commas. A coordinate is logical px from the left/top edge, a negative one (`-0`
+included) px from the right/bottom edge, and `N%` a fraction of the window, so an
+outline fits any size. For example
`window_shape = "0 14, 14 0, -160 0, -148 3, -14 3, -0 17, -0 -14, -14 -0, 14 -0, 0 -14"`
-cuts the corners and steps the top edge down for its last 160 px. The ring,
-shadow, glass and pointer picking follow the outline. An outline that does not
-parse is refused when the theme loads; one that crosses itself at a window's
-size (a window narrower than its notches) falls back to the rounded rectangle,
-as do maximized and fullscreen windows. `window_top_band` (colour) and
-`window_top_band_height` (logical px, 0 = none) paint a strip along the top of
-the titlebar, clipped by the shape. The titlebar's icon, title and controls
-(and the tab strip's right end) keep in from the outline's slanted or cut ends
-over the rows they occupy; a notch they do not reach into is left to the clip.
-The outline's GL programs are built the first time a theme asks for one, so a
-theme without `window_shape` or `taskbar_shape` never pays for them. The
-`chamfer-blue` pack (`assets/themes/chamfer-blue.toml`, not yet offered in the picker) is an example.
-
-`[theme].taskbar_shape` does the same for the taskbar, against the bar's own
-box (so `-0` is the bar's right or bottom edge): for example
+cuts the corners and steps the top edge down for its last 160 px. Ring, shadow,
+glass and pointer picking follow the outline. An unparseable outline is refused
+at load; one that crosses itself at a window's size (narrower than its notches)
+falls back to the rounded rectangle, as do maximized and fullscreen windows.
+`window_top_band` (colour) and `window_top_band_height` (px, 0 = none) paint a
+strip along the top of the titlebar, clipped by the shape. Titlebar icon, title,
+controls and the tab strip's right end keep in from slanted or cut ends over the
+rows they occupy. The outline's GL programs are built the first time a theme
+asks for one, so themes without `window_shape` or `taskbar_shape` never pay for
+them.
+
+**Taskbar shape.** `taskbar_shape` does the same against the bar's own box (`-0`
+is its right or bottom edge) and replaces `taskbar_radius`; for example
`"0 -0, 14 0, 300 0, 312 6, -14 6, -0 -0"` is a raised left section, a 6 px step
-down and a slanted right tip. It replaces `taskbar_radius`. Items keep clear of
-the slanted ends but not of a notch in the middle, the notch is transparent and
-clicks in it reach what is below, and glass follows the outline. The bar is
-painted once per layout change, not per frame.
-
-The lock's background always paints opaque, even if `lock_bg` supplies alpha;
-`lock_wallpaper_opacity` controls its wallpaper overlay. Actual image pixels,
-PDF paper/content, application-provided icons and fixed layout/hit-test
-geometry retain their content or structural dimensions.
-
-## Colors
-
-| Key | Built-in default |
-| --- | --- |
-| `window_bg` | `"rgba(7.6,9,11,0.80)"` |
-| `window_fg` | `"rgba(245,245,245,1)"` |
-| `window_dim` | `"rgba(214,214,214,1)"` |
-| `window_border` | `"rgba(255,255,255,0.09)"` |
-| `window_border_hover` | `"rgba(255,255,255,0.13)"` |
-| `window_divider` | `"rgba(255,255,255,0.045)"` |
-| `window_close_hover` | `"rgba(237,27,46,1)"` |
-| `text_secondary` | `"rgba(214,214,214,1)"` |
-| `app_bg` | `"rgba(24,28,34,1)"` |
-| `app_toolbar` | `"rgba(29,34,41,1)"` |
-| `app_sidebar` | `"rgba(27,33,40,1)"` |
-| `app_bar` | `"rgba(35,42,51,1)"` |
-| `app_item` | `"rgba(34,40,46,1)"` |
-| `app_item_hover` | `"rgba(37,43,50,1)"` |
-| `app_item_border` | `"rgba(45,51,58,1)"` |
-| `app_item_selected` | `"rgba(78,37,46,1)"` |
-| `app_nav_selected` | `"rgba(91,36,46,1)"` |
-| `app_divider` | `"rgba(55,63,72,1)"` |
-| `app_icon` | `"rgba(214,214,214,1)"` |
-| `status_connected` | `"rgba(51,219.3,114.75,1)"` |
-| `display_tile_border` | `"rgba(255,255,255,0.16)"` |
-| `scrollbar_thumb` | `"rgba(89,98,110,1)"` |
-| `scrollbar_thumb_active` | `unset` |
-| `scrollbar_glow` | `1.0` (strength of the thumb's light; `0` makes the thumb flat, with no highlight stripe) |
-| `bg` | `"rgba(9,11,24,1)"` |
-| `fg` | `"rgba(245,245,245,1)"` |
-| `dim` | `"rgba(214,214,214,1)"` |
-| `faint` | `"rgba(160,160,160,1)"` |
-| `accent` | `"rgba(94,234,212,1)"` |
-| `surface` | `"rgba(255,255,255,0.05)"` |
-| `border` | `"rgba(255,255,255,0.09)"` |
-| `accent_2` | `"rgba(167,139,250,1)"` |
-| `accent_3` | `"rgba(244,114,182,1)"` |
-| `danger` | `"rgba(248,113,113,1)"` |
-| `glass` | `"rgba(15,19,38,0.56)"` |
-| `glass_strong` | `"rgba(12,15,30,0.74)"` |
-| `taskbar_bg` | `"rgba(24,28,34,0.96)"` |
-| `border_soft` | `"rgba(255,255,255,0.06)"` |
-| `border_hover` | `"rgba(255,255,255,0.22)"` |
-| `surface_hover` | `"rgba(255,255,255,0.08)"` |
-| `taskbar_surface` | `"rgba(255,255,255,0.025)"` |
-| `taskbar_hover` | `"rgba(255,255,255,0.05)"` |
-| `taskbar_border` | `"rgba(255,255,255,0.07)"` |
-| `taskbar_outline` | `unset` |
-| `on_accent` | `"rgba(8,33,28,1)"` |
-| `border_focus` | `"rgba(94,234,212,0.4)"` |
-| `caret` | `unset` |
-| `selection` | `unset` |
-| `selection_fg` | `unset` |
-| `field_bg` | `"rgba(21,26,31,1)"` |
-| `field_border` | `"rgba(63,70,77,1)"` |
-| `field_border_focus` | `unset` |
-| `shadow` | `"rgba(0,0,0,0.35)"` |
-| `border_glow_enabled` | `true` |
-| `border_glow` | `"rgba(237,27,46,0.6)"` (alpha 0 turns the highlight off) |
-| `relief_dark` | `"rgba(0,0,0,0.35)"` (neumorphic shadow cast away from the light) |
-| `relief_light` | `"rgba(255,255,255,0.1)"` (neumorphic shadow cast toward the light) |
-| `start_menu_bg` | `"rgba(29,34,41,0.98)"` |
-| `start_menu_border` | `"rgba(255,255,255,0.12)"` |
-| `start_menu_search_bg` | `"rgba(21,26,31,1)"` |
-| `start_menu_selected_bg` | `"rgba(255,255,255,0.045)"` |
-| `start_menu_selected_border` | `"rgba(237,27,46,0.35)"` |
-| `start_menu_selected_marker` | `"rgba(237,27,46,1)"` |
-| `toggle_track` | `"rgba(255,255,255,0.12)"` |
-| `control_thumb` | `"rgba(255,255,255,1)"` |
-| `slider_track` | `"rgba(255,255,255,0.08)"` |
-| `pill_bg` | `"rgba(255,255,255,0.05)"` |
-| `swatch_border` | `"rgba(255,255,255,0.1)"` |
-| `swatch_border_selected` | `"rgba(255,255,255,0.6)"` |
-| `settings_card_bg` | `"rgba(255,255,255,0.025)"` |
-| `lock_bg` | `"rgba(4,5,7,1)"` |
-| `lock_fg` | `"rgba(247,247,250,1)"` |
-| `lock_dim` | `"rgba(168,173,186,1)"` |
-| `lock_divider` | `"rgba(76,82,92,0.6)"` |
-| `lock_session_fg` | `"rgba(219,222,230,1)"` |
-| `switcher_bg` | `"rgba(9,10,14,1)"` |
-| `switcher_border` | `"rgba(153,51,66,0.65)"` |
-| `switcher_item_bg` | `"rgba(23,26,31,1)"` |
-| `switcher_item_border` | `"rgba(255,255,255,0.13)"` |
-| `switcher_fg` | `"rgba(240,242,247,1)"` |
-| `switcher_dim` | `"rgba(153,158,168,1)"` |
-| `switcher_icon_bg` | `"rgba(26,28,33,1)"` |
-| `switcher_selected_border` | `"rgba(255,31,51,1)"` |
-| `calendar_border` | `"rgba(255,255,255,0.16)"` |
-| `osd_border` | `"rgba(255,255,255,0.12)"` |
-| `screenshot_shade` | `"rgba(0,0,0,0.36)"` |
-| `screenshot_border` | `"rgba(255,6,23,1)"` |
-| `screenshot_fg` | `"rgba(255,255,255,1)"` |
-| `screenshot_label_bg` | `"rgba(10,13,15,0.95)"` |
-| `screenshot_label_border` | `"rgba(255,255,255,0.2)"` |
-| `battery_bg` | `"rgba(5,10,10,0.28)"` |
-| `battery_full` | `"rgba(32,226,157,1)"` |
-| `battery_low` | `"rgba(250,204,65,1)"` |
-| `battery_critical` | `"rgba(245,75,85,1)"` |
-| `battery_shimmer` | `"rgba(110,255,200,1)"` |
-| `desktop_fg` | `"rgba(238,241,251,1)"` |
-| `desktop_text_shadow` | `"rgba(0,0,0,0.22)"` |
-| `desktop_hover` | `"rgba(255,255,255,0.06)"` |
-| `desktop_selected` | `"rgba(237,27,46,0.12)"` |
-| `desktop_selection` | `"rgba(237,27,46,0.15)"` |
-| `desktop_selection_border` | `"rgba(237,27,46,1)"` |
-| `desktop_drop_border` | `"rgba(237,27,46,0.8)"` |
-| `desktop_dialog_bg` | `"rgba(9,11,24,0.98)"` |
-| `desktop_notice_bg` | `"rgba(31,9,15,0.95)"` |
-| `desktop_icon_start` | `"rgba(64,166,168,1)"` |
-| `desktop_icon_end` | `"rgba(89,79,158,1)"` |
-| `file_broken` | `"rgba(239,68,68,1)"` |
-| `file_folder_back` | `"rgba(163,171,181,1)"` |
-| `file_folder_front` | `"rgba(184,191,201,1)"` |
-| `file_document` | `"rgba(148,163,184,1)"` |
-| `file_document_lines` | `"rgba(203,213,225,1)"` |
-| `file_spinner` | `"rgba(166,173,184,1)"` |
-| `image_checker_dark` | `"rgba(33,36,38,1)"` |
-| `image_checker_light` | `"rgba(43,46,48,1)"` |
-| `image_crop_shade` | `"rgba(0,0,0,0.58)"` |
-| `image_crop_border` | `"rgba(255,255,255,1)"` |
-| `image_crop_grid` | `"rgba(255,255,255,0.4)"` |
-| `image_dialog_backdrop` | `"rgba(0,0,0,0.65)"` |
-| `pdf_page_shadow` | `"rgba(0,0,0,0.35)"` |
-| `pdf_page_border` | `"rgba(0,0,0,0.15)"` |
-| `pdf_loading` | `"rgba(153,153,153,1)"` |
-| `pdf_search_match` | `"rgba(255,230,0,0.4)"` |
-| `pdf_search_match_active` | `"rgba(255,153,0,0.65)"` |
-| `pdf_thumbnail_bg` | `"rgba(242,245,250,1)"` |
-| `pdf_thumbnail_shadow` | `"rgba(0,0,0,0.3)"` |
-| `pdf_search_shadow` | `"rgba(0,0,0,0.4)"` |
-| `pdf_dialog_backdrop` | `"rgba(0,0,0,0.6)"` |
-| `dialog_backdrop` | `"rgba(0,0,0,0.18)"` |
-| `shell_accent` | `unset` |
-| `shell_on_accent` | `unset` |
-| `shell_border_focus` | `unset` |
-| `window_close_fg` | `"rgba(255,255,255,1)"` |
-| `start_button_hover` | `"rgba(255,255,255,0.035)"` |
-| `start_button_indicator` | `"rgba(255,255,255,0.5)"` |
-| `polkit_backdrop` | `"rgba(0,0,0,0.55)"` |
-| `power_menu_backdrop` | `"rgba(0,0,0,0.45)"` |
-
-`accent_2`, `accent_3`, `glass_strong` and `border_focus` are compatibility
-keys retained by the reader and saver; current painters use the specific
-surface and control tokens above. `scrollbar_thumb_active` now overrides the
-hover/drag color; omitted, it follows the surface accent.
-
-## Sizes and styling
-
-Numeric tokens accept 0–4096 unless constrained below. Fractions ending in
-`_alpha` or `_opacity`, and `dialog_glyph_lift`, accept 0–1.
-
-| Key | Built-in default |
-| --- | --- |
-| `font_size` | `13.0` |
-| `radius` | `5.0` |
-| `radius_md` | `7.0` |
-| `radius_lg` | `10.0` |
-| `title_size` | `13.5` |
-| `chrome_height` | `46.0` |
-| `chrome_control_gap` | `4.0` |
-| `window_shape` | `""` (the rounded rectangle) |
-| `window_top_band` | `rgba(0,0,0,0)` |
-| `window_top_band_height` | `0.0` |
-| `taskbar_shape` | `""` (the rounded rectangle) |
-| `taskbar_title_size` | `12.5` |
-| `clock_bold`, `clock_italic` | `false` |
-| `taskbar_size` | `44.0` |
-| `taskbar_edge_gap` | `0.0` |
-| `taskbar_length` | `100.0` |
-| `taskbar_radius` | `0.0` |
-| `taskbar_outline_width` | `1.0` |
-| `chip_gap` | `4.0` |
-| `chip_width` | `220.0` |
-| `start_button_gap` | `4.0` |
-| `start_button_icon_size` | `42.0` |
-| `button_font_size` | `12.5` |
-| `caret_width` | `1.5` |
-| `scrollbar_width` | `8.0` |
-| `selection_alpha` | `0.35` |
-| `field_radius` | `8.0` |
-| `shadow_size` | `24.0` |
-| `shadow_offset_y` | `8.0` |
-| `relief_depth` | `0.0` (off). Neumorphic relief: buttons and fields cast a dark and a light shadow this many px from their edge |
-| `relief_softness` | `0.0` (1.5 x `relief_depth`), fade-out length of those shadows |
-| `relief_light_angle` | `135.0`, degrees counter-clockwise from the right (135 is the upper left) |
-
-| `border_glow_length` | `72.0` |
-| `border_glow_reach` | `56.0` |
-| `border_glow_depth` | `3.0` |
-| `start_menu_width` | `0` (automatic) |
-| `start_menu_max_height` | `0` (automatic) |
-| `start_menu_radius` | `14.0` |
-| `start_menu_left_pad` | `2.0` |
-| `start_menu_bottom_pad` | `6.0` |
-| `start_menu_icon_left_pad` | `2.0` |
-| `start_menu_icon_bottom_pad` | `6.0` |
-| `settings_radius` | `8` |
-| `settings_sidebar_radius` | `10` |
-| `settings_card_radius` | `9` |
-| `settings_title_size` | `17` |
-| `settings_description_size` | `12` |
-| `checkbox_radius` | `4` |
-| `toggle_radius` | `5` |
-| `toggle_thumb_radius` | `4` |
-| `slider_track_height` | `5.5` |
-| `slider_settings_track_height` | `11` |
-| `slider_thumb_size` | `12` |
-| `slider_settings_thumb_height` | `20` |
-| `slider_thumb_radius` | `4` |
-| `slider_track_grow` | `0.25` |
-| `slider_track_tint_alpha` | `0.45` |
-| `slider_fill_alpha` | `0.6` |
-| `pill_active_alpha` | `0.16` |
-| `pill_border_active_alpha` | `0.55` |
-| `segmented_selected_alpha` | `0.15` |
-| `swatch_radius` | `6` |
-| `swatch_glow_alpha` | `0.8` |
-| `dialog_badge_radius` | `16` |
-| `dialog_badge_alpha` | `0.18` |
-| `dialog_glyph_lift` | `0.3` |
-| `dialog_title_size` | `26` |
-| `dialog_subtitle_size` | `15` |
-| `dialog_inset_radius` | `12` |
-| `scrollbar_radius` | `3` |
-| `scrollbar_rest_width` | `0.75` |
-| `scrollbar_active_width` | `1.125` |
-| `switcher_radius` | `24` |
-| `switcher_item_radius` | `12` |
-| `switcher_icon_radius` | `10` |
-| `switcher_selection_radius` | `15` |
-| `switcher_title_size` | `15` |
-| `switcher_app_size` | `12` |
-| `calendar_radius` | `9` |
-| `calendar_opacity` | `0.98` |
-| `osd_radius` | `10` |
-| `osd_opacity` | `0.97` |
-| `lock_wallpaper_opacity` | `0.24` |
-| `image_checker_size` | `12` |
-| `start_button_radius` | `6` |
-| `mini_map_bg_opacity` | `0.91` |
-| `mini_map_grid_alpha` | `0.065` |
-| `mini_map_border_alpha` | `0.12` |
-| `mini_map_window_alpha` | `0.55` |
-| `mini_map_marker_alpha` | `0.12` |
-| `mini_map_marker_border_alpha` | `0.85` |
-| `mini_map_radius` | `4` |
-| `app_text_size` | `13` |
-| `app_heading_size` | `12` |
-| `app_status_size` | `11.5` |
-| `desktop_text_size` | `11.5` |
-| `window_close_hover_alpha` | `0.85` |
-| `button_disabled_alpha` | `0.5` |
-| `button_hover_brightness` | `1.08` |
-| `button_selected_alpha` | `0.6` |
-| `button_selected_hover_alpha` | `0.7` |
+down and a slanted right tip. Items keep clear of slanted ends but not of a
+notch in the middle; the notch is transparent, clicks in it reach what is below,
+and glass follows the outline. The bar is painted once per layout change.
+
+**Lock.** The lock background always paints opaque even if `lock_bg` has alpha;
+`lock_wallpaper_opacity` sets its wallpaper overlay. Image pixels, PDF content,
+application icons and fixed layout/hit-test geometry keep their own dimensions.
+
+## Defaults
+
+Every key below is optional. Entries marked `unset` follow another token.
+
+### Colors
+
+```text
+# Windows and text
+window_bg = "rgba(7.6,9,11,0.80)" window_fg = "rgba(245,245,245,1)"
+window_dim = "rgba(214,214,214,1)" window_border = "rgba(255,255,255,0.09)"
+window_border_hover = "rgba(255,255,255,0.13)" window_divider = "rgba(255,255,255,0.045)"
+window_close_hover = "rgba(237,27,46,1)" window_close_fg = "rgba(255,255,255,1)"
+text_secondary = "rgba(214,214,214,1)"
+# Base palette and fields
+bg = "rgba(9,11,24,1)" fg = "rgba(245,245,245,1)" dim = "rgba(214,214,214,1)"
+faint = "rgba(160,160,160,1)" accent = "rgba(94,234,212,1)" accent_2 = "rgba(167,139,250,1)"
+accent_3 = "rgba(244,114,182,1)" surface = "rgba(255,255,255,0.05)"
+surface_hover = "rgba(255,255,255,0.08)" border = "rgba(255,255,255,0.09)"
+border_soft = "rgba(255,255,255,0.06)" border_hover = "rgba(255,255,255,0.22)"
+border_focus = "rgba(94,234,212,0.4)" border_glow_enabled = true
+border_glow = "rgba(237,27,46,0.6)" danger = "rgba(248,113,113,1)" glass = "rgba(15,19,38,0.56)"
+glass_strong = "rgba(12,15,30,0.74)" on_accent = "rgba(8,33,28,1)" caret = unset
+selection = unset selection_fg = unset field_bg = "rgba(21,26,31,1)"
+field_border = "rgba(63,70,77,1)" field_border_focus = unset shadow = "rgba(0,0,0,0.35)"
+shell_accent = unset shell_on_accent = unset shell_border_focus = unset
+# Controls
+scrollbar_thumb = "rgba(89,98,110,1)" scrollbar_thumb_active = unset scrollbar_glow = 1.0
+toggle_track = "rgba(255,255,255,0.12)" control_thumb = "rgba(255,255,255,1)"
+slider_track = "rgba(255,255,255,0.08)" pill_bg = "rgba(255,255,255,0.05)"
+swatch_border = "rgba(255,255,255,0.1)" swatch_border_selected = "rgba(255,255,255,0.6)"
+settings_card_bg = "rgba(255,255,255,0.025)" dialog_backdrop = "rgba(0,0,0,0.18)"
+relief_dark = "rgba(0,0,0,0.35)" relief_light = "rgba(255,255,255,0.1)"
+# Taskbar, start menu, battery
+taskbar_bg = "rgba(24,28,34,0.96)" taskbar_surface = "rgba(255,255,255,0.025)"
+taskbar_hover = "rgba(255,255,255,0.05)" taskbar_border = "rgba(255,255,255,0.07)"
+taskbar_outline = unset start_menu_bg = "rgba(29,34,41,0.98)"
+start_menu_border = "rgba(255,255,255,0.12)" start_menu_search_bg = "rgba(21,26,31,1)"
+start_menu_selected_bg = "rgba(255,255,255,0.045)"
+start_menu_selected_border = "rgba(237,27,46,0.35)"
+start_menu_selected_marker = "rgba(237,27,46,1)" start_button_hover = "rgba(255,255,255,0.035)"
+start_button_indicator = "rgba(255,255,255,0.5)" battery_bg = "rgba(5,10,10,0.28)"
+battery_full = "rgba(32,226,157,1)" battery_low = "rgba(250,204,65,1)"
+battery_critical = "rgba(245,75,85,1)" battery_shimmer = "rgba(110,255,200,1)"
+# Overlays and lock
+switcher_bg = "rgba(9,10,14,1)" switcher_border = "rgba(153,51,66,0.65)"
+switcher_item_bg = "rgba(23,26,31,1)" switcher_item_border = "rgba(255,255,255,0.13)"
+switcher_fg = "rgba(240,242,247,1)" switcher_dim = "rgba(153,158,168,1)"
+switcher_icon_bg = "rgba(26,28,33,1)" switcher_selected_border = "rgba(255,31,51,1)"
+calendar_border = "rgba(255,255,255,0.16)" osd_border = "rgba(255,255,255,0.12)"
+screenshot_shade = "rgba(0,0,0,0.36)" screenshot_border = "rgba(255,6,23,1)"
+screenshot_fg = "rgba(255,255,255,1)" screenshot_label_bg = "rgba(10,13,15,0.95)"
+screenshot_label_border = "rgba(255,255,255,0.2)" polkit_backdrop = "rgba(0,0,0,0.55)"
+power_menu_backdrop = "rgba(0,0,0,0.45)" lock_bg = "rgba(4,5,7,1)" lock_fg = "rgba(247,247,250,1)"
+lock_dim = "rgba(168,173,186,1)" lock_divider = "rgba(76,82,92,0.6)"
+lock_session_fg = "rgba(219,222,230,1)"
+# Desktop and apps
+desktop_fg = "rgba(238,241,251,1)" desktop_text_shadow = "rgba(0,0,0,0.22)"
+desktop_hover = "rgba(255,255,255,0.06)" desktop_selected = "rgba(237,27,46,0.12)"
+desktop_selection = "rgba(237,27,46,0.15)" desktop_selection_border = "rgba(237,27,46,1)"
+desktop_drop_border = "rgba(237,27,46,0.8)" desktop_dialog_bg = "rgba(9,11,24,0.98)"
+desktop_notice_bg = "rgba(31,9,15,0.95)" desktop_icon_start = "rgba(64,166,168,1)"
+desktop_icon_end = "rgba(89,79,158,1)" file_broken = "rgba(239,68,68,1)"
+file_folder_back = "rgba(163,171,181,1)" file_folder_front = "rgba(184,191,201,1)"
+file_document = "rgba(148,163,184,1)" file_document_lines = "rgba(203,213,225,1)"
+file_spinner = "rgba(166,173,184,1)" image_checker_dark = "rgba(33,36,38,1)"
+image_checker_light = "rgba(43,46,48,1)" image_crop_shade = "rgba(0,0,0,0.58)"
+image_crop_border = "rgba(255,255,255,1)" image_crop_grid = "rgba(255,255,255,0.4)"
+image_dialog_backdrop = "rgba(0,0,0,0.65)" pdf_page_shadow = "rgba(0,0,0,0.35)"
+pdf_page_border = "rgba(0,0,0,0.15)" pdf_loading = "rgba(153,153,153,1)"
+pdf_search_match = "rgba(255,230,0,0.4)" pdf_search_match_active = "rgba(255,153,0,0.65)"
+pdf_thumbnail_bg = "rgba(242,245,250,1)" pdf_thumbnail_shadow = "rgba(0,0,0,0.3)"
+pdf_search_shadow = "rgba(0,0,0,0.4)" pdf_dialog_backdrop = "rgba(0,0,0,0.6)"
+status_connected = "rgba(51,219.3,114.75,1)" display_tile_border = "rgba(255,255,255,0.16)"
+app_bg = "rgba(24,28,34,1)" app_toolbar = "rgba(29,34,41,1)" app_sidebar = "rgba(27,33,40,1)"
+app_bar = "rgba(35,42,51,1)" app_item = "rgba(34,40,46,1)" app_item_hover = "rgba(37,43,50,1)"
+app_item_border = "rgba(45,51,58,1)" app_item_selected = "rgba(78,37,46,1)"
+app_nav_selected = "rgba(91,36,46,1)" app_divider = "rgba(55,63,72,1)"
+app_icon = "rgba(214,214,214,1)"
+```
+
+Notes: `accent_2`, `accent_3`, `glass_strong` and `border_focus` are
+compatibility keys kept by the reader and saver; painters use the specific
+tokens. `scrollbar_thumb_active` overrides the hover/drag color (unset: the
+surface accent). `border_glow` alpha 0 turns the highlight off. `scrollbar_glow`
+is the strength of the thumb's light (`0` = flat thumb, no highlight stripe).
+`relief_dark` and `relief_light` are the neumorphic shadows cast away from and
+toward the light.
+
+### Sizes and styling
+
+Numeric tokens accept 0–4096 unless constrained below; `*_alpha`, `*_opacity`
+and `dialog_glyph_lift` accept 0–1. `""` for a shape means the rounded
+rectangle; `0` for `start_menu_width` and `start_menu_max_height` means
+automatic.
+
+```text
+# Base
+font_size = 13.0 radius = 5.0 radius_md = 7.0 radius_lg = 10.0 title_size = 13.5
+chrome_height = 46.0 chrome_control_gap = 4.0 window_shape = "" window_top_band = "rgba(0,0,0,0)"
+window_top_band_height = 0.0 window_close_hover_alpha = 0.85 shadow_size = 24.0
+shadow_offset_y = 8.0 relief_depth = 0.0 relief_softness = 0.0 relief_light_angle = 135.0
+border_glow_length = 72.0 border_glow_reach = 56.0 border_glow_depth = 3.0
+# Taskbar, clock, start menu
+taskbar_shape = "" taskbar_title_size = 12.5 taskbar_size = 44.0 taskbar_edge_gap = 0.0
+taskbar_length = 100.0 taskbar_radius = 0.0 taskbar_outline_width = 1.0 clock_bold = false
+clock_italic = false chip_gap = 4.0 chip_width = 220.0 start_button_gap = 4.0
+start_button_icon_size = 42.0 start_menu_width = 0 start_menu_max_height = 0
+start_menu_radius = 14.0 start_menu_left_pad = 2.0 start_menu_bottom_pad = 6.0
+start_menu_icon_left_pad = 2.0 start_menu_icon_bottom_pad = 6.0 start_button_radius = 6
+# Controls
+button_font_size = 12.5 button_disabled_alpha = 0.5 button_hover_brightness = 1.08
+button_selected_alpha = 0.6 button_selected_hover_alpha = 0.7 caret_width = 1.5
+scrollbar_width = 8.0 scrollbar_radius = 3 scrollbar_rest_width = 0.75
+scrollbar_active_width = 1.125 selection_alpha = 0.35 field_radius = 8.0 settings_radius = 8
+settings_sidebar_radius = 10 settings_card_radius = 9 settings_title_size = 17
+settings_description_size = 12 checkbox_radius = 4 toggle_radius = 5 toggle_thumb_radius = 4
+slider_track_height = 5.5 slider_settings_track_height = 11 slider_thumb_size = 12
+slider_settings_thumb_height = 20 slider_thumb_radius = 4 slider_track_grow = 0.25
+slider_track_tint_alpha = 0.45 slider_fill_alpha = 0.6 pill_active_alpha = 0.16
+pill_border_active_alpha = 0.55 segmented_selected_alpha = 0.15 swatch_radius = 6
+swatch_glow_alpha = 0.8 dialog_badge_radius = 16 dialog_badge_alpha = 0.18
+dialog_glyph_lift = 0.3 dialog_title_size = 26 dialog_subtitle_size = 15 dialog_inset_radius = 12
+# Overlays and apps
+switcher_radius = 24 switcher_item_radius = 12 switcher_icon_radius = 10
+switcher_selection_radius = 15 switcher_title_size = 15 switcher_app_size = 12
+calendar_radius = 9 calendar_opacity = 0.98 osd_radius = 10 osd_opacity = 0.97
+lock_wallpaper_opacity = 0.24 image_checker_size = 12 mini_map_bg_opacity = 0.91
+mini_map_grid_alpha = 0.065 mini_map_border_alpha = 0.12 mini_map_window_alpha = 0.55
+mini_map_marker_alpha = 0.12 mini_map_marker_border_alpha = 0.85 mini_map_radius = 4
+app_text_size = 13 app_heading_size = 12 app_status_size = 11.5 desktop_text_size = 11.5
+```
+
+Further ranges: `chrome_height` 28–84, `chrome_control_gap` 0–24, `chip_width`
+64–400, `taskbar_length` 20–100 (percent), `taskbar_outline_width` 0–8,
+`scrollbar_width` 4–24, `scrollbar_rest_width` and `scrollbar_active_width`
+0.25–1.125 times the configured width, `image_checker_size` 1–128.
+
+`relief_depth` (0 = off) is how many px buttons and fields cast a dark and a
+light shadow from their edge; `relief_softness` (0 = 1.5 × depth) is the fade
+length; `relief_light_angle` is degrees counter-clockwise from the right (135 =
+upper left). Layouts cap some dimensions to fit; the scrollbar reserves room for
+its maximum width, and `slider_*` keys control slider geometry while sharing the
+scrollbar feedback.
+
+**Taskbar geometry.** `taskbar_height` aliases `taskbar_size`. The bar is flush,
+full-width and square by default. `taskbar_edge_gap` (0–64 px; Appearance's
+**Taskbar gap from edge**) floats it off its screen edge, `taskbar_length`
+shortens it (centred; never narrower than its items need, 420 px) and
+`taskbar_radius` rounds it (a pill at half the bar's height). Windows and panels
+treat the bar and its gap as reserved space. `taskbar_outline_width` and
+`taskbar_outline` (unset: `border_soft`) style the bar's outline: a flush bar
+draws it only on the side facing the windows, a floating or rounded one all
+round. `taskbar_border` stays the colour of the window buttons' and battery's
+outlines.
### Component relief
-When `relief_depth` is greater than zero, individual controls can opt into
-`"flat"`, `"raised"`, or `"inset"` relief. Flat is the default for components
-that did not previously use explicit relief. The standard slider progress fill
-overlays the start of the track, so an inset `slider_track_relief` can have its
-left-side groove shadow covered by that fill. The shaded slider and toggle paths
-(`slider_shaded`, `toggle_shaded`) keep their procedural lighting and add these
-shadows on top, dropping only what the relief would double: the toggle's hand-made
-track rim under a non-flat track relief, and the knob's cast shadow under a
-non-flat thumb relief. A groove's shadows skip its knob, and a knob's stay inside
-its track (toggle) or the slider's box, so neither crosses the thumb or outlives
-the control's damage bounds. A theme that leaves the keys `flat` renders exactly
-as before. Raised shadows reach `relief_depth + relief_softness` past a box: use
-`inset` for segments, rows and pills packed into a layout.
-
-| Key | Built-in default | Description |
-| --- | --- | --- |
-| `button_relief` | `"flat"` | Resting primary/secondary button relief |
-| `button_pressed_relief` | `"flat"` | Pressed or selected button relief |
-| `field_relief` | `"flat"` | Text field frame relief |
-| `dialog_inset_relief` | `"flat"` | Dialog recessed content panel relief |
-| `dialog_frame_relief` | `"flat"` | Dialog card relief; raised shadows lie outside the card |
-| `settings_card_relief` | `"flat"` | Cards around Settings entries. The page scrolls in a clipped container, so a raised card's shadow is cut at its edge: prefer `inset` |
-| `taskbar_chip_relief` | `"flat"` | Taskbar window chip, idle. Shaded inside the edge (the chip raster has no margin): `inset` is a groove, `raised` swaps the lights. Main theme only; `[taskbar_theme]` does not carry it |
-| `taskbar_chip_active_relief` | `"flat"` | The focused taskbar chip; same rules |
-| `select_relief` | `"flat"` | Resting select/dropdown control relief |
-| `select_popup_relief` | `"flat"` | Select/dropdown popup container relief |
-| `checkbox_relief` | `"flat"` | Checkbox frame relief |
-| `toggle_track_relief` | `"flat"` | Toggle track relief (plain and shaded) |
-| `toggle_thumb_relief` | `"flat"` | Toggle knob relief (plain and shaded) |
-| `slider_track_relief` | `"flat"` | Slider track relief (plain and shaded) |
-| `slider_thumb_relief` | `"flat"` | Slider thumb relief (plain and shaded) |
-| `segmented_relief` | `"flat"` | Segmented control frame relief |
-| `segmented_selected_relief` | `"flat"` | Selected segment relief |
-| `stepper_relief` | `"flat"` | Stepper frame relief |
-| `swatch_relief` | `"flat"` | Colour swatch relief |
-| `pill_relief` | `"flat"` | Slider value readout (pill) relief |
-| `row_hover_relief` | `"flat"` | Hovered or pressed list row relief |
-| `row_selected_relief` | `"flat"` | Selected list row relief |
-| `scrollbar_track_relief` | `"flat"` | Scrollbar channel: `flat` draws no track, `inset` cuts a groove the thumb sits in. Pair with `scrollbar_glow = 0` for a flat thumb |
-| Additional constraint | Range |
-| --- | --- |
-| `chrome_height` | 28–84 |
-| `chrome_control_gap` | 0–24 |
-| `chip_width` | 64–400 |
-| `taskbar_length` | 20–100 (percent) |
-| `taskbar_outline_width` | 0–8 |
-| `scrollbar_width` | 4–24 |
-| `scrollbar_rest_width`, `scrollbar_active_width` | 0.25–1.125 times the configured width |
-| `image_checker_size` | 1–128 |
-
-`taskbar_height` is an alias for `taskbar_size`. The taskbar is a flush,
-full-width, square bar by default. `taskbar_edge_gap` (0–64 logical px, in
-Appearance as **Taskbar gap from edge**) floats it off the screen edge it sits
-on, `taskbar_length` (a percentage of that edge, centred; never narrower than
-its items need, 420 px) shortens it, and `taskbar_radius` (px; a pill at half
-the bar's height) rounds its corners. Windows and panels treat the bar and its
-gap as reserved space. `taskbar_outline_width` is the thickness of the bar's own
-outline and the optional colour `taskbar_outline` its colour (unset: `border_soft`,
-which drew the bar's single hairline before). A flush bar draws the outline on the
-side facing the windows only; a floating or rounded one draws it all round.
-`taskbar_border` stays the colour of the window buttons' and battery's outlines.
-The Radius presets (Sharp, Default, Round) leave `taskbar_radius` alone. Layouts cap some dimensions to
-fit their available space. The scrollbar reserves room for its maximum width;
-`slider_*` keys control slider geometry while sharing the scrollbar feedback.
+When `relief_depth` > 0, controls can opt into `"flat"` (default), `"raised"` or
+`"inset"` relief through these keys, all defaulting to `"flat"`:
+
+```text
+button_relief button_pressed_relief field_relief dialog_inset_relief
+dialog_frame_relief settings_card_relief taskbar_chip_relief
+taskbar_chip_active_relief select_relief select_popup_relief checkbox_relief
+toggle_track_relief toggle_thumb_relief slider_track_relief slider_thumb_relief
+segmented_relief segmented_selected_relief stepper_relief swatch_relief
+pill_relief row_hover_relief row_selected_relief scrollbar_track_relief
+```
+
+- Raised shadows reach `relief_depth + relief_softness` past a box and are cut
+ at clipped containers, so use `inset` for segments, rows, pills and
+ `settings_card_relief` (the page scrolls in a clipped container). `dialog_frame_relief`
+ raised shadows lie outside the card.
+- The standard slider fill overlays the start of the track, so an inset
+ `slider_track_relief` can have its left groove shadow covered. The shaded
+ slider and toggle paths keep their procedural lighting and add relief on top,
+ dropping only what it would double (the toggle's track rim under a non-flat
+ track relief, the knob's cast shadow under a non-flat thumb relief). Shadows
+ skip the knob and stay inside the track or slider box.
+- `taskbar_chip_relief` and `taskbar_chip_active_relief` (focused chip) shade
+ inside the edge: `inset` is a groove, `raised` swaps the lights. Main theme
+ only; `[taskbar_theme]` does not carry them.
+- `scrollbar_track_relief`: `flat` draws no track, `inset` cuts a groove for the
+ thumb. Pair with `scrollbar_glow = 0` for a flat thumb.
+- A theme leaving everything `flat` renders as before.
## Strings
-| Key | Built-in default | Meaning |
+| Key | Default | Meaning |
| --- | --- | --- |
-| `font` | `"Manrope"` | Compositor's preferred proportional font family |
-| `mono_font` | `"JetBrains Mono"` | Compositor's preferred monospace font family |
+| `font` | `"Manrope"` | Preferred proportional font family |
+| `mono_font` | `"JetBrains Mono"` | Preferred monospace font family |
| `start_button_icon` | `""` | Bundled Redi logo; otherwise an absolute image path |
-In **Settings → Appearance → Start menu**, **Choose file…** selects a PNG or
-SVG for the Start button logo and applies it immediately. **Reset to default**
-restores the bundled R logo. Both choices are saved with the theme. A preview
-beside the buttons shows the logo as the taskbar draws it (the bundled R when a
-chosen file cannot be loaded). The **Menu width** (400–900) and **Menu height**
-(360–900) sliders in the same section set `start_menu_width` and
-`start_menu_max_height`; the menu is still capped to the output. Left at `0`
-(the default) the menu is sized to the screen: 560 x 600 on a screen of about
-1700 x 1070 logical pixels or more, and the same share of the screen (33% wide,
-56% high) on smaller ones, never below 400 x 360. **Size to screen** returns to
-that.
+**Settings → Appearance → Start menu:** **Choose file…** picks a PNG or SVG for
+the Start button logo and applies it at once; **Reset to default** restores the
+bundled R. Both are saved with the theme, and a preview shows the logo as the
+taskbar draws it (the R if the file cannot be loaded). **Menu width** (400–900)
+and **Menu height** (360–900) set `start_menu_width` and `start_menu_max_height`,
+capped to the output. At `0` the menu is sized to the screen: 560 x 600 on
+about 1700 x 1070 logical px or more, otherwise 33% wide and 56% high, never
+below 400 x 360. **Size to screen** returns to that.
diff --git a/po/rediwm.pot b/po/rediwm.pot
index f53a722..9c3b000 100644
--- a/po/rediwm.pot
+++ b/po/rediwm.pot
@@ -31,6 +31,10 @@ msgstr ""
msgid "1 second"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "1.1.1.1, 2606:4700:4700::1111"
+msgstr ""
+
#: src/control_center/sections/desktop.zig
msgid "1.5 seconds"
msgstr ""
@@ -55,6 +59,14 @@ msgstr ""
msgid "180°"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "192.168.1.1"
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "192.168.1.20"
+msgstr ""
+
#: src/control_center/sections/desktop.zig
msgid "2 seconds"
msgstr ""
@@ -63,6 +75,14 @@ msgstr ""
msgid "200%"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "2001:db8::20"
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "24"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "24-hour clock"
msgstr ""
@@ -91,6 +111,14 @@ msgstr ""
msgid "60 seconds"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "64"
+msgstr ""
+
+#: src/control_center/sections/network_proxy.zig
+msgid "8080"
+msgstr ""
+
#: src/control_center/sections/display.zig
msgid "90°"
msgstr ""
@@ -107,6 +135,10 @@ msgstr ""
msgid "A file with this name exists. Replace it?"
msgstr ""
+#: src/control_center/sections/network.zig
+msgid "A hardware switch is blocking a radio."
+msgstr ""
+
#: src/printing/ladder.zig
msgid "A matched device-node path is a regular file or another wrong file type."
msgstr ""
@@ -143,6 +175,10 @@ msgstr ""
msgid "Accept jobs"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "Access point"
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "Account details · {name}"
msgstr ""
@@ -227,6 +263,10 @@ msgstr ""
msgid "Additional setup required"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Address"
+msgstr ""
+
#: src/control_center/sections/printers_add.zig
msgid "Address checks support IPP printers. Other connections can be tested with an explicit print after setup."
msgstr ""
@@ -239,6 +279,10 @@ msgstr ""
msgid "Administrator privileges are required to continue."
msgstr ""
+#: src/control_center/search_index.zig
+msgid "Airplane mode"
+msgstr ""
+
#: src/control_center/sections/services.zig
msgid "All"
msgstr ""
@@ -339,11 +383,19 @@ msgstr ""
msgid "Applications"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "Applied."
+msgstr ""
+
+#: src/control_center/sections/network_proxy.zig
+msgid "Applied. Apps you start from now on use this proxy."
+msgstr ""
+
#: src/control_center/sections/desktop.zig
msgid "Applies to output edges and the space between automatic tiles."
msgstr ""
-#: src/images/app_render.zig
+#: src/control_center/sections/network_proxy.zig
msgid "Apply"
msgstr ""
@@ -387,6 +439,10 @@ msgstr ""
msgid "Apps and web pages"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "Apps that follow the system proxy use this. A manual proxy is also given to apps started from RediWM."
+msgstr ""
+
#: src/files/archive.zig
msgid "Archive contains an unsafe path"
msgstr ""
@@ -523,7 +579,7 @@ msgstr ""
msgid "Auto-join this network"
msgstr ""
-#: src/printing/options.zig
+#: src/control_center/sections/network_details.zig
msgid "Automatic"
msgstr ""
@@ -583,6 +639,10 @@ msgstr ""
msgid "Balanced"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "Band"
+msgstr ""
+
#: src/control_center/sections/sound.zig
msgid "Bass Boost"
msgstr ""
@@ -727,6 +787,10 @@ msgstr ""
msgid "Browser"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "Bypass the proxy for"
+msgstr ""
+
#: src/images/app_render.zig
msgid "C: crop · Ctrl+S: save · Delete: trash"
msgstr ""
@@ -1043,6 +1107,22 @@ msgstr ""
msgid "Check printer power, the address, and access through the network or VPN."
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Check the DNS server addresses."
+msgstr ""
+
+#: src/control_center/sections/network_proxy.zig
+msgid "Check the HTTP proxy host and port (1–65535)."
+msgstr ""
+
+#: src/control_center/sections/network_proxy.zig
+msgid "Check the HTTPS proxy host and port (1–65535)."
+msgstr ""
+
+#: src/control_center/sections/network_proxy.zig
+msgid "Check the SOCKS host and port (1–65535)."
+msgstr ""
+
#: src/printing/ladder.zig
msgid "Check the configured CUPS server and whether the print service is installed and available."
msgstr ""
@@ -1195,6 +1275,10 @@ msgstr ""
msgid "Classic (stacking)"
msgstr ""
+#: src/editor/app_recent.zig
+msgid "Clear Recent"
+msgstr ""
+
#: src/control_center/search.zig
msgid "Clear search"
msgstr ""
@@ -1283,6 +1367,14 @@ msgstr ""
msgid "Completed"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "Configuration"
+msgstr ""
+
+#: src/control_center/sections/network_proxy.zig
+msgid "Configuration URL"
+msgstr ""
+
#: src/control_center/sections/network.zig
msgid "Configure this network with a network tool"
msgstr ""
@@ -1299,6 +1391,10 @@ msgstr ""
msgid "Confirm Pairing"
msgstr ""
+#: src/control_center/sections/network.zig
+msgid "Confirm forget"
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "Confirm new password"
msgstr ""
@@ -1307,6 +1403,10 @@ msgstr ""
msgid "Confirm password"
msgstr ""
+#: src/control_center/sections/network_vpn.zig
+msgid "Confirm remove"
+msgstr ""
+
#: src/printing/ladder.zig
msgid "Confirm resolution using the printer's self-test or a measured ruler test."
msgstr ""
@@ -1347,7 +1447,7 @@ msgstr ""
msgid "Connecting Ethernet…"
msgstr ""
-#: src/files/app_paint.zig
+#: src/control_center/sections/network_vpn.zig
msgid "Connecting…"
msgstr ""
@@ -1363,6 +1463,14 @@ msgstr ""
msgid "Connection failed. Check the password and try again."
msgstr ""
+#: src/network/manager_edit.zig
+msgid "Connection forgotten."
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "Connection settings"
+msgstr ""
+
#: src/session/lock_view.zig
msgid "Continue"
msgstr ""
@@ -1437,6 +1545,10 @@ msgstr ""
msgid "Could not change permissions"
msgstr ""
+#: src/control_center/sections/network.zig
+msgid "Could not change the radios. Check access to /dev/rfkill."
+msgstr ""
+
#: src/printing/admin.zig
msgid "Could not clear the canonical default override."
msgstr ""
@@ -1473,6 +1585,10 @@ msgstr ""
msgid "Could not extract archive"
msgstr ""
+#: src/network/manager_edit.zig
+msgid "Could not forget the connection."
+msgstr ""
+
#: src/files/app_dialogs.zig
msgid "Could not load applications"
msgstr ""
@@ -1605,6 +1721,10 @@ msgstr ""
msgid "Could not read the AppImage's application details"
msgstr ""
+#: src/network/manager_edit.zig
+msgid "Could not read the connection settings."
+msgstr ""
+
#: src/files/client_dnd.zig
msgid "Could not read the dropped items"
msgstr ""
@@ -1617,7 +1737,7 @@ msgstr ""
msgid "Could not request CUPS start."
msgstr ""
-#: src/systemd/requests.zig
+#: src/network/manager_access.zig
msgid "Could not request authentication. Check that polkit is running."
msgstr ""
@@ -1677,6 +1797,10 @@ msgstr ""
msgid "Could not save the Files setting."
msgstr ""
+#: src/network/manager_edit.zig
+msgid "Could not save the connection settings."
+msgstr ""
+
#: src/control_center/welcome.zig
msgid "Could not save the default app. Please try again."
msgstr ""
@@ -1769,6 +1893,10 @@ msgstr ""
msgid "Could not start the authentication request."
msgstr ""
+#: src/network/manager_edit.zig
+msgid "Could not start the connection."
+msgstr ""
+
#: src/session/power_requests.zig
msgid "Could not start the power command."
msgstr ""
@@ -1777,6 +1905,10 @@ msgstr ""
msgid "Could not start the request."
msgstr ""
+#: src/network/manager_edit.zig
+msgid "Could not stop the connection."
+msgstr ""
+
#: src/systemd/live.zig
msgid "Could not subscribe to service updates."
msgstr ""
@@ -1907,7 +2039,7 @@ msgstr ""
msgid "DISPLAY"
msgstr ""
-#: src/control_center/sections/network.zig
+#: src/control_center/sections/network_details.zig
msgid "DNS servers"
msgstr ""
@@ -2091,7 +2223,7 @@ msgstr ""
msgid "Disable while typing"
msgstr ""
-#: src/control_center/sections/services.zig
+#: src/control_center/sections/network_details.zig
msgid "Disabled"
msgstr ""
@@ -2115,7 +2247,7 @@ msgstr ""
msgid "Disconnecting Ethernet…"
msgstr ""
-#: src/network/manager.zig
+#: src/control_center/sections/network_vpn.zig
msgid "Disconnecting…"
msgstr ""
@@ -2323,10 +2455,18 @@ msgstr ""
msgid "ETA: {value}s"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "Each bypass entry must be at most 64 characters."
+msgstr ""
+
#: src/control_center/sections/appearance_rows.zig
msgid "Edge glow"
msgstr ""
+#: src/control_center/sections/network.zig
+msgid "Edit settings…"
+msgstr ""
+
#: src/control_center/sections/shortcuts.zig
msgid "Edit shortcut"
msgstr ""
@@ -2419,6 +2559,14 @@ msgstr ""
msgid "Enter a valid CUPS administrator username and password."
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Enter a valid IPv4 address."
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "Enter a valid IPv6 address."
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "Enter a valid full name."
msgstr ""
@@ -2427,10 +2575,30 @@ msgstr ""
msgid "Enter a valid username and full name."
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Enter an IPv4 prefix length from 1 to 32."
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "Enter an IPv6 prefix length from 1 to 128."
+msgstr ""
+
#: src/control_center/sections/printers.zig
msgid "Enter an account permitted to administer the local CUPS server."
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "Enter an http://, https:// or file:// address."
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "Enter at least one DNS server, or choose Automatic."
+msgstr ""
+
+#: src/control_center/sections/network_proxy.zig
+msgid "Enter at least one proxy."
+msgstr ""
+
#: src/files/app_paint.zig
msgid "Enter confirms · Esc cancels"
msgstr ""
@@ -2847,14 +3015,26 @@ msgstr ""
msgid "Force quit…"
msgstr ""
+#: src/control_center/sections/network.zig
+msgid "Forget"
+msgstr ""
+
#: src/control_center/sections/bluetooth.zig
msgid "Forget Device"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Forget connection"
+msgstr ""
+
#: src/control_center/sections/bluetooth.zig
msgid "Forget this device? Pair it again to reconnect."
msgstr ""
+#: src/network/manager_edit.zig
+msgid "Forgetting…"
+msgstr ""
+
#: src/control_center/sections/region.zig
msgid "Formats Preview"
msgstr ""
@@ -2891,7 +3071,7 @@ msgstr ""
msgid "Gap ({n} px)"
msgstr ""
-#: src/control_center/sections/network.zig
+#: src/control_center/sections/network_details.zig
msgid "Gateway"
msgstr ""
@@ -2923,6 +3103,14 @@ msgstr ""
msgid "Groups"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "HTTP proxy"
+msgstr ""
+
+#: src/control_center/sections/network_proxy.zig
+msgid "HTTPS proxy"
+msgstr ""
+
#: src/control_center/sections/network.zig
msgid "Hardware blocked"
msgstr ""
@@ -2975,14 +3163,42 @@ msgstr ""
msgid "INPUT"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "IP address and DNS"
+msgstr ""
+
#: src/control_center/sections/printers_add.zig
msgid "IPP Everywhere / AirPrint"
msgstr ""
-#: src/control_center/sections/network.zig
+#: src/control_center/sections/network_editor.zig
+msgid "IPv4"
+msgstr ""
+
+#: src/control_center/sections/network_details.zig
msgid "IPv4 address"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "IPv4 {v4} · IPv6 {v6}"
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "IPv6"
+msgstr ""
+
+#: src/control_center/sections/network_details.zig
+msgid "IPv6 DNS servers"
+msgstr ""
+
+#: src/control_center/sections/network_details.zig
+msgid "IPv6 address"
+msgstr ""
+
+#: src/control_center/sections/network_details.zig
+msgid "IPv6 gateway"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "Icon bottom padding"
msgstr ""
@@ -3359,10 +3575,14 @@ msgstr ""
msgid "Link permissions cannot be changed"
msgstr ""
-#: src/control_center/sections/network.zig
+#: src/control_center/sections/network_details.zig
msgid "Link speed"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "Link-local only"
+msgstr ""
+
#: src/files/app_torrents.zig
msgid "List"
msgstr ""
@@ -3379,6 +3599,10 @@ msgstr ""
msgid "Loading applications…"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Loading connection settings…"
+msgstr ""
+
#: src/images/app_render.zig
msgid "Loading image…"
msgstr ""
@@ -3459,10 +3683,14 @@ msgstr ""
msgid "Low battery warning"
msgstr ""
-#: src/control_center/sections/network.zig
+#: src/control_center/sections/network_details.zig
msgid "MAC address"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "MTU"
+msgstr ""
+
#: src/control_center/sections/display.zig
msgid "Main display"
msgstr ""
@@ -3487,6 +3715,10 @@ msgstr ""
msgid "Manage…"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "Manual"
+msgstr ""
+
#: src/control_center/sections/printers_details.zig
msgid "Margins (mm): left {left}, right {right}, top {top}, bottom {bottom}"
msgstr ""
@@ -3559,6 +3791,10 @@ msgstr ""
msgid "Metadata…"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Metered connection"
+msgstr ""
+
#: src/control_center/sections/shortcuts.zig
msgid "Mic Mute"
msgstr ""
@@ -3835,10 +4071,18 @@ msgstr ""
msgid "Night light temperature"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "No"
+msgstr ""
+
#: src/control_center/sections/bluetooth.zig
msgid "No Bluetooth adapter found"
msgstr ""
+#: src/control_center/sections/network_vpn.zig
+msgid "No VPN connections. Add one with your VPN's NetworkManager plugin or nmcli; it then appears here."
+msgstr ""
+
#: src/control_center/sections/network.zig
msgid "No Wi-Fi adapter found"
msgstr ""
@@ -4187,6 +4431,10 @@ msgstr ""
msgid "Open File"
msgstr ""
+#: src/editor/app.zig
+msgid "Open Recent"
+msgstr ""
+
#: src/control_center/sections/shortcuts.zig
msgid "Open System Monitor"
msgstr ""
@@ -4255,6 +4503,14 @@ msgstr ""
msgid "Original location unknown: these items have no Trash information"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "Other"
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "Other (unchanged)"
+msgstr ""
+
#: src/files/properties.zig
msgid "Others"
msgstr ""
@@ -4495,6 +4751,10 @@ msgstr ""
msgid "Pointer speed"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "Port"
+msgstr ""
+
#: src/control_center/sections/desktop.zig
msgid "Position"
msgstr ""
@@ -4583,6 +4843,10 @@ msgstr ""
msgid "Poweroff Auto"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Prefix length"
+msgstr ""
+
#: src/session/lock_account.zig
msgid "Press Enter to log in"
msgstr ""
@@ -4783,6 +5047,10 @@ msgstr ""
msgid "Properties — Escape closes"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "Proxy"
+msgstr ""
+
#: src/control_center/sections/shortcuts.zig
msgid "Put the computer to sleep."
msgstr ""
@@ -5237,6 +5505,10 @@ msgstr ""
msgid "Running"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "SOCKS host"
+msgstr ""
+
#: src/control_center/sections/sound.zig
msgid "SOUND"
msgstr ""
@@ -5345,6 +5617,10 @@ msgstr ""
msgid "Saved {name}"
msgstr ""
+#: src/network/manager_edit.zig
+msgid "Saved."
+msgstr ""
+
#: src/control_center/sections/portals.zig
msgid "Saved. Changes apply next time you sign in."
msgstr ""
@@ -5449,6 +5725,10 @@ msgstr ""
msgid "Search devices…"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "Search domains"
+msgstr ""
+
#: src/system_monitor/app.zig
msgid "Search name, PID or user"
msgstr ""
@@ -5541,6 +5821,10 @@ msgstr ""
msgid "Selected process"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Servers, separated by commas"
+msgstr ""
+
#: src/control_center/sections/services.zig
msgid "Service"
msgstr ""
@@ -5597,6 +5881,10 @@ msgstr ""
msgid "Share screen"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "Shared"
+msgstr ""
+
#: src/control_center/sections/appearance.zig
msgid "Sharp"
msgstr ""
@@ -5685,6 +5973,10 @@ msgstr ""
msgid "Sign-in required"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "Signal"
+msgstr ""
+
#: src/session/greeter.zig
msgid "Signing in…"
msgstr ""
@@ -5877,7 +6169,7 @@ msgstr ""
msgid "State unavailable"
msgstr ""
-#: src/control_center/sections/network.zig
+#: src/control_center/sections/network_details.zig
msgid "Status"
msgstr ""
@@ -6017,6 +6309,10 @@ msgstr ""
msgid "System preferences, display, appearance and input"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "System proxy settings need the gsettings-desktop-schemas package."
+msgstr ""
+
#: src/control_center/sections/services.zig
msgid "Systemd is unavailable."
msgstr ""
@@ -6161,6 +6457,18 @@ msgstr ""
msgid "The CUPS client configuration could not be read or is invalid."
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "The IPv4 gateway is not a valid address."
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "The IPv6 gateway is not a valid address."
+msgstr ""
+
+#: src/control_center/sections/network_editor.zig
+msgid "The MTU must be between 576 and 9000, or empty."
+msgstr ""
+
#: src/control_center/sections/appearance_colors.zig
msgid "The RediWM block in gtk.css is incomplete. Repair it before applying colors."
msgstr ""
@@ -6185,6 +6493,10 @@ msgstr ""
msgid "The configured power mode is unavailable."
msgstr ""
+#: src/network/manager_edit.zig
+msgid "The connection request was refused."
+msgstr ""
+
#: src/control_center/sections/printers_tools.zig
msgid "The current printer resolution is unavailable."
msgstr ""
@@ -6653,6 +6965,10 @@ msgstr ""
msgid "Turned off"
msgstr ""
+#: src/control_center/sections/network.zig
+msgid "Turns off Wi-Fi, Bluetooth and other radios."
+msgstr ""
+
#: src/printing/options.zig
msgid "Two-sided printing"
msgstr ""
@@ -6729,10 +7045,14 @@ msgstr ""
msgid "Unknown key"
msgstr ""
-#: src/control_center/sections/services.zig
+#: src/control_center/sections/network.zig
msgid "Unlock"
msgstr ""
+#: src/control_center/sections/network.zig
+msgid "Unlock to change connection settings."
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "Unlock to make account changes."
msgstr ""
@@ -6865,6 +7185,10 @@ msgstr ""
msgid "Uses the main theme. Apply again after changing it; restart apps to see the colors."
msgstr ""
+#: src/control_center/search_index.zig
+msgid "VPN"
+msgstr ""
+
#: src/control_center/sections/desktop.zig
msgid "Vertical Pan"
msgstr ""
@@ -6901,6 +7225,10 @@ msgstr ""
msgid "WPA2 / WPA3 Personal"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "WPA2/WPA3 Personal"
+msgstr ""
+
#: src/control_center/sections/network.zig
msgid "WPA3 Personal"
msgstr ""
@@ -6913,7 +7241,7 @@ msgstr ""
msgid "Waiting for authentication service…"
msgstr ""
-#: src/control_center/sections/services.zig
+#: src/control_center/sections/network.zig
msgid "Waiting for authentication…"
msgstr ""
@@ -7121,6 +7449,10 @@ msgstr ""
msgid "Xwayland: {active}× active. Restart the compositor to apply {pending}×."
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "Yes"
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "You"
msgstr ""
@@ -7141,7 +7473,7 @@ msgstr ""
msgid "You can restore them later from Trash."
msgstr ""
-#: src/control_center/sections/network.zig
+#: src/network/popup.zig
msgid "You're connected to this network"
msgstr ""
@@ -7149,6 +7481,10 @@ msgstr ""
msgid "You're online."
msgstr ""
+#: src/control_center/sections/network.zig
+msgid "Your account is not allowed to change network connections."
+msgstr ""
+
#: src/control_center/sections/printers_details.zig
msgid "Your default printer"
msgstr ""
@@ -7349,10 +7685,18 @@ msgstr ""
msgid "export look"
msgstr ""
+#: src/control_center/sections/network_editor.zig
+msgid "fe80::1"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "files folders application"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "flight radios bluetooth wi-fi rfkill"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "gaps tiling"
msgstr ""
@@ -7369,6 +7713,14 @@ msgstr ""
msgid "hotkeys keybindings bindings terminal screenshot volume brightness workspaces"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "http https socks pac proxy server bypass"
+msgstr ""
+
+#: src/control_center/sections/network_proxy.zig
+msgid "http://wpad.example.com/wpad.dat"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "icons pack"
msgstr ""
@@ -7381,6 +7733,10 @@ msgstr ""
msgid "import pack"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "ipv4 ipv6 static dhcp gateway mtu metered forget saved network"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "keep icons in place"
msgstr ""
@@ -7421,6 +7777,10 @@ msgstr ""
msgid "locale translation"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "localhost, 127.0.0.0/8, ::1"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "logo launcher"
msgstr ""
@@ -7521,6 +7881,10 @@ msgstr ""
msgid "printing cups add queue jobs paper driver label"
msgstr ""
+#: src/control_center/sections/network_proxy.zig
+msgid "proxy.example.com"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "recycle bin"
msgstr ""
@@ -7733,6 +8097,10 @@ msgstr ""
msgid "wired internet adapter"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "wireguard openvpn tunnel private network"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "wireless internet wlan hotspot hidden network"
msgstr ""
@@ -7749,6 +8117,10 @@ msgstr ""
msgid "{action} failed"
msgstr ""
+#: src/control_center/sections/network_details.zig
+msgid "{band} · channel {channel}"
+msgstr ""
+
#: src/control_center/sections/desktop.zig
msgid "{columns} × {rows} · {n} screen total"
msgid_plural "{columns} × {rows} · {n} screens total"
diff --git a/src/Server.zig b/src/Server.zig
index 1f29ca7..283ea83 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -256,6 +256,12 @@ power_profiles: ?*power_profiles_mod.Manager = null,
/// and nested sessions.
app_scopes: ?*@import("session/app_scope.zig").Scopes = null,
network: ?*@import("network/manager.zig").Manager = null,
+/// The system proxy (GSettings), read when the first child is spawned and
+/// replaced when Settings applies a new one.
+proxy: @import("network/proxy.zig").Config = .{},
+proxy_loaded: bool = false,
+/// Which radios were blocked before airplane mode switched them all off.
+rfkill_before: ?@import("platform").rfkill.State = null,
bluetooth: ?*@import("bluetooth.zig").Manager = null,
services: ?*services_mod.Manager = null,
qt_app_colors: bool = false,
@@ -401,6 +407,16 @@ pub fn applyChildEnvWithToken(server: *Server, map: *child_env.Map, token: ?[]co
.cursor_size = server.config.input.cursor_size,
.cursor_path = cursor_theme.childSearchPath(),
});
+ if (!server.greeter_mode) try @import("network/proxy.zig").environment(map, server.systemProxy());
+}
+
+/// The system proxy, read from GSettings the first time it is needed.
+pub fn systemProxy(server: *Server) *@import("network/proxy.zig").Config {
+ if (!server.proxy_loaded) {
+ server.proxy_loaded = true;
+ server.proxy = @import("network/proxy_gsettings.zig").read();
+ }
+ return &server.proxy;
}
// server/xwayland_scale.zig
diff --git a/src/config/theme_pack.zig b/src/config/theme_pack.zig
index 1cbafff..0e94d87 100644
--- a/src/config/theme_pack.zig
+++ b/src/config/theme_pack.zig
@@ -238,6 +238,27 @@ pub fn list(a: A, io: Io, env: std.process.Environ, config_path: []const u8) ![]
return out.toOwnedSlice(a);
}
+/// Packs that still load (so a config naming one keeps its look) but are not
+/// offered in the picker, unless one is the active theme. Uncomment to offer
+/// them again.
+const picker_hidden = [_][]const u8{
+ "redi-mocha",
+ "gold",
+};
+
+/// `list` minus `picker_hidden`; the active pack always stays so the picker
+/// shows what is applied. Lookup (`find`, config load, IPC) is unaffected.
+pub fn pickerList(a: A, io: Io, env: std.process.Environ, config_path: []const u8, active: []const u8) ![]Pack {
+ var out: std.ArrayList(Pack) = .empty;
+ for (try list(a, io, env, config_path)) |p| {
+ const hidden = for (picker_hidden) |id| {
+ if (std.mem.eql(u8, id, p.id)) break true;
+ } else false;
+ if (!hidden or std.mem.eql(u8, p.id, active)) try out.append(a, p);
+ }
+ return out.toOwnedSlice(a);
+}
+
pub fn find(a: A, io: Io, env: std.process.Environ, config_path: []const u8, id: []const u8) !?Pack {
if (!validId(id)) return error.InvalidPackId;
for (try list(a, io, env, config_path)) |p| if (std.mem.eql(u8, p.id, id)) return p;
diff --git a/src/control_center/AGENTS.md b/src/control_center/AGENTS.md
index c8eca64..93196f2 100644
--- a/src/control_center/AGENTS.md
+++ b/src/control_center/AGENTS.md
@@ -77,3 +77,23 @@ helpers (and `panel.ControlCenter`); `sections/` one file per page.
* `sections/users_helper.zig` owns the account helper request and authorization
lifetime; `users.zig` owns the account UI.
+
+## Network page
+
+* **The page is `sections/network*.zig`:** `network.zig` (section state, the
+ overview, Ethernet and Wi-Fi cards, airplane mode), `network_details.zig`
+ (the address rows), `network_editor.zig` (the connection settings editor),
+ `network_vpn.zig`, `network_proxy.zig`, `network_fields.zig` (text fields that
+ keep their text across a rebuild: capture before the arena resets, never read
+ a captured widget afterwards), `network_ui.zig` (small builders).
+* **Writes go through `network/manager_profile.zig`:** read the settings with
+ `GetSettings`, replace only the keys the editor owns, `Update` with the
+ interactive flag. An `Update` without a secret keeps the stored one (verified),
+ so never add secret handling. The Unlock gate is `manager_access.zig`; proxy
+ is per user and ungated.
+* **`i18n.tr` text is not a `std.fmt` format**: use `i18n.fmt` with named
+ placeholders. `panel.translatedLabels` runs at call time, never in a
+ file-level `const`.
+* **Tests never touch the host:** `tests/nm_fake.py` is a fake NetworkManager
+ and polkit on the session bus; the proxy test sets `GSETTINGS_BACKEND=keyfile`
+ with a scratch `XDG_CONFIG_HOME`; nothing may write `/dev/rfkill`.
diff --git a/src/control_center/ControlCenter.zig b/src/control_center/ControlCenter.zig
index 2035863..ff412fb 100644
--- a/src/control_center/ControlCenter.zig
+++ b/src/control_center/ControlCenter.zig
@@ -247,6 +247,7 @@ pub fn destroy(cc: *ControlCenter) void {
cc.input.arena.deinit();
cc.services.deinit();
cc.printers.deinit();
+ if (cc.server.network) |m| m.cancelUnlock();
cc.network.deinit();
if (cc.page == .bluetooth) if (cc.server.bluetooth) |m| m.closed();
cc.bluetooth.deinit();
diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zig
index cc421b6..66c4682 100644
--- a/src/control_center/search_index.zig
+++ b/src/control_center/search_index.zig
@@ -77,6 +77,10 @@ const source_entries = [_]SourceEntry{
.{ .page = .audio, .title = i18n.msg("Audio output device"), .target = "@Audio output", .heading = i18n.msg("Audio output"), .keywords = i18n.msg("speakers headphones sound default") },
.{ .page = .network, .title = i18n.msg("Wi-Fi"), .target = "wifi_card", .keywords = i18n.msg("wireless internet wlan hotspot hidden network") },
.{ .page = .network, .title = i18n.msg("Ethernet"), .target = "ethernet_card", .keywords = i18n.msg("wired internet adapter") },
+ .{ .page = .network, .title = i18n.msg("IP address and DNS"), .target = "ethernet_edit", .keywords = i18n.msg("ipv4 ipv6 static dhcp gateway mtu metered forget saved network") },
+ .{ .page = .network, .title = i18n.msg("Proxy"), .target = "proxy_card", .keywords = i18n.msg("http https socks pac proxy server bypass") },
+ .{ .page = .network, .title = i18n.msg("VPN"), .target = "vpn_card", .keywords = i18n.msg("wireguard openvpn tunnel private network") },
+ .{ .page = .network, .title = i18n.msg("Airplane mode"), .target = "network_airplane_row", .keywords = i18n.msg("flight radios bluetooth wi-fi rfkill") },
.{ .page = .appearance, .title = i18n.msg("Wallpaper"), .target = "@Wallpaper", .heading = i18n.msg("Wallpaper"), .keywords = i18n.msg("background desktop image folder") },
.{ .page = .appearance, .title = i18n.msg("Theme"), .target = "@Theme", .heading = i18n.msg("Theme"), .keywords = i18n.msg("colors colours dark light preset") },
.{ .page = .appearance, .title = i18n.msg("Icon theme"), .target = "icon_theme", .keywords = i18n.msg("icons pack") },
diff --git a/src/control_center/sections/appearance_rows.zig b/src/control_center/sections/appearance_rows.zig
index 1adb82d..808e057 100644
--- a/src/control_center/sections/appearance_rows.zig
+++ b/src/control_center/sections/appearance_rows.zig
@@ -62,7 +62,7 @@ const PxHandler = appearance.PxHandler;
/// The theme and taskbar theme pickers; returns the matched preset.
pub fn buildThemeRows(out: *Section, arena: std.mem.Allocator) ?usize {
- out.presets = theme_presets.list(arena, out.cc.server.io, out.cc.server.environ, out.cc.server.config.path) catch &.{};
+ out.presets = theme_presets.pickerList(arena, out.cc.server.io, out.cc.server.environ, out.cc.server.config.path, out.cc.server.config.theme_base) catch &.{};
var preset_labels: [][]const u8 = &.{};
var matched_index: ?usize = null;
if (arena.alloc([]const u8, out.presets.len)) |labels| {
diff --git a/src/control_center/sections/network.zig b/src/control_center/sections/network.zig
index a9cbb5a..f29994a 100644
--- a/src/control_center/sections/network.zig
+++ b/src/control_center/sections/network.zig
@@ -9,6 +9,20 @@ const gpa = @import("../../main.zig").gpa;
const ui = @import("ui");
const W = ui.layout.Widget;
const Allocator = std.mem.Allocator;
+const widgets = @import("network_ui.zig");
+const text = widgets.text;
+const icon = widgets.icon;
+const group = widgets.group;
+const card = widgets.card;
+const divider = widgets.divider;
+const status = widgets.status;
+const summary = widgets.summary;
+const action = widgets.action;
+const details = @import("network_details.zig");
+const editor = @import("network_editor.zig");
+const proxy_card = @import("network_proxy.zig");
+const vpn_card = @import("network_vpn.zig");
+const rfkill = @import("platform").rfkill;
pub const Section = struct {
arena: std.heap.ArenaAllocator = .init(gpa),
@@ -31,6 +45,14 @@ pub const Section = struct {
focus_requested: bool = false,
message: []const u8 = "",
copied: ?usize = null,
+ edit: editor.State = .{},
+ proxy: proxy_card.State = .{},
+ /// A Wi-Fi network's Forget waits for a second click.
+ forget_armed: bool = false,
+ /// The VPN row whose Remove waits for a second click.
+ vpn_forget: ?usize = null,
+ /// What the last airplane-mode change did, when it failed.
+ airplane_note: []const u8 = "",
pub fn clearForm(s: *Section) void {
s.password.clear();
@@ -45,9 +67,12 @@ pub const Section = struct {
s.name_data = null;
s.focus_name = .{};
s.focus_requested = false;
+ s.forget_armed = false;
}
pub fn deinit(s: *Section) void {
s.clearForm();
+ s.edit.close();
+ s.proxy.deinit();
if (s.password.storage.len != 0) secure.free(s.password.storage);
s.arena.deinit();
}
@@ -58,70 +83,16 @@ pub const Section = struct {
}
};
-fn text(value: []const u8, size: f32, dim: bool) W {
- const t = panel.palette();
- return .{ .kind = .{ .text = .{ .content = value, .font_size = size, .weight = if (dim) 400 else 600, .color = if (dim) t.dim else t.fg } } };
-}
-fn icon(id: ui.layout.IconId, size: f32, accent: bool) W {
- return .{ .kind = .{ .icon = .{ .id = id, .color = if (accent) panel.palette().accent else panel.palette().fg } }, .width = .{ .fixed = size }, .height = .{ .fixed = size } };
-}
-fn group(a: Allocator, direction: ui.layout.Direction, items: []const W) !W {
- return .{ .kind = .container, .direction = direction, .gap = 10, .@"align" = if (direction == .row) .center else .stretch, .width = .{ .percent = 1 }, .children = try a.dupe(W, items) };
-}
-fn card(a: Allocator, items: []const W) !W {
- var w = try group(a, .column, items);
- const t = panel.palette();
- w.kind = .{ .rect = .{ .color = t.app_item, .radius = 9, .border_width = 1, .border_color = t.app_item_border, .relief = t.settings_card_relief } };
- w.padding = ui.layout.Edges.all(16);
- w.gap = 14;
- return w;
-}
-fn divider(vertical: bool) W {
- return .{ .kind = .{ .rect = .{ .color = panel.palette().border_soft } }, .width = if (vertical) .{ .fixed = 1 } else .{ .percent = 1 }, .height = if (vertical) .{ .fixed = 58 } else .{ .fixed = 1 } };
-}
-fn status(a: Allocator, value: []const u8, active: bool) !W {
- var label = text(value, 13, true);
- label.width = .{ .flex = 1 };
- if (active) label.kind.text.color = panel.palette().accent;
- return group(a, .row, &.{
- .{ .kind = .{ .rect = .{ .color = if (active) panel.palette().accent else panel.palette().dim, .radius = 4 } }, .width = .{ .fixed = 7 }, .height = .{ .fixed = 7 } },
- label,
- });
-}
-fn summary(a: Allocator, glyph: ui.layout.IconId, title: []const u8, state: []const u8, description: []const u8, active: bool) !W {
- var labels = try group(a, .column, &.{ text(title, 14, false), try status(a, state, active), text(description, 12, true) });
- labels.width = .{ .flex = 1 };
- labels.gap = 5;
- var w = try group(a, .row, &.{ icon(glyph, 30, active), labels });
- w.width = .{ .flex = 1 };
- return w;
-}
-fn action(cc: *panel.ControlCenter, name: []const u8, value: []const u8, id: usize, callback: *const fn (?*anyopaque, usize) void, disabled: bool) W {
- return .{ .name = name, .kind = .{ .button = .{ .label = value, .owner = cc, .id = id, .on_click = callback, .state = if (disabled) .disabled else .idle } }, .height = .{ .fixed = 34 } };
-}
fn switchWidget(cc: *panel.ControlCenter, name: []const u8, id: usize, on: bool, disabled: bool) W {
return .{ .name = name, .kind = .{ .toggle = .{ .style = .settings, .on = on, .disabled = disabled, .owner = cc, .id = id, .on_change = switched } } };
}
-fn speed(a: Allocator, eth: network.Ethernet) ![]const u8 {
- if (!eth.carrier or eth.speed == 0) return "—";
- return if (eth.speed >= 1000) std.fmt.allocPrint(a, "{d:.1} Gbps", .{@as(f32, @floatFromInt(eth.speed)) / 1000}) else std.fmt.allocPrint(a, "{d} Mbps", .{eth.speed});
-}
-fn chosenEthernet(s: *Section, m: *network.Manager) ?*const network.Ethernet {
- for (m.ethernet[0..m.ethernet_count]) |*eth| if (std.mem.eql(u8, s.ethernet_path.slice(), eth.path.slice())) return eth;
- if (m.ethernet_count == 0) return null;
- var selected: *const network.Ethernet = &m.ethernet[0];
- for (m.ethernet[0..m.ethernet_count]) |*eth| if (eth.connected()) {
- selected = eth;
- break;
- };
- s.ethernet_path = selected.path;
- return selected;
-}
pub fn build(s: *Section, cc: *panel.ControlCenter) void {
const saved_scroll = if (s.list) |list| list.kind.scroll_container else ui.layout.ScrollState{};
if (s.name_field) |field| s.name_data = field.kind.text_input;
s.name_field = null;
+ s.edit.capture();
+ s.proxy.capture();
s.list = null;
_ = s.arena.reset(.retain_capacity);
// A service/radio change closes the form and wipes any entered secret.
@@ -146,7 +117,7 @@ pub fn build(s: *Section, cc: *panel.ControlCenter) void {
fn tree(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
const m = cc.server.network;
const available = if (m) |n| n.available else false;
- const eth = if (m) |n| chosenEthernet(s, n) else null;
+ const eth = if (m) |n| details.chosenEthernet(s, n) else null;
const connected_wifi: ?*const network.Network = if (m) |n| for (n.networks[0..n.count]) |*net| {
if (net.connected) break net;
} else null else null;
@@ -164,7 +135,7 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
else => if (m.?.state >= 50) i18n.tr("Internet access not verified") else i18n.tr("No internet connection"),
};
const wifi_state: []const u8 = if (!available) i18n.tr("Unavailable") else if (!m.?.hardware) i18n.tr("Hardware blocked") else if (!m.?.enabled) i18n.tr("Turned off") else if (m.?.device.len == 0) i18n.tr("No adapter") else if (connected_wifi != null) i18n.tr("Connected") else i18n.tr("Not connected");
- const eth_detail = if (eth) |e| if (e.connected() and e.address.len != 0) try std.fmt.allocPrint(a, "{s} · {s}", .{ try speed(a, e.*), e.address.slice() }) else try a.dupe(u8, e.name.slice()) else i18n.tr("No wired adapter");
+ const eth_detail = if (eth) |e| if (e.connected() and e.link.v4.address.len != 0) try std.fmt.allocPrint(a, "{s} · {s}", .{ try details.speed(a, e.*), details.bareAddress(e.link.v4.address.slice()) }) else try a.dupe(u8, e.name.slice()) else i18n.tr("No wired adapter");
const wifi_detail = if (connected_wifi) |net| try std.fmt.allocPrint(a, "{s} · {s}", .{ network.networkName(net), if (net.strength >= 80) @as([]const u8, i18n.tr("Excellent")) else if (net.strength >= 55) i18n.tr("Good") else i18n.tr("Weak") }) else i18n.tr("Wireless connections");
const overview_width = @as(f32, @floatFromInt(cc.panel_box.width)) - panel.sidebarWidth(cc) - 100;
var description_width: f32 = 0;
@@ -190,7 +161,46 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
var columns = try group(a, if (stacked) .column else .row, &.{ ethernet, wifi });
columns.@"align" = .start;
columns.gap = 16;
- return group(a, .column, &.{ overview, columns });
+ var page: std.ArrayList(W) = .empty;
+ try page.append(a, overview);
+ if (try airplaneRow(cc, a)) |row| try page.append(a, row);
+ if (m) |n| if (try accessRow(cc, a, n)) |row| try page.append(a, row);
+ try page.append(a, columns);
+ if (try editor.build(cc, a)) |edit_card| try page.append(a, edit_card);
+ try page.append(a, try vpn_card.build(cc, a));
+ try page.append(a, try proxy_card.build(cc, a));
+ return group(a, .column, page.items);
+}
+
+/// Airplane mode: every radio blocked by software (`/dev/rfkill`), which
+/// NetworkManager and BlueZ both follow. Hidden where there is no rfkill.
+fn airplaneRow(cc: *panel.ControlCenter, a: Allocator) !?W {
+ const state = rfkill.read();
+ if (state.count == 0) return null;
+ var labels = try group(a, .column, &.{ text(i18n.tr("Airplane mode"), 14, false), text(if (cc.network.airplane_note.len != 0) cc.network.airplane_note else if (state.hardBlocked()) i18n.tr("A hardware switch is blocking a radio.") else i18n.tr("Turns off Wi-Fi, Bluetooth and other radios."), 12, true) });
+ labels.width = .{ .flex = 1 };
+ labels.gap = 4;
+ var toggle = switchWidget(cc, "network_airplane", 2, state.allBlocked(), state.hardBlocked());
+ toggle.kind.toggle.disabled = state.hardBlocked();
+ var row = try card(a, &.{try group(a, .row, &.{ icon(.power, 26, state.allBlocked()), labels, toggle })});
+ row.name = "network_airplane_row";
+ return row;
+}
+
+/// The Unlock prompt, or a line saying what the last change did.
+fn accessRow(cc: *panel.ControlCenter, a: Allocator, m: *const network.Manager) !?W {
+ const locked = m.access == .locked or m.unlocking;
+ const message: []const u8 = if (m.unlocking) i18n.tr("Waiting for authentication…") else if (m.access == .locked) i18n.tr("Unlock to change connection settings.") else if (m.access == .denied) i18n.tr("Your account is not allowed to change network connections.") else if (cc.network.edit.open) "" else m.edit_message;
+ if (message.len == 0) return null;
+ var label = text(message, 13, true);
+ label.width = .{ .flex = 1 };
+ if (!locked) return try group(a, .row, &.{label});
+ var unlock = action(cc, "network_unlock", i18n.tr("Unlock"), 0, unlockClicked, m.unlocking);
+ unlock.kind.button.leading_icon = .lock;
+ unlock.width = .auto;
+ var row = try group(a, .row, &.{ label, unlock });
+ row.name = "network_access";
+ return row;
}
fn ethernetCard(s: *Section, cc: *panel.ControlCenter, a: Allocator, eth: ?*const network.Ethernet) !W {
const m = cc.server.network;
@@ -213,16 +223,15 @@ fn ethernetCard(s: *Section, cc: *panel.ControlCenter, a: Allocator, eth: ?*cons
}
try items.append(a, .{ .name = "ethernet_adapter", .kind = .{ .select = .{ .labels = names, .selected = selected, .owner = cc, .on_change = adapterChanged } }, .width = .{ .percent = 1 }, .height = .{ .fixed = 34 } });
}
- var details = try card(a, &.{
- try detail(cc, a, i18n.tr("Status"), if (eth) |e| e.status() else i18n.tr("Unavailable"), null, if (eth) |e| e.connected() else false, true),
- try detail(cc, a, i18n.tr("Link speed"), if (eth) |e| try speed(a, e.*) else "—", null, false, false),
- try detail(cc, a, i18n.tr("IPv4 address"), if (eth) |e| e.address.slice() else "", 0, false, false),
- try detail(cc, a, i18n.tr("Gateway"), if (eth) |e| e.gateway.slice() else "", 1, false, false),
- try detail(cc, a, i18n.tr("DNS servers"), if (eth) |e| e.dns.slice() else "", 2, false, false),
- try detail(cc, a, i18n.tr("MAC address"), if (eth) |e| e.mac.slice() else "", 3, false, false),
- });
- details.gap = 6;
- try items.append(a, details);
+ var rows = try card(a, try details.ethernetRows(cc, a, eth));
+ rows.gap = 6;
+ try items.append(a, rows);
+ if (eth) |e| {
+ var edit = action(cc, "ethernet_edit", i18n.tr("Edit settings…"), 1, editClicked, ethernetProfile(m, e).len == 0 or cc.network.edit.open);
+ edit.kind.button.variant = .secondary;
+ edit.width = .auto;
+ try items.append(a, edit);
+ }
if (m) |n| {
if (n.wired_message.len > 0) try items.append(a, text(n.wired_message, 12, true));
}
@@ -230,24 +239,12 @@ fn ethernetCard(s: *Section, cc: *panel.ControlCenter, a: Allocator, eth: ?*cons
result.name = "ethernet_card";
return result;
}
-fn detail(cc: *panel.ControlCenter, a: Allocator, title: []const u8, value: []const u8, copy_id: ?usize, active: bool, status_chip: bool) !W {
- var key_label = text(title, 12, true);
- key_label.width = .auto;
- key_label.min_width = 96;
- var val = if (status_chip) try status(a, value, active) else text(if (value.len == 0) "—" else try a.dupe(u8, value), 12, true);
- val.width = .{ .flex = 1 };
- var row = try group(a, .row, &.{ key_label, val });
- row.height = .{ .fixed = 30 };
- if (copy_id) |id| {
- var copy = action(cc, try std.fmt.allocPrint(a, "ethernet_copy_{d}", .{id}), "", id, copyDetail, value.len == 0);
- copy.kind.button.icon = if (cc.network.copied == id) .checkmark else .copy;
- copy.kind.button.variant = .ghost;
- copy.width = .{ .fixed = 26 };
- copy.height = .{ .fixed = 26 };
- row.children = try a.dupe(W, &.{ key_label, val, copy });
- }
- return row;
+fn ethernetProfile(m: ?*network.Manager, e: *const network.Ethernet) []const u8 {
+ const manager = m orelse return "";
+ if (details.profileOf(manager, e.active_connection.slice())) |saved| return saved.path.slice();
+ return e.profile.slice();
}
+
fn wifiCard(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
const m = cc.server.network;
const available = if (m) |n| n.available and n.hardware and n.enabled and n.device.len != 0 else false;
@@ -312,7 +309,14 @@ fn wifiCard(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
}
fn form(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
if (s.selected) |net| {
- if (net.connected) return group(a, .column, &.{text(i18n.tr("You're connected to this network"), 12, true)});
+ if (net.connected) {
+ var shown: std.ArrayList(W) = .empty;
+ try shown.append(a, try wifiActions(s, cc, a, net));
+ try shown.appendSlice(a, try details.wifiRows(cc, a, net));
+ var result = try group(a, .column, shown.items);
+ result.gap = 2;
+ return result;
+ }
if (net.security == .unsupported and net.saved.len == 0) return group(a, .column, &.{text(i18n.tr("Configure this network with a network tool"), 12, true)});
}
var items: std.ArrayList(W) = .empty;
@@ -326,6 +330,7 @@ fn form(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
try items.append(a, .{ .name = "wifi_security", .kind = .{ .select = .{ .labels = panel.translatedLabels(&.{ i18n.msg("WPA2 / WPA3 Personal"), i18n.msg("WPA3 Personal"), i18n.msg("Open") }), .selected = if (s.security == .personal) 0 else if (s.security == .sae) 1 else 2, .owner = cc, .on_change = securityChanged } }, .width = .{ .percent = 1 }, .height = .{ .fixed = 34 } });
}
const net = s.selected orelse network.Network{ .security = s.security };
+ if (!s.hidden and net.saved.len != 0) try items.append(a, try wifiActions(s, cc, a, net));
if (net.security == .personal or net.security == .sae) {
if (s.password.storage.len == 0) {
s.password.storage = try secure.alloc(u8, 128);
@@ -351,11 +356,113 @@ fn form(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
if (s.hidden) s.name_field = &result.children[1];
return result;
}
+/// Edit, Forget and (for the connected network) Disconnect and auto-connect.
+fn wifiActions(s: *Section, cc: *panel.ControlCenter, a: Allocator, net: network.Network) !W {
+ const m = cc.server.network.?;
+ const profile = if (net.connected) m.wifi.profile.slice() else net.saved.slice();
+ const saved = network.savedAt(m, profile);
+ const locked = m.access == .locked or m.access == .denied or m.unlocking or m.edit_busy;
+ var items: std.ArrayList(W) = .empty;
+ if (saved) |sv| {
+ var toggle: W = .{ .name = "wifi_autoconnect", .kind = .{ .checkbox = .{ .label = i18n.tr("Connect automatically"), .checked = sv.autoconnect, .disabled = locked, .owner = cc, .on_change = autoconnectToggled } }, .width = .{ .percent = 1 } };
+ toggle.padding = ui.layout.Edges.xy(0, 6);
+ try items.append(a, toggle);
+ }
+ var buttons: std.ArrayList(W) = .empty;
+ if (net.connected) {
+ var disconnect = action(cc, "wifi_disconnect", i18n.tr("Disconnect"), 0, disconnectClicked, m.busy);
+ disconnect.kind.button.variant = .secondary;
+ try buttons.append(a, disconnect);
+ }
+ if (profile.len != 0) {
+ var edit = action(cc, "wifi_edit", i18n.tr("Edit settings…"), 0, editClicked, s.edit.open);
+ edit.kind.button.variant = .secondary;
+ try buttons.append(a, edit);
+ var forget = action(cc, "wifi_forget", if (s.forget_armed) i18n.tr("Confirm forget") else i18n.tr("Forget"), 0, wifiForgetClicked, locked);
+ forget.kind.button.variant = .ghost;
+ try buttons.append(a, forget);
+ }
+ if (buttons.items.len != 0) {
+ var row = try group(a, .row, buttons.items);
+ row.padding = ui.layout.Edges.xy(0, 6);
+ try items.append(a, row);
+ }
+ return group(a, .column, items.items);
+}
+fn unlockClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (cc.server.network) |m| m.unlock();
+ cc.refresh();
+}
+fn disconnectClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (cc.server.network) |m| m.disconnectWifi();
+}
+/// Edit for the Wi-Fi network in the list (id 0) or the Ethernet adapter (id 1).
+fn editClicked(raw: ?*anyopaque, id: usize) void {
+ const cc = owner(raw);
+ const m = cc.server.network orelse return;
+ if (id == 1) {
+ const eth = details.chosenEthernet(&cc.network, m) orelse return;
+ return editor.open(cc, ethernetProfile(m, eth));
+ }
+ const net = cc.network.selected orelse return;
+ editor.open(cc, if (net.connected) m.wifi.profile.slice() else net.saved.slice());
+}
+fn wifiForgetClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const s = &cc.network;
+ const m = cc.server.network orelse return;
+ const net = s.selected orelse return;
+ if (!s.forget_armed) {
+ s.forget_armed = true;
+ return cc.refresh();
+ }
+ const profile = if (net.connected) m.wifi.profile.slice() else net.saved.slice();
+ m.forget(profile);
+ s.clearForm();
+ cc.refresh();
+}
+fn autoconnectToggled(raw: ?*anyopaque, _: usize, on: bool) void {
+ const cc = owner(raw);
+ const m = cc.server.network orelse return;
+ const net = cc.network.selected orelse return;
+ m.setAutoconnect(if (net.connected) m.wifi.profile.slice() else net.saved.slice(), on);
+}
fn owner(raw: ?*anyopaque) *panel.ControlCenter {
return @ptrCast(@alignCast(raw.?));
}
+/// Turning airplane mode on remembers which radios were already blocked, so
+/// turning it off puts them back as they were rather than waking them all.
+fn airplaneChanged(cc: *panel.ControlCenter, on: bool) void {
+ cc.network.airplane_note = "";
+ const failed = i18n.tr("Could not change the radios. Check access to /dev/rfkill.");
+ if (on) {
+ cc.server.rfkill_before = rfkill.read();
+ rfkill.blockAll(true) catch {
+ cc.server.rfkill_before = null;
+ cc.network.airplane_note = failed;
+ };
+ } else {
+ const before = cc.server.rfkill_before;
+ cc.server.rfkill_before = null;
+ if (before) |snapshot| {
+ if (snapshot.allBlocked()) rfkill.blockAll(false) catch {
+ cc.network.airplane_note = failed;
+ } else rfkill.restore(&snapshot) catch {
+ cc.network.airplane_note = failed;
+ };
+ } else rfkill.blockAll(false) catch {
+ cc.network.airplane_note = failed;
+ };
+ }
+}
fn switched(raw: ?*anyopaque, id: usize, on: bool) void {
const cc = owner(raw);
+ if (id == 2) {
+ airplaneChanged(cc, on);
+ return cc.refresh();
+ }
const m = cc.server.network orelse return;
if (id == 0) {
cc.network.copied = null;
@@ -373,22 +480,6 @@ fn adapterChanged(raw: ?*anyopaque, _: usize, index: usize) void {
cc.network.copied = null;
cc.refresh();
}
-fn copyDetail(raw: ?*anyopaque, id: usize) void {
- const cc = owner(raw);
- const m = cc.server.network orelse return;
- const eth = chosenEthernet(&cc.network, m) orelse return;
- const value = switch (id) {
- 0 => eth.address.slice(),
- 1 => eth.gateway.slice(),
- 2 => eth.dns.slice(),
- 3 => eth.mac.slice(),
- else => return,
- };
- if (value.len == 0) return;
- @import("../../clipboard.zig").copyText(cc.server, value);
- cc.network.copied = id;
- cc.refresh();
-}
fn scanClicked(raw: ?*anyopaque, _: usize) void {
const cc = owner(raw);
if (cc.server.network) |m| m.opened();
diff --git a/src/control_center/sections/network_details.zig b/src/control_center/sections/network_details.zig
new file mode 100644
index 0000000..ba8a21f
--- /dev/null
+++ b/src/control_center/sections/network_details.zig
@@ -0,0 +1,200 @@
+//! The rows that describe a connection (addresses, gateway, DNS, hardware and
+//! link details), for the wired adapter and the Wi-Fi network in use. Each
+//! address row has a copy button.
+
+const i18n = @import("i18n");
+const std = @import("std");
+const panel = @import("../panel.zig");
+const network = @import("../../network/manager.zig");
+const ui = @import("ui");
+const W = ui.layout.Widget;
+const Allocator = std.mem.Allocator;
+const widgets = @import("network_ui.zig");
+const text = widgets.text;
+const group = widgets.group;
+const status = widgets.status;
+const action = widgets.action;
+
+/// What a copy button copies. The value is also the button's id; Wi-Fi
+/// buttons add `wifi_offset`.
+pub const Field = enum(usize) { address4 = 0, gateway4 = 1, dns4 = 2, mac = 3, address6 = 4, gateway6 = 5, dns6 = 6, domains = 7, bssid = 8 };
+pub const wifi_offset: usize = 100;
+
+pub fn speed(a: Allocator, eth: network.Ethernet) ![]const u8 {
+ if (!eth.carrier or eth.speed == 0) return "—";
+ return if (eth.speed >= 1000) std.fmt.allocPrint(a, "{d:.1} Gbps", .{@as(f32, @floatFromInt(eth.speed)) / 1000}) else std.fmt.allocPrint(a, "{d} Mbps", .{eth.speed});
+}
+
+pub fn chosenEthernet(s: anytype, m: *network.Manager) ?*const network.Ethernet {
+ for (m.ethernet[0..m.ethernet_count]) |*eth| if (std.mem.eql(u8, s.ethernet_path.slice(), eth.path.slice())) return eth;
+ if (m.ethernet_count == 0) return null;
+ var selected: *const network.Ethernet = &m.ethernet[0];
+ for (m.ethernet[0..m.ethernet_count]) |*eth| if (eth.connected()) {
+ selected = eth;
+ break;
+ };
+ s.ethernet_path = selected.path;
+ return selected;
+}
+
+pub fn methodLabel(method: network.Method) []const u8 {
+ return switch (method) {
+ .auto => i18n.tr("Automatic"),
+ .manual => i18n.tr("Manual"),
+ .link_local => i18n.tr("Link-local only"),
+ .shared => i18n.tr("Shared"),
+ .disabled => i18n.tr("Disabled"),
+ .other => i18n.tr("Other"),
+ };
+}
+
+pub fn securityLabel(security: network.Security) []const u8 {
+ return switch (security) {
+ .open => i18n.tr("Open"),
+ .personal => i18n.tr("WPA2/WPA3 Personal"),
+ .sae => i18n.tr("WPA3 Personal"),
+ .unsupported => i18n.tr("Other"),
+ };
+}
+
+/// "5 GHz · channel 36" from a frequency in MHz.
+pub fn band(a: Allocator, mhz: u32) ![]const u8 {
+ if (mhz == 0) return "";
+ const ghz: []const u8, const channel: u32 = if (mhz < 3000) .{ "2.4 GHz", if (mhz == 2484) 14 else (mhz -| 2407) / 5 } else if (mhz < 5925) .{ "5 GHz", (mhz -| 5000) / 5 } else .{ "6 GHz", (mhz -| 5950) / 5 };
+ const buffer = try a.alloc(u8, 64);
+ return i18n.fmt(buffer, i18n.tr("{band} · channel {channel}"), .{ .band = ghz, .channel = channel }) catch ghz;
+}
+
+/// The profile an active connection was made from.
+pub fn profileOf(m: *const network.Manager, active: []const u8) ?*const network.Saved {
+ for (m.actives[0..m.active_count]) |act| if (std.mem.eql(u8, act.path.slice(), active)) return network.savedAt(m, act.profile.slice());
+ return null;
+}
+
+fn configuration(a: Allocator, saved: ?*const network.Saved) ![]const u8 {
+ const profile = saved orelse return "";
+ const buffer = try a.alloc(u8, 96);
+ return i18n.fmt(buffer, i18n.tr("IPv4 {v4} · IPv6 {v6}"), .{ .v4 = methodLabel(profile.method4), .v6 = methodLabel(profile.method6) }) catch "";
+}
+
+/// One "title value" row; `copy` adds a copy button when the value is not empty.
+pub fn detail(cc: *panel.ControlCenter, a: Allocator, prefix: []const u8, title: []const u8, value: []const u8, copy: ?Field, active: bool, status_chip: bool) !W {
+ var key_label = text(title, 12, true);
+ key_label.width = .auto;
+ key_label.min_width = 96;
+ var val = if (status_chip) try status(a, value, active) else text(if (value.len == 0) "—" else try a.dupe(u8, value), 12, true);
+ val.width = .{ .flex = 1 };
+ var row = try group(a, .row, &.{ key_label, val });
+ row.height = .{ .fixed = 30 };
+ if (copy) |field| {
+ const id = @intFromEnum(field) + if (std.mem.eql(u8, prefix, "wifi")) wifi_offset else 0;
+ var button = action(cc, try std.fmt.allocPrint(a, "{s}_copy_{d}", .{ prefix, @intFromEnum(field) }), "", id, copyDetail, value.len == 0);
+ button.kind.button.icon = if (cc.network.copied == id) .checkmark else .copy;
+ button.kind.button.variant = .ghost;
+ button.width = .{ .fixed = 26 };
+ button.height = .{ .fixed = 26 };
+ row.children = try a.dupe(W, &.{ key_label, val, button });
+ }
+ return row;
+}
+
+fn linkRows(cc: *panel.ControlCenter, a: Allocator, prefix: []const u8, link: *const network.Link, mac: []const u8, rows: *std.ArrayList(W)) !void {
+ try rows.append(a, try detail(cc, a, prefix, i18n.tr("IPv4 address"), link.v4.address.slice(), .address4, false, false));
+ try rows.append(a, try detail(cc, a, prefix, i18n.tr("Gateway"), link.v4.gateway.slice(), .gateway4, false, false));
+ try rows.append(a, try detail(cc, a, prefix, i18n.tr("DNS servers"), link.v4.dns.slice(), .dns4, false, false));
+ // IPv6 is often absent; only the address is always listed.
+ try rows.append(a, try detail(cc, a, prefix, i18n.tr("IPv6 address"), link.v6.address.slice(), .address6, false, false));
+ if (link.v6.gateway.len != 0) try rows.append(a, try detail(cc, a, prefix, i18n.tr("IPv6 gateway"), link.v6.gateway.slice(), .gateway6, false, false));
+ if (link.v6.dns.len != 0) try rows.append(a, try detail(cc, a, prefix, i18n.tr("IPv6 DNS servers"), link.v6.dns.slice(), .dns6, false, false));
+ var domains: network.Text(256) = link.v4.domains;
+ if (link.v6.domains.len != 0 and domains.len == 0) domains = link.v6.domains;
+ if (domains.len != 0) try rows.append(a, try detail(cc, a, prefix, i18n.tr("Search domains"), domains.slice(), .domains, false, false));
+ try rows.append(a, try detail(cc, a, prefix, i18n.tr("MAC address"), mac, .mac, false, false));
+}
+
+/// The Ethernet card's rows.
+pub fn ethernetRows(cc: *panel.ControlCenter, a: Allocator, eth: ?*const network.Ethernet) ![]W {
+ var rows: std.ArrayList(W) = .empty;
+ const e = eth orelse &network.Ethernet{};
+ try rows.append(a, try detail(cc, a, "ethernet", i18n.tr("Status"), if (eth != null) e.status() else i18n.tr("Unavailable"), null, e.connected(), true));
+ try rows.append(a, try detail(cc, a, "ethernet", i18n.tr("Link speed"), if (eth != null) try speed(a, e.*) else "—", null, false, false));
+ if (e.connected()) {
+ const config = try configuration(a, if (cc.server.network) |m| profileOf(m, e.active_connection.slice()) else null);
+ if (config.len != 0) try rows.append(a, try detail(cc, a, "ethernet", i18n.tr("Configuration"), config, null, false, false));
+ }
+ try linkRows(cc, a, "ethernet", &e.link, e.mac.slice(), &rows);
+ return rows.items;
+}
+
+/// The expanded Wi-Fi row of the connected network.
+pub fn wifiRows(cc: *panel.ControlCenter, a: Allocator, net: network.Network) ![]W {
+ const m = cc.server.network orelse return &.{};
+ var rows: std.ArrayList(W) = .empty;
+ try rows.append(a, try detail(cc, a, "wifi", i18n.tr("Security"), securityLabel(net.security), null, false, false));
+ try rows.append(a, try detail(cc, a, "wifi", i18n.tr("Signal"), try std.fmt.allocPrint(a, "{d}%", .{net.strength}), null, false, false));
+ const channel = try band(a, net.frequency);
+ if (channel.len != 0) try rows.append(a, try detail(cc, a, "wifi", i18n.tr("Band"), channel, null, false, false));
+ if (m.wifi.bitrate != 0) try rows.append(a, try detail(cc, a, "wifi", i18n.tr("Link speed"), try std.fmt.allocPrint(a, "{d} Mbps", .{m.wifi.bitrate / 1000}), null, false, false));
+ if (net.bssid.len != 0) try rows.append(a, try detail(cc, a, "wifi", i18n.tr("Access point"), net.bssid.slice(), .bssid, false, false));
+ const config = try configuration(a, network.savedAt(m, m.wifi.profile.slice()));
+ if (config.len != 0) try rows.append(a, try detail(cc, a, "wifi", i18n.tr("Configuration"), config, null, false, false));
+ try linkRows(cc, a, "wifi", &m.wifi.link, m.wifi.mac.slice(), &rows);
+ return rows.items;
+}
+
+/// The first address of a list, without its "/prefix".
+pub fn bareAddress(value: []const u8) []const u8 {
+ const end = std.mem.indexOfAny(u8, value, "/,") orelse value.len;
+ return value[0..end];
+}
+
+/// Text for a copy button, without the "/prefix" parts that address rows show.
+fn bare(buffer: []u8, value: []const u8) []const u8 {
+ var len: usize = 0;
+ var skipping = false;
+ for (value) |ch| {
+ if (ch == '/') skipping = true else if (ch == ',') skipping = false;
+ if (skipping or len == buffer.len) continue;
+ buffer[len] = ch;
+ len += 1;
+ }
+ return buffer[0..len];
+}
+
+fn copyDetail(raw: ?*anyopaque, id: usize) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(raw.?));
+ const m = cc.server.network orelse return;
+ const wifi = id >= wifi_offset;
+ const field: Field = std.enums.fromInt(Field, if (wifi) id - wifi_offset else id) orelse return;
+ const link: *const network.Link, const mac: []const u8 = if (wifi) .{ &m.wifi.link, m.wifi.mac.slice() } else blk: {
+ const eth = chosenEthernet(&cc.network, m) orelse return;
+ break :blk .{ &eth.link, eth.mac.slice() };
+ };
+ var bssid: []const u8 = "";
+ if (wifi) for (m.networks[0..m.count]) |net| if (net.connected) {
+ bssid = net.bssid.slice();
+ };
+ const value = switch (field) {
+ .address4 => link.v4.address.slice(),
+ .gateway4 => link.v4.gateway.slice(),
+ .dns4 => link.v4.dns.slice(),
+ .mac => mac,
+ .address6 => link.v6.address.slice(),
+ .gateway6 => link.v6.gateway.slice(),
+ .dns6 => link.v6.dns.slice(),
+ .domains => if (link.v4.domains.len != 0) link.v4.domains.slice() else link.v6.domains.slice(),
+ .bssid => bssid,
+ };
+ if (value.len == 0) return;
+ var buffer: [256]u8 = undefined;
+ @import("../../clipboard.zig").copyText(cc.server, bare(&buffer, value));
+ cc.network.copied = id;
+ cc.refresh();
+}
+
+test "copied addresses lose their prefix lengths" {
+ var buffer: [64]u8 = undefined;
+ try std.testing.expectEqualStrings("192.168.1.100", bare(&buffer, "192.168.1.100/24"));
+ try std.testing.expectEqualStrings("10.0.0.2, fe80::1", bare(&buffer, "10.0.0.2/24, fe80::1/64"));
+ try std.testing.expectEqualStrings("1.1.1.1, 1.0.0.1", bare(&buffer, "1.1.1.1, 1.0.0.1"));
+}
diff --git a/src/control_center/sections/network_editor.zig b/src/control_center/sections/network_editor.zig
new file mode 100644
index 0000000..cdddc10
--- /dev/null
+++ b/src/control_center/sections/network_editor.zig
@@ -0,0 +1,325 @@
+//! The connection settings editor: auto-connect, IPv4 and IPv6 addressing, DNS,
+//! MTU and metered for one saved connection. The values are read from the
+//! profile when it opens and written back as a whole by Save (see
+//! `network/manager_profile.zig`); nothing here talks to D-Bus directly.
+
+const i18n = @import("i18n");
+const std = @import("std");
+const panel = @import("../panel.zig");
+const network = @import("../../network/manager.zig");
+const profile_mod = @import("../../network/manager_profile.zig");
+const ui = @import("ui");
+const gpa = @import("../../main.zig").gpa;
+const W = ui.layout.Widget;
+const Allocator = std.mem.Allocator;
+const widgets = @import("network_ui.zig");
+const text = widgets.text;
+const group = widgets.group;
+const card = widgets.card;
+const action = widgets.action;
+
+pub const Field = enum { v4_address, v4_prefix, v4_gateway, v6_address, v6_prefix, v6_gateway, dns, mtu };
+const fields = @import("network_fields.zig");
+
+/// Select indices for a family's method; the last exists only for a method the
+/// editor cannot express (shared), which then stays as it is.
+fn methodLabels(other: bool) []const []const u8 {
+ return if (other) panel.translatedLabels(&.{ i18n.msg("Automatic"), i18n.msg("Manual"), i18n.msg("Link-local only"), i18n.msg("Disabled"), i18n.msg("Other (unchanged)") }) else panel.translatedLabels(&.{ i18n.msg("Automatic"), i18n.msg("Manual"), i18n.msg("Link-local only"), i18n.msg("Disabled") });
+}
+fn dnsLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Automatic"), i18n.msg("Custom") });
+}
+fn meteredLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Automatic"), i18n.msg("Yes"), i18n.msg("No") });
+}
+
+pub const State = struct {
+ open: bool = false,
+ path: network.Path = .{},
+ /// The fields hold the profile at `path` (filled once per opening).
+ filled: bool = false,
+ v4: usize = 0,
+ v6: usize = 0,
+ v4_other: bool = false,
+ v6_other: bool = false,
+ dns_custom: bool = false,
+ metered: usize = 0,
+ autoconnect: bool = true,
+ forget_armed: bool = false,
+ problem: []const u8 = "",
+ fields: fields.Slots(Field) = .{},
+
+ pub fn capture(s: *State) void {
+ s.fields.capture();
+ }
+ pub fn close(s: *State) void {
+ s.fields.release();
+ s.* = .{};
+ }
+};
+
+fn methodIndex(method: network.Method, other: *bool) usize {
+ return switch (method) {
+ .auto => 0,
+ .manual => 1,
+ .link_local => 2,
+ .disabled => 3,
+ .shared, .other => blk: {
+ other.* = true;
+ break :blk 4;
+ },
+ };
+}
+
+fn methodOf(index: usize) network.Method {
+ return switch (index) {
+ 0 => .auto,
+ 1 => .manual,
+ 2 => .link_local,
+ 3 => .disabled,
+ else => .other,
+ };
+}
+
+fn prefixText(buffer: []u8, prefix: u8) []const u8 {
+ return if (prefix == 0) "" else std.fmt.bufPrint(buffer, "{d}", .{prefix}) catch "";
+}
+
+fn fill(s: *State, cc: *panel.ControlCenter, p: *const profile_mod.Profile) void {
+ s.fields.release();
+ s.v4_other = false;
+ s.v6_other = false;
+ s.v4 = methodIndex(p.v4.method, &s.v4_other);
+ s.v6 = methodIndex(p.v6.method, &s.v6_other);
+ var number: [8]u8 = undefined;
+ const first4: profile_mod.Address = if (p.v4.count > 0) p.v4.addresses[0] else .{};
+ const first6: profile_mod.Address = if (p.v6.count > 0) p.v6.addresses[0] else .{};
+ s.fields.set(cc, .v4_address, first4.text.slice(), i18n.tr("192.168.1.20"));
+ s.fields.set(cc, .v4_prefix, prefixText(&number, first4.prefix), i18n.tr("24"));
+ s.fields.set(cc, .v4_gateway, p.v4.gateway.slice(), i18n.tr("192.168.1.1"));
+ s.fields.set(cc, .v6_address, first6.text.slice(), i18n.tr("2001:db8::20"));
+ s.fields.set(cc, .v6_prefix, prefixText(&number, first6.prefix), i18n.tr("64"));
+ s.fields.set(cc, .v6_gateway, p.v6.gateway.slice(), i18n.tr("fe80::1"));
+ var dns: [400]u8 = undefined;
+ const joined = if (p.v4.dns.len != 0 and p.v6.dns.len != 0) std.fmt.bufPrint(&dns, "{s}, {s}", .{ p.v4.dns.slice(), p.v6.dns.slice() }) catch p.v4.dns.slice() else if (p.v4.dns.len != 0) p.v4.dns.slice() else p.v6.dns.slice();
+ s.dns_custom = joined.len != 0;
+ s.fields.set(cc, .dns, joined, i18n.tr("1.1.1.1, 2606:4700:4700::1111"));
+ s.fields.set(cc, .mtu, if (p.mtu == 0) "" else std.fmt.bufPrint(&number, "{d}", .{p.mtu}) catch "", i18n.tr("Automatic"));
+ s.metered = if (p.metered == 1) 1 else if (p.metered == 2) 2 else 0;
+ s.autoconnect = p.autoconnect;
+ s.filled = true;
+}
+
+/// Opens the editor on `path` and asks for its settings.
+pub fn open(cc: *panel.ControlCenter, path: []const u8) void {
+ const s = &cc.network.edit;
+ if (path.len == 0) return;
+ s.close();
+ s.open = true;
+ s.path = network.Path.init(path);
+ if (cc.server.network) |m| m.readProfile(path);
+ cc.refresh();
+}
+
+pub fn close(cc: *panel.ControlCenter) void {
+ cc.network.edit.close();
+ if (cc.server.network) |m| {
+ m.profile = null;
+ m.edit_message = "";
+ }
+ cc.refresh();
+}
+
+fn locked(m: *const network.Manager) bool {
+ return m.access == .locked or m.access == .denied or m.unlocking;
+}
+
+const labeled = fields.labeled;
+
+fn select(cc: *panel.ControlCenter, name: []const u8, labels: []const []const u8, selected: usize, id: usize) W {
+ return .{ .name = name, .kind = .{ .select = .{ .labels = labels, .selected = selected, .owner = cc, .id = id, .on_change = selectChanged } }, .width = .{ .percent = 1 }, .height = .{ .fixed = 34 } };
+}
+
+fn familyRows(s: *State, cc: *panel.ControlCenter, a: Allocator, items: *std.ArrayList(W), v6: bool) !void {
+ const method = if (v6) s.v6 else s.v4;
+ const other = if (v6) s.v6_other else s.v4_other;
+ try items.append(a, try labeled(a, if (v6) i18n.tr("IPv6") else i18n.tr("IPv4"), select(cc, if (v6) "edit_v6_method" else "edit_v4_method", methodLabels(other), method, if (v6) 6 else 4)));
+ if (method != 1) return;
+ var row = try group(a, .row, &.{
+ try s.fields.input(a, if (v6) .v6_address else .v4_address, if (v6) "edit_v6_address" else "edit_v4_address", i18n.tr("Address")),
+ try s.fields.input(a, if (v6) .v6_prefix else .v4_prefix, if (v6) "edit_v6_prefix" else "edit_v4_prefix", i18n.tr("Prefix length")),
+ try s.fields.input(a, if (v6) .v6_gateway else .v4_gateway, if (v6) "edit_v6_gateway" else "edit_v4_gateway", i18n.tr("Gateway")),
+ });
+ row.@"align" = .start;
+ row.children[0].width = .{ .flex = 3 };
+ row.children[1].width = .{ .flex = 1 };
+ row.children[2].width = .{ .flex = 3 };
+ try items.append(a, row);
+}
+
+/// The editor card, or null while closed.
+pub fn build(cc: *panel.ControlCenter, a: Allocator) !?W {
+ const s = &cc.network.edit;
+ if (!s.open) return null;
+ const m = cc.server.network orelse return null;
+ var items: std.ArrayList(W) = .empty;
+ var title = text(i18n.tr("Connection settings"), 20, false);
+ title.width = .{ .flex = 1 };
+ const profile = if (m.profile) |p| if (std.mem.eql(u8, p.path.slice(), s.path.slice())) &m.profile.? else null else null;
+ if (profile) |p| {
+ if (!s.filled) fill(s, cc, p);
+ var name = text(try a.dupe(u8, if (std.unicode.utf8ValidateSlice(p.id.slice())) p.id.slice() else i18n.tr("Connection")), 12, true);
+ name.width = .auto;
+ try items.append(a, try group(a, .row, &.{ title, name }));
+ } else {
+ try items.append(a, title);
+ try items.append(a, text(if (m.edit_message.len != 0) m.edit_message else i18n.tr("Loading connection settings…"), 12, true));
+ var close_button = action(cc, "edit_cancel", i18n.tr("Close"), 0, cancelClicked, false);
+ close_button.width = .auto;
+ try items.append(a, close_button);
+ var empty = try card(a, items.items);
+ empty.name = "edit_card";
+ return empty;
+ }
+ const busy = m.edit_busy or locked(m);
+ try items.append(a, .{ .name = "edit_autoconnect", .kind = .{ .checkbox = .{ .label = i18n.tr("Connect automatically"), .checked = s.autoconnect, .owner = cc, .on_change = autoconnectChanged } }, .width = .{ .percent = 1 } });
+ try familyRows(s, cc, a, &items, false);
+ try familyRows(s, cc, a, &items, true);
+ try items.append(a, try labeled(a, i18n.tr("DNS servers"), select(cc, "edit_dns_mode", dnsLabels(), if (s.dns_custom) 1 else 0, 20)));
+ if (s.dns_custom) try items.append(a, try s.fields.input(a, .dns, "edit_dns", i18n.tr("Servers, separated by commas")));
+ var lower = try group(a, .row, &.{
+ try s.fields.input(a, .mtu, "edit_mtu", i18n.tr("MTU")),
+ try labeled(a, i18n.tr("Metered connection"), select(cc, "edit_metered", meteredLabels(), s.metered, 10)),
+ });
+ lower.@"align" = .start;
+ lower.children[0].width = .{ .flex = 1 };
+ lower.children[1].width = .{ .flex = 1 };
+ try items.append(a, lower);
+ const message = if (s.problem.len != 0) s.problem else m.edit_message;
+ if (message.len != 0) try items.append(a, text(message, 12, true));
+ var forget = action(cc, "edit_forget", if (s.forget_armed) i18n.tr("Confirm forget") else i18n.tr("Forget connection"), 1, forgetClicked, busy);
+ forget.kind.button.variant = .ghost;
+ forget.width = .auto;
+ var save = action(cc, "edit_save", i18n.tr("Save"), 0, saveClicked, busy);
+ save.kind.button.variant = .primary;
+ const cancel = action(cc, "edit_cancel", i18n.tr("Cancel"), 0, cancelClicked, false);
+ var spacer: W = .{ .kind = .container, .width = .{ .flex = 1 } };
+ spacer.height = .{ .fixed = 1 };
+ try items.append(a, try group(a, .row, &.{ forget, spacer, cancel, save }));
+ var result = try card(a, items.items);
+ result.name = "edit_card";
+ return result;
+}
+
+fn owner(raw: ?*anyopaque) *panel.ControlCenter {
+ return @ptrCast(@alignCast(raw.?));
+}
+
+fn selectChanged(raw: ?*anyopaque, id: usize, index: usize) void {
+ const cc = owner(raw);
+ const s = &cc.network.edit;
+ s.fields.capture();
+ switch (id) {
+ 4 => s.v4 = index,
+ 6 => s.v6 = index,
+ 10 => s.metered = index,
+ 20 => s.dns_custom = index == 1,
+ else => {},
+ }
+ s.problem = "";
+ cc.refresh();
+}
+
+fn autoconnectChanged(raw: ?*anyopaque, _: usize, value: bool) void {
+ owner(raw).network.edit.autoconnect = value;
+}
+
+fn cancelClicked(raw: ?*anyopaque, _: usize) void {
+ close(owner(raw));
+}
+
+fn forgetClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const s = &cc.network.edit;
+ const m = cc.server.network orelse return;
+ if (!s.forget_armed) {
+ s.forget_armed = true;
+ cc.refresh();
+ return;
+ }
+ m.forget(s.path.slice());
+ close(cc);
+}
+
+fn parsePrefix(value: []const u8, max: u8) ?u8 {
+ const n = std.fmt.parseInt(u8, std.mem.trim(u8, value, " "), 10) catch return null;
+ return if (n >= 1 and n <= max) n else null;
+}
+
+fn validIp(value: []const u8, v6: bool) bool {
+ const t = std.mem.trim(u8, value, " ");
+ if (v6) _ = std.Io.net.Ip6Address.parse(t, 0) catch return false else _ = std.Io.net.Ip4Address.parse(t, 0) catch return false;
+ return true;
+}
+
+/// Reads one family's fields into `f`, or names the problem.
+fn collectFamily(s: *const State, f: *profile_mod.Family, index: usize, v6: bool) ?[]const u8 {
+ const method = methodOf(index);
+ f.method = method;
+ if (method == .other or method != .manual) return null;
+ const address = std.mem.trim(u8, s.fields.value(if (v6) .v6_address else .v4_address), " ");
+ const prefix = parsePrefix(s.fields.value(if (v6) .v6_prefix else .v4_prefix), if (v6) 128 else 32) orelse return if (v6) i18n.tr("Enter an IPv6 prefix length from 1 to 128.") else i18n.tr("Enter an IPv4 prefix length from 1 to 32.");
+ if (!validIp(address, v6)) return if (v6) i18n.tr("Enter a valid IPv6 address.") else i18n.tr("Enter a valid IPv4 address.");
+ const gateway = std.mem.trim(u8, s.fields.value(if (v6) .v6_gateway else .v4_gateway), " ");
+ if (gateway.len != 0 and !validIp(gateway, v6)) return if (v6) i18n.tr("The IPv6 gateway is not a valid address.") else i18n.tr("The IPv4 gateway is not a valid address.");
+ f.addresses[0] = .{ .text = network.Text(48).init(address), .prefix = prefix };
+ if (f.count == 0) f.count = 1;
+ f.gateway.set(gateway);
+ return null;
+}
+
+fn collectDns(s: *const State, p: *profile_mod.Profile) ?[]const u8 {
+ p.v4.dns = .{};
+ p.v6.dns = .{};
+ p.v4.ignore_auto_dns = false;
+ p.v6.ignore_auto_dns = false;
+ if (!s.dns_custom) return null;
+ var any = false;
+ var items = std.mem.tokenizeAny(u8, s.fields.value(.dns), ", ");
+ while (items.next()) |item| {
+ const v6 = std.mem.indexOfScalar(u8, item, ':') != null;
+ if (!validIp(item, v6)) return i18n.tr("Check the DNS server addresses.");
+ @import("../../network/manager_props.zig").append(if (v6) &p.v6.dns else &p.v4.dns, item);
+ any = true;
+ }
+ if (!any) return i18n.tr("Enter at least one DNS server, or choose Automatic.");
+ p.v4.ignore_auto_dns = true;
+ p.v6.ignore_auto_dns = true;
+ return null;
+}
+
+fn saveClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const s = &cc.network.edit;
+ const m = cc.server.network orelse return;
+ var p = (m.profile orelse return);
+ s.problem = "";
+ p.autoconnect = s.autoconnect;
+ p.metered = if (s.metered == 1) 1 else if (s.metered == 2) 2 else 0;
+ const mtu = std.mem.trim(u8, s.fields.value(.mtu), " ");
+ if (mtu.len == 0) p.mtu = 0 else {
+ const n = std.fmt.parseInt(u32, mtu, 10) catch 0;
+ if (n < 576 or n > 9000) {
+ s.problem = i18n.tr("The MTU must be between 576 and 9000, or empty.");
+ return cc.refresh();
+ }
+ p.mtu = n;
+ }
+ if (collectFamily(s, &p.v4, s.v4, false) orelse collectFamily(s, &p.v6, s.v6, true) orelse collectDns(s, &p)) |problem| {
+ s.problem = problem;
+ return cc.refresh();
+ }
+ m.saveProfile(p);
+ s.forget_armed = false;
+ cc.refresh();
+}
diff --git a/src/control_center/sections/network_fields.zig b/src/control_center/sections/network_fields.zig
new file mode 100644
index 0000000..b0b5f68
--- /dev/null
+++ b/src/control_center/sections/network_fields.zig
@@ -0,0 +1,64 @@
+//! Text fields that keep what was typed across a rebuild of the widget tree.
+//! The tree is rebuilt on every refresh, so a form keeps each field's data
+//! (and a pointer to the field in the current tree) in a `Slots`.
+
+const std = @import("std");
+const panel = @import("../panel.zig");
+const ui = @import("ui");
+const gpa = @import("../../main.zig").gpa;
+const W = ui.layout.Widget;
+const Allocator = std.mem.Allocator;
+const widgets = @import("network_ui.zig");
+
+pub const Slot = struct { data: ?ui.layout.TextInputData = null, widget: ?*W = null };
+
+fn typed(_: ?*anyopaque, _: usize, _: []const u8) void {}
+
+/// A caption above a control.
+pub fn labeled(a: Allocator, title: []const u8, control: W) !W {
+ var column = try widgets.group(a, .column, &.{ widgets.text(title, 12, true), control });
+ column.gap = 6;
+ return column;
+}
+
+pub fn Slots(comptime Field: type) type {
+ return struct {
+ items: [std.enums.values(Field).len]Slot = @splat(.{}),
+
+ const Self = @This();
+
+ /// Keeps what was typed; call before the tree is rebuilt.
+ pub fn capture(self: *Self) void {
+ for (&self.items) |*slot| {
+ if (slot.widget) |w| slot.data = w.kind.text_input;
+ slot.widget = null;
+ }
+ }
+ pub fn release(self: *Self) void {
+ self.capture();
+ for (&self.items) |*slot| {
+ if (slot.data) |data| gpa.free(data.value);
+ slot.* = .{};
+ }
+ }
+ pub fn value(self: *const Self, f: Field) []const u8 {
+ const slot = self.items[@intFromEnum(f)];
+ if (slot.widget) |w| return w.kind.text_input.value;
+ if (slot.data) |d| return d.value;
+ return "";
+ }
+ pub fn set(self: *Self, cc: *panel.ControlCenter, f: Field, content: []const u8, placeholder: []const u8) void {
+ const slot = &self.items[@intFromEnum(f)];
+ if (slot.data) |old| gpa.free(old.value);
+ slot.data = .{ .placeholder = placeholder, .value = gpa.dupe(u8, content) catch @constCast(&[_]u8{}), .owner = cc, .id = @intFromEnum(f), .on_change = typed };
+ }
+ /// A captioned field bound to `f`, for the tree being built.
+ pub fn input(self: *Self, a: Allocator, f: Field, name: []const u8, title: []const u8) !W {
+ const slot = &self.items[@intFromEnum(f)];
+ const control: W = .{ .name = name, .kind = .{ .text_input = slot.data.? }, .width = .{ .percent = 1 }, .height = .{ .fixed = 36 } };
+ const column = try labeled(a, title, control);
+ slot.widget = &column.children[1];
+ return column;
+ }
+ };
+}
diff --git a/src/control_center/sections/network_proxy.zig b/src/control_center/sections/network_proxy.zig
new file mode 100644
index 0000000..1edee93
--- /dev/null
+++ b/src/control_center/sections/network_proxy.zig
@@ -0,0 +1,180 @@
+//! The Proxy card: Off, Manual (HTTP, HTTPS, SOCKS and a bypass list) or an
+//! automatic configuration script. Applying stores the setting in GSettings
+//! (what GTK/GIO apps and Firefox's "system proxy" read) and updates the
+//! environment of apps RediWM starts from then on. It is per user and never
+//! needs authentication.
+
+const i18n = @import("i18n");
+const std = @import("std");
+const panel = @import("../panel.zig");
+const proxy = @import("../../network/proxy.zig");
+const gsettings = @import("../../network/proxy_gsettings.zig");
+const ui = @import("ui");
+const W = ui.layout.Widget;
+const Allocator = std.mem.Allocator;
+const widgets = @import("network_ui.zig");
+const fields = @import("network_fields.zig");
+const text = widgets.text;
+const group = widgets.group;
+const card = widgets.card;
+const action = widgets.action;
+
+pub const Field = enum { http_host, http_port, https_host, https_port, socks_host, socks_port, ignore, pac };
+
+pub const State = struct {
+ loaded: bool = false,
+ available: bool = true,
+ mode: usize = 0,
+ problem: []const u8 = "",
+ message: []const u8 = "",
+ fields: fields.Slots(Field) = .{},
+
+ pub fn capture(s: *State) void {
+ s.fields.capture();
+ }
+ pub fn deinit(s: *State) void {
+ s.fields.release();
+ }
+};
+
+fn modeLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Off"), i18n.msg("Manual"), i18n.msg("Automatic") });
+}
+
+fn fill(cc: *panel.ControlCenter) void {
+ const s = &cc.network.proxy;
+ const config = cc.server.systemProxy();
+ s.fields.release();
+ s.available = gsettings.available();
+ s.mode = @intFromEnum(config.mode);
+ var port: [8]u8 = undefined;
+ const pairs = [_]struct { host: Field, port: Field, endpoint: proxy.Endpoint }{
+ .{ .host = .http_host, .port = .http_port, .endpoint = config.http },
+ .{ .host = .https_host, .port = .https_port, .endpoint = config.https },
+ .{ .host = .socks_host, .port = .socks_port, .endpoint = config.socks },
+ };
+ for (pairs) |pair| {
+ s.fields.set(cc, pair.host, pair.endpoint.host.slice(), i18n.tr("proxy.example.com"));
+ s.fields.set(cc, pair.port, if (pair.endpoint.port == 0) "" else std.fmt.bufPrint(&port, "{d}", .{pair.endpoint.port}) catch "", i18n.tr("8080"));
+ }
+ s.fields.set(cc, .ignore, config.ignore.slice(), i18n.tr("localhost, 127.0.0.0/8, ::1"));
+ s.fields.set(cc, .pac, config.pac.slice(), i18n.tr("http://wpad.example.com/wpad.dat"));
+ s.loaded = true;
+}
+
+fn endpointRow(s: *State, a: Allocator, host: Field, port: Field, name: []const u8, title: []const u8) !W {
+ var host_name: [32]u8 = undefined;
+ var port_name: [32]u8 = undefined;
+ var row = try group(a, .row, &.{
+ try s.fields.input(a, host, try a.dupe(u8, std.fmt.bufPrint(&host_name, "proxy_{s}_host", .{name}) catch name), title),
+ try s.fields.input(a, port, try a.dupe(u8, std.fmt.bufPrint(&port_name, "proxy_{s}_port", .{name}) catch name), i18n.tr("Port")),
+ });
+ row.@"align" = .start;
+ row.children[0].width = .{ .flex = 4 };
+ row.children[1].width = .{ .flex = 1 };
+ return row;
+}
+
+pub fn build(cc: *panel.ControlCenter, a: Allocator) !W {
+ const s = &cc.network.proxy;
+ if (!s.loaded) fill(cc);
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, text(i18n.tr("Proxy"), 20, false));
+ try items.append(a, text(i18n.tr("Apps that follow the system proxy use this. A manual proxy is also given to apps started from RediWM."), 12, true));
+ if (!s.available) {
+ try items.append(a, text(i18n.tr("System proxy settings need the gsettings-desktop-schemas package."), 12, true));
+ var unavailable = try card(a, items.items);
+ unavailable.name = "proxy_card";
+ return unavailable;
+ }
+ const mode = fields.labeled(a, i18n.tr("Proxy"), .{ .name = "proxy_mode", .kind = .{ .select = .{ .labels = modeLabels(), .selected = s.mode, .owner = cc, .on_change = modeChanged } }, .width = .{ .percent = 1 }, .height = .{ .fixed = 34 } });
+ try items.append(a, try mode);
+ if (s.mode == @intFromEnum(proxy.Mode.manual)) {
+ try items.append(a, try endpointRow(s, a, .http_host, .http_port, "http", i18n.tr("HTTP proxy")));
+ try items.append(a, try endpointRow(s, a, .https_host, .https_port, "https", i18n.tr("HTTPS proxy")));
+ try items.append(a, try endpointRow(s, a, .socks_host, .socks_port, "socks", i18n.tr("SOCKS host")));
+ try items.append(a, try s.fields.input(a, .ignore, "proxy_ignore", i18n.tr("Bypass the proxy for")));
+ } else if (s.mode == @intFromEnum(proxy.Mode.auto)) {
+ try items.append(a, try s.fields.input(a, .pac, "proxy_pac", i18n.tr("Configuration URL")));
+ }
+ const message = if (s.problem.len != 0) s.problem else s.message;
+ if (message.len != 0) try items.append(a, text(message, 12, true));
+ var apply = action(cc, "proxy_apply", i18n.tr("Apply"), 0, applyClicked, false);
+ apply.kind.button.variant = .primary;
+ apply.width = .auto;
+ var row = try group(a, .row, &.{apply});
+ row.justify = .end;
+ try items.append(a, row);
+ var result = try card(a, items.items);
+ result.name = "proxy_card";
+ return result;
+}
+
+fn owner(raw: ?*anyopaque) *panel.ControlCenter {
+ return @ptrCast(@alignCast(raw.?));
+}
+
+fn modeChanged(raw: ?*anyopaque, _: usize, index: usize) void {
+ const cc = owner(raw);
+ const s = &cc.network.proxy;
+ s.fields.capture();
+ s.mode = index;
+ s.problem = "";
+ s.message = "";
+ cc.refresh();
+}
+
+fn endpoint(s: *const State, host: Field, port: Field, out: *proxy.Endpoint, label: []const u8) ?[]const u8 {
+ const h = std.mem.trim(u8, s.fields.value(host), " ");
+ const p = std.mem.trim(u8, s.fields.value(port), " ");
+ out.* = .{};
+ // The schema's default port is filled in even when there is no host: no host, no proxy.
+ if (h.len == 0) return null;
+ if (!proxy.validHost(h)) return label;
+ out.port = proxy.parsePort(p) orelse return label;
+ out.host.set(h);
+ return null;
+}
+
+fn applyClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const s = &cc.network.proxy;
+ var config = cc.server.systemProxy().*;
+ s.problem = "";
+ s.message = "";
+ config.mode = @enumFromInt(s.mode);
+ switch (config.mode) {
+ .off => {},
+ .manual => {
+ if (endpoint(s, .http_host, .http_port, &config.http, i18n.tr("Check the HTTP proxy host and port (1–65535).")) orelse
+ endpoint(s, .https_host, .https_port, &config.https, i18n.tr("Check the HTTPS proxy host and port (1–65535).")) orelse
+ endpoint(s, .socks_host, .socks_port, &config.socks, i18n.tr("Check the SOCKS host and port (1–65535).")) orelse
+ (if (!config.http.set() and !config.https.set() and !config.socks.set()) i18n.tr("Enter at least one proxy.") else null)) |problem|
+ {
+ s.problem = problem;
+ return cc.refresh();
+ }
+ config.ignore = .{};
+ var entries = proxy.ignoreEntries(s.fields.value(.ignore));
+ while (entries.next()) |entry| {
+ if (entry.len > 64) {
+ s.problem = i18n.tr("Each bypass entry must be at most 64 characters.");
+ return cc.refresh();
+ }
+ @import("../../network/manager_props.zig").append(&config.ignore, entry);
+ }
+ },
+ .auto => {
+ const url = std.mem.trim(u8, s.fields.value(.pac), " ");
+ if (!proxy.validPac(url)) {
+ s.problem = i18n.tr("Enter an http://, https:// or file:// address.");
+ return cc.refresh();
+ }
+ config.pac.set(url);
+ },
+ }
+ cc.server.proxy = config;
+ gsettings.writeAsync(config);
+ s.message = if (config.mode == .manual) i18n.tr("Applied. Apps you start from now on use this proxy.") else i18n.tr("Applied.");
+ cc.refresh();
+}
diff --git a/src/control_center/sections/network_ui.zig b/src/control_center/sections/network_ui.zig
new file mode 100644
index 0000000..611a740
--- /dev/null
+++ b/src/control_center/sections/network_ui.zig
@@ -0,0 +1,49 @@
+//! Small widget builders shared by the Network page's cards.
+const i18n = @import("i18n");
+const std = @import("std");
+const panel = @import("../panel.zig");
+const ui = @import("ui");
+const W = ui.layout.Widget;
+const Allocator = std.mem.Allocator;
+
+pub fn text(value: []const u8, size: f32, dim: bool) W {
+ const t = panel.palette();
+ return .{ .kind = .{ .text = .{ .content = value, .font_size = size, .weight = if (dim) 400 else 600, .color = if (dim) t.dim else t.fg } } };
+}
+pub fn icon(id: ui.layout.IconId, size: f32, accent: bool) W {
+ return .{ .kind = .{ .icon = .{ .id = id, .color = if (accent) panel.palette().accent else panel.palette().fg } }, .width = .{ .fixed = size }, .height = .{ .fixed = size } };
+}
+pub fn group(a: Allocator, direction: ui.layout.Direction, items: []const W) !W {
+ return .{ .kind = .container, .direction = direction, .gap = 10, .@"align" = if (direction == .row) .center else .stretch, .width = .{ .percent = 1 }, .children = try a.dupe(W, items) };
+}
+pub fn card(a: Allocator, items: []const W) !W {
+ var w = try group(a, .column, items);
+ const t = panel.palette();
+ w.kind = .{ .rect = .{ .color = t.app_item, .radius = 9, .border_width = 1, .border_color = t.app_item_border, .relief = t.settings_card_relief } };
+ w.padding = ui.layout.Edges.all(16);
+ w.gap = 14;
+ return w;
+}
+pub fn divider(vertical: bool) W {
+ return .{ .kind = .{ .rect = .{ .color = panel.palette().border_soft } }, .width = if (vertical) .{ .fixed = 1 } else .{ .percent = 1 }, .height = if (vertical) .{ .fixed = 58 } else .{ .fixed = 1 } };
+}
+pub fn status(a: Allocator, value: []const u8, active: bool) !W {
+ var label = text(value, 13, true);
+ label.width = .{ .flex = 1 };
+ if (active) label.kind.text.color = panel.palette().accent;
+ return group(a, .row, &.{
+ .{ .kind = .{ .rect = .{ .color = if (active) panel.palette().accent else panel.palette().dim, .radius = 4 } }, .width = .{ .fixed = 7 }, .height = .{ .fixed = 7 } },
+ label,
+ });
+}
+pub fn summary(a: Allocator, glyph: ui.layout.IconId, title: []const u8, state: []const u8, description: []const u8, active: bool) !W {
+ var labels = try group(a, .column, &.{ text(title, 14, false), try status(a, state, active), text(description, 12, true) });
+ labels.width = .{ .flex = 1 };
+ labels.gap = 5;
+ var w = try group(a, .row, &.{ icon(glyph, 30, active), labels });
+ w.width = .{ .flex = 1 };
+ return w;
+}
+pub fn action(cc: *panel.ControlCenter, name: []const u8, value: []const u8, id: usize, callback: *const fn (?*anyopaque, usize) void, disabled: bool) W {
+ return .{ .name = name, .kind = .{ .button = .{ .label = value, .owner = cc, .id = id, .on_click = callback, .state = if (disabled) .disabled else .idle } }, .height = .{ .fixed = 34 } };
+}
diff --git a/src/control_center/sections/network_vpn.zig b/src/control_center/sections/network_vpn.zig
new file mode 100644
index 0000000..351628d
--- /dev/null
+++ b/src/control_center/sections/network_vpn.zig
@@ -0,0 +1,112 @@
+//! The VPN card: NetworkManager's VPN and WireGuard connections, with connect,
+//! disconnect and remove. Importing a configuration is left to the VPN's own
+//! NetworkManager plugin or `nmcli`. A connection that needs a password at
+//! connect time has no secret agent here to ask for it: it must keep its
+//! credentials in the profile.
+
+const i18n = @import("i18n");
+const std = @import("std");
+const panel = @import("../panel.zig");
+const network = @import("../../network/manager.zig");
+const ui = @import("ui");
+const W = ui.layout.Widget;
+const Allocator = std.mem.Allocator;
+const widgets = @import("network_ui.zig");
+const text = widgets.text;
+const icon = widgets.icon;
+const group = widgets.group;
+const card = widgets.card;
+const action = widgets.action;
+
+const max_rows = 32;
+const Entry = struct { profile: network.Path = .{}, name: network.Text(64) = .{}, active: network.Path = .{}, state: u32 = 0 };
+
+pub fn isVpn(kind: []const u8) bool {
+ return std.mem.eql(u8, kind, "vpn") or std.mem.eql(u8, kind, "wireguard");
+}
+
+fn collect(m: *const network.Manager, out: *[max_rows]Entry) usize {
+ var count: usize = 0;
+ for (m.saved[0..m.saved_count]) |saved| {
+ if (!saved.loaded or !isVpn(saved.kind.slice()) or count == max_rows) continue;
+ out[count] = .{ .profile = saved.path, .name = saved.id };
+ for (m.actives[0..m.active_count]) |act| if (std.mem.eql(u8, act.profile.slice(), saved.path.slice())) {
+ out[count].active = act.path;
+ out[count].state = act.state;
+ };
+ count += 1;
+ }
+ return count;
+}
+
+fn stateLabel(state: u32, active: bool) []const u8 {
+ if (!active) return i18n.tr("Not connected");
+ return switch (state) {
+ 1 => i18n.tr("Connecting…"),
+ 2 => i18n.tr("Connected"),
+ 3 => i18n.tr("Disconnecting…"),
+ else => i18n.tr("Not connected"),
+ };
+}
+
+pub fn build(cc: *panel.ControlCenter, a: Allocator) !W {
+ const m = cc.server.network;
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, text(i18n.tr("VPN"), 20, false));
+ var entries: [max_rows]Entry = undefined;
+ const count = if (m) |n| collect(n, &entries) else 0;
+ const locked = if (m) |n| n.access == .locked or n.access == .denied or n.unlocking or n.edit_busy else true;
+ for (entries[0..count], 0..) |entry, i| {
+ const connected = entry.active.len != 0 and entry.state == 2;
+ var labels = try group(a, .column, &.{ text(try a.dupe(u8, entry.name.slice()), 15, false), text(stateLabel(entry.state, entry.active.len != 0), 12, true) });
+ labels.width = .{ .flex = 1 };
+ labels.gap = 5;
+ const busy = entry.active.len != 0 and entry.state != 2;
+ var toggle = action(cc, try std.fmt.allocPrint(a, "vpn_toggle_{d}", .{i}), if (entry.active.len != 0) i18n.tr("Disconnect") else i18n.tr("Connect"), i, toggleClicked, busy);
+ toggle.kind.button.variant = if (entry.active.len != 0) .secondary else .primary;
+ toggle.width = .auto;
+ var remove = action(cc, try std.fmt.allocPrint(a, "vpn_remove_{d}", .{i}), if (cc.network.vpn_forget == i) i18n.tr("Confirm remove") else i18n.tr("Remove"), i, removeClicked, locked or entry.active.len != 0);
+ remove.kind.button.variant = .ghost;
+ remove.width = .auto;
+ var row = try group(a, .row, &.{ icon(.lock, 24, connected), labels, toggle, remove });
+ row.name = try std.fmt.allocPrint(a, "vpn_row_{d}", .{i});
+ row.padding = ui.layout.Edges.xy(10, 8);
+ try items.append(a, row);
+ }
+ if (count == 0) try items.append(a, text(i18n.tr("No VPN connections. Add one with your VPN's NetworkManager plugin or nmcli; it then appears here."), 12, true));
+ var result = try card(a, items.items);
+ result.name = "vpn_card";
+ return result;
+}
+
+fn owner(raw: ?*anyopaque) *panel.ControlCenter {
+ return @ptrCast(@alignCast(raw.?));
+}
+
+fn entryAt(cc: *panel.ControlCenter, index: usize, out: *[max_rows]Entry) ?Entry {
+ const m = cc.server.network orelse return null;
+ const count = collect(m, out);
+ return if (index < count) out[index] else null;
+}
+
+fn toggleClicked(raw: ?*anyopaque, index: usize) void {
+ const cc = owner(raw);
+ var entries: [max_rows]Entry = undefined;
+ const entry = entryAt(cc, index, &entries) orelse return;
+ const m = cc.server.network.?;
+ if (entry.active.len != 0) m.deactivate(entry.active.slice()) else m.activate(entry.profile.slice());
+ cc.refresh();
+}
+
+fn removeClicked(raw: ?*anyopaque, index: usize) void {
+ const cc = owner(raw);
+ var entries: [max_rows]Entry = undefined;
+ const entry = entryAt(cc, index, &entries) orelse return;
+ if (cc.network.vpn_forget != index) {
+ cc.network.vpn_forget = index;
+ return cc.refresh();
+ }
+ cc.network.vpn_forget = null;
+ cc.server.network.?.forget(entry.profile.slice());
+ cc.refresh();
+}
diff --git a/src/editor/AGENTS.md b/src/editor/AGENTS.md
index 0de5e15..ebdd55b 100644
--- a/src/editor/AGENTS.md
+++ b/src/editor/AGENTS.md
@@ -100,3 +100,17 @@
strip the user scrolled away. Go through `tabX`/`tabAt`/`tabCloseBox`; a tab
at the edge is partly drawn (the strip is clipped), so hit tests must stay
inside `tabRight()`. Names are ellipsized; the unsaved dot never is.
+
+## Open Recent
+
+* **The history is Files' (`files/recent.zig`, `recently-used.xbel`), not an
+ editor file.** `app_recent.zig` rereads it each time the menu opens (text
+ files that still exist, newest 10) and `recordRecent` adds to it after a
+ load or save, on a short-lived thread (it rewrites the whole file, which
+ GLib loads and saves). GLib drops a bookmark with no application entry, so
+ tests that seed the file need one. The editor links glib for this.
+* **The submenu is drawn by the editor beside the menu** (`menu_selected` stays
+ on the Open Recent row, `sub_selected` is its own highlight; keyboard focus is
+ in the submenu whenever `sub_selected` is set). It overlaps the menu's edge so
+ the pointer never crosses a gap. Menu rows are indexed by `Action`: the test
+ helper `menu_action` in `tests/editor.py` mirrors the row and separator order.
diff --git a/src/editor/app.zig b/src/editor/app.zig
index cafeff0..240451b 100644
--- a/src/editor/app.zig
+++ b/src/editor/app.zig
@@ -25,6 +25,7 @@ const app_search = @import("app_search.zig");
const app_edit = @import("app_edit.zig");
const app_controls = @import("app_controls.zig");
const app_drafts = @import("app_drafts.zig");
+const app_recent = @import("app_recent.zig");
const drafts = @import("drafts.zig");
const a = std.heap.c_allocator;
pub const top: f64 = 40;
@@ -41,8 +42,10 @@ 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, 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 Action = enum { new, open, open_recent, save, save_as, find, replace, wrap };
+pub const labels = [_]i18n.Message{ i18n.msg("New"), i18n.msg("Open"), i18n.msg("Open Recent"), i18n.msg("Save"), i18n.msg("Save As"), i18n.msg("Find"), i18n.msg("Replace"), i18n.msg("Word Wrap") };
+/// The menu row whose submenu lists the recent files.
+pub const recent_row = @intFromEnum(Action.open_recent);
pub const Tab = struct {
id: usize,
doc: Document = .{},
@@ -101,6 +104,12 @@ pub const App = struct {
menu_open: bool = false,
menu_selected: ?usize = null,
menu_anchor: f64 = 0,
+ /// The Open Recent submenu is showing; `sub_selected` is its highlighted row.
+ sub_open: bool = false,
+ sub_selected: ?usize = null,
+ /// Paths for that submenu, newest first, reread each time the menu opens.
+ recent: std.ArrayList([:0]u8) = .empty,
+ environ: std.process.Environ = .empty,
has_titlebar: bool = true,
dragging: bool = false,
drag_word: ?[2]usize = null,
@@ -144,6 +153,7 @@ pub const App = struct {
}
pub fn deinit(self: *App) void {
self.deinitDrafts();
+ self.deinitRecent();
if (self.operation) |job| job.deinit();
for (self.tabs.items) |t| t.deinit();
self.tabs.deinit(a);
@@ -246,6 +256,12 @@ pub const App = struct {
pub const finishClose = app_files.finishClose;
pub const act = app_files.act;
+ pub const refreshRecent = app_recent.refreshRecent;
+ pub const recordRecent = app_recent.recordRecent;
+ pub const clearRecent = app_recent.clearRecent;
+ pub const recentEnabled = app_recent.enabled;
+ pub const deinitRecent = app_recent.deinitRecent;
+
pub const openDrafts = app_drafts.openDrafts;
pub const stepDrafts = app_drafts.stepDrafts;
pub const draftTimeout = app_drafts.draftTimeout;
diff --git a/src/editor/app_files.zig b/src/editor/app_files.zig
index 3b7a2ca..399b532 100644
--- a/src/editor/app_files.zig
+++ b/src/editor/app_files.zig
@@ -82,6 +82,7 @@ pub fn sync(self: *App) void {
t.scroll_x = 0;
t.measure = .{};
self.notice_len = 0;
+ self.recordRecent(job.path);
self.changed();
},
.save => if (self.findTab(job.tab_id)) |i| {
@@ -92,6 +93,7 @@ pub fn sync(self: *App) void {
t.stamp = job.stamp;
if (t.doc.revision == job.revision) t.doc.saved = t.doc.position;
self.message(tr("Saved"));
+ self.recordRecent(job.path);
self.changed();
if (self.close_tab == t.id and !t.doc.modified()) self.finishClose();
},
@@ -179,6 +181,7 @@ pub fn act(self: *App, action: Action) void {
switch (action) {
.new => self.newTab() catch |err| self.failure(err),
.open => self.choose(false),
+ .open_recent => {}, // the menu opens its submenu; nothing to run
.save => self.save(false),
.save_as => self.save(true),
.find => {
diff --git a/src/editor/app_input.zig b/src/editor/app_input.zig
index 1e0fc12..4bd9f6d 100644
--- a/src/editor/app_input.zig
+++ b/src/editor/app_input.zig
@@ -13,6 +13,7 @@ const App = app_mod.App;
const top = app_mod.top;
const status_h = app_mod.status_h;
const labels = app_mod.labels;
+const recent = @import("app_recent.zig");
/// The byte offset nearest a point given relative to the text origin.
pub fn indexAt(self: *App, x: f64, y: f64) usize {
@@ -27,11 +28,28 @@ pub fn handleMotion(self: *App, x: f64, y: f64) void {
self.py = y;
if (self.proximityChanged(old_x, old_y, x, y)) self.glow_dirty = true;
if (self.menu_open) {
+ if (recent.hit(self, x, y)) |row| {
+ if (self.sub_selected != row or self.menu_selected != app_mod.recent_row) self.dirty = true;
+ self.sub_selected = row;
+ self.menu_selected = app_mod.recent_row;
+ return;
+ }
+ // Inside the submenu but between rows: keep what is open.
+ if (recent.contains(self, x, y)) return;
const hovered = self.menuHit(x, y);
- if (hovered != self.menu_selected) {
+ if (hovered != self.menu_selected or self.sub_selected != null) {
self.menu_selected = hovered;
+ self.sub_selected = null;
self.dirty = true;
}
+ // Moving along the menu opens the submenu on its row and closes it on any other.
+ if (hovered) |row| {
+ const want = row == app_mod.recent_row and self.recentEnabled();
+ if (want != self.sub_open) {
+ self.sub_open = want;
+ self.dirty = true;
+ }
+ }
return;
}
if (self.dragging) {
@@ -76,7 +94,18 @@ pub fn handleButton(self: *App, code: u32, pressed: bool) void {
return;
}
if (self.menu_open) {
+ if (recent.hit(self, self.px, self.py)) |row| {
+ recent.activate(self, row);
+ return;
+ }
+ if (recent.contains(self, self.px, self.py)) return;
const row = self.menuHit(self.px, self.py);
+ if (row == app_mod.recent_row) {
+ // Opening a submenu is not choosing a command: the menu stays.
+ if (self.recentEnabled()) self.sub_open = true;
+ self.dirty = true;
+ return;
+ }
self.dismissMenu();
if (row) |i| self.act(@enumFromInt(i));
return;
@@ -195,19 +224,47 @@ pub fn handleKey(self: *App, sym: u32, utf8: []const u8) void {
self.toggleMenu(self.menu_anchor);
return;
}
+ if (self.menu_open and self.sub_selected != null) {
+ // Keyboard focus is in the Open Recent submenu.
+ const count = recent.rowCount(self);
+ const at = self.sub_selected.?;
+ switch (sym) {
+ c.XKB_KEY_Escape, c.XKB_KEY_Left, c.XKB_KEY_Right => {
+ self.sub_selected = null;
+ self.sub_open = false;
+ },
+ c.XKB_KEY_Down => self.sub_selected = (at + 1) % count,
+ c.XKB_KEY_Up => self.sub_selected = (at + count - 1) % count,
+ c.XKB_KEY_Home => self.sub_selected = 0,
+ c.XKB_KEY_End => self.sub_selected = count - 1,
+ c.XKB_KEY_Return, c.XKB_KEY_KP_Enter, c.XKB_KEY_space => recent.activate(self, at),
+ else => {},
+ }
+ self.dirty = true;
+ return;
+ }
if (self.menu_open) {
+ // Moving by keyboard never opens the submenu; Right/Left/Enter on its row does.
switch (sym) {
c.XKB_KEY_Escape => self.dismissMenu(),
c.XKB_KEY_Down => self.menu_selected = if (self.menu_selected) |i| (i + 1) % labels.len else 0,
c.XKB_KEY_Up => self.menu_selected = if (self.menu_selected) |i| (i + labels.len - 1) % labels.len else labels.len - 1,
c.XKB_KEY_Home => self.menu_selected = 0,
c.XKB_KEY_End => self.menu_selected = labels.len - 1,
- c.XKB_KEY_Return, c.XKB_KEY_KP_Enter, c.XKB_KEY_space => if (self.menu_selected) |i| {
- self.dismissMenu();
- self.act(@enumFromInt(i));
+ c.XKB_KEY_Return, c.XKB_KEY_KP_Enter, c.XKB_KEY_space, c.XKB_KEY_Right, c.XKB_KEY_Left => if (self.menu_selected) |i| {
+ if (i == app_mod.recent_row) {
+ if (self.recentEnabled()) {
+ self.sub_open = true;
+ self.sub_selected = 0;
+ }
+ } else if (sym != c.XKB_KEY_Right and sym != c.XKB_KEY_Left) {
+ self.dismissMenu();
+ self.act(@enumFromInt(i));
+ }
},
else => {},
}
+ if (self.menu_selected != app_mod.recent_row and self.sub_selected == null) self.sub_open = false;
self.dirty = true;
if (!self.ctrl) return;
self.dismissMenu();
diff --git a/src/editor/app_paint.zig b/src/editor/app_paint.zig
index e5a1740..d78118c 100644
--- a/src/editor/app_paint.zig
+++ b/src/editor/app_paint.zig
@@ -22,6 +22,7 @@ const App = app_mod.App;
const top = app_mod.top;
const status_h = app_mod.status_h;
const labels = app_mod.labels;
+const recent_row = app_mod.recent_row;
const Tab = app_mod.Tab;
const fill = app_mod.fill;
const drawEllipsis = @import("../files/app_draw.zig").drawEllipsis;
@@ -136,6 +137,8 @@ pub fn tabRight(self: *const App) f64 {
pub fn dismissMenu(self: *App) void {
if (!self.menu_open) return;
self.menu_open = false;
+ self.sub_open = false;
+ self.sub_selected = null;
self.dirty = true;
}
@@ -145,6 +148,9 @@ pub fn toggleMenu(self: *App, anchor: f64) void {
self.menu_anchor = anchor;
self.menu_open = !self.menu_open;
self.menu_selected = null;
+ self.sub_open = false;
+ self.sub_selected = null;
+ if (self.menu_open) self.refreshRecent();
self.dirty = true;
}
@@ -160,7 +166,7 @@ pub fn menuBox(self: *const App) menu.Rect {
pub fn menuRow(self: *const App, i: usize) menu.Rect {
const box = self.menuBox();
- const separators: usize = @as(usize, if (i >= 2) 1 else 0) + @as(usize, if (i >= 4) 1 else 0);
+ const separators: usize = @as(usize, if (i >= 3) 1 else 0) + @as(usize, if (i >= 5) 1 else 0);
return .{ .x = box.x + menu.padding, .y = box.y + @as(f64, @floatFromInt(menu.padding + i * menu.row_height + separators * menu.separator_space)), .w = box.w - 2 * menu.padding, .h = menu.row_height };
}
@@ -172,15 +178,26 @@ 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, .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 };
+ const icons = [_]?IconId{ .plus, .open, .clock, .save, .save, .search, .search, if (self.wrap) .checkmark else null };
+ const hints = [_]?[]const u8{ "CTRL+N", "CTRL+O", null, "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],
.icon = icons[i],
.selected = self.menu_selected == i,
- .separator = i == 2 or i == 4,
+ .separator = i == 3 or i == 5,
+ .disabled = i == recent_row and !self.recentEnabled(),
}, true);
+ // The chevron says the row opens a submenu.
+ const row = self.menuRow(recent_row);
+ if (ui.Layer.begin(cr, .{ .x = @floatCast(row.x + row.w - 24), .y = @floatCast(row.y + (row.h - 14) / 2), .w = 14, .h = 14 })) |l| {
+ var layer = l;
+ var color = theme.global.app_fg orelse theme.global.window_fg;
+ color[3] *= if (self.recentEnabled()) 0.6 else 0.25;
+ layer.renderer.drawIcon(0, 0, 14, 14, .{ .id = .chevron_right, .color = color });
+ layer.finish();
+ }
+ if (self.sub_open) @import("app_recent.zig").paint(self, cr);
}
pub fn paintButton(self: *App, cr: *c.cairo_t, r: field.Rect, label: []const u8, selected: bool) void {
diff --git a/src/editor/app_recent.zig b/src/editor/app_recent.zig
new file mode 100644
index 0000000..40672ae
--- /dev/null
+++ b/src/editor/app_recent.zig
@@ -0,0 +1,229 @@
+//! Open Recent: the freedesktop recent-file history Files also uses
+//! (`files/recent.zig`), read when the menu opens and added to after a file is
+//! loaded or saved. The submenu hangs beside the "Open Recent" row.
+
+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 menu = @import("ui").context_menu;
+const history = @import("../files/recent.zig");
+const draw = @import("../files/app_draw.zig");
+const formats = @import("formats.zig");
+const app_mod = @import("app.zig");
+const App = app_mod.App;
+const a = std.heap.c_allocator;
+
+/// Files listed in the submenu.
+pub const shown = 10;
+/// Candidates examined (text files that still exist) before giving up.
+const scan_limit = 80;
+pub const width: f64 = 340;
+
+fn newer(_: void, x: history.Entry, y: history.Entry) bool {
+ return x.opened > y.opened;
+}
+
+fn clearList(self: *App) void {
+ for (self.recent.items) |path| a.free(path);
+ self.recent.clearRetainingCapacity();
+}
+
+pub fn deinitRecent(self: *App) void {
+ clearList(self);
+ self.recent.deinit(a);
+}
+
+/// Rereads the history, newest first, keeping only text files that exist.
+pub fn refreshRecent(self: *App) void {
+ clearList(self);
+ const entries = history.read(a, self.io, self.environ) catch return;
+ defer {
+ for (entries) |entry| a.free(entry.path);
+ a.free(entries);
+ }
+ std.mem.sort(history.Entry, entries, {}, newer);
+ var scanned: usize = 0;
+ for (entries) |entry| {
+ if (self.recent.items.len >= shown or scanned >= scan_limit) break;
+ scanned += 1;
+ if (!formats.candidate(entry.path)) continue;
+ var st: c.struct_stat = undefined;
+ if (c.stat(entry.path.ptr, &st) != 0 or st.st_mode & c.S_IFMT != c.S_IFREG) continue;
+ const owned = a.dupeSentinel(u8, entry.path, 0) catch return;
+ self.recent.append(a, owned) catch {
+ a.free(owned);
+ return;
+ };
+ }
+}
+
+const Record = struct {
+ path: [:0]u8,
+ io: std.Io,
+ environ: std.process.Environ,
+};
+
+fn recordWork(job: *Record) void {
+ defer {
+ a.free(job.path);
+ a.destroy(job);
+ }
+ history.recordBy(a, job.io, job.environ, job.path, "RediWM Editor", "rediwm-editor %f") catch {};
+}
+
+/// Adds `path` to the shared history. The file is rewritten on a short-lived
+/// thread, so a large history never stalls typing.
+pub fn recordRecent(self: *App, path: []const u8) void {
+ const owned = a.dupeSentinel(u8, path, 0) catch return;
+ var absolute = owned;
+ if (!std.fs.path.isAbsolute(path)) {
+ // A path given on the command line is relative to where we started.
+ defer a.free(owned);
+ var buffer: [std.fs.max_path_bytes]u8 = undefined;
+ const resolved = c.realpath(owned.ptr, &buffer) orelse return;
+ absolute = a.dupeSentinel(u8, std.mem.span(resolved), 0) catch return;
+ }
+ const job = a.create(Record) catch {
+ a.free(absolute);
+ return;
+ };
+ job.* = .{ .path = absolute, .io = self.io, .environ = self.environ };
+ const thread = std.Thread.spawn(.{}, recordWork, .{job}) catch {
+ a.free(job.path);
+ a.destroy(job);
+ return;
+ };
+ thread.detach();
+}
+
+/// Rows of the submenu: each recent file, then Clear Recent.
+pub fn rowCount(self: *const App) usize {
+ return self.recent.items.len + 1;
+}
+
+pub fn enabled(self: *const App) bool {
+ return self.recent.items.len > 0;
+}
+
+pub fn box(self: *const App) menu.Rect {
+ const main = self.menuBox();
+ const height: f64 = @floatFromInt(rowCount(self) * menu.row_height + 2 * menu.padding + menu.separator_space);
+ const window_w: f64 = @floatFromInt(self.w);
+ const window_h: f64 = @floatFromInt(self.h);
+ const w = @min(width, @max(menu.width, window_w - 12));
+ // Beside the menu, on the side that has room, overlapping its edge so the
+ // pointer never crosses a gap.
+ const left = main.x + 4 - w;
+ const x = if (left >= 6) left else @min(main.x + main.w - 4, @max(6, window_w - w - 6));
+ const row = self.menuRow(app_mod.recent_row);
+ return .{
+ .x = x,
+ .y = std.math.clamp(row.y - menu.padding, 6, @max(6, window_h - height - 6)),
+ .w = w,
+ .h = height,
+ };
+}
+
+pub fn rowBox(self: *const App, i: usize) menu.Rect {
+ const b = box(self);
+ const separator: f64 = if (i >= self.recent.items.len) menu.separator_space else 0;
+ return .{
+ .x = b.x + menu.padding,
+ .y = b.y + @as(f64, @floatFromInt(menu.padding + i * menu.row_height)) + separator,
+ .w = b.w - 2 * menu.padding,
+ .h = menu.row_height,
+ };
+}
+
+pub fn hit(self: *const App, x: f64, y: f64) ?usize {
+ if (!self.sub_open) return null;
+ for (0..rowCount(self)) |i| if (rowBox(self, i).contains(x, y)) return i;
+ return null;
+}
+
+pub fn contains(self: *const App, x: f64, y: f64) bool {
+ return self.sub_open and box(self).contains(x, y);
+}
+
+/// Opens (or, for the last row, clears) the chosen entry.
+pub fn activate(self: *App, i: usize) void {
+ if (i < self.recent.items.len) {
+ const path = a.dupe(u8, self.recent.items[i]) catch return;
+ defer a.free(path);
+ self.dismissMenu();
+ self.open(path);
+ } else {
+ self.dismissMenu();
+ self.clearRecent();
+ }
+}
+
+/// Forgets the text files in the shared history (the kind Open Recent lists),
+/// which also takes them out of Files' Recent view; other kinds stay.
+pub fn clearRecent(self: *App) void {
+ clearList(self);
+ self.sub_open = false;
+ self.dirty = true;
+ const job = a.create(Forget) catch return;
+ job.* = .{ .io = self.io, .environ = self.environ };
+ const thread = std.Thread.spawn(.{}, forgetWork, .{job}) catch {
+ a.destroy(job);
+ return;
+ };
+ thread.detach();
+}
+
+const Forget = struct { io: std.Io, environ: std.process.Environ };
+
+fn forgetWork(job: *Forget) void {
+ defer a.destroy(job);
+ history.forgetWhere(a, job.io, job.environ, &formats.candidate) catch {};
+}
+
+fn homeRelative(buffer: []u8, home: ?[]const u8, dir: []const u8) []const u8 {
+ if (home) |h| if (h.len > 1 and std.mem.startsWith(u8, dir, h) and (dir.len == h.len or dir[h.len] == '/')) {
+ return std.fmt.bufPrint(buffer, "~{s}", .{dir[h.len..]}) catch dir;
+ };
+ return dir;
+}
+
+pub fn paint(self: *App, cr: *c.cairo_t) void {
+ const b = box(self);
+ menu.frame(cr, b, true);
+ const fg = theme.global.app_fg orelse theme.global.window_fg;
+ const text_size = ui.textSize();
+ const metrics = ui.fontMetrics(cr, text_size);
+ var scratch: [std.fs.max_path_bytes]u8 = undefined;
+ for (self.recent.items, 0..) |path, i| {
+ const r = rowBox(self, i);
+ menu.row(cr, r, .{ .label = "", .icon = .edit, .selected = self.sub_selected == i }, true);
+ const base = std.fs.path.basename(path);
+ const name = if (std.unicode.utf8ValidateSlice(base)) base else tr("Text file");
+ const baseline = r.y + (r.h + metrics.ascent - metrics.descent) / 2;
+ const room = r.w - 36 - 12;
+ const dir = homeRelative(&scratch, self.environ.getPosix("HOME"), std.fs.path.dirname(path) orelse "");
+ const dir_ok = std.unicode.utf8ValidateSlice(dir);
+ const name_room = if (dir_ok and dir.len > 0) @min(ui.measureText(cr, name, text_size, false), room * 0.6) else room;
+ ui.setSource(cr, fg);
+ draw.drawEllipsis(cr, name, r.x + 36, baseline, name_room, text_size, false);
+ if (dir_ok and dir.len > 0) {
+ var dim = fg;
+ dim[3] *= 0.4;
+ ui.setSource(cr, dim);
+ const dir_room = room - name_room - 10;
+ if (dir_room > 24) {
+ const w = @min(ui.measureText(cr, dir, ui.statusSize(), false), dir_room);
+ draw.drawEllipsis(cr, dir, r.x + r.w - 12 - w, r.y + (r.h + metrics.ascent - metrics.descent) / 2, dir_room, ui.statusSize(), false);
+ }
+ }
+ }
+ menu.row(cr, rowBox(self, self.recent.items.len), .{
+ .label = tr("Clear Recent"),
+ .icon = .close,
+ .selected = self.sub_selected == self.recent.items.len,
+ .separator = true,
+ }, true);
+}
diff --git a/src/editor/main.zig b/src/editor/main.zig
index 513b521..d4af7f9 100644
--- a/src/editor/main.zig
+++ b/src/editor/main.zig
@@ -197,6 +197,7 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impo
const display = try wl.Display.connect(null);
defer display.disconnect();
var self = Client{ .display = display, .app = try app_mod.App.init(init.io) };
+ self.app.environ = init.minimal.environ;
self.app.openDrafts(init.minimal.environ);
for (paths) |path| self.app.open(path);
self.ime = .{ .app = &self.app };
diff --git a/src/files/recent.zig b/src/files/recent.zig
index 5624181..d868077 100644
--- a/src/files/recent.zig
+++ b/src/files/recent.zig
@@ -25,6 +25,7 @@ extern fn g_bookmark_file_set_mime_type(bookmark: *anyopaque, uri: [*:0]const u8
extern fn g_bookmark_file_add_application(bookmark: *anyopaque, uri: [*:0]const u8, name: [*:0]const u8, exec: [*:0]const u8) void;
extern fn g_bookmark_file_to_data(bookmark: *anyopaque, length: *usize, err: ?*?*anyopaque) ?[*:0]u8;
extern fn g_file_set_contents_full(filename: [*:0]const u8, data: [*]const u8, length: isize, flags: c_int, mode: c_int, err: ?*?*anyopaque) c_int;
+extern fn g_bookmark_file_remove_item(bookmark: *anyopaque, uri: [*:0]const u8, err: ?*?*anyopaque) c_int;
extern fn g_strfreev(strings: [*:null]?[*:0]u8) void;
extern fn g_free(memory: ?*anyopaque) void;
@@ -81,6 +82,11 @@ pub fn read(a: Allocator, io: std.Io, env: std.process.Environ) ![]Entry {
/// Re-read before writing so another window's latest entries are preserved.
pub fn record(a: Allocator, io: std.Io, env: std.process.Environ, opened: []const u8) !void {
+ return recordBy(a, io, env, opened, "RediWM Files", "rediwm-files %f");
+}
+
+/// `record` on behalf of another application (the name and command GLib stores).
+pub fn recordBy(a: Allocator, io: std.Io, env: std.process.Environ, opened: []const u8, app_name: [:0]const u8, exec: [:0]const u8) !void {
if (!std.fs.path.isAbsolute(opened)) return;
const filename = try path(a, env);
defer a.free(filename);
@@ -93,11 +99,15 @@ pub fn record(a: Allocator, io: std.Io, env: std.process.Environ, opened: []cons
const mime = try a.dupeSentinel(u8, mime_db.guess(opened), 0);
defer a.free(mime);
g_bookmark_file_set_mime_type(bookmark, uri, mime);
- g_bookmark_file_add_application(bookmark, uri, "RediWM Files", "rediwm-files %f");
+ g_bookmark_file_add_application(bookmark, uri, app_name, exec);
const now = g_date_time_new_now_utc();
defer g_date_time_unref(now);
g_bookmark_file_set_visited_date_time(bookmark, uri, now);
g_bookmark_file_set_modified_date_time(bookmark, uri, now);
+ try write(io, filename, bookmark);
+}
+
+fn write(io: std.Io, filename: [:0]const u8, bookmark: *anyopaque) !void {
try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(filename).?);
var length: usize = 0;
const data = g_bookmark_file_to_data(bookmark, &length, null) orelse return error.WriteHistoryFailed;
@@ -105,3 +115,22 @@ pub fn record(a: Allocator, io: std.Io, env: std.process.Environ, opened: []cons
// G_FILE_SET_CONTENTS_CONSISTENT: atomic replacement, private on first creation.
if (g_file_set_contents_full(filename, data, @intCast(length), 1, 0o600, null) == 0) return error.WriteHistoryFailed;
}
+
+/// Drops every local entry `drop` accepts, re-reading first like `record`.
+pub fn forgetWhere(a: Allocator, io: std.Io, env: std.process.Environ, drop: *const fn ([]const u8) bool) !void {
+ const filename = try path(a, env);
+ defer a.free(filename);
+ const bookmark = try load(a, io, filename);
+ defer g_bookmark_file_free(bookmark);
+ var count: usize = 0;
+ const uris = g_bookmark_file_get_uris(bookmark, &count);
+ defer g_strfreev(uris);
+ var removed = false;
+ for (uris[0..count]) |maybe_uri| {
+ const uri = maybe_uri orelse continue;
+ const decoded = clipboard.decodeLocalPath(a, std.mem.span(uri)) catch continue;
+ defer a.free(decoded);
+ if (drop(decoded) and g_bookmark_file_remove_item(bookmark, uri, null) != 0) removed = true;
+ }
+ if (removed) try write(io, filename, bookmark);
+}
diff --git a/src/gl_vendor.zig b/src/gl_vendor.zig
new file mode 100644
index 0000000..e06a8f3
--- /dev/null
+++ b/src/gl_vendor.zig
@@ -0,0 +1,139 @@
+//! glvnd's libEGL loads every vendor library it finds, in file-name order, at
+//! the first EGL call. The NVIDIA one drags in tens of MiB of driver
+//! (`libnvidia-eglcore`, `libnvidia-gpucomp`) that is read from disk and
+//! relocated even when there is no NVIDIA GPU to use it: on the live medium
+//! that is ~90 MiB of squashfs reads and 0.6-1.2 s of every boot, and the
+//! greeter and the session both pay it.
+//!
+//! So when the machine has no NVIDIA GPU, EGL is told to use every vendor file
+//! except NVIDIA's. The decision needs positive proof of absence: unreadable
+//! sysfs, a loaded `nvidia` module or `/dev/nvidiactl` all leave glvnd alone.
+//! A GPU plugged in after start (Thunderbolt eGPU) is not seen by this process
+//! until the compositor restarts.
+const std = @import("std");
+const Io = std.Io;
+
+const log = std.log.scoped(.gl_vendor);
+
+extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
+
+const filenames_env = "__EGL_VENDOR_LIBRARY_FILENAMES";
+const dirs_env = "__EGL_VENDOR_LIBRARY_DIRS";
+/// glvnd's default search path, /etc first: a file there hides one of the same
+/// name below it.
+const search_dirs = [_][]const u8{ "/etc/glvnd/egl_vendor.d", "/usr/share/glvnd/egl_vendor.d" };
+const max_vendors = 16;
+const nvidia_pci_vendor = "0x10de";
+
+pub const Vendor = struct {
+ dir: []const u8,
+ name: []const u8,
+ nvidia: bool,
+};
+
+/// Call before anything can reach EGL. An environment the user or a packager
+/// set (either variable) is never overridden.
+pub fn skipAbsentNvidia(io: Io, environ: std.process.Environ) void {
+ if (environ.getPosix(filenames_env) != null or environ.getPosix(dirs_env) != null) return;
+ if (nvidiaMayBePresent(io)) return;
+
+ var names: [max_vendors][64]u8 = undefined;
+ var vendors: [max_vendors]Vendor = undefined;
+ var count: usize = 0;
+ for (search_dirs) |dir_path| {
+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch continue;
+ defer dir.close(io);
+ var it = dir.iterate();
+ while (it.next(io) catch return) |entry| {
+ if (!std.mem.endsWith(u8, entry.name, ".json") or entry.name.len > names[0].len) continue;
+ if (hidden(vendors[0..count], entry.name)) continue;
+ // More vendors than any machine has: not a layout to second-guess.
+ if (count == max_vendors) return;
+ var contents: [2048]u8 = undefined;
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = std.fmt.bufPrint(&path_buf, "{s}/{s}", .{ dir_path, entry.name }) catch return;
+ const text = Io.Dir.cwd().readFile(io, path, &contents) catch return;
+ @memcpy(names[count][0..entry.name.len], entry.name);
+ vendors[count] = .{
+ .dir = dir_path,
+ .name = names[count][0..entry.name.len],
+ // By name too: a vendor file can be a stub with no library path.
+ .nvidia = std.ascii.findIgnoreCase(entry.name, "nvidia") != null or
+ std.ascii.findIgnoreCase(text, "nvidia") != null,
+ };
+ count += 1;
+ }
+ }
+
+ var list: [max_vendors * 128]u8 = undefined;
+ const joined = withoutNvidia(vendors[0..count], &list) orelse return;
+ if (setenv(filenames_env, joined.ptr, 0) != 0) return;
+ log.info("no NVIDIA GPU: EGL vendors limited to {s}", .{joined});
+}
+
+fn hidden(seen: []const Vendor, name: []const u8) bool {
+ for (seen) |v| if (std.mem.eql(u8, v.name, name)) return true;
+ return false;
+}
+
+/// The vendor files glvnd should use, `dir/name:dir/name` in file-name order
+/// as glvnd would load them; null when that would not differ from its own
+/// search (no NVIDIA file) or would leave it nothing.
+pub fn withoutNvidia(vendors: []Vendor, buf: []u8) ?[:0]const u8 {
+ var any_nvidia = false;
+ for (vendors) |v| any_nvidia = any_nvidia or v.nvidia;
+ if (!any_nvidia) return null;
+ std.mem.sort(Vendor, vendors, {}, struct {
+ fn less(_: void, a: Vendor, b: Vendor) bool {
+ return std.mem.lessThan(u8, a.name, b.name);
+ }
+ }.less);
+ var len: usize = 0;
+ for (vendors) |v| {
+ if (v.nvidia) continue;
+ const sep: []const u8 = if (len == 0) "" else ":";
+ const piece = std.fmt.bufPrint(buf[len..], "{s}{s}/{s}", .{ sep, v.dir, v.name }) catch return null;
+ len += piece.len;
+ }
+ if (len == 0 or len >= buf.len) return null;
+ buf[len] = 0;
+ return buf[0..len :0];
+}
+
+/// False only when the PCI bus was read completely and has no NVIDIA device.
+fn nvidiaMayBePresent(io: Io) bool {
+ const cwd = Io.Dir.cwd();
+ // The driver may be loaded for a device that is not on the PCI bus.
+ for ([_][]const u8{ "/sys/module/nvidia", "/dev/nvidiactl" }) |path| {
+ if (cwd.access(io, path, .{})) |_| return true else |_| {}
+ }
+ var dir = cwd.openDir(io, "/sys/bus/pci/devices", .{ .iterate = true }) catch return true;
+ defer dir.close(io);
+ var it = dir.iterate();
+ while (it.next(io) catch return true) |entry| {
+ var path_buf: [128]u8 = undefined;
+ const path = std.fmt.bufPrint(&path_buf, "{s}/vendor", .{entry.name}) catch return true;
+ var buf: [16]u8 = undefined;
+ const text = dir.readFile(io, path, &buf) catch return true;
+ if (std.mem.eql(u8, std.mem.trim(u8, text, " \r\n"), nvidia_pci_vendor)) return true;
+ }
+ return false;
+}
+
+test "withoutNvidia keeps glvnd's order and drops NVIDIA's vendor" {
+ var buf: [256]u8 = undefined;
+ var v = [_]Vendor{
+ .{ .dir = "/usr/share/glvnd/egl_vendor.d", .name = "50_mesa.json", .nvidia = false },
+ .{ .dir = "/usr/share/glvnd/egl_vendor.d", .name = "10_nvidia.json", .nvidia = true },
+ .{ .dir = "/etc/glvnd/egl_vendor.d", .name = "20_other.json", .nvidia = false },
+ };
+ try std.testing.expectEqualStrings(
+ "/etc/glvnd/egl_vendor.d/20_other.json:/usr/share/glvnd/egl_vendor.d/50_mesa.json",
+ withoutNvidia(&v, &buf).?,
+ );
+ // Nothing to drop, or nothing left: glvnd's own search stays in charge.
+ var mesa_only = [_]Vendor{.{ .dir = "/usr/share/glvnd/egl_vendor.d", .name = "50_mesa.json", .nvidia = false }};
+ try std.testing.expect(withoutNvidia(&mesa_only, &buf) == null);
+ var nvidia_only = [_]Vendor{.{ .dir = "/usr/share/glvnd/egl_vendor.d", .name = "10_nvidia.json", .nvidia = true }};
+ try std.testing.expect(withoutNvidia(&nvidia_only, &buf) == null);
+}
diff --git a/src/main.zig b/src/main.zig
index 1391d16..9f49df1 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -90,6 +90,9 @@ fn start(init: std.process.Init) !bool {
// cache in ~/.cache. So every program it builds is a full compile on each
// start (tens of ms): it builds only those it draws with (server/setup.zig).
if (greeter and setenv("MESA_SHADER_CACHE_DISABLE", "true", 0) != 0) return error.OutOfMemory;
+ // glvnd would otherwise load the NVIDIA EGL stack on every machine, GPU or
+ // not. Must run before the backend (and so EGL) starts.
+ @import("gl_vendor.zig").skipAbsentNvidia(init.io, init.minimal.environ);
var server: Server = undefined;
try server.init(
diff --git a/src/network/manager.zig b/src/network/manager.zig
index 34a57f2..3f5f042 100644
--- a/src/network/manager.zig
+++ b/src/network/manager.zig
@@ -15,6 +15,8 @@ pub const wireless = nm ++ ".Device.Wireless";
pub const wired = nm ++ ".Device.Wired";
pub const device_iface = nm ++ ".Device";
pub const ip4_iface = nm ++ ".IP4Config";
+pub const ip6_iface = nm ++ ".IP6Config";
+pub const active_iface = nm ++ ".Connection.Active";
pub const ap_iface = nm ++ ".AccessPoint";
pub const settings_iface = nm ++ ".Settings.Connection";
pub const properties = "org.freedesktop.DBus.Properties";
@@ -23,27 +25,18 @@ const Presence = @import("config").taskbar_items.Presence;
const manager_bus = @import("manager_bus.zig");
const manager_objects = @import("manager_objects.zig");
const manager_actions = @import("manager_actions.zig");
+const manager_access = @import("manager_access.zig");
+const manager_edit = @import("manager_edit.zig");
+pub const Profile = @import("manager_profile.zig").Profile;
+pub const Access = manager_access.Access;
-pub fn Text(comptime capacity: usize) type {
- return struct {
- bytes: [capacity]u8 = @splat(0),
- len: usize = 0,
- pub fn set(self: *@This(), value: []const u8) void {
- self.len = @min(value.len, capacity);
- @memcpy(self.bytes[0..self.len], value[0..self.len]);
- }
- pub fn slice(self: *const @This()) []const u8 {
- return self.bytes[0..self.len];
- }
- pub fn init(value: []const u8) @This() {
- var t: @This() = .{};
- t.set(value);
- return t;
- }
- };
-}
-pub const Path = Text(256);
-pub const Security = enum { open, personal, sae, unsupported };
+const types = @import("types.zig");
+pub const Text = types.Text;
+pub const Path = types.Path;
+pub const Security = types.Security;
+pub const Method = types.Method;
+pub const Config = types.Config;
+pub const Link = types.Link;
pub const Network = struct {
path: Path = .{},
ssid: Text(32) = .{},
@@ -51,6 +44,27 @@ pub const Network = struct {
security: Security = .open,
connected: bool = false,
saved: Path = .{},
+ /// MHz, and the access point's own hardware address.
+ frequency: u32 = 0,
+ bssid: Text(24) = .{},
+};
+/// The Wi-Fi adapter in use and what it was given.
+pub const WifiLink = struct {
+ name: Text(64) = .{},
+ mac: Text(64) = .{},
+ /// kbit/s of the current link.
+ bitrate: u32 = 0,
+ link: Link = .{},
+ /// The active connection object, and the saved profile it was made from.
+ active: Path = .{},
+ profile: Path = .{},
+};
+pub const ActiveConnection = struct {
+ path: Path = .{},
+ profile: Path = .{},
+ id: Text(64) = .{},
+ kind: Text(32) = .{},
+ state: u32 = 0,
};
pub const Ethernet = struct {
path: Path = .{},
@@ -58,9 +72,11 @@ pub const Ethernet = struct {
driver: Text(64) = .{},
mac: Text(64) = .{},
ip4: Path = .{},
- address: Text(256) = .{},
- gateway: Text(64) = .{},
- dns: Text(256) = .{},
+ ip6: Path = .{},
+ active_connection: Path = .{},
+ /// The first saved profile that fits this adapter.
+ profile: Path = .{},
+ link: Link = .{},
state: u32 = 0,
managed: bool = false,
carrier: bool = false,
@@ -85,16 +101,32 @@ pub const Ethernet = struct {
};
}
};
-pub const Ip4 = struct { path: Path, address: Text(256) = .{}, gateway: Text(64) = .{}, dns: Text(256) = .{} };
pub const Device = struct {
path: Path = .{},
active: Path = .{},
+ name: Text(64) = .{},
+ mac: Text(64) = .{},
+ ip4: Path = .{},
+ ip6: Path = .{},
+ active_connection: Path = .{},
+ bitrate: u32 = 0,
state: u32 = 0,
aps: [256]Path = @splat(.{}),
count: usize = 0,
last_scan: i64 = -1,
};
-pub const Saved = struct { path: Path = .{}, ssid: Text(32) = .{}, security: Security = .open, loaded: bool = false };
+pub const Saved = struct {
+ path: Path = .{},
+ ssid: Text(32) = .{},
+ security: Security = .open,
+ loaded: bool = false,
+ id: Text(64) = .{},
+ /// `connection.type`: 802-11-wireless, 802-3-ethernet, vpn, wireguard...
+ kind: Text(32) = .{},
+ autoconnect: bool = true,
+ method4: Method = .auto,
+ method6: Method = .auto,
+};
pub const Request = struct { manager: *Manager, epoch: u64, path: Path, wired_generation: u64 = 0 };
pub const PasswordUpdate = struct {
manager: *Manager,
@@ -132,6 +164,17 @@ pub const Manager = struct {
connectivity: u32 = 0,
ethernet: [16]Ethernet = @splat(.{}),
ethernet_count: usize = 0,
+ /// Whether saved connections may be changed, and the Unlock prompt state.
+ access: Access = .unknown,
+ access_pending: bool = false,
+ unlocking: bool = false,
+ /// The profile the editor has open, once its settings arrived.
+ profile: ?Profile = null,
+ edit_busy: bool = false,
+ edit_message: []const u8 = "",
+ wifi: WifiLink = .{},
+ actives: [32]ActiveConnection = @splat(.{}),
+ active_count: usize = 0,
wired_pending: ?Path = null,
wired_want_connected: bool = false,
wired_accepted: bool = false,
@@ -218,6 +261,14 @@ pub const Manager = struct {
self.state = 0;
self.connectivity = 0;
self.ethernet_count = 0;
+ self.wifi = .{};
+ self.active_count = 0;
+ self.access = .unknown;
+ self.access_pending = false;
+ self.unlocking = false;
+ self.profile = null;
+ self.edit_busy = false;
+ self.edit_message = "";
self.wired_pending = null;
self.wired_message = "";
if (self.wired_timer) |timer| timer.timerUpdate(0) catch {};
@@ -237,6 +288,16 @@ pub const Manager = struct {
pub const applySaved = manager_objects.applySaved;
pub const fetchSaved = manager_objects.fetchSaved;
+ pub const checkAccess = manager_access.check;
+ pub const unlock = manager_access.unlock;
+ pub const cancelUnlock = manager_access.cancelUnlock;
+ pub const readProfile = manager_edit.readProfile;
+ pub const saveProfile = manager_edit.saveProfile;
+ pub const setAutoconnect = manager_edit.setAutoconnect;
+ pub const forget = manager_edit.forget;
+ pub const activate = manager_edit.activate;
+ pub const deactivate = manager_edit.deactivate;
+ pub const disconnectWifi = manager_edit.disconnectWifi;
pub const searching = manager_actions.searching;
pub const stopScan = manager_actions.stopScan;
pub const scan = manager_actions.scan;
@@ -248,6 +309,12 @@ pub const Manager = struct {
pub const action = manager_actions.action;
pub const failed = manager_actions.failed;
};
+/// The saved profile at `path`, once its settings were read.
+pub fn savedAt(self: *const Manager, path: []const u8) ?*const Saved {
+ if (path.len == 0) return null;
+ for (self.saved[0..self.saved_count]) |*saved| if (eq(u8, saved.path.slice(), path)) return saved;
+ return null;
+}
pub fn sameNetwork(a: Network, b: Network) bool {
return a.security == b.security and eq(u8, a.ssid.slice(), b.ssid.slice());
}
@@ -270,7 +337,7 @@ pub fn joinError(net: Network, password: []const u8) ?[]const u8 {
}
const manager_settings = @import("manager_settings.zig");
-pub const addressList = manager_settings.addressList;
+pub const parseMethod = manager_settings.parseMethod;
pub const writeWiredSettings = manager_settings.writeWiredSettings;
pub const parseSaved = manager_settings.parseSaved;
pub const writeSettings = manager_settings.writeSettings;
diff --git a/src/network/manager_access.zig b/src/network/manager_access.zig
new file mode 100644
index 0000000..91bb357
--- /dev/null
+++ b/src/network/manager_access.zig
@@ -0,0 +1,100 @@
+//! Whether changing saved connections is allowed. Like Services' unlock, this
+//! asks polkit for the action NetworkManager checks for `Update`/`Delete`
+//! (`settings.modify.system`). It is asked once without interaction when the
+//! page loads: where policy already allows it (an active local session, the
+//! usual default) there is nothing to unlock and no button shows. Otherwise the
+//! page offers Unlock, which asks again with interaction. polkit still decides
+//! every request; this only keeps the page honest about what will work.
+
+const i18n = @import("i18n");
+const std = @import("std");
+const dbus = @import("dbus");
+const wire = dbus.wire;
+const gpa = @import("../main.zig").gpa;
+const eq = std.mem.eql;
+const manager_mod = @import("manager.zig");
+const Manager = manager_mod.Manager;
+
+pub const Access = enum { unknown, open, locked, denied };
+
+pub const action_id = "org.freedesktop.NetworkManager.settings.modify.system";
+const cancellation = "rediwm-settings-network-unlock";
+const polkit_name = "org.freedesktop.PolicyKit1";
+const polkit_path = "/org/freedesktop/PolicyKit1/Authority";
+const polkit_authority = polkit_name ++ ".Authority";
+
+const Check = struct { manager: *Manager, epoch: u64, interactive: bool };
+
+pub fn check(self: *Manager, interactive: bool) void {
+ const conn = self.conn orelse return;
+ const unique = conn.unique_name orelse return;
+ if (interactive and self.unlocking) return;
+ if (!interactive and self.access_pending) return;
+ var body: wire.Writer = .{ .allocator = gpa };
+ defer body.deinit();
+ body.alignTo(8) catch return;
+ body.string("system-bus-name") catch return;
+ const subject = body.beginArray(8) catch return;
+ body.string("name") catch return;
+ body.variant("s") catch return;
+ body.string(unique) catch return;
+ body.endArray(subject) catch return;
+ body.string(action_id) catch return;
+ const details = body.beginArray(8) catch return;
+ body.endArray(details) catch return;
+ body.uint32(@intFromBool(interactive)) catch return;
+ body.string(cancellation) catch return;
+ const req = gpa.create(Check) catch return;
+ req.* = .{ .manager = self, .epoch = self.epoch, .interactive = interactive };
+ _ = conn.callWithFlags(polkit_name, polkit_path, polkit_authority, "CheckAuthorization", "(sa{sv})sa{ss}us", &body, req, checked, if (interactive) 120000 else 5000, 0) catch {
+ gpa.destroy(req);
+ return;
+ };
+ if (interactive) {
+ self.unlocking = true;
+ self.edit_message = "";
+ self.refresh();
+ } else self.access_pending = true;
+}
+
+pub fn unlock(self: *Manager) void {
+ if (self.access == .open) return;
+ check(self, true);
+}
+
+/// Withdraws a pending prompt so no dialog outlives its Settings window.
+pub fn cancelUnlock(self: *Manager) void {
+ if (!self.unlocking) return;
+ self.unlocking = false;
+ const conn = self.conn orelse return;
+ var body: wire.Writer = .{ .allocator = gpa };
+ defer body.deinit();
+ body.string(cancellation) catch return;
+ _ = conn.call(polkit_name, polkit_path, polkit_authority, "CancelCheckAuthorization", "s", &body, null, null, 1000) catch return;
+ conn.flush() catch {};
+}
+
+fn checked(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const req: *Check = @ptrCast(@alignCast(owner.?));
+ defer gpa.destroy(req);
+ const self = req.manager;
+ if (self.closing or self.epoch != req.epoch) return;
+ if (req.interactive) self.unlocking = false else self.access_pending = false;
+ defer self.refresh();
+ var msg = result catch return unavailable(self, req.interactive);
+ if (msg.kind != .method_return or !eq(u8, msg.headers.signature, "(bba{ss})")) return unavailable(self, req.interactive);
+ msg.body.alignTo(8) catch return unavailable(self, req.interactive);
+ const authorized = msg.body.boolean() catch return unavailable(self, req.interactive);
+ const challenge = msg.body.boolean() catch return unavailable(self, req.interactive);
+ if (authorized) {
+ self.access = .open;
+ } else if (req.interactive) {
+ self.access = .locked;
+ self.edit_message = i18n.tr("Authentication was cancelled or denied.");
+ } else self.access = if (challenge) .locked else .denied;
+}
+
+/// No polkit, or no answer: do not block. NetworkManager still decides every call.
+fn unavailable(self: *Manager, interactive: bool) void {
+ if (interactive) self.edit_message = i18n.tr("Could not request authentication. Check that polkit is running.") else self.access = .open;
+}
diff --git a/src/network/manager_edit.zig b/src/network/manager_edit.zig
new file mode 100644
index 0000000..25cb6f2
--- /dev/null
+++ b/src/network/manager_edit.zig
@@ -0,0 +1,232 @@
+//! Changing saved connections: reading a profile for the editor, saving it,
+//! forgetting it, and the quick actions (auto-connect, disconnect). Writes are
+//! read-modify-write (see `manager_profile.zig`) and carry the interactive
+//! authorization flag, so polkit may ask through the session's agent.
+
+const i18n = @import("i18n");
+const std = @import("std");
+const dbus = @import("dbus");
+const wire = dbus.wire;
+const gpa = @import("../main.zig").gpa;
+const secure = @import("secure_allocator.zig").allocator;
+const eq = std.mem.eql;
+const manager_mod = @import("manager.zig");
+const Manager = manager_mod.Manager;
+const nm = manager_mod.nm;
+const root = manager_mod.root;
+const device_iface = manager_mod.device_iface;
+const settings_iface = manager_mod.settings_iface;
+const Path = manager_mod.Path;
+const Request = manager_mod.Request;
+const profile_mod = @import("manager_profile.zig");
+const Profile = profile_mod.Profile;
+
+const Mode = enum { full, autoconnect };
+const Save = struct { manager: *Manager, epoch: u64, profile: Profile, mode: Mode };
+
+fn writable(self: *const Manager) bool {
+ return self.available and self.conn != null and !self.edit_busy and (self.access == .open or self.access == .unknown);
+}
+
+fn fail(self: *Manager, message: []const u8) void {
+ self.edit_busy = false;
+ self.edit_message = message;
+ self.refresh();
+}
+
+pub fn readProfile(self: *Manager, path: []const u8) void {
+ if (!self.available or self.conn == null or path.len == 0) return;
+ self.profile = null;
+ const req = gpa.create(Request) catch return;
+ req.* = .{ .manager = self, .epoch = self.epoch, .path = Path.init(path) };
+ const b: wire.Writer = .{ .allocator = secure };
+ _ = self.conn.?.call(self.owner.slice(), path, settings_iface, "GetSettings", "", &b, req, gotProfile, 5000) catch {
+ gpa.destroy(req);
+ return fail(self, i18n.tr("Could not read the connection settings."));
+ };
+ self.edit_message = "";
+}
+
+fn gotProfile(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const req: *Request = @ptrCast(@alignCast(owner.?));
+ defer gpa.destroy(req);
+ const self = req.manager;
+ if (self.closing or self.epoch != req.epoch) return;
+ var msg = result catch return fail(self, i18n.tr("Could not read the connection settings."));
+ if (!self.fromOwner(msg) or msg.kind != .method_return or !eq(u8, msg.headers.signature, "a{sa{sv}}")) return fail(self, i18n.tr("Could not read the connection settings."));
+ self.profile = profile_mod.parse(&msg.body, req.path.slice()) catch return fail(self, i18n.tr("Could not read the connection settings."));
+ self.refresh();
+}
+
+pub fn saveProfile(self: *Manager, profile: Profile) void {
+ startSave(self, profile, .full);
+}
+
+pub fn setAutoconnect(self: *Manager, path: []const u8, on: bool) void {
+ startSave(self, .{ .path = Path.init(path), .autoconnect = on }, .autoconnect);
+}
+
+fn startSave(self: *Manager, profile: Profile, mode: Mode) void {
+ if (!writable(self) or profile.path.len == 0) return;
+ const req = gpa.create(Save) catch return;
+ req.* = .{ .manager = self, .epoch = self.epoch, .profile = profile, .mode = mode };
+ const b: wire.Writer = .{ .allocator = secure };
+ _ = self.conn.?.call(self.owner.slice(), profile.path.slice(), settings_iface, "GetSettings", "", &b, req, saveSettings, 5000) catch {
+ gpa.destroy(req);
+ return fail(self, i18n.tr("Could not save the connection settings."));
+ };
+ self.edit_busy = true;
+ self.edit_message = i18n.tr("Saving…");
+ self.refresh();
+}
+
+fn saveSettings(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const req: *Save = @ptrCast(@alignCast(owner.?));
+ const self = req.manager;
+ if (self.closing or self.epoch != req.epoch) return gpa.destroy(req);
+ const msg = result catch return saveFailed(req);
+ if (!self.fromOwner(msg) or msg.kind != .method_return or !eq(u8, msg.headers.signature, "a{sa{sv}}")) return saveFailed(req);
+ var b: wire.Writer = .{ .allocator = secure };
+ defer b.deinit();
+ var settings = msg.body;
+ if (req.mode == .autoconnect) {
+ var reader = msg.body;
+ var current = profile_mod.parse(&reader, req.profile.path.slice()) catch return saveFailed(req);
+ current.autoconnect = req.profile.autoconnect;
+ req.profile = current;
+ }
+ profile_mod.write(&settings, &b, &req.profile) catch return saveFailed(req);
+ _ = conn.callWithFlags(self.owner.slice(), req.profile.path.slice(), settings_iface, "Update", "a{sa{sv}}", &b, req, saved, 15000, wire.flag_allow_interactive_authorization) catch return saveFailed(req);
+}
+
+fn saveFailed(req: *Save) void {
+ const self = req.manager;
+ const current = self.epoch == req.epoch and !self.closing;
+ gpa.destroy(req);
+ if (current) fail(self, i18n.tr("Could not save the connection settings."));
+}
+
+fn saved(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const req: *Save = @ptrCast(@alignCast(owner.?));
+ defer gpa.destroy(req);
+ const self = req.manager;
+ if (self.closing or self.epoch != req.epoch) return;
+ const msg = result catch return fail(self, i18n.tr("Could not save the connection settings."));
+ if (!self.fromOwner(msg) or msg.kind != .method_return) return fail(self, i18n.tr("Could not save the connection settings."));
+ self.edit_busy = false;
+ self.edit_message = if (req.mode == .full) i18n.tr("Saved.") else "";
+ for (self.saved[0..self.saved_count]) |*s| if (eq(u8, s.path.slice(), req.profile.path.slice())) {
+ s.loaded = false;
+ };
+ // New addresses only apply when the connection is made again.
+ if (req.mode == .full) reactivate(self, req.profile.path.slice());
+ self.fetch();
+ self.refresh();
+}
+
+/// Brings up `profile` again on the adapter that is using it.
+fn reactivate(self: *Manager, profile: []const u8) void {
+ const device: Path = if (eq(u8, self.wifi.profile.slice(), profile)) self.device else blk: {
+ for (self.ethernet[0..self.ethernet_count]) |eth| {
+ for (self.actives[0..self.active_count]) |act| {
+ if (eq(u8, act.path.slice(), eth.active_connection.slice()) and eq(u8, act.profile.slice(), profile)) break :blk eth.path;
+ }
+ }
+ return;
+ };
+ if (device.len == 0) return;
+ var b: wire.Writer = .{ .allocator = secure };
+ defer b.deinit();
+ b.objectPath(profile) catch return;
+ b.objectPath(device.slice()) catch return;
+ b.objectPath("/") catch return;
+ const req = gpa.create(Request) catch return;
+ req.* = .{ .manager = self, .epoch = self.epoch, .path = .{} };
+ _ = self.conn.?.callWithFlags(self.owner.slice(), root, nm, "ActivateConnection", "ooo", &b, req, done, 15000, wire.flag_allow_interactive_authorization) catch gpa.destroy(req);
+}
+
+pub fn forget(self: *Manager, path: []const u8) void {
+ if (!writable(self) or path.len == 0) return;
+ const req = gpa.create(Request) catch return;
+ req.* = .{ .manager = self, .epoch = self.epoch, .path = Path.init(path) };
+ const b: wire.Writer = .{ .allocator = secure };
+ _ = self.conn.?.callWithFlags(self.owner.slice(), path, settings_iface, "Delete", "", &b, req, forgotten, 15000, wire.flag_allow_interactive_authorization) catch {
+ gpa.destroy(req);
+ return fail(self, i18n.tr("Could not forget the connection."));
+ };
+ self.edit_busy = true;
+ self.edit_message = i18n.tr("Forgetting…");
+ self.refresh();
+}
+
+fn forgotten(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const req: *Request = @ptrCast(@alignCast(owner.?));
+ defer gpa.destroy(req);
+ const self = req.manager;
+ if (self.closing or self.epoch != req.epoch) return;
+ const msg = result catch return fail(self, i18n.tr("Could not forget the connection."));
+ if (!self.fromOwner(msg) or msg.kind != .method_return) return fail(self, i18n.tr("Could not forget the connection."));
+ self.edit_busy = false;
+ self.edit_message = i18n.tr("Connection forgotten.");
+ if (self.profile) |p| if (eq(u8, p.path.slice(), req.path.slice())) {
+ self.profile = null;
+ };
+ self.fetch();
+ self.refresh();
+}
+
+pub fn disconnectWifi(self: *Manager) void {
+ if (!self.available or self.conn == null or self.device.len == 0) return;
+ const req = gpa.create(Request) catch return;
+ req.* = .{ .manager = self, .epoch = self.epoch, .path = .{} };
+ const b: wire.Writer = .{ .allocator = secure };
+ _ = self.conn.?.callWithFlags(self.owner.slice(), self.device.slice(), device_iface, "Disconnect", "", &b, req, done, 15000, wire.flag_allow_interactive_authorization) catch gpa.destroy(req);
+}
+
+fn done(owner: ?*anyopaque, _: *dbus.Connection, _: dbus.Connection.Failure!wire.Message) void {
+ const req: *Request = @ptrCast(@alignCast(owner.?));
+ defer gpa.destroy(req);
+ const self = req.manager;
+ if (self.closing or self.epoch != req.epoch) return;
+ self.fetch();
+}
+
+/// Brings up a profile that needs no adapter (a VPN).
+pub fn activate(self: *Manager, profile: []const u8) void {
+ if (!self.available or self.conn == null or profile.len == 0) return;
+ var b: wire.Writer = .{ .allocator = secure };
+ defer b.deinit();
+ b.objectPath(profile) catch return;
+ b.objectPath("/") catch return;
+ b.objectPath("/") catch return;
+ const req = gpa.create(Request) catch return;
+ req.* = .{ .manager = self, .epoch = self.epoch, .path = .{} };
+ _ = self.conn.?.callWithFlags(self.owner.slice(), root, nm, "ActivateConnection", "ooo", &b, req, vpnDone, 15000, wire.flag_allow_interactive_authorization) catch {
+ gpa.destroy(req);
+ return fail(self, i18n.tr("Could not start the connection."));
+ };
+ self.edit_message = "";
+}
+
+pub fn deactivate(self: *Manager, active: []const u8) void {
+ if (!self.available or self.conn == null or active.len == 0) return;
+ var b: wire.Writer = .{ .allocator = secure };
+ defer b.deinit();
+ b.objectPath(active) catch return;
+ const req = gpa.create(Request) catch return;
+ req.* = .{ .manager = self, .epoch = self.epoch, .path = .{} };
+ _ = self.conn.?.callWithFlags(self.owner.slice(), root, nm, "DeactivateConnection", "o", &b, req, vpnDone, 15000, wire.flag_allow_interactive_authorization) catch {
+ gpa.destroy(req);
+ return fail(self, i18n.tr("Could not stop the connection."));
+ };
+ self.edit_message = "";
+}
+
+fn vpnDone(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const req: *Request = @ptrCast(@alignCast(owner.?));
+ defer gpa.destroy(req);
+ const self = req.manager;
+ if (self.closing or self.epoch != req.epoch) return;
+ _ = result catch return fail(self, i18n.tr("The connection request was refused."));
+ self.fetch();
+}
diff --git a/src/network/manager_objects.zig b/src/network/manager_objects.zig
index 758490f..1e80a58 100644
--- a/src/network/manager_objects.zig
+++ b/src/network/manager_objects.zig
@@ -15,16 +15,20 @@ const wireless = manager_mod.wireless;
const wired = manager_mod.wired;
const device_iface = manager_mod.device_iface;
const ip4_iface = manager_mod.ip4_iface;
+const ip6_iface = manager_mod.ip6_iface;
+const active_iface = manager_mod.active_iface;
const ap_iface = manager_mod.ap_iface;
const settings_iface = manager_mod.settings_iface;
const Path = manager_mod.Path;
const Network = manager_mod.Network;
const Ethernet = manager_mod.Ethernet;
-const Ip4 = manager_mod.Ip4;
+const Config = manager_mod.Config;
+const ActiveConnection = manager_mod.ActiveConnection;
+const props_mod = @import("manager_props.zig");
+const IpObject = struct { v6: bool, cfg: Config };
const Device = manager_mod.Device;
const Request = manager_mod.Request;
const sameNetwork = manager_mod.sameNetwork;
-const addressList = manager_mod.addressList;
const parseSaved = manager_mod.parseSaved;
pub fn fetch(self: *Manager) void {
@@ -66,6 +70,7 @@ pub fn gotObjects(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connecti
self.scan_pending = false;
self.scan();
}
+ if (self.access == .unknown) self.checkAccess(false);
self.refresh();
}
@@ -80,8 +85,10 @@ pub fn parseObjects(self: *Manager, b: *wire.Reader) !void {
defer paths.deinit(gpa);
var ethernet: std.ArrayList(Ethernet) = .empty;
defer ethernet.deinit(gpa);
- var configs: std.ArrayList(Ip4) = .empty;
+ var configs: std.ArrayList(IpObject) = .empty;
defer configs.deinit(gpa);
+ var actives: std.ArrayList(ActiveConnection) = .empty;
+ defer actives.deinit(gpa);
var state: u32 = 0;
var connectivity: u32 = 0;
var objects = try b.array(8);
@@ -92,11 +99,14 @@ pub fn parseObjects(self: *Manager, b: *wire.Reader) !void {
var ap: Network = .{ .path = Path.init(path) };
var dev: Device = .{ .path = Path.init(path) };
var eth: Ethernet = .{ .path = Path.init(path) };
- var ip4: Ip4 = .{ .path = Path.init(path) };
+ var cfg: Config = .{ .path = Path.init(path) };
+ var act: ActiveConnection = .{ .path = Path.init(path) };
var is_ap = false;
var is_wifi = false;
var is_wired = false;
var is_ip4 = false;
+ var is_ip6 = false;
+ var is_active = false;
var flags: u32 = 0;
var wpa: u32 = 0;
var rsn: u32 = 0;
@@ -108,16 +118,34 @@ pub fn parseObjects(self: *Manager, b: *wire.Reader) !void {
is_wifi = is_wifi or eq(u8, iface, wireless);
is_wired = is_wired or eq(u8, iface, wired);
is_ip4 = is_ip4 or eq(u8, iface, ip4_iface);
+ is_ip6 = is_ip6 or eq(u8, iface, ip6_iface);
+ is_active = is_active or eq(u8, iface, active_iface);
var props = try ifaces.array(8);
while (props.offset < props.bytes.len) {
try props.alignTo(8);
const key = try props.string();
const sig = try props.variant();
if (eq(u8, iface, device_iface)) {
- if (eq(u8, key, "Interface") and eq(u8, sig, "s")) eth.name.set(try props.string()) else if (eq(u8, key, "Driver") and eq(u8, sig, "s")) eth.driver.set(try props.string()) else if (eq(u8, key, "Managed") and eq(u8, sig, "b")) eth.managed = try props.boolean() else if (eq(u8, key, "Ip4Config") and eq(u8, sig, "o")) eth.ip4.set(try props.objectPath()) else if (eq(u8, key, "HwAddress") and eq(u8, sig, "s")) eth.mac.set(try props.string()) else if (eq(u8, key, "AvailableConnections") and eq(u8, sig, "ao")) {
+ if (eq(u8, key, "Interface") and eq(u8, sig, "s")) {
+ eth.name.set(try props.string());
+ dev.name = eth.name;
+ } else if (eq(u8, key, "Driver") and eq(u8, sig, "s")) eth.driver.set(try props.string()) else if (eq(u8, key, "Managed") and eq(u8, sig, "b")) eth.managed = try props.boolean() else if (eq(u8, key, "Ip4Config") and eq(u8, sig, "o")) {
+ eth.ip4.set(try props.objectPath());
+ dev.ip4 = eth.ip4;
+ } else if (eq(u8, key, "Ip6Config") and eq(u8, sig, "o")) {
+ eth.ip6.set(try props.objectPath());
+ dev.ip6 = eth.ip6;
+ } else if (eq(u8, key, "ActiveConnection") and eq(u8, sig, "o")) {
+ eth.active_connection.set(try props.objectPath());
+ dev.active_connection = eth.active_connection;
+ } else if (eq(u8, key, "HwAddress") and eq(u8, sig, "s")) {
+ eth.mac.set(try props.string());
+ dev.mac = eth.mac;
+ } else if (eq(u8, key, "AvailableConnections") and eq(u8, sig, "ao")) {
var list = try props.array(4);
while (list.offset < list.bytes.len) {
- _ = try list.objectPath();
+ const profile = try list.objectPath();
+ if (!eth.has_profile) eth.profile.set(profile);
eth.has_profile = true;
}
} else if (eq(u8, key, "State") and eq(u8, sig, "u")) {
@@ -130,8 +158,12 @@ pub fn parseObjects(self: *Manager, b: *wire.Reader) !void {
if (eq(u8, key, "Carrier") and eq(u8, sig, "b")) eth.carrier = try props.boolean() else if (eq(u8, key, "Speed") and eq(u8, sig, "u")) eth.speed = try props.uint32() else if (eq(u8, key, "HwAddress") and eq(u8, sig, "s")) eth.mac.set(try props.string()) else try props.skip(sig);
continue;
}
- if (eq(u8, iface, ip4_iface)) {
- if (eq(u8, key, "Gateway") and eq(u8, sig, "s")) ip4.gateway.set(try props.string()) else if (eq(u8, key, "AddressData") and eq(u8, sig, "aa{sv}")) ip4.address = try addressList(&props) else if (eq(u8, key, "NameserverData") and eq(u8, sig, "aa{sv}")) ip4.dns = try addressList(&props) else try props.skip(sig);
+ if (eq(u8, iface, ip4_iface) or eq(u8, iface, ip6_iface)) {
+ if (!try props_mod.ipProperty(&cfg, eq(u8, iface, ip6_iface), key, sig, &props)) try props.skip(sig);
+ continue;
+ }
+ if (eq(u8, iface, active_iface)) {
+ if (eq(u8, key, "Id") and eq(u8, sig, "s")) act.id.set(try props.string()) else if (eq(u8, key, "Type") and eq(u8, sig, "s")) act.kind.set(try props.string()) else if (eq(u8, key, "Connection") and eq(u8, sig, "o")) act.profile.set(try props.objectPath()) else if (eq(u8, key, "State") and eq(u8, sig, "u")) act.state = try props.uint32() else try props.skip(sig);
continue;
}
if (eq(u8, iface, nm) and eq(u8, key, "State") and eq(u8, sig, "u")) {
@@ -153,6 +185,14 @@ pub fn parseObjects(self: *Manager, b: *wire.Reader) !void {
}
} else if (eq(u8, iface, wireless) and eq(u8, key, "LastScan") and eq(u8, sig, "x")) {
dev.last_scan = @bitCast(try props.uint64());
+ } else if (eq(u8, iface, wireless) and eq(u8, key, "Bitrate") and eq(u8, sig, "u")) {
+ dev.bitrate = try props.uint32();
+ } else if (eq(u8, iface, wireless) and eq(u8, key, "HwAddress") and eq(u8, sig, "s")) {
+ dev.mac.set(try props.string());
+ } else if (eq(u8, iface, ap_iface) and eq(u8, key, "Frequency") and eq(u8, sig, "u")) {
+ ap.frequency = try props.uint32();
+ } else if (eq(u8, iface, ap_iface) and eq(u8, key, "HwAddress") and eq(u8, sig, "s")) {
+ ap.bssid.set(try props.string());
} else if (eq(u8, iface, ap_iface) and eq(u8, key, "Ssid") and eq(u8, sig, "ay")) {
var bytes = try props.array(1);
ap.ssid.set(try bytes.take(bytes.bytes.len - bytes.offset));
@@ -165,7 +205,8 @@ pub fn parseObjects(self: *Manager, b: *wire.Reader) !void {
}
if (is_wifi and devices.items.len < 16) try devices.append(gpa, dev);
if (is_wired and ethernet.items.len < self.ethernet.len) try ethernet.append(gpa, eth);
- if (is_ip4 and configs.items.len < 64) try configs.append(gpa, ip4);
+ if ((is_ip4 or is_ip6) and configs.items.len < 64) try configs.append(gpa, .{ .v6 = is_ip6, .cfg = cfg });
+ if (is_active and actives.items.len < self.actives.len) try actives.append(gpa, act);
}
self.available = true;
self.state = state;
@@ -173,18 +214,15 @@ pub fn parseObjects(self: *Manager, b: *wire.Reader) !void {
self.ethernet_count = ethernet.items.len;
for (ethernet.items, self.ethernet[0..self.ethernet_count]) |eth, *out| {
out.* = eth;
- if (eth.connected()) for (configs.items) |config| {
- if (!eq(u8, config.path.slice(), eth.ip4.slice())) continue;
- out.address = config.address;
- out.gateway = config.gateway;
- out.dns = config.dns;
- break;
- };
+ if (eth.connected()) out.link = linkOf(configs.items, eth.ip4.slice(), eth.ip6.slice());
}
+ self.active_count = actives.items.len;
+ @memcpy(self.actives[0..actives.items.len], actives.items);
self.checkWired();
self.count = 0;
const previous_device = self.device;
self.device = .{};
+ self.wifi = .{};
var chosen: ?*Device = null;
for (devices.items) |*dev| {
if (chosen == null or dev.state == 100) chosen = dev;
@@ -193,6 +231,13 @@ pub fn parseObjects(self: *Manager, b: *wire.Reader) !void {
if (!eq(u8, previous_device.slice(), dev.path.slice()) or dev.last_scan != self.last_scan) self.stopScan();
self.last_scan = dev.last_scan;
self.device = dev.path;
+ self.wifi = .{ .name = dev.name, .mac = dev.mac, .bitrate = if (dev.state == 100) dev.bitrate else 0, .active = dev.active_connection };
+ if (dev.state == 100) {
+ self.wifi.link = linkOf(configs.items, dev.ip4.slice(), dev.ip6.slice());
+ for (actives.items) |active| if (eq(u8, active.path.slice(), dev.active_connection.slice())) {
+ self.wifi.profile = active.profile;
+ };
+ }
for (aps.items) |candidate| {
var belongs = false;
for (dev.aps[0..dev.count]) |p| if (eq(u8, p.slice(), candidate.path.slice())) {
@@ -269,6 +314,15 @@ pub fn parseObjects(self: *Manager, b: *wire.Reader) !void {
if (eq(u8, self.message, i18n.tr("NetworkManager is unavailable"))) self.message = "";
}
+fn linkOf(configs: []const IpObject, ip4: []const u8, ip6: []const u8) manager_mod.Link {
+ var link: manager_mod.Link = .{};
+ for (configs) |config| {
+ if (!config.v6 and eq(u8, config.cfg.path.slice(), ip4)) link.v4 = config.cfg;
+ if (config.v6 and eq(u8, config.cfg.path.slice(), ip6)) link.v6 = config.cfg;
+ }
+ return link;
+}
+
pub fn less(_: void, a: Network, b: Network) bool {
if (a.connected != b.connected) return a.connected;
if (a.strength != b.strength) return a.strength > b.strength;
diff --git a/src/network/manager_profile.zig b/src/network/manager_profile.zig
new file mode 100644
index 0000000..d1fa45d
--- /dev/null
+++ b/src/network/manager_profile.zig
@@ -0,0 +1,408 @@
+//! A saved connection as the editor shows it, read from NetworkManager's
+//! `a{sa{sv}}` settings and written back. Only the keys the editor owns are
+//! replaced; every other entry (secrets' flags, routes, 802.1x, ...) is copied
+//! unchanged, and secrets themselves are never in `GetSettings` at all.
+
+const std = @import("std");
+const wire = @import("dbus").wire;
+const types = @import("types.zig");
+const props_mod = @import("manager_props.zig");
+const Text = types.Text;
+const Path = types.Path;
+const Method = types.Method;
+const eq = std.mem.eql;
+
+pub const max_addresses = 4;
+pub const Address = struct { text: Text(48) = .{}, prefix: u8 = 0 };
+pub const Family = struct {
+ method: Method = .auto,
+ addresses: [max_addresses]Address = @splat(.{}),
+ count: usize = 0,
+ gateway: Text(48) = .{},
+ /// This family's own servers, comma separated.
+ dns: Text(192) = .{},
+ ignore_auto_dns: bool = false,
+};
+pub const Profile = struct {
+ path: Path = .{},
+ id: Text(64) = .{},
+ kind: Text(32) = .{},
+ autoconnect: bool = true,
+ /// NMMetered: 0 decided by NetworkManager, 1 yes, 2 no.
+ metered: i32 = 0,
+ /// 0 leaves the size to the driver.
+ mtu: u32 = 0,
+ v4: Family = .{},
+ v6: Family = .{},
+
+ fn mtuSection(self: *const Profile) []const u8 {
+ return if (eq(u8, self.kind.slice(), "802-11-wireless")) "802-11-wireless" else "802-3-ethernet";
+ }
+};
+
+pub fn methodText(method: Method, v6: bool) []const u8 {
+ return switch (method) {
+ .auto => "auto",
+ .manual => "manual",
+ .link_local => "link-local",
+ .shared => "shared",
+ .disabled => if (v6) "disabled" else "disabled",
+ .other => "auto",
+ };
+}
+
+pub fn parseMethod(value: []const u8) Method {
+ if (eq(u8, value, "auto") or eq(u8, value, "dhcp")) return .auto;
+ if (eq(u8, value, "manual")) return .manual;
+ if (eq(u8, value, "link-local")) return .link_local;
+ if (eq(u8, value, "shared")) return .shared;
+ if (eq(u8, value, "disabled") or eq(u8, value, "ignore")) return .disabled;
+ return .other;
+}
+
+// ---- reading -------------------------------------------------------------
+
+pub fn parse(settings: *wire.Reader, path: []const u8) !Profile {
+ var out: Profile = .{ .path = Path.init(path) };
+ var sections = try settings.array(8);
+ while (sections.offset < sections.bytes.len) {
+ try sections.alignTo(8);
+ const section = try sections.string();
+ var props = try sections.array(8);
+ while (props.offset < props.bytes.len) {
+ try props.alignTo(8);
+ const key = try props.string();
+ const sig = try props.variant();
+ try readProperty(&out, section, key, sig, &props);
+ }
+ }
+ return out;
+}
+
+fn readProperty(out: *Profile, section: []const u8, key: []const u8, sig: []const u8, props: *wire.Reader) !void {
+ if (eq(u8, section, "connection")) {
+ if (eq(u8, key, "id") and eq(u8, sig, "s")) return out.id.set(try props.string());
+ if (eq(u8, key, "type") and eq(u8, sig, "s")) return out.kind.set(try props.string());
+ if (eq(u8, key, "autoconnect") and eq(u8, sig, "b")) {
+ out.autoconnect = try props.boolean();
+ return;
+ }
+ if (eq(u8, key, "metered") and eq(u8, sig, "i")) {
+ out.metered = try props.int(i32);
+ return;
+ }
+ } else if (eq(u8, section, "ipv4") or eq(u8, section, "ipv6")) {
+ const v6 = eq(u8, section, "ipv6");
+ const family = if (v6) &out.v6 else &out.v4;
+ if (eq(u8, key, "method") and eq(u8, sig, "s")) {
+ family.method = parseMethod(try props.string());
+ return;
+ }
+ if (eq(u8, key, "address-data") and eq(u8, sig, "aa{sv}")) return readAddresses(family, props);
+ if (eq(u8, key, "gateway") and eq(u8, sig, "s")) return family.gateway.set(try props.string());
+ if (eq(u8, key, "ignore-auto-dns") and eq(u8, sig, "b")) {
+ family.ignore_auto_dns = try props.boolean();
+ return;
+ }
+ if (!v6 and eq(u8, key, "dns") and eq(u8, sig, "au")) {
+ var list = try props.array(4);
+ while (list.offset < list.bytes.len) {
+ const value = try list.uint32();
+ const bytes: [4]u8 = @bitCast(value);
+ var text: [16]u8 = undefined;
+ props_mod.append(&family.dns, std.fmt.bufPrint(&text, "{d}.{d}.{d}.{d}", .{ bytes[0], bytes[1], bytes[2], bytes[3] }) catch continue);
+ }
+ return;
+ }
+ if (v6 and eq(u8, key, "dns") and eq(u8, sig, "aay")) {
+ var list = try props.array(4);
+ while (list.offset < list.bytes.len) {
+ var bytes = try list.array(1);
+ const data = try bytes.take(bytes.bytes.len - bytes.offset);
+ if (data.len != 16) continue;
+ var text: [48]u8 = undefined;
+ props_mod.append(&family.dns, props_mod.formatIp6(&text, data[0..16].*));
+ }
+ return;
+ }
+ } else if (eq(u8, section, "802-3-ethernet") or eq(u8, section, "802-11-wireless")) {
+ if (eq(u8, key, "mtu") and eq(u8, sig, "u")) {
+ out.mtu = try props.uint32();
+ return;
+ }
+ }
+ try props.skip(sig);
+}
+
+fn readAddresses(family: *Family, props: *wire.Reader) !void {
+ var list = try props.array(4);
+ while (list.offset < list.bytes.len) {
+ var entries = try list.array(8);
+ var address: Address = .{};
+ while (entries.offset < entries.bytes.len) {
+ try entries.alignTo(8);
+ const key = try entries.string();
+ const sig = try entries.variant();
+ if (eq(u8, key, "address") and eq(u8, sig, "s")) address.text.set(try entries.string()) else if (eq(u8, key, "prefix") and eq(u8, sig, "u")) address.prefix = @intCast(@min(try entries.uint32(), 255)) else try entries.skip(sig);
+ }
+ if (address.text.len != 0 and family.count < max_addresses) {
+ family.addresses[family.count] = address;
+ family.count += 1;
+ }
+ }
+}
+
+// ---- writing -------------------------------------------------------------
+
+const Kind = enum { connection, v4, v6, mtu, other };
+
+fn beginSection(b: *wire.Writer, name: []const u8) !wire.Writer.Array {
+ try b.alignTo(8);
+ try b.string(name);
+ return b.beginArray(8);
+}
+
+fn prop(b: *wire.Writer, name: []const u8, sig: []const u8) !void {
+ try b.alignTo(8);
+ try b.string(name);
+ try b.variant(sig);
+}
+
+fn classify(name: []const u8, p: *const Profile) Kind {
+ if (eq(u8, name, "connection")) return .connection;
+ if (eq(u8, name, "ipv4") and p.v4.method != .other) return .v4;
+ if (eq(u8, name, "ipv6") and p.v6.method != .other) return .v6;
+ if (eq(u8, name, p.mtuSection())) return .mtu;
+ return .other;
+}
+
+fn owned(kind: Kind, key: []const u8) bool {
+ const keys: []const []const u8 = switch (kind) {
+ .connection => &.{ "autoconnect", "metered" },
+ .v4, .v6 => &.{ "method", "address-data", "addresses", "gateway", "dns", "dns-data", "ignore-auto-dns" },
+ .mtu => &.{"mtu"},
+ .other => return false,
+ };
+ for (keys) |name| if (eq(u8, name, key)) return true;
+ return false;
+}
+
+fn writeOwned(b: *wire.Writer, kind: Kind, p: *const Profile) !void {
+ switch (kind) {
+ .connection => {
+ try prop(b, "autoconnect", "b");
+ try b.boolean(p.autoconnect);
+ if (p.metered != 0) {
+ try prop(b, "metered", "i");
+ try b.int(i32, p.metered);
+ }
+ },
+ .v4, .v6 => try writeFamily(b, if (kind == .v6) &p.v6 else &p.v4, kind == .v6),
+ .mtu => if (p.mtu != 0) {
+ try prop(b, "mtu", "u");
+ try b.uint32(p.mtu);
+ },
+ .other => {},
+ }
+}
+
+fn writeFamily(b: *wire.Writer, f: *const Family, v6: bool) !void {
+ try prop(b, "method", "s");
+ try b.string(methodText(f.method, v6));
+ if (f.method == .manual and f.count != 0) {
+ try prop(b, "address-data", "aa{sv}");
+ const list = try b.beginArray(4);
+ for (f.addresses[0..f.count]) |address| {
+ const dict = try b.beginArray(8);
+ try prop(b, "address", "s");
+ try b.string(address.text.slice());
+ try prop(b, "prefix", "u");
+ try b.uint32(address.prefix);
+ try b.endArray(dict);
+ }
+ try b.endArray(list);
+ if (f.gateway.len != 0) {
+ try prop(b, "gateway", "s");
+ try b.string(f.gateway.slice());
+ }
+ }
+ if (f.dns.len != 0) {
+ try prop(b, "dns", if (v6) "aay" else "au");
+ const list = try b.beginArray(4);
+ var items = std.mem.tokenizeAny(u8, f.dns.slice(), ", ");
+ while (items.next()) |item| {
+ if (v6) {
+ const address = std.Io.net.Ip6Address.parse(item, 0) catch return error.InvalidDns;
+ const bytes = try b.beginArray(1);
+ try b.raw(&address.bytes);
+ try b.endArray(bytes);
+ } else {
+ const address = std.Io.net.Ip4Address.parse(item, 0) catch return error.InvalidDns;
+ try b.uint32(@bitCast(address.bytes));
+ }
+ }
+ try b.endArray(list);
+ }
+ if (f.ignore_auto_dns) {
+ try prop(b, "ignore-auto-dns", "b");
+ try b.boolean(true);
+ }
+}
+
+/// Copies `settings` into `b`, replacing what the editor owns with `p`.
+pub fn write(settings: *wire.Reader, b: *wire.Writer, p: *const Profile) !void {
+ b.endian = settings.endian;
+ const all = try b.beginArray(8);
+ var seen: [5]bool = @splat(false);
+ var sections = try settings.array(8);
+ while (sections.offset < sections.bytes.len) {
+ try sections.alignTo(8);
+ const name = try sections.string();
+ const kind = classify(name, p);
+ seen[@intFromEnum(kind)] = true;
+ const out = try beginSection(b, name);
+ var entries = try sections.array(8);
+ while (entries.offset < entries.bytes.len) {
+ try entries.alignTo(8);
+ const start = entries.offset;
+ const key = try entries.string();
+ const sig = try entries.variant();
+ try entries.skip(sig);
+ if (owned(kind, key)) continue;
+ try b.alignTo(8);
+ try b.raw(entries.bytes[start..entries.offset]);
+ }
+ try writeOwned(b, kind, p);
+ try b.endArray(out);
+ }
+ // A profile may lack a section the editor sets (no ipv6 yet, no mtu).
+ const missing = [_]struct { kind: Kind, name: []const u8 }{
+ .{ .kind = .connection, .name = "connection" },
+ .{ .kind = .v4, .name = "ipv4" },
+ .{ .kind = .v6, .name = "ipv6" },
+ .{ .kind = .mtu, .name = p.mtuSection() },
+ };
+ for (missing) |m| {
+ if (seen[@intFromEnum(m.kind)]) continue;
+ if (m.kind == .v4 and p.v4.method == .other) continue;
+ if (m.kind == .v6 and p.v6.method == .other) continue;
+ if (m.kind == .mtu and p.mtu == 0) continue;
+ const out = try beginSection(b, m.name);
+ try writeOwned(b, m.kind, p);
+ try b.endArray(out);
+ }
+ try b.endArray(all);
+}
+
+// ---- tests ---------------------------------------------------------------
+
+fn sample(b: *wire.Writer) !void {
+ const all = try b.beginArray(8);
+ const connection = try beginSection(b, "connection");
+ try prop(b, "id", "s");
+ try b.string("Studio_5G");
+ try prop(b, "type", "s");
+ try b.string("802-11-wireless");
+ try prop(b, "autoconnect", "b");
+ try b.boolean(true);
+ try b.endArray(connection);
+ const wifi = try beginSection(b, "802-11-wireless");
+ try prop(b, "ssid", "ay");
+ const ssid = try b.beginArray(1);
+ try b.raw("Studio_5G");
+ try b.endArray(ssid);
+ try b.endArray(wifi);
+ const security = try beginSection(b, "802-11-wireless-security");
+ try prop(b, "key-mgmt", "s");
+ try b.string("wpa-psk");
+ try prop(b, "psk-flags", "u");
+ try b.uint32(0);
+ try b.endArray(security);
+ const ip4 = try beginSection(b, "ipv4");
+ try prop(b, "method", "s");
+ try b.string("auto");
+ try b.endArray(ip4);
+ try b.endArray(all);
+}
+
+test "editing a profile keeps what the editor does not own" {
+ var original: wire.Writer = .{ .allocator = std.testing.allocator };
+ defer original.deinit();
+ try sample(&original);
+ var reader: wire.Reader = .{ .bytes = original.bytes.items };
+ var profile = try parse(&reader, "/p/1");
+ try std.testing.expectEqualStrings("Studio_5G", profile.id.slice());
+ try std.testing.expect(profile.autoconnect and profile.v4.method == .auto and profile.v6.method == .auto);
+
+ profile.autoconnect = false;
+ profile.metered = 1;
+ profile.mtu = 1400;
+ profile.v4.method = .manual;
+ profile.v4.addresses[0] = .{ .text = Text(48).init("10.0.0.5"), .prefix = 24 };
+ profile.v4.count = 1;
+ profile.v4.gateway.set("10.0.0.1");
+ profile.v4.dns.set("1.1.1.1, 9.9.9.9");
+ profile.v4.ignore_auto_dns = true;
+ profile.v6.method = .manual;
+ profile.v6.addresses[0] = .{ .text = Text(48).init("2001:db8::5"), .prefix = 64 };
+ profile.v6.count = 1;
+ profile.v6.dns.set("2001:db8::53");
+
+ var edited: wire.Writer = .{ .allocator = std.testing.allocator };
+ defer edited.deinit();
+ reader = .{ .bytes = original.bytes.items };
+ try write(&reader, &edited, &profile);
+ // Untouched entries survive byte for byte, and no secret was invented.
+ try std.testing.expect(std.mem.indexOf(u8, edited.bytes.items, "key-mgmt") != null);
+ try std.testing.expect(std.mem.indexOf(u8, edited.bytes.items, "psk-flags") != null);
+ try std.testing.expect(std.mem.indexOf(u8, edited.bytes.items, "Studio_5G") != null);
+
+ var again: wire.Reader = .{ .bytes = edited.bytes.items };
+ const back = try parse(&again, "/p/1");
+ try std.testing.expect(!back.autoconnect);
+ try std.testing.expectEqual(@as(i32, 1), back.metered);
+ try std.testing.expectEqual(@as(u32, 1400), back.mtu);
+ try std.testing.expect(back.v4.method == .manual and back.v4.count == 1);
+ try std.testing.expectEqualStrings("10.0.0.5", back.v4.addresses[0].text.slice());
+ try std.testing.expectEqual(@as(u8, 24), back.v4.addresses[0].prefix);
+ try std.testing.expectEqualStrings("10.0.0.1", back.v4.gateway.slice());
+ try std.testing.expectEqualStrings("1.1.1.1, 9.9.9.9", back.v4.dns.slice());
+ try std.testing.expect(back.v4.ignore_auto_dns);
+ try std.testing.expect(back.v6.method == .manual);
+ try std.testing.expectEqualStrings("2001:db8::5", back.v6.addresses[0].text.slice());
+ try std.testing.expectEqualStrings("2001:db8::53", back.v6.dns.slice());
+
+ // Going back to automatic drops the addresses and the gateway.
+ var auto = back;
+ auto.v4.method = .auto;
+ auto.v4.dns = .{};
+ auto.v4.ignore_auto_dns = false;
+ var third: wire.Writer = .{ .allocator = std.testing.allocator };
+ defer third.deinit();
+ var second: wire.Reader = .{ .bytes = edited.bytes.items };
+ try write(&second, &third, &auto);
+ var last: wire.Reader = .{ .bytes = third.bytes.items };
+ const final = try parse(&last, "/p/1");
+ try std.testing.expect(final.v4.method == .auto and final.v4.count == 0 and final.v4.gateway.len == 0 and final.v4.dns.len == 0);
+ try std.testing.expect(final.v6.method == .manual);
+}
+
+test "an unrecognised method leaves that family untouched" {
+ var original: wire.Writer = .{ .allocator = std.testing.allocator };
+ defer original.deinit();
+ const all = try original.beginArray(8);
+ const ip4 = try beginSection(&original, "ipv4");
+ try prop(&original, "method", "s");
+ try original.string("shared");
+ try original.endArray(ip4);
+ try original.endArray(all);
+ var reader: wire.Reader = .{ .bytes = original.bytes.items };
+ var profile = try parse(&reader, "/p/2");
+ try std.testing.expect(profile.v4.method == .shared);
+ profile.v4.method = .other;
+ var out: wire.Writer = .{ .allocator = std.testing.allocator };
+ defer out.deinit();
+ reader = .{ .bytes = original.bytes.items };
+ try write(&reader, &out, &profile);
+ try std.testing.expect(std.mem.indexOf(u8, out.bytes.items, "shared") != null);
+}
diff --git a/src/network/manager_props.zig b/src/network/manager_props.zig
new file mode 100644
index 0000000..5e0c4e4
--- /dev/null
+++ b/src/network/manager_props.zig
@@ -0,0 +1,136 @@
+//! Reading the properties of NetworkManager's IP configuration objects (IPv4
+//! and IPv6) and formatting addresses as text.
+
+const std = @import("std");
+const dbus = @import("dbus");
+const wire = dbus.wire;
+const eq = std.mem.eql;
+const types = @import("types.zig");
+const Text = types.Text;
+const Config = types.Config;
+
+/// Adds `value` to a comma separated list, dropping what does not fit.
+pub fn append(out: anytype, value: []const u8) void {
+ const separator: []const u8 = if (out.len == 0) "" else ", ";
+ if (out.len + separator.len + value.len > out.bytes.len) return;
+ @memcpy(out.bytes[out.len..][0..separator.len], separator);
+ out.len += separator.len;
+ @memcpy(out.bytes[out.len..][0..value.len], value);
+ out.len += value.len;
+}
+
+/// RFC 5952 text for an IPv6 address: lowercase, no leading zeros, and the
+/// longest run of zero groups (two or more) written as "::".
+pub fn formatIp6(buffer: *[48]u8, bytes: [16]u8) []const u8 {
+ var groups: [8]u16 = undefined;
+ for (&groups, 0..) |*g, i| g.* = std.mem.readInt(u16, bytes[i * 2 ..][0..2], .big);
+ var best_start: usize = 8;
+ var best_len: usize = 0;
+ var i: usize = 0;
+ while (i < 8) {
+ if (groups[i] != 0) {
+ i += 1;
+ continue;
+ }
+ var j = i;
+ while (j < 8 and groups[j] == 0) j += 1;
+ if (j - i > best_len) {
+ best_start = i;
+ best_len = j - i;
+ }
+ i = j;
+ }
+ if (best_len < 2) best_start = 8;
+ var len: usize = 0;
+ i = 0;
+ while (i < 8) {
+ if (i == best_start) {
+ buffer[len] = ':';
+ buffer[len + 1] = ':';
+ len += 2;
+ i += best_len;
+ continue;
+ }
+ if (len > 0 and buffer[len - 1] != ':') {
+ buffer[len] = ':';
+ len += 1;
+ }
+ len += (std.fmt.bufPrint(buffer[len..], "{x}", .{groups[i]}) catch return buffer[0..len]).len;
+ i += 1;
+ }
+ return buffer[0..len];
+}
+
+/// An `aa{sv}` list of {address, prefix}, as "address/prefix" separated by commas.
+pub fn addressList(b: *wire.Reader, with_prefix: bool) !Text(256) {
+ var out: Text(256) = .{};
+ var list = try b.array(4);
+ while (list.offset < list.bytes.len) {
+ var entries = try list.array(8);
+ var address: []const u8 = "";
+ var prefix: ?u32 = null;
+ while (entries.offset < entries.bytes.len) {
+ try entries.alignTo(8);
+ const key = try entries.string();
+ const sig = try entries.variant();
+ if (eq(u8, key, "address") and eq(u8, sig, "s")) address = try entries.string() else if (eq(u8, key, "prefix") and eq(u8, sig, "u")) prefix = try entries.uint32() else try entries.skip(sig);
+ }
+ if (address.len == 0) continue;
+ var text: [96]u8 = undefined;
+ const value = if (with_prefix and prefix != null) std.fmt.bufPrint(&text, "{s}/{d}", .{ address, prefix.? }) catch address else address;
+ append(&out, value);
+ }
+ return out;
+}
+
+/// An `as` list joined with commas.
+pub fn stringList(b: *wire.Reader) !Text(256) {
+ var out: Text(256) = .{};
+ var list = try b.array(4);
+ while (list.offset < list.bytes.len) append(&out, try list.string());
+ return out;
+}
+
+/// IPv6 `Nameservers`: an `aay` of 16-byte addresses.
+pub fn nameservers6(b: *wire.Reader) !Text(256) {
+ var out: Text(256) = .{};
+ var list = try b.array(4);
+ while (list.offset < list.bytes.len) {
+ var bytes = try list.array(1);
+ const data = try bytes.take(bytes.bytes.len - bytes.offset);
+ if (data.len != 16) continue;
+ var text: [48]u8 = undefined;
+ append(&out, formatIp6(&text, data[0..16].*));
+ }
+ return out;
+}
+
+/// One property of an IP4Config or IP6Config object. Returns false when the
+/// key is not one we keep, and the caller must skip the value.
+pub fn ipProperty(cfg: *Config, v6: bool, key: []const u8, sig: []const u8, props: *wire.Reader) !bool {
+ if (eq(u8, key, "Gateway") and eq(u8, sig, "s")) {
+ cfg.gateway.set(try props.string());
+ } else if (eq(u8, key, "AddressData") and eq(u8, sig, "aa{sv}")) {
+ cfg.address = try addressList(props, true);
+ } else if (!v6 and eq(u8, key, "NameserverData") and eq(u8, sig, "aa{sv}")) {
+ cfg.dns = try addressList(props, false);
+ } else if (v6 and eq(u8, key, "Nameservers") and eq(u8, sig, "aay")) {
+ cfg.dns = try nameservers6(props);
+ } else if (eq(u8, key, "Searches") and eq(u8, sig, "as")) {
+ cfg.domains = try stringList(props);
+ } else return false;
+ return true;
+}
+
+test "IPv6 text follows RFC 5952" {
+ var buffer: [48]u8 = undefined;
+ const cases = [_]struct { bytes: [16]u8, text: []const u8 }{
+ .{ .bytes = .{ 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, .text = "2001:db8::1" },
+ .{ .bytes = .{ 0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0x02, 0x1b, 0x63, 0xff, 0xfe, 0x94, 0x7a, 0xb2 }, .text = "fe80::21b:63ff:fe94:7ab2" },
+ .{ .bytes = @splat(0), .text = "::" },
+ .{ .bytes = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, .text = "::1" },
+ .{ .bytes = .{ 0x20, 0x01, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1 }, .text = "2001:0:1:0:1:0:1:1" },
+ .{ .bytes = .{ 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 }, .text = "2001:db8:0:1::1" },
+ };
+ for (cases) |case| try std.testing.expectEqualStrings(case.text, formatIp6(&buffer, case.bytes));
+}
diff --git a/src/network/manager_settings.zig b/src/network/manager_settings.zig
index 94dbfe9..bf9aea0 100644
--- a/src/network/manager_settings.zig
+++ b/src/network/manager_settings.zig
@@ -11,28 +11,13 @@ const Path = manager.Path;
const Network = manager.Network;
const Saved = manager.Saved;
-pub fn addressList(b: *wire.Reader) !Text(256) {
- var out: Text(256) = .{};
- var list = try b.array(4);
- while (list.offset < list.bytes.len) {
- var entries = try list.array(8);
- while (entries.offset < entries.bytes.len) {
- try entries.alignTo(8);
- const key = try entries.string();
- const sig = try entries.variant();
- if (eq(u8, key, "address") and eq(u8, sig, "s")) {
- const value = try entries.string();
- const separator: []const u8 = if (out.len == 0) "" else ", ";
- if (out.len + separator.len + value.len <= out.bytes.len) {
- @memcpy(out.bytes[out.len..][0..separator.len], separator);
- out.len += separator.len;
- @memcpy(out.bytes[out.len..][0..value.len], value);
- out.len += value.len;
- }
- } else try entries.skip(sig);
- }
- }
- return out;
+pub fn parseMethod(value: []const u8) manager.Method {
+ if (eq(u8, value, "auto") or eq(u8, value, "dhcp")) return .auto;
+ if (eq(u8, value, "manual")) return .manual;
+ if (eq(u8, value, "link-local")) return .link_local;
+ if (eq(u8, value, "shared")) return .shared;
+ if (eq(u8, value, "disabled") or eq(u8, value, "ignore")) return .disabled;
+ return .other;
}
pub fn writeWiredSettings(b: *wire.Writer, name: []const u8) !void {
@@ -64,7 +49,16 @@ pub fn parseSaved(b: *wire.Reader, path: Path) !Saved {
try props.alignTo(8);
const key = try props.string();
const sig = try props.variant();
- if (eq(u8, section_name, "802-11-wireless") and eq(u8, key, "ssid") and eq(u8, sig, "ay")) {
+ if (eq(u8, section_name, "connection") and eq(u8, key, "id") and eq(u8, sig, "s")) {
+ out.id.set(try props.string());
+ } else if (eq(u8, section_name, "connection") and eq(u8, key, "type") and eq(u8, sig, "s")) {
+ out.kind.set(try props.string());
+ } else if (eq(u8, section_name, "connection") and eq(u8, key, "autoconnect") and eq(u8, sig, "b")) {
+ out.autoconnect = try props.boolean();
+ } else if ((eq(u8, section_name, "ipv4") or eq(u8, section_name, "ipv6")) and eq(u8, key, "method") and eq(u8, sig, "s")) {
+ const method = parseMethod(try props.string());
+ if (eq(u8, section_name, "ipv4")) out.method4 = method else out.method6 = method;
+ } else if (eq(u8, section_name, "802-11-wireless") and eq(u8, key, "ssid") and eq(u8, sig, "ay")) {
var bytes = try props.array(1);
out.ssid.set(try bytes.take(bytes.bytes.len - bytes.offset));
} else if (eq(u8, section_name, "802-11-wireless-security") and eq(u8, key, "key-mgmt") and eq(u8, sig, "s")) {
diff --git a/src/network/proxy.zig b/src/network/proxy.zig
new file mode 100644
index 0000000..98e052f
--- /dev/null
+++ b/src/network/proxy.zig
@@ -0,0 +1,133 @@
+//! The system proxy setting: its model, input checks and the environment
+//! variables spawned apps get. Storage is GSettings (`proxy_gsettings.zig`),
+//! the same keys GTK/GIO apps and Firefox's "system proxy" already read.
+//! NetworkManager has no manual proxy at all (only a per-connection PAC URL).
+
+const std = @import("std");
+const types = @import("types.zig");
+const Text = types.Text;
+
+pub const Mode = enum { off, manual, auto };
+pub const Endpoint = struct {
+ host: Text(128) = .{},
+ port: u16 = 0,
+ pub fn set(self: Endpoint) bool {
+ return self.host.len != 0 and self.port != 0;
+ }
+};
+pub const Config = struct {
+ mode: Mode = .off,
+ http: Endpoint = .{},
+ https: Endpoint = .{},
+ socks: Endpoint = .{},
+ /// Hosts that bypass the proxy, comma separated.
+ ignore: Text(512) = .{},
+ /// Where an automatic configuration script lives.
+ pac: Text(256) = .{},
+};
+
+/// A host name or address as a proxy host: no scheme, path, port or spaces.
+pub fn validHost(host: []const u8) bool {
+ if (host.len == 0 or host.len > 128) return false;
+ for (host) |c| {
+ if (c <= ' ' or c == '/' or c == '@' or c == '[' or c == ']' or c == '\\') return false;
+ }
+ // A colon belongs to an IPv6 literal; anything else with one is host:port.
+ if (std.mem.indexOfScalar(u8, host, ':') != null) {
+ _ = std.Io.net.Ip6Address.parse(host, 0) catch return false;
+ }
+ return true;
+}
+
+pub fn parsePort(value: []const u8) ?u16 {
+ const n = std.fmt.parseInt(u16, std.mem.trim(u8, value, " "), 10) catch return null;
+ return if (n == 0) null else n;
+}
+
+pub fn validPac(url: []const u8) bool {
+ if (url.len == 0 or url.len > 256) return false;
+ for (url) |c| if (c <= ' ') return false;
+ for ([_][]const u8{ "http://", "https://", "file://" }) |scheme| {
+ if (std.mem.startsWith(u8, url, scheme) and url.len > scheme.len) return true;
+ }
+ return false;
+}
+
+/// The ignore list as separate entries (commas and spaces both separate).
+pub fn ignoreEntries(list: []const u8) std.mem.TokenIterator(u8, .any) {
+ return std.mem.tokenizeAny(u8, list, ", ");
+}
+
+fn endpointUrl(buffer: []u8, scheme: []const u8, e: Endpoint) ![]const u8 {
+ const v6 = std.mem.indexOfScalar(u8, e.host.slice(), ':') != null;
+ return std.fmt.bufPrint(buffer, "{s}://{s}{s}{s}:{d}", .{ scheme, if (v6) "[" else "", e.host.slice(), if (v6) "]" else "", e.port });
+}
+
+fn put(map: *std.process.Environ.Map, lower: []const u8, upper: []const u8, value: []const u8) !void {
+ try map.put(lower, value);
+ try map.put(upper, value);
+}
+
+/// Adds the proxy variables for children. Only a manual setting exports
+/// anything: a script cannot be written as a variable, and Off must not strip
+/// what the user's own login environment sets.
+pub fn environment(map: *std.process.Environ.Map, config: *const Config) !void {
+ if (config.mode != .manual) return;
+ var buffer: [300]u8 = undefined;
+ if (config.http.set()) try put(map, "http_proxy", "HTTP_PROXY", try endpointUrl(&buffer, "http", config.http));
+ if (config.https.set()) try put(map, "https_proxy", "HTTPS_PROXY", try endpointUrl(&buffer, "http", config.https));
+ if (config.socks.set()) try put(map, "all_proxy", "ALL_PROXY", try endpointUrl(&buffer, "socks5h", config.socks));
+ if (config.ignore.len != 0) {
+ var joined: [520]u8 = undefined;
+ var len: usize = 0;
+ var entries = ignoreEntries(config.ignore.slice());
+ while (entries.next()) |entry| {
+ if (len + entry.len + 1 > joined.len) break;
+ if (len != 0) {
+ joined[len] = ',';
+ len += 1;
+ }
+ @memcpy(joined[len..][0..entry.len], entry);
+ len += entry.len;
+ }
+ if (len != 0) try put(map, "no_proxy", "NO_PROXY", joined[0..len]);
+ }
+}
+
+test "manual proxies export both spellings and bracket IPv6 hosts" {
+ var map = std.process.Environ.Map.init(std.testing.allocator);
+ defer map.deinit();
+ var config: Config = .{ .mode = .manual };
+ config.http = .{ .host = Text(128).init("proxy.example"), .port = 3128 };
+ config.https = .{ .host = Text(128).init("2001:db8::1"), .port = 3129 };
+ config.socks = .{ .host = Text(128).init("127.0.0.1"), .port = 1080 };
+ config.ignore.set("localhost, 10.0.0.0/8 ::1");
+ try environment(&map, &config);
+ try std.testing.expectEqualStrings("http://proxy.example:3128", map.get("http_proxy").?);
+ try std.testing.expectEqualStrings("http://proxy.example:3128", map.get("HTTP_PROXY").?);
+ try std.testing.expectEqualStrings("http://[2001:db8::1]:3129", map.get("https_proxy").?);
+ try std.testing.expectEqualStrings("socks5h://127.0.0.1:1080", map.get("ALL_PROXY").?);
+ try std.testing.expectEqualStrings("localhost,10.0.0.0/8,::1", map.get("no_proxy").?);
+}
+
+test "off and automatic leave the environment alone" {
+ var map = std.process.Environ.Map.init(std.testing.allocator);
+ defer map.deinit();
+ try map.put("http_proxy", "http://mine:1");
+ var config: Config = .{ .mode = .off };
+ config.http = .{ .host = Text(128).init("proxy.example"), .port = 3128 };
+ try environment(&map, &config);
+ config.mode = .auto;
+ try environment(&map, &config);
+ try std.testing.expectEqualStrings("http://mine:1", map.get("http_proxy").?);
+ try std.testing.expect(map.get("HTTP_PROXY") == null);
+}
+
+test "input checks" {
+ try std.testing.expect(validHost("proxy.example") and validHost("10.1.2.3") and validHost("2001:db8::1"));
+ try std.testing.expect(!validHost("") and !validHost("http://proxy") and !validHost("proxy:8080") and !validHost("a b") and !validHost("[::1]"));
+ try std.testing.expectEqual(@as(?u16, 8080), parsePort(" 8080 "));
+ try std.testing.expect(parsePort("0") == null and parsePort("70000") == null and parsePort("x") == null and parsePort("") == null);
+ try std.testing.expect(validPac("http://wpad.local/wpad.dat") and validPac("file:///etc/proxy.pac"));
+ try std.testing.expect(!validPac("wpad.local/wpad.dat") and !validPac("http://") and !validPac("http://a b"));
+}
diff --git a/src/network/proxy_gsettings.zig b/src/network/proxy_gsettings.zig
new file mode 100644
index 0000000..41d1b91
--- /dev/null
+++ b/src/network/proxy_gsettings.zig
@@ -0,0 +1,138 @@
+//! The system proxy in GSettings (`org.gnome.system.proxy`), through the GIO
+//! ABI declared by hand (GLib's headers never go through translate-c). The
+//! schemas come with gsettings-desktop-schemas; `g_settings_new` aborts on a
+//! missing schema, so every entry point checks first.
+
+const std = @import("std");
+const proxy = @import("proxy.zig");
+const Text = @import("types.zig").Text;
+const a = std.heap.c_allocator;
+
+extern fn g_settings_schema_source_get_default() ?*anyopaque;
+extern fn g_settings_schema_source_lookup(source: *anyopaque, schema_id: [*:0]const u8, recursive: c_int) ?*anyopaque;
+extern fn g_settings_schema_unref(schema: *anyopaque) void;
+extern fn g_settings_new(schema_id: [*:0]const u8) *anyopaque;
+extern fn g_object_unref(object: *anyopaque) void;
+extern fn g_settings_get_string(settings: *anyopaque, key: [*:0]const u8) [*:0]u8;
+extern fn g_settings_get_int(settings: *anyopaque, key: [*:0]const u8) c_int;
+extern fn g_settings_get_strv(settings: *anyopaque, key: [*:0]const u8) [*:null]?[*:0]u8;
+extern fn g_settings_set_string(settings: *anyopaque, key: [*:0]const u8, value: [*:0]const u8) c_int;
+extern fn g_settings_set_int(settings: *anyopaque, key: [*:0]const u8, value: c_int) c_int;
+extern fn g_settings_set_strv(settings: *anyopaque, key: [*:0]const u8, value: ?[*:null]const ?[*:0]const u8) c_int;
+extern fn g_settings_sync() void;
+extern fn g_free(memory: ?*anyopaque) void;
+extern fn g_strfreev(strings: [*:null]?[*:0]u8) void;
+
+const base = "org.gnome.system.proxy";
+const schemas = [_][*:0]const u8{ base, base ++ ".http", base ++ ".https", base ++ ".socks" };
+
+/// All four schemas are installed.
+pub fn available() bool {
+ const source = g_settings_schema_source_get_default() orelse return false;
+ for (schemas) |id| {
+ const schema = g_settings_schema_source_lookup(source, id, 1) orelse return false;
+ g_settings_schema_unref(schema);
+ }
+ return true;
+}
+
+fn string(settings: *anyopaque, key: [*:0]const u8, out: anytype) void {
+ const value = g_settings_get_string(settings, key);
+ defer g_free(value);
+ out.set(std.mem.span(value));
+}
+
+fn endpoint(id: [*:0]const u8) proxy.Endpoint {
+ const settings = g_settings_new(id);
+ defer g_object_unref(settings);
+ var out: proxy.Endpoint = .{};
+ string(settings, "host", &out.host);
+ const port = g_settings_get_int(settings, "port");
+ out.port = if (port > 0 and port <= 65535) @intCast(port) else 0;
+ return out;
+}
+
+/// The current setting; the defaults when the schemas are missing.
+pub fn read() proxy.Config {
+ var out: proxy.Config = .{};
+ if (!available()) return out;
+ const settings = g_settings_new(base);
+ defer g_object_unref(settings);
+ var mode: Text(16) = .{};
+ string(settings, "mode", &mode);
+ out.mode = if (std.mem.eql(u8, mode.slice(), "manual")) .manual else if (std.mem.eql(u8, mode.slice(), "auto")) .auto else .off;
+ string(settings, "autoconfig-url", &out.pac);
+ const hosts = g_settings_get_strv(settings, "ignore-hosts");
+ defer g_strfreev(hosts);
+ var i: usize = 0;
+ while (hosts[i]) |host| : (i += 1) @import("manager_props.zig").append(&out.ignore, std.mem.span(host));
+ out.http = endpoint(base ++ ".http");
+ out.https = endpoint(base ++ ".https");
+ out.socks = endpoint(base ++ ".socks");
+ return out;
+}
+
+fn writeEndpoint(id: [*:0]const u8, e: proxy.Endpoint) void {
+ const settings = g_settings_new(id);
+ defer g_object_unref(settings);
+ var host: [129]u8 = undefined;
+ @memcpy(host[0..e.host.len], e.host.slice());
+ host[e.host.len] = 0;
+ _ = g_settings_set_string(settings, "host", @ptrCast(&host));
+ _ = g_settings_set_int(settings, "port", e.port);
+}
+
+/// Stores `config`. Blocks until the backend has it, so call it off the main thread.
+pub fn write(config: *const proxy.Config) void {
+ if (!available()) return;
+ const settings = g_settings_new(base);
+ defer g_object_unref(settings);
+ _ = g_settings_set_string(settings, "mode", switch (config.mode) {
+ .off => "none",
+ .manual => "manual",
+ .auto => "auto",
+ });
+ if (config.pac.len != 0) {
+ var pac: [257]u8 = undefined;
+ @memcpy(pac[0..config.pac.len], config.pac.slice());
+ pac[config.pac.len] = 0;
+ _ = g_settings_set_string(settings, "autoconfig-url", @ptrCast(&pac));
+ }
+ // The ignore list: one NUL-terminated copy of the text, split in place.
+ var text: [513]u8 = undefined;
+ var pointers: [65:null]?[*:0]const u8 = @splat(null);
+ var len: usize = 0;
+ var count: usize = 0;
+ var entries = proxy.ignoreEntries(config.ignore.slice());
+ while (entries.next()) |entry| {
+ if (count == pointers.len or len + entry.len + 1 > text.len) break;
+ @memcpy(text[len..][0..entry.len], entry);
+ text[len + entry.len] = 0;
+ pointers[count] = @ptrCast(text[len..].ptr);
+ count += 1;
+ len += entry.len + 1;
+ }
+ _ = g_settings_set_strv(settings, "ignore-hosts", &pointers);
+ writeEndpoint(base ++ ".http", config.http);
+ writeEndpoint(base ++ ".https", config.https);
+ writeEndpoint(base ++ ".socks", config.socks);
+ g_settings_sync();
+}
+
+const Job = struct { config: proxy.Config };
+
+fn work(job: *Job) void {
+ defer a.destroy(job);
+ write(&job.config);
+}
+
+/// `write` on a short-lived thread: a dconf write talks to the session bus.
+pub fn writeAsync(config: proxy.Config) void {
+ const job = a.create(Job) catch return;
+ job.* = .{ .config = config };
+ const thread = std.Thread.spawn(.{}, work, .{job}) catch {
+ a.destroy(job);
+ return;
+ };
+ thread.detach();
+}
diff --git a/src/network/types.zig b/src/network/types.zig
new file mode 100644
index 0000000..0e87235
--- /dev/null
+++ b/src/network/types.zig
@@ -0,0 +1,36 @@
+//! Small plain types shared by the NetworkManager client and its parsers.
+
+const std = @import("std");
+
+pub fn Text(comptime capacity: usize) type {
+ return struct {
+ bytes: [capacity]u8 = @splat(0),
+ len: usize = 0,
+ pub fn set(self: *@This(), value: []const u8) void {
+ self.len = @min(value.len, capacity);
+ @memcpy(self.bytes[0..self.len], value[0..self.len]);
+ }
+ pub fn slice(self: *const @This()) []const u8 {
+ return self.bytes[0..self.len];
+ }
+ pub fn init(value: []const u8) @This() {
+ var t: @This() = .{};
+ t.set(value);
+ return t;
+ }
+ };
+}
+pub const Path = Text(256);
+pub const Security = enum { open, personal, sae, unsupported };
+/// How a profile gets its addresses for one family.
+pub const Method = enum { auto, manual, link_local, shared, disabled, other };
+/// What NetworkManager assigned one interface for one address family (an
+/// IP4Config or IP6Config object); addresses read "address/prefix".
+pub const Config = struct {
+ path: Path = .{},
+ address: Text(256) = .{},
+ gateway: Text(64) = .{},
+ dns: Text(256) = .{},
+ domains: Text(256) = .{},
+};
+pub const Link = struct { v4: Config = .{}, v6: Config = .{} };
diff --git a/src/network_tests.zig b/src/network_tests.zig
new file mode 100644
index 0000000..72b499a
--- /dev/null
+++ b/src/network_tests.zig
@@ -0,0 +1,5 @@
+test {
+ _ = @import("network/manager_props.zig");
+ _ = @import("network/manager_profile.zig");
+ _ = @import("network/proxy.zig");
+}
diff --git a/src/platform/AGENTS.md b/src/platform/AGENTS.md
index 85032fb..8922a1b 100644
--- a/src/platform/AGENTS.md
+++ b/src/platform/AGENTS.md
@@ -4,7 +4,8 @@ The one place the OS shows: child handles (`child.zig`), directory watching
(`watch.zig`), the program's own path (`exe.zig`), who is on the other end of a
unix socket (`peer.zig`), process attributes such as no core dumps and no new
privileges (`process.zig`), descriptors that wake a poll loop (`wake.zig`),
-where the system's helper programs live (`tool.zig`), seccomp-BPF filters
+where the system's helper programs live (`tool.zig`), radio kill switches for
+airplane mode (`rfkill.zig`: Linux only, other systems report no radios), seccomp-BPF filters
(`seccomp.zig`, for the PDF viewer and the theme helper), and
`child.h`/`self_exe.h`/`peer.h`/`process.h` for C and C++, and `fs.zig`
(rename without replacing, stat), and `dirwalk.zig` (reading a directory and
diff --git a/src/platform/mod.zig b/src/platform/mod.zig
index fa2c667..0febc58 100644
--- a/src/platform/mod.zig
+++ b/src/platform/mod.zig
@@ -14,6 +14,7 @@ pub const peer = @import("peer.zig");
pub const process = @import("process.zig");
pub const wake = @import("wake.zig");
pub const power_supply = @import("power_supply.zig");
+pub const rfkill = @import("rfkill.zig");
pub const charge_limit = @import("charge_limit.zig");
pub const watch = @import("watch.zig");
pub const seccomp = @import("seccomp.zig");
@@ -27,6 +28,7 @@ test {
_ = fs;
_ = peer;
_ = process;
+ _ = rfkill;
_ = wake;
_ = system;
_ = tool;
diff --git a/src/platform/rfkill.zig b/src/platform/rfkill.zig
new file mode 100644
index 0000000..c9edf58
--- /dev/null
+++ b/src/platform/rfkill.zig
@@ -0,0 +1,106 @@
+//! Radio kill switches: which radios exist and whether software blocks them,
+//! and blocking or restoring them (airplane mode). Linux reads and writes
+//! `/dev/rfkill`; other systems report no radios.
+//!
+//! Reading `/dev/rfkill` yields one ADD event per radio already present. NetworkManager and BlueZ
+//! follow a soft block by themselves, so nothing else needs to be told.
+
+const std = @import("std");
+const builtin = @import("builtin");
+
+pub const max_radios = 32;
+/// The kernel's `struct rfkill_event` (version 1, which every kernel returns
+/// to an 8-byte read).
+pub const Event = extern struct { idx: u32, kind: u8, op: u8, soft: u8, hard: u8 };
+pub const op_add = 0;
+pub const op_change = 2;
+pub const op_change_all = 3;
+const kind_all = 0;
+
+pub const Radio = struct { idx: u32 = 0, soft: bool = false, hard: bool = false };
+pub const State = struct {
+ radios: [max_radios]Radio = @splat(.{}),
+ count: usize = 0,
+
+ /// Every radio is blocked by software (and there is at least one).
+ pub fn allBlocked(self: *const State) bool {
+ if (self.count == 0) return false;
+ for (self.radios[0..self.count]) |radio| if (!radio.soft and !radio.hard) return false;
+ return true;
+ }
+ /// Some radio is blocked by a switch software cannot move.
+ pub fn hardBlocked(self: *const State) bool {
+ for (self.radios[0..self.count]) |radio| if (radio.hard) return true;
+ return false;
+ }
+ fn add(self: *State, event: Event) void {
+ if (event.op != op_add or self.count == max_radios) return;
+ self.radios[self.count] = .{ .idx = event.idx, .soft = event.soft != 0, .hard = event.hard != 0 };
+ self.count += 1;
+ }
+};
+
+pub fn blockAllEvent(block: bool) Event {
+ return .{ .idx = 0, .kind = kind_all, .op = op_change_all, .soft = @intFromBool(block), .hard = 0 };
+}
+
+pub fn changeEvent(idx: u32, block: bool) Event {
+ return .{ .idx = idx, .kind = kind_all, .op = op_change, .soft = @intFromBool(block), .hard = 0 };
+}
+
+const supported = builtin.os.tag == .linux;
+const linux = std.os.linux;
+
+fn open(flags: linux.O) ?std.posix.fd_t {
+ const rc = std.posix.system.open("/dev/rfkill", flags, @as(c_uint, 0));
+ return if (rc < 0) null else @intCast(rc);
+}
+
+/// The radios now present; empty where there is no rfkill.
+pub fn read() State {
+ var state: State = .{};
+ if (!supported) return state;
+ const fd = open(.{ .ACCMODE = .RDONLY, .NONBLOCK = true, .CLOEXEC = true }) orelse return state;
+ defer _ = std.posix.system.close(fd);
+ while (true) {
+ var event: Event = undefined;
+ const n = std.posix.system.read(fd, @ptrCast(&event), @sizeOf(Event));
+ if (n != @sizeOf(Event)) break;
+ state.add(event);
+ }
+ return state;
+}
+
+fn send(event: Event) !void {
+ if (!supported) return error.Unsupported;
+ const fd = open(.{ .ACCMODE = .WRONLY, .CLOEXEC = true }) orelse return error.AccessDenied;
+ defer _ = std.posix.system.close(fd);
+ if (std.posix.system.write(fd, @ptrCast(&event), @sizeOf(Event)) != @sizeOf(Event)) return error.WriteFailed;
+}
+
+pub fn blockAll(block: bool) !void {
+ try send(blockAllEvent(block));
+}
+
+/// Puts each radio in `before` back as it was (those since removed are skipped).
+pub fn restore(before: *const State) !void {
+ for (before.radios[0..before.count]) |radio| try send(changeEvent(radio.idx, radio.soft));
+}
+
+test "radio states" {
+ try std.testing.expectEqual(@as(usize, 8), @sizeOf(Event));
+ var state: State = .{};
+ try std.testing.expect(!state.allBlocked());
+ state.add(.{ .idx = 0, .kind = 1, .op = op_add, .soft = 1, .hard = 0 });
+ state.add(.{ .idx = 1, .kind = 2, .op = op_add, .soft = 0, .hard = 0 });
+ state.add(.{ .idx = 9, .kind = 2, .op = op_change, .soft = 1, .hard = 0 });
+ try std.testing.expectEqual(@as(usize, 2), state.count);
+ try std.testing.expect(!state.allBlocked() and !state.hardBlocked());
+ state.radios[1].soft = true;
+ try std.testing.expect(state.allBlocked());
+ state.radios[0] = .{ .idx = 0, .soft = false, .hard = true };
+ try std.testing.expect(state.allBlocked() and state.hardBlocked());
+ try std.testing.expectEqual(@as(u8, 1), blockAllEvent(true).soft);
+ try std.testing.expectEqual(@as(u8, op_change_all), blockAllEvent(false).op);
+ try std.testing.expectEqual(@as(u32, 3), changeEvent(3, false).idx);
+}
diff --git a/src/ui_tests.zig b/src/ui_tests.zig
index cd70616..54ef21b 100644
--- a/src/ui_tests.zig
+++ b/src/ui_tests.zig
@@ -63,6 +63,7 @@ test {
_ = @import("start_menu/catalog_cache.zig");
_ = @import("startup.zig");
_ = @import("startup_tasks.zig");
+ _ = @import("gl_vendor.zig");
_ = @import("start_menu/launch.zig");
_ = @import("start_menu/search.zig");
_ = @import("start_menu/model.zig");
diff --git a/tests/appearance_settings.py b/tests/appearance_settings.py
index 1109243..e403192 100644
--- a/tests/appearance_settings.py
+++ b/tests/appearance_settings.py
@@ -408,7 +408,10 @@ def test_appearance_settings():
# Picking a theme preserves personal edits, including the
# opacity set above. Only Reset discards those overrides.
- theme_indices = {pack["id"]: i for i, pack in enumerate(ipc.query("theme.list")["packs"])}
+ # IPC lists every pack; the picker leaves out the retired ones (picker_hidden)
+ # unless one is active, so positions are counted over the rest.
+ shown_packs = [pack for pack in ipc.query("theme.list")["packs"] if pack["id"] not in ("redi-mocha", "gold")]
+ theme_indices = {pack["id"]: i for i, pack in enumerate(shown_packs)}
light_index = theme_indices["rediwm-light"]
dark_index = theme_indices["rediwm-dark"]
before_switch = read_config()
@@ -521,8 +524,7 @@ def test_appearance_settings():
ipc.wait_for_panel_settled("control_center")
assert ui.scroll_into_view("theme")["selected_index"] == light_index
# Redi Blue applies every supplied token and survives reload.
- blue_index = next(i for i, pack in enumerate(ipc.query("theme.list")["packs"])
- if pack["id"] == "redi-blue")
+ blue_index = theme_indices["redi-blue"]
click_widget(ui.scroll_into_view("theme"))
ipc.key_press("Home")
for _ in range(blue_index):
diff --git a/tests/editor.py b/tests/editor.py
index 1146612..717aade 100644
--- a/tests/editor.py
+++ b/tests/editor.py
@@ -22,6 +22,21 @@ def run():
(docs / "binary.txt").write_bytes(b"binary\x00data")
from PIL import Image
Image.new("RGB", (40, 40), "red").save(docs / "z image.png")
+ gamma = docs / "gamma.txt"
+ gamma.write_text("from the recent list\n")
+ # An older shared history: a text file, a missing one and a picture. Open
+ # Recent must offer only the first.
+ entries = "".join(
+ f'<bookmark href="{path.as_uri()}" added="2020-01-01T00:00:00Z" modified="2020-01-01T00:00:00Z" visited="2020-01-01T00:00:0{n}Z">'
+ f'<info><metadata owner="http://freedesktop.org"><mime:mime-type type="{mime}"/>'
+ '<bookmark:applications><bookmark:application name="Seed" exec="seed %f" modified="2020-01-01T00:00:00Z" count="1"/></bookmark:applications>'
+ '</metadata></info></bookmark>'
+ for n, (path, mime) in enumerate([(gamma, "text/plain"), (docs / "gone.txt", "text/plain"), (docs / "z image.png", "image/png")]))
+ (tmp / "data").mkdir()
+ (tmp / "data" / "recently-used.xbel").write_text(
+ '<?xml version="1.0" encoding="UTF-8"?>\n<xbel version="1.0" '
+ 'xmlns:bookmark="http://www.freedesktop.org/standards/desktop-bookmarks" '
+ 'xmlns:mime="http://www.freedesktop.org/standards/shared-mime-info">' + entries + '</xbel>\n')
config = tmp / "config.toml"
config.write_text('[compositor]\nxwayland = false\n')
env = dict(os.environ, HOME=directory, XDG_RUNTIME_DIR=directory,
@@ -80,7 +95,7 @@ def run():
box = ipc.get_window_debug(win["id"])["client_box"]
# CSD hosts the menu in its header; SSD uses the tab bar.
click(win, box["width"] - (132 if csd else 18), 23)
- separators = int(row >= 2) + int(row >= 4)
+ separators = int(row >= 3) + int(row >= 5)
click(win, box["width"] - 200, (52 if csd else 44) + 6 + row * 32 + separators * 7 + 16)
def window_control(offset):
@@ -120,11 +135,31 @@ def run():
title("alpha.txt")
key(21, ctrl=True) # redo x
title("* alpha.txt")
- menu_action(2) # Save through the application menu.
+ menu_action(3) # Save through the application menu.
wait_for(lambda: first.read_bytes() == b"\xef\xbb\xbfhello\r\nworld\r\nx", "save bytes and BOM/CRLF")
title("alpha.txt")
print("Space opens text; typing, undo/redo and lossless save", flush=True)
+ # A load and a save add the file to the shared history under the editor's name.
+ history = tmp / "data" / "recently-used.xbel"
+ wait_for(lambda: "RediWM Editor" in history.read_text() and "alpha.txt" in history.read_text(), "editor records recent files")
+ # Open Recent lists the newest text file first (the one just saved), then the
+ # seeded one; the missing file and the picture are left out.
+ def recent_entry(index):
+ win = editor()
+ box = ipc.get_window_debug(win["id"])["client_box"]
+ click(win, box["width"] - (132 if csd else 18), 23)
+ y = (52 if csd else 44) + 6 + 2 * 32 + 16
+ click(win, box["width"] - 200, y) # the row opens its submenu beside the menu
+ click(win, box["width"] - 460, y + index * 32)
+ recent_entry(1)
+ win = title("gamma.txt")
+ assert "(2/2)" in win["title"], win
+ key(17, ctrl=True) # close it again
+ win = title("alpha.txt")
+ assert "(1/1)" in win["title"], win
+ print("Open Recent lists text files that exist and opens one", flush=True)
+
ipc.focus_window(files["id"])
key(106) # next file in grid
key(57)
@@ -230,7 +265,7 @@ def run():
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
+ menu_action(6) # Replace is also discoverable in the menu
ipc.type_text("catfish")
key(15)
key(14) # Empty replacement deletes every match
diff --git a/tests/network_settings.py b/tests/network_settings.py
new file mode 100644
index 0000000..ade683d
--- /dev/null
+++ b/tests/network_settings.py
@@ -0,0 +1,363 @@
+#!/usr/bin/env python3
+"""Settings → Network against the fake NetworkManager (tests/nm_fake.py); never touches host networking."""
+import json
+import os
+from pathlib import Path
+import select
+import queue
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+
+from ipc_client import IPCClient, spawn_compositor, stop_process
+from power_profiles import wait_for, read_line
+from ui_driver import UIDriver
+
+HERE = Path(__file__).resolve().parent
+
+
+def start_fake():
+ process = subprocess.Popen([sys.executable, str(HERE / 'nm_fake.py')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
+ assert select.select([process.stdout], [], [], 5)[0]
+ assert process.stdout.readline().strip() == 'ready'
+ return process
+
+
+class Page:
+ """The compositor, its Settings window and the fake NetworkManager."""
+
+ def __init__(self, ipc, fake):
+ self.ipc, self.fake, self.ui, self.events = ipc, fake, UIDriver(ipc), []
+ # Lines can arrive together; a thread keeps them from hiding in a buffer.
+ self.lines = queue.Queue()
+ threading.Thread(target=self.pump, daemon=True).start()
+
+ def pump(self):
+ for line in self.fake.stdout:
+ self.lines.put(json.loads(line))
+
+ def labels(self):
+ return [w['label'] for w in self.ui.widgets() if w.get('label')]
+
+ def find(self, name):
+ return self.ui.find(name, panel='control_center')
+
+ def has(self, name):
+ return any(w.get('name') == name for w in self.ui.widgets())
+
+ def command(self, **values):
+ self.fake.stdin.write(json.dumps(values) + '\n')
+ self.fake.stdin.flush()
+ while True:
+ line = self.lines.get(timeout=5)
+ if line == {'done': True}:
+ return
+ self.events.append(line)
+
+ def drain(self, wait=0.0):
+ try:
+ while True:
+ self.events.append(self.lines.get(timeout=wait) if wait else self.lines.get_nowait())
+ except queue.Empty:
+ pass
+
+ def event(self, key, timeout=5):
+ """The next fake event that has `key`."""
+ deadline = time.monotonic() + timeout
+ while True:
+ self.drain()
+ for i, line in enumerate(self.events):
+ if key in line:
+ return self.events.pop(i)
+ assert time.monotonic() < deadline, f'no {key} event; saw {self.events}'
+ time.sleep(.05)
+
+ def no_event(self, key):
+ self.drain(.5)
+ assert not any(key in line for line in self.events), self.events
+
+ def click(self, name):
+ wait_for(lambda: self.has(name) and not self.find(name)['is_disabled'], name + ' enabled')
+ if not name.startswith('wifi_'):
+ self.ui.click(self.ui.scroll_into_view(name, panel='control_center'), panel='control_center')
+ self.ui.wait_settled('control_center')
+ return
+ for _ in range(14):
+ widget = self.find(name)
+ if widget['visible'] and not widget['clipped']:
+ self.ui.click(widget, panel='control_center')
+ self.ui.wait_settled('control_center')
+ return
+ # The Wi-Fi list scrolls inside the page, which scrolls too.
+ outer = next(w for w in self.ui.widgets() if w['role'] == 'scroll_container')
+ inner = self.find('wifi_networks') if name.startswith('wifi_') and self.has('wifi_networks') else None
+ viewport = inner if inner and inner['visible'] and not inner['clipped'] else outer
+ box = viewport['global_box']
+ self.ipc.move_cursor(box['x'] + box['width'] - 8, box['y'] + box['height'] // 2)
+ self.ipc.scroll(0, -120 if widget['box']['y'] > viewport['box']['y'] else 120)
+ self.ui.wait_settled('control_center')
+ raise AssertionError('could not reveal ' + name)
+
+ def key(self, code):
+ for pressed in (True, False):
+ self.ipc.action('key', {'keycode': code, 'pressed': pressed})
+ time.sleep(.12)
+
+ def choose(self, name, steps):
+ """Open a dropdown and move `steps` entries down (negative: up) with the keyboard."""
+ self.click(name)
+ for _ in range(abs(steps)):
+ self.key(108 if steps > 0 else 103)
+ self.key(28)
+ self.ui.wait_settled('control_center')
+
+ def clear(self, name):
+ self.click(name)
+ self.key(107) # End
+ for _ in range(60):
+ self.key(14)
+
+ def type_into(self, name, text):
+ self.click(name)
+ self.ipc.type_text(text)
+ self.ui.wait_settled('control_center')
+
+ def open_network(self):
+ self.ipc.open_control_center()
+ self.ui.wait_settled('control_center')
+ self.ui.click('network', panel='control_center')
+
+
+def details(page):
+ page.open_network()
+ wait_for(lambda: '192.168.1.100/24' in page.labels(), 'Ethernet IPv4 address with its prefix')
+ page.ui.wait_settled('control_center')
+ shown = page.labels()
+ for want in ('2001:db8::2a/64', 'fe80::1', '2001:db8::53', 'lan', '3C:EC:EF:12:34:56', '1.1.1.1, 1.0.0.1'):
+ assert want in shown, (want, shown)
+ wait_for(lambda: 'IPv4 Automatic · IPv6 Automatic' in page.labels(), 'Ethernet profile methods')
+ print('Ethernet shows IPv4, IPv6, search domains and the profile methods', flush=True)
+
+ page.ui.click(page.find('wifi_network_0'), panel='control_center')
+ page.ui.wait_settled('control_center')
+ wait_for(lambda: '10.0.0.23/24' in page.labels(), 'Wi-Fi IPv4 address')
+ shown = page.labels()
+ for want in ('WPA2/WPA3 Personal', '90%', '5 GHz · channel 36', '866 Mbps', '11:22:33:44:55:01', '10.0.0.1',
+ 'fe80::a8bb:ccff:fedd:ee01/64', 'AA:BB:CC:DD:EE:01'):
+ assert want in shown, (want, shown)
+ assert not page.has('network_unlock'), 'policy allows changes: nothing to unlock'
+ print('Wi-Fi details: security, signal, band, link speed, access point and addresses', flush=True)
+
+
+def edits(page):
+ # Auto-connect is one quick toggle; the rest of the profile must survive it.
+ page.click('wifi_autoconnect')
+ event = page.event('update')
+ assert event['update'].endswith('/Settings/1') and event['settings']['connection']['autoconnect'] is False, event
+ assert event['settings']['802-11-wireless-security']['key-mgmt'] == 'wpa-psk', 'secret settings were dropped'
+ assert event['settings']['802-11-wireless']['ssid'] == list(b'REDI_Home')
+ page.click('wifi_autoconnect')
+ assert page.event('update')['settings']['connection']['autoconnect'] is True
+ print('Auto-connect toggles in place and keeps the rest of the profile', flush=True)
+
+ page.click('wifi_edit')
+ wait_for(lambda: page.has('edit_v4_method'), 'editor opens with the profile')
+ page.choose('edit_v4_method', 1) # Manual
+ wait_for(lambda: page.has('edit_v4_address'), 'manual IPv4 fields')
+ # A bad prefix is refused before anything is sent.
+ page.type_into('edit_v4_address', '10.0.0.77')
+ page.type_into('edit_v4_prefix', '99')
+ page.click('edit_save')
+ wait_for(lambda: 'Enter an IPv4 prefix length from 1 to 32.' in page.labels(), 'prefix validation message')
+ page.no_event('update')
+ page.click('edit_v4_prefix')
+ for _ in range(2):
+ page.key(14) # backspace
+ page.type_into('edit_v4_prefix', '24')
+ page.type_into('edit_v4_gateway', '10.0.0.1')
+ page.choose('edit_dns_mode', 1) # Custom
+ page.type_into('edit_dns', '1.1.1.1, 2606:4700:4700::1111')
+ page.type_into('edit_mtu', '1400')
+ page.choose('edit_metered', 1) # Yes
+ page.click('edit_save')
+ event = page.event('update')
+ settings = event['settings']
+ assert settings['ipv4']['method'] == 'manual', settings['ipv4']
+ assert settings['ipv4']['address-data'] == [{'address': '10.0.0.77', 'prefix': 24}], settings['ipv4']
+ assert settings['ipv4']['gateway'] == '10.0.0.1' and settings['ipv4']['ignore-auto-dns'] is True
+ assert settings['ipv4']['dns'] == [int.from_bytes(bytes([1, 1, 1, 1]), sys.byteorder)], settings['ipv4']
+ assert settings['ipv6']['dns'] == [list(bytes.fromhex('26064700470000000000000000001111'))], settings['ipv6']
+ assert settings['ipv6']['method'] == 'auto' and settings['connection']['metered'] == 1, settings
+ assert settings['802-11-wireless']['mtu'] == 1400 and settings['802-11-wireless']['ssid'] == list(b'REDI_Home')
+ assert settings['802-11-wireless-security']['key-mgmt'] == 'wpa-psk'
+ activated = page.event('activate')
+ assert activated['activate'].endswith('/Settings/1') and activated['device'].endswith('/Devices/1'), activated
+ wait_for(lambda: 'Saved.' in page.labels(), 'saved message')
+ print('Editor saves manual IPv4, custom DNS, MTU and metered, then reapplies the connection', flush=True)
+ shot = Path('/tmp/rediwm-network-editor.png')
+ shot.unlink(missing_ok=True)
+ page.ipc.screenshot(str(shot))
+
+ page.click('edit_forget')
+ assert page.find('edit_forget')['label'] == 'Confirm forget'
+ page.no_event('delete')
+ page.click('edit_forget')
+ assert page.event('delete')['delete'].endswith('/Settings/1')
+ wait_for(lambda: not page.has('edit_card'), 'editor closes after forgetting')
+ print('Forget asks twice, then deletes the profile', flush=True)
+
+
+def locked(page):
+ page.open_network()
+ wait_for(lambda: page.has('network_unlock'), 'Unlock prompt when polkit wants authentication')
+ assert 'Unlock to change connection settings.' in page.labels()
+ page.ui.click(page.find('wifi_network_0'), panel='control_center')
+ page.ui.wait_settled('control_center')
+ assert page.find('wifi_forget')['is_disabled'] and page.find('wifi_autoconnect')['is_disabled']
+ page.click('network_unlock')
+ while not page.event('interactive')['interactive']:
+ pass # the quiet check made when the page opened came first
+ wait_for(lambda: not page.has('network_unlock'), 'Unlock goes away once authorised')
+ wait_for(lambda: not page.find('wifi_forget')['is_disabled'], 'actions enable after unlocking')
+ print('Unlock asks polkit with interaction and enables the actions', flush=True)
+
+
+def vpn(page):
+ page.open_network()
+ wait_for(lambda: 'Work VPN' in page.labels() and 'wg0' in page.labels(), 'VPN and WireGuard profiles are listed')
+ assert 'Studio_5G' not in [w['label'] for w in page.ui.widgets() if (w.get('name') or '').startswith('vpn_')], 'Wi-Fi profiles are not VPNs'
+ states = [w['label'] for w in page.ui.widgets() if w.get('label') in ('Connected', 'Not connected')]
+ assert page.find('vpn_toggle_0')['label'] == 'Disconnect' and page.find('vpn_toggle_1')['label'] == 'Connect', 'one VPN is up, one is not'
+ page.click('vpn_toggle_1') # connect wg0
+ event = page.event('activate')
+ assert event['activate'].endswith('/Settings/5') and event['device'] == '/', event
+ wait_for(lambda: page.find('vpn_toggle_1')['label'] == 'Disconnect', 'wg0 shows connected')
+ page.click('vpn_toggle_0') # disconnect the OpenVPN one
+ page.event('deactivate')
+ wait_for(lambda: page.find('vpn_toggle_0')['label'] == 'Connect', 'Work VPN shows disconnected')
+ print('VPN list, connect and disconnect', flush=True)
+ page.click('vpn_remove_0')
+ assert page.find('vpn_remove_0')['label'] == 'Confirm remove'
+ page.no_event('delete')
+ page.click('vpn_remove_0')
+ assert page.event('delete')['delete'].endswith('/Settings/4')
+ wait_for(lambda: 'Work VPN' not in page.labels(), 'removed VPN leaves the list')
+ print('Remove asks twice, then deletes the VPN profile', flush=True)
+
+
+def proxy(page, tmp):
+ keyfile = tmp / 'config' / 'glib-2.0' / 'settings' / 'keyfile'
+
+ def stored():
+ import configparser
+ parser = configparser.ConfigParser(interpolation=None)
+ parser.optionxform = str
+ parser.read(keyfile)
+ return parser
+
+ def spawn_env():
+ received, probe = tmp / 'child-env.json', tmp / 'env.py'
+ received.unlink(missing_ok=True)
+ probe.write_text('import os, json, sys\nfrom pathlib import Path\n'
+ 'Path(sys.argv[1]).write_text(json.dumps({k: v for k, v in os.environ.items() if "proxy" in k.lower()}))\n')
+ page.ipc.action('spawn', {'argv': [sys.executable, str(probe), str(received)]})
+ wait_for(received.exists, 'app environment')
+ time.sleep(.1)
+ return json.loads(received.read_text())
+
+ page.open_network()
+ wait_for(lambda: page.has('proxy_mode'), 'proxy card')
+ page.choose('proxy_mode', 1) # Manual
+ wait_for(lambda: page.has('proxy_http_host'), 'manual proxy fields')
+ page.type_into('proxy_http_host', 'proxy.test')
+ page.clear('proxy_http_port')
+ page.type_into('proxy_http_port', '99999')
+ page.click('proxy_apply')
+ wait_for(lambda: 'Check the HTTP proxy host and port (1–65535).' in page.labels(), 'port validation')
+ assert not keyfile.exists() or stored().get('system/proxy', 'mode', fallback="'none'") == "'none'", 'nothing is stored for a bad value'
+ page.clear('proxy_http_port') # the schema fills in 8080
+ page.type_into('proxy_http_port', '3128')
+ page.type_into('proxy_socks_host', '127.0.0.1')
+ page.type_into('proxy_socks_port', '1080')
+ page.clear('proxy_ignore')
+ page.type_into('proxy_ignore', 'localhost, 10.0.0.0/8')
+ page.click('proxy_apply')
+ wait_for(lambda: any('Applied.' in label for label in page.labels()), 'applied message: ' + repr([l for l in page.labels() if 'proxy' in l.lower() or 'Check' in l or 'Enter' in l or 'port' in l.lower()]))
+ wait_for(lambda: keyfile.exists() and stored().get('system/proxy', 'mode', fallback='') == "'manual'", 'GSettings mode', timeout=10)
+ config = stored()
+ assert config.get('system/proxy/http', 'host') == "'proxy.test'" and config.get('system/proxy/http', 'port') == '3128', dict(config['system/proxy/http'])
+ assert config.get('system/proxy/socks', 'host') == "'127.0.0.1'" and config.get('system/proxy/socks', 'port') == '1080'
+ assert config.get('system/proxy', 'ignore-hosts') == "['localhost', '10.0.0.0/8']", config.get('system/proxy', 'ignore-hosts')
+ env = spawn_env()
+ assert env.get('http_proxy') == 'http://proxy.test:3128' and env.get('HTTP_PROXY') == env['http_proxy'], env
+ assert env.get('all_proxy') == 'socks5h://127.0.0.1:1080' and env.get('no_proxy') == 'localhost,10.0.0.0/8', env
+ assert 'https_proxy' not in env, env
+ print('Manual proxy is stored in GSettings and exported to apps started afterwards', flush=True)
+
+ page.choose('proxy_mode', 1) # Automatic
+ wait_for(lambda: page.has('proxy_pac'), 'PAC field')
+ page.type_into('proxy_pac', 'wpad.local/wpad.dat')
+ page.click('proxy_apply')
+ wait_for(lambda: 'Enter an http://, https:// or file:// address.' in page.labels(), 'PAC validation')
+ page.clear('proxy_pac')
+ page.type_into('proxy_pac', 'http://wpad.test/wpad.dat')
+ page.click('proxy_apply')
+ wait_for(lambda: stored().get('system/proxy', 'mode', fallback='') == "'auto'", 'automatic mode stored', timeout=10)
+ assert stored().get('system/proxy', 'autoconfig-url') == "'http://wpad.test/wpad.dat'"
+ assert 'http_proxy' not in spawn_env(), 'a script cannot be exported as a variable'
+ print('Automatic proxy stores its script address and exports nothing', flush=True)
+
+ page.choose('proxy_mode', -2) # Automatic -> Off
+ page.click('proxy_apply')
+ wait_for(lambda: stored().get('system/proxy', 'mode', fallback='') == "'none'", 'proxy off stored', timeout=10)
+ assert not spawn_env()
+ print('Off stores none and stops exporting', flush=True)
+
+
+def run(scenario, scale=1):
+ fake = start_fake()
+ with tempfile.TemporaryDirectory(prefix='rediwm-network-') as directory:
+ tmp = Path(directory)
+ process, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get('REDIWM_TEST_RENDERER', 'gles2'), config_content='[compositor]\nxwayland = false\n', env_extra={
+ 'DBUS_SYSTEM_BUS_ADDRESS': os.environ['DBUS_SESSION_BUS_ADDRESS'], 'DBUS_SESSION_BUS_ADDRESS': '', 'XDG_CACHE_HOME': str(tmp),
+ 'PIPEWIRE_RUNTIME_DIR': str(tmp), 'PULSE_SERVER': 'unix:/nonexistent-rediwm-test-pulse',
+ # GSettings writes go to a file in the scratch directory, never the user's dconf.
+ 'GSETTINGS_BACKEND': 'keyfile', 'XDG_CONFIG_HOME': str(tmp / 'config'),
+ })
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ page = Page(ipc, fake)
+ if scenario == 'vpn':
+ vpn(page)
+ elif scenario == 'proxy':
+ proxy(page, tmp)
+ elif scenario == 'locked':
+ page.command(polkit='challenge')
+ locked(page)
+ else:
+ details(page)
+ shot = Path('/tmp/rediwm-network-details.png')
+ shot.unlink(missing_ok=True)
+ ipc.screenshot(str(shot))
+ edits(page)
+ except BaseException:
+ log.flush()
+ print(Path(log.name).read_text()[-6000:] if hasattr(log, 'name') else 'no log', file=sys.stderr)
+ raise
+ finally:
+ stop_process(process)
+ fake.kill()
+ fake.wait()
+
+
+if __name__ == '__main__':
+ run('open')
+ run('locked')
+ run('vpn')
+ if subprocess.run(['gsettings', 'list-schemas'], capture_output=True, text=True).stdout.count('org.gnome.system.proxy'):
+ run('proxy')
+ else:
+ print('SKIP: proxy needs the org.gnome.system.proxy schemas')
+ print('PASS Network settings: details, editing, forgetting and unlock')
diff --git a/tests/nm_fake.py b/tests/nm_fake.py
new file mode 100644
index 0000000..12a2215
--- /dev/null
+++ b/tests/nm_fake.py
@@ -0,0 +1,254 @@
+#!/usr/bin/env python3
+"""A fake NetworkManager on the session bus for the Network settings tests.
+
+Run as a subprocess: it prints one JSON line per event the compositor causes
+(updates, deletes, activations) and takes JSON commands on stdin, answering each
+with {"done": true}. Never talks to the host's NetworkManager.
+"""
+import json
+import sys
+import warnings
+warnings.simplefilter('ignore', DeprecationWarning)
+from gi.repository import Gio, GLib
+
+NM = 'org.freedesktop.NetworkManager'
+ROOT = '/org/freedesktop/NetworkManager'
+OBJECTS_ROOT = '/org/freedesktop'
+SETTINGS = ROOT + '/Settings'
+CONN = NM + '.Settings.Connection'
+WIFI = ROOT + '/Devices/1'
+ETH = ROOT + '/Devices/2'
+AP = ROOT + '/AccessPoint/'
+v = GLib.Variant
+bus = Gio.bus_get_sync(Gio.BusType.SESSION)
+
+
+def ip(a, b, c, d):
+ """An IPv4 address as NetworkManager's `dns` property carries it: network byte order."""
+ return int.from_bytes(bytes([a, b, c, d]), sys.byteorder)
+
+
+def settings(kind, name, **extra):
+ """a{sa{sv}} for a saved profile."""
+ out = {'connection': {'id': v('s', name), 'type': v('s', kind), 'autoconnect': v('b', True)},
+ 'ipv4': {'method': v('s', 'auto')}, 'ipv6': {'method': v('s', 'auto')}}
+ if kind == '802-11-wireless':
+ out['802-11-wireless'] = {'ssid': v('ay', list(name.encode()))}
+ out['802-11-wireless-security'] = {'key-mgmt': v('s', 'wpa-psk'), 'psk-flags': v('u', 0)}
+ if kind == '802-3-ethernet':
+ out['802-3-ethernet'] = {}
+ if kind == 'vpn':
+ out['vpn'] = {'service-type': v('s', 'org.freedesktop.NetworkManager.openvpn')}
+ if kind == 'wireguard':
+ out['wireguard'] = {'listen-port': v('u', 0)}
+ for section, props in extra.items():
+ out.setdefault(section.replace('_', '-'), {}).update(props)
+ return out
+
+
+state = {
+ 'enabled': True, 'hardware': True, 'global_state': 70, 'connectivity': 4,
+ 'wifi_active': 1, 'eth_state': 100, 'vpn_active': [4],
+ # polkit answer to CheckAuthorization: 'yes', 'challenge' (needs interaction) or 'no'
+ 'polkit': 'yes', 'polkit_grant': True,
+ 'profiles': {
+ SETTINGS + '/1': v('a{sa{sv}}', settings('802-11-wireless', 'REDI_Home')),
+ SETTINGS + '/2': v('a{sa{sv}}', settings('802-3-ethernet', 'Wired connection 1')),
+ SETTINGS + '/3': v('a{sa{sv}}', settings('802-11-wireless', 'Studio_5G')),
+ SETTINGS + '/4': v('a{sa{sv}}', settings('vpn', 'Work VPN')),
+ SETTINGS + '/5': v('a{sa{sv}}', settings('wireguard', 'wg0')),
+ },
+}
+names = ['REDI_Home', 'Studio_5G', 'Cafe_WiFi']
+freq = [5180, 2437, 5955]
+
+
+def array_of_dicts(items):
+ return v('aa{sv}', [{k: val for k, val in item.items()} for item in items])
+
+
+def objects():
+ result = {ROOT: {NM: {'WirelessEnabled': v('b', state['enabled']), 'WirelessHardwareEnabled': v('b', state['hardware']),
+ 'State': v('u', state['global_state']), 'Connectivity': v('u', state['connectivity'])}}}
+ for path in state['profiles']:
+ result[path] = {CONN: {}}
+ result[ETH] = {NM + '.Device': {'Interface': v('s', 'enp4s0'), 'Driver': v('s', 'r8169'), 'Managed': v('b', True), 'State': v('u', state['eth_state']),
+ 'Ip4Config': v('o', ROOT + '/IP4Config/2'), 'Ip6Config': v('o', ROOT + '/IP6Config/2'),
+ 'ActiveConnection': v('o', ROOT + '/ActiveConnection/2'),
+ 'AvailableConnections': v('ao', [SETTINGS + '/2'])},
+ NM + '.Device.Wired': {'Carrier': v('b', True), 'Speed': v('u', 2500), 'HwAddress': v('s', '3C:EC:EF:12:34:56')}}
+ result[ROOT + '/IP4Config/2'] = {NM + '.IP4Config': {
+ 'AddressData': array_of_dicts([{'address': v('s', '192.168.1.100'), 'prefix': v('u', 24)}]), 'Gateway': v('s', '192.168.1.1'),
+ 'NameserverData': array_of_dicts([{'address': v('s', '1.1.1.1')}, {'address': v('s', '1.0.0.1')}]), 'Searches': v('as', ['lan'])}}
+ result[ROOT + '/IP6Config/2'] = {NM + '.IP6Config': {
+ 'AddressData': array_of_dicts([{'address': v('s', '2001:db8::2a'), 'prefix': v('u', 64)}]), 'Gateway': v('s', 'fe80::1'),
+ 'Nameservers': v('aay', [list(bytes.fromhex('20010db8000000000000000000000053'))])}}
+ result[ROOT + '/ActiveConnection/2'] = {NM + '.Connection.Active': {'Id': v('s', 'Wired connection 1'), 'Type': v('s', '802-3-ethernet'),
+ 'Connection': v('o', SETTINGS + '/2'), 'State': v('u', 2)}}
+ active = state['wifi_active']
+ result[WIFI] = {NM + '.Device': {'Interface': v('s', 'wlan0'), 'State': v('u', 100 if active else 30), 'Ip4Config': v('o', ROOT + '/IP4Config/1'),
+ 'Ip6Config': v('o', ROOT + '/IP6Config/1'), 'ActiveConnection': v('o', ROOT + '/ActiveConnection/1' if active else '/'),
+ 'HwAddress': v('s', 'AA:BB:CC:DD:EE:01')},
+ NM + '.Device.Wireless': {'LastScan': v('x', 1), 'Bitrate': v('u', 866000), 'HwAddress': v('s', 'AA:BB:CC:DD:EE:01'),
+ 'ActiveAccessPoint': v('o', AP + str(active) if active else '/'),
+ 'AccessPoints': v('ao', [AP + str(i + 1) for i in range(len(names))])}}
+ result[ROOT + '/IP4Config/1'] = {NM + '.IP4Config': {
+ 'AddressData': array_of_dicts([{'address': v('s', '10.0.0.23'), 'prefix': v('u', 24)}]), 'Gateway': v('s', '10.0.0.1'),
+ 'NameserverData': array_of_dicts([{'address': v('s', '10.0.0.1')}])}}
+ result[ROOT + '/IP6Config/1'] = {NM + '.IP6Config': {
+ 'AddressData': array_of_dicts([{'address': v('s', 'fe80::a8bb:ccff:fedd:ee01'), 'prefix': v('u', 64)}])}}
+ result[ROOT + '/ActiveConnection/1'] = {NM + '.Connection.Active': {'Id': v('s', 'REDI_Home'), 'Type': v('s', '802-11-wireless'),
+ 'Connection': v('o', SETTINGS + '/1'), 'State': v('u', 2)}}
+ for n in state['vpn_active']:
+ result[ROOT + '/ActiveConnection/%d' % n] = {NM + '.Connection.Active': {
+ 'Id': v('s', 'Work VPN' if n == 4 else 'wg0'), 'Type': v('s', 'vpn' if n == 4 else 'wireguard'),
+ 'Connection': v('o', SETTINGS + '/%d' % n), 'State': v('u', 2)}}
+ for i, name in enumerate(names):
+ result[AP + str(i + 1)] = {NM + '.AccessPoint': {'Ssid': v('ay', list(name.encode())), 'Strength': v('y', 90 - i * 20), 'Flags': v('u', 1),
+ 'WpaFlags': v('u', 0), 'RsnFlags': v('u', 0x100), 'Frequency': v('u', freq[i]),
+ 'HwAddress': v('s', '11:22:33:44:55:0%d' % (i + 1))}}
+ return result
+
+
+def emit(path, iface, member, params):
+ bus.emit_signal(None, path, iface, member, params)
+ bus.flush_sync()
+
+
+def changed():
+ emit(ROOT, 'org.freedesktop.DBus.Properties', 'PropertiesChanged', v('(sa{sv}as)', (NM, {'WirelessEnabled': v('b', state['enabled'])}, [])))
+
+
+def event(**values):
+ print(json.dumps(values), flush=True)
+
+
+def plain(value):
+ """JSON-friendly copy of an unpacked value."""
+ if isinstance(value, dict):
+ return {k: plain(x) for k, x in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [plain(x) for x in value]
+ if isinstance(value, bytes):
+ return list(value)
+ return value
+
+
+def method(c, sender, path, iface, name, params, inv):
+ if name == 'GetManagedObjects':
+ inv.return_value(v('(a{oa{sa{sv}}})', (objects(),)))
+ elif name == 'GetSettings':
+ inv.return_value(GLib.Variant.new_tuple(state['profiles'][path]))
+ else:
+ handler = HANDLERS.get(name)
+ if handler is None:
+ inv.return_dbus_error(NM + '.Failed', 'fake has no ' + name)
+ else:
+ handler(path, params, inv)
+
+
+HANDLERS = {}
+PROFILE_XML = ('<interface name="%s"><method name="GetSettings"><arg direction="out" type="a{sa{sv}}"/></method>'
+ '<method name="Update"><arg direction="in" type="a{sa{sv}}"/></method><method name="Delete"/></interface>' % CONN)
+
+
+def update(path, params, inv):
+ state['profiles'][path] = params.get_child_value(0)
+ event(update=path, settings=plain(state['profiles'][path].unpack()))
+ inv.return_value(v('()', ()))
+ emit(path, CONN, 'Updated', None)
+
+
+def delete(path, params, inv):
+ state['profiles'].pop(path, None)
+ event(delete=path)
+ inv.return_value(v('()', ()))
+ emit(OBJECTS_ROOT, 'org.freedesktop.DBus.ObjectManager', 'InterfacesRemoved', v('(oas)', (path, [CONN])))
+
+
+def activate(path, params, inv):
+ profile, device, specific = params.unpack()
+ event(activate=profile, device=device, specific=specific)
+ if device == '/': # a VPN needs no adapter
+ n = int(profile.rsplit('/', 1)[-1])
+ if n not in state['vpn_active']:
+ state['vpn_active'].append(n)
+ inv.return_value(v('(o)', (ROOT + '/ActiveConnection/%d' % n,)))
+ else:
+ inv.return_value(v('(o)', (ROOT + '/ActiveConnection/1',)))
+ changed()
+
+
+def deactivate(path, params, inv):
+ event(deactivate=params.unpack()[0])
+ n = int(params.unpack()[0].rsplit('/', 1)[-1])
+ if n in state['vpn_active']:
+ state['vpn_active'].remove(n)
+ inv.return_value(v('()', ()))
+ changed()
+
+
+def disconnect(path, params, inv):
+ event(disconnect=path)
+ if path == WIFI:
+ state['wifi_active'] = 0
+ inv.return_value(v('()', ()))
+ changed()
+
+
+def check_authorization(path, params, inv):
+ interactive = bool(params.unpack()[3] & 1)
+ event(polkit=params.unpack()[1], interactive=interactive)
+ answer = state['polkit']
+ if answer == 'challenge' and interactive:
+ granted = state['polkit_grant']
+ if granted:
+ state['polkit'] = 'yes'
+ inv.return_value(v('((bba{ss}))', ((granted, not granted, {}),)))
+ else:
+ inv.return_value(v('((bba{ss}))', ((answer == 'yes', answer == 'challenge', {}),)))
+
+
+HANDLERS.update({'DeactivateConnection': deactivate, 'Update': update, 'Delete': delete, 'ActivateConnection': activate, 'Disconnect': disconnect, 'CheckAuthorization': check_authorization})
+
+
+def register(path, xml):
+ node = Gio.DBusNodeInfo.new_for_xml('<node>' + xml + '</node>')
+ for info in node.interfaces:
+ bus.register_object(path, info, method, lambda *a: v('b', state['enabled']), lambda *a: True)
+
+
+def command(channel, cond):
+ request = json.loads(sys.stdin.readline())
+ COMMANDS(request)
+ changed()
+ event(done=True)
+ return True
+
+
+def default_commands(request):
+ state.update(request)
+
+
+COMMANDS = default_commands
+
+
+def start():
+ register(OBJECTS_ROOT, '<interface name="org.freedesktop.DBus.ObjectManager"><method name="GetManagedObjects"><arg direction="out" type="a{oa{sa{sv}}}"/></method></interface>')
+ for path in list(state['profiles']):
+ register(path, PROFILE_XML)
+ register(ROOT, '<interface name="%s"><property name="WirelessEnabled" type="b" access="readwrite"/><method name="ActivateConnection"><arg direction="in" type="o"/><arg direction="in" type="o"/><arg direction="in" type="o"/><arg direction="out" type="o"/></method><method name="DeactivateConnection"><arg direction="in" type="o"/></method></interface>' % NM)
+ register(WIFI, '<interface name="%s.Device.Wireless"><method name="RequestScan"><arg direction="in" type="a{sv}"/></method></interface>' % NM)
+ register(WIFI, '<interface name="%s.Device"><method name="Disconnect"/></interface>' % NM)
+ register(ETH, '<interface name="%s.Device"><method name="Disconnect"/></interface>' % NM)
+ register('/org/freedesktop/PolicyKit1/Authority', '<interface name="org.freedesktop.PolicyKit1.Authority"><method name="CheckAuthorization">'
+ '<arg direction="in" type="(sa{sv})"/><arg direction="in" type="s"/><arg direction="in" type="a{ss}"/><arg direction="in" type="u"/><arg direction="in" type="s"/>'
+ '<arg direction="out" type="(bba{ss})"/></method></interface>')
+ Gio.bus_own_name_on_connection(bus, 'org.freedesktop.PolicyKit1', Gio.BusNameOwnerFlags.NONE, None, None)
+ GLib.io_add_watch(sys.stdin.fileno(), GLib.IO_IN, command)
+ Gio.bus_own_name_on_connection(bus, NM, Gio.BusNameOwnerFlags.NONE, lambda *_: print('ready', flush=True), None)
+ GLib.MainLoop().run()
+
+
+if __name__ == '__main__':
+ start()
diff --git a/tests/wifi_popup.py b/tests/wifi_popup.py
index b6c73da..1065471 100644
--- a/tests/wifi_popup.py
+++ b/tests/wifi_popup.py
@@ -356,7 +356,7 @@ def settings(scale):
ipc.open_control_center()
ui.wait_settled('control_center')
ui.click('network', panel='control_center')
- wait_for(lambda: '192.168.1.100' in labels(), 'Ethernet address')
+ wait_for(lambda: '192.168.1.100/24' in labels(), 'Ethernet address')
ui.wait_settled('control_center')
body_width = ipc.get_shell_state()['control_center']['box']['width']
axis = 'x' if body_width >= 1000 else 'y'
@@ -371,7 +371,7 @@ def settings(scale):
click('ethernet_enabled')
assert read_line(fake) == {'ethernet': False, 'new': False}
wait_for(lambda: not find('ethernet_enabled')['on'] and ready(), 'Ethernet disconnected')
- assert '192.168.1.100' not in labels()
+ assert '192.168.1.100/24' not in labels()
command(hold_eth=True)
click('ethernet_enabled')
assert read_line(fake) == {'ethernet': True, 'new': False}