Run in the background, with a status icon and autostart

Closing the main window now asks whether to keep Regent running in the
background or to quit, and remembers the choice (reversible in
Preferences). A backgrounded Regent still answers requests: the approval
drain presents the hidden window for a prompt and hides it again once the
whole request is answered, so the application that asked regains focus.
The two-window invariant becomes "the main window is presentable exactly
when the responder can serve prompts". With no key, or a stopped signer,
closing still quits.

A StatusNotifierItem (ksni) adds Show/Hide Regent, Preferences and Quit;
it is menu-only on activate, because GNOME's AppIndicator extension waits
out the double-click interval whenever an Activate method exists. A new
"Background" preference group carries the close action, the icon toggle
and start-at-login, which registers with org.freedesktop.portal.Background
(so GNOME lists the app under Background Apps) and starts it with
--background.

Also: dialogs parent to the visible window rather than the primary one, a
signer start-failure dialog is suppressed while the window is hidden, and
the Requests group moves to the bottom of Preferences.
This commit is contained in:
raucao committed 2026-11-28 12:42:18 +04:00
1 parent 767046b159
commit c71f110f6f
20 files changed
+1580 -67

No files matched your search

+62 -7
View File
@@ -191,14 +191,16 @@ data/ desktop, metainfo, gschema, icons, resources (ui/*.blp, sty
(`data/resources/ui/keys.blp`) around the existing `KeysView`. A second
`AppState` would mean a second registry and a second signer on one device key
(see M5), so the registry is created once in `application.rs` and shared.
- **The invariant: the main window is visible exactly when the responder can
- **The invariant: the main window is presentable exactly when the responder can
serve prompts.** The approval dialogs are parented to the main window, so a
request must never arrive without it. With no keys there is nothing to sign
with and nothing to listen for, so the identities window is the whole app;
closing the main window **quits the app** (`connect_close_request` →
`app.quit()`), because the identities window would otherwise keep the process —
and a signer that can answer nothing — alive behind a window the user believes
they closed.
with and nothing to listen for, so the identities window is the whole app. With
a key the main window exists and the signer runs, but it may be **hidden in the
background** (M12): the approval drain presents it for a dialog and hides it
again once the request is answered. Closing the main window is no longer a plain
quit — see M12 — but with no key, or a stopped signer, it still quits, because a
hidden window that can answer nothing is the "signer that answers nothing" this
shape exists to avoid.
- **The launch decision** (`Windows::build` + `present_primary`): no keys ⇒
present the identities window only; keys ⇒ the main window, whose first page is
Apps. `follow_keys` (a `state.listen` callback) follows the *transition*: the
@@ -213,7 +215,11 @@ data/ desktop, metainfo, gschema, icons, resources (ui/*.blp, sty
`app.focus`, `app.lock` and `present_preferences` all go through it. Do not
reintroduce `app.windows().first()` — it is creation order — and note that
`app.focus` used to present *every* window, which would pop the hidden
identities window open on every notification click.
identities window open on every notification click. With the window able to be
hidden, a **dialog** is parented through `Windows::visible_parent()`
(`active_window()`, else `primary()`): an `AdwDialog` inside a hidden window is
silently invisible, so `present_preferences`/`present_about`/`present_connect`/
`pair_uri` must never parent to a window that is off screen.
- The identities window is created once and `set_hide_on_close(true)`:
`AppState::listen` cannot unregister and its closures capture widgets, so a
window destroyed and rebuilt would leave listeners pointing at dead widgets.
@@ -241,6 +247,55 @@ data/ desktop, metainfo, gschema, icons, resources (ui/*.blp, sty
*before* `app.run()`, because starting with an empty vault would let the next
save overwrite the real keys (the shape M8 closed).
## Running in the background (M12)
- **Closing asks, hides, or quits.** `close-action` (GSettings, default `ask`)
picks: `ask` shows an `AdwAlertDialog` (Cancel / Keep Running / Quit) with a
"Remember this choice" checkbox; `background` hides; `quit` ends the app. The
dialog's default and suggested response is Keep Running, and its close
response is Cancel, so Escape and the dialog's X mean "stay as you are".
`Windows::request_close` always returns `Propagation::Stop` — GTK must never
destroy the window — and the choice is only offered while
`SignerRunner::status()` is `Running`: with no key, or a stopped signer,
closing quits as before. While a prompt is on screen the close is **ignored**,
so the ask dialog cannot stack on top of it (only a keyboard/WM close reaches
`close_request` at all; the modal prompt blocks pointer closes).
- **The window may be hidden while the signer runs.** Hiding a window keeps the
process alive (GtkApplication holds while a window exists), so no
`g_application_hold()` is needed. `PrimaryHandle` is the main window plus one
`auto` flag: `present`/`hide`/`toggle` are user-initiated and clear it;
`present_for_prompt` presents a hidden window and sets it; the responder's
`Notice::RequestAnswered` calls `restore_after_prompt`, which hides only if the
flag is set. **The hide follows the request, not the dialog** — a locked vault
asks twice (approve, then unlock), so hiding when `present_question` returns
would flicker and strand the unlock dialog on a window it just hid.
- **Notifications still fire while hidden.** `notify_pending` runs *before*
`present_for_prompt`, so the user is away (the window is hidden) and a
notification goes out; a click lands on `app.focus` → `present_primary`, which
is a user-initiated present (it clears the auto flag, so the window stays).
- **The status icon** (`ui/tray.rs`) is a ksni StatusNotifierItem on the shared
tokio runtime: Show/Hide Regent, Preferences…, Quit Regent. Left-click **opens
the menu** (`MENU_ON_ACTIVATE`), not `Activate`: the GNOME AppIndicator
extension waits out the double-click interval on every click when an `Activate`
method exists, so the menu-only interface is what makes it open at once.
It holds only `Send` state and talks to the main loop over an `async_channel`;
visibility/status/pending go back through a shared `Arc<Mutex<TrayModel>>` and
`Handle::update`. `show-tray-icon` (default true) gates it. A missing host
(stock GNOME without the AppIndicator extension) is **not** an error:
`watcher_offline` logs (once per offline event) and returns `true`, so the icon
appears the moment a host does. A start is asynchronous, so `tray_starting`
guards against a second activation putting two items on the bus, and the
completion re-checks the preference before showing it.
- **GNOME's Background Apps listing** (and autostart) needs the
`org.freedesktop.portal.Background` portal — hiding the window alone does not
list the app. `portal::request_background` is a hand-rolled `gio` D-Bus call
(not `ashpd`, which would pull a second zbus major in beside ksni's). Called
when hiding to the background and at startup when `autostart` is set.
`--background` starts with no window (the autostart `Exec`); the flag is
stripped from the argv GApplication parses.
- **`g_application_quit()` never emits `close_request`**, so the menu's Quit,
Ctrl+Q and the tray's Quit bypass the dialog with no "quitting" flag.
## Apps, permissions and the activity log (M5)
- `apps.json` is the single source of truth for what an app may do without
Generated
+320
View File
@@ -29,12 +29,33 @@ dependencies = [
"cpufeatures 0.2.17",
]
[[package]]
name = "arc-swap"
version = "1.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5"
dependencies = [
"rustversion",
]
[[package]]
name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "async-broadcast"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
dependencies = [
"event-listener",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-channel"
version = "2.5.0"
@@ -47,6 +68,28 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "async-recursion"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "async-trait"
version = "0.1.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "async-utility"
version = "0.3.2"
@@ -406,6 +449,15 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-queue"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.23"
@@ -524,6 +576,33 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "endi"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
[[package]]
name = "enumflags2"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
dependencies = [
"enumflags2_derive",
"serde",
]
[[package]]
name = "enumflags2_derive"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "equivalent"
version = "1.0.3"
@@ -572,6 +651,12 @@ dependencies = [
"serde",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -671,6 +756,19 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
[[package]]
name = "futures-lite"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
dependencies = [
"fastrand",
"futures-core",
"futures-io",
"parking",
"pin-project-lite",
]
[[package]]
name = "futures-macro"
version = "0.3.34"
@@ -1048,6 +1146,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hex-conservative"
version = "0.2.3"
@@ -1351,6 +1455,21 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "ksni"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d49a7ac89853917f01d75f6bac3e7c8e282ae621dd63fbbfc50fe331304fa580"
dependencies = [
"arc-swap",
"crossbeam-queue",
"futures-util",
"pastey",
"serde",
"tokio",
"zbus",
]
[[package]]
name = "libadwaita"
version = "0.9.2"
@@ -1387,6 +1506,12 @@ version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.3"
@@ -1570,6 +1695,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f933a4265d5cdad61d19bbdfc972ea5726d56cd8d3d57b8f2d3c365dd42bee9"
[[package]]
name = "ordered-stream"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
dependencies = [
"futures-core",
"pin-project-lite",
]
[[package]]
name = "pango"
version = "0.22.9"
@@ -1599,6 +1734,12 @@ version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
[[package]]
name = "pastey"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "pbkdf2"
version = "0.13.0"
@@ -1873,6 +2014,7 @@ dependencies = [
"glib",
"gtk4",
"image",
"ksni",
"libadwaita",
"nostr",
"nostr-sdk",
@@ -1952,6 +2094,19 @@ dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags 2.13.2",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
@@ -2092,6 +2247,17 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_repr"
version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
@@ -2265,6 +2431,19 @@ version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -2334,6 +2513,7 @@ dependencies = [
"signal-hook-registry",
"socket2",
"tokio-macros",
"tracing",
"windows-sys 0.61.2",
]
@@ -2523,9 +2703,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
@@ -2566,6 +2758,17 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "uds_windows"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -2637,6 +2840,17 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"
[[package]]
name = "uuid"
version = "1.29.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
dependencies = [
"js-sys",
"serde_core",
"wasm-bindgen",
]
[[package]]
name = "version-compare"
version = "0.2.1"
@@ -2898,6 +3112,71 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zbus"
version = "5.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"
dependencies = [
"async-broadcast",
"async-recursion",
"async-trait",
"enumflags2",
"event-listener",
"futures-core",
"futures-lite",
"hex",
"libc",
"ordered-stream",
"rustix",
"serde",
"serde_repr",
"tokio",
"tracing",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow",
"zbus_macros",
"zbus_names",
"zvariant",
]
[[package]]
name = "zbus_macros"
version = "5.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"
dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.10",
"zbus_names",
"zvariant",
"zvariant_utils",
]
[[package]]
name = "zbus_names"
version = "4.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"
dependencies = [
"serde",
"winnow",
"zvariant",
]
[[package]]
name = "zcheapstr"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907"
dependencies = [
"serde",
]
[[package]]
name = "zerocopy"
version = "0.8.63"
@@ -2989,3 +3268,44 @@ name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zvariant"
version = "5.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7"
dependencies = [
"endi",
"enumflags2",
"serde",
"winnow",
"zcheapstr",
"zvariant_derive",
"zvariant_utils",
]
[[package]]
name = "zvariant_derive"
version = "5.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d"
dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.10",
"zvariant_utils",
]
[[package]]
name = "zvariant_utils"
version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.10",
"winnow",
]
+4
View File
@@ -20,6 +20,10 @@ nostr-sdk = { version = "0.45", default-features = false, features = ["rustls-tl
# built per fetch with the validated addresses pinned (see `store::icons`).
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "time", "signal", "net"] }
# The status-bar indicator, via the KDE/freedesktop StatusNotifierItem spec.
# Tokio (not the `blocking` API): it shares Regent's runtime. zbus opens its own
# session connection and never owns the app's D-Bus name.
ksni = { version = "0.3", default-features = false, features = ["tokio"] }
async-channel = "2"
serde_json = { version = "1", features = ["preserve_order"] }
serde = { version = "1", features = ["derive"] }
+22 -1
View File
@@ -29,7 +29,7 @@ export HOME=$TMP_HOME
export CARGO_HOME=${CARGO_HOME:-$ORIGINAL_HOME/.cargo}
cleanup() {
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} ${NOTIFY_STUB:-} 2>/dev/null
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} ${NOTIFY_STUB:-} ${BACKGROUND:-} 2>/dev/null
wait 2>/dev/null
rm -rf "$TMP_HOME"
}
@@ -376,6 +376,27 @@ check $? "with no keys the identities window is the whole app"
! grep -q 'signer listening' "$TMP_HOME/first-run.log"
check $? "with no keys the signer does not start"
printf '\n== running in the background ==\n'
# `--background` is what autostart runs: no window, signer listening. Whether the
# window is hidden cannot be observed from outside, but starting and serving can.
GDK_BACKEND=broadway BROADWAY_DISPLAY=:11 \
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_GRESOURCE="$ROOT/$BUILD/data/resources/org.kosmos.raucao.Regent.gresource" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
"$ROOT/$BUILD/regent" --background >"$TMP_HOME/background.log" 2>&1 &
BACKGROUND=$!
sleep 6
grep -q 'signer listening' "$TMP_HOME/background.log"
check $? "a --background launch starts the signer with no window"
kill -0 "$BACKGROUND" 2>/dev/null
check $? "and stays running in the background"
kill "$BACKGROUND" 2>/dev/null
sleep 1
BACKGROUND=
printf '\n'
if [ "$fails" = 0 ]; then
printf 'all checks passed\n'
+1
View File
@@ -9,4 +9,5 @@ Terminal=false
Categories=Utility;Security;
Keywords=nostr;signer;keys;nip46;nip-46;
StartupNotify=true
X-GNOME-UsesNotifications=true
MimeType=x-scheme-handler/nostrconnect;
+15
View File
@@ -21,6 +21,21 @@
<summary>Load application icons</summary>
<description>Fetch and show the icon an application declares in its pairing metadata, from the application's own server, after you approve it. Turning this off stops all icon fetches and leaves the initials in place.</description>
</key>
<key name="close-action" type="s">
<default>'ask'</default>
<summary>What closing the window does</summary>
<description>What happens when the main window is closed while the signer is listening: 'ask' shows a dialog, 'background' keeps Regent running so it can answer requests, 'quit' ends the application. Only offered while the signer runs; with no key, or a stopped signer, closing quits.</description>
</key>
<key name="show-tray-icon" type="b">
<default>true</default>
<summary>Show a status icon</summary>
<description>Show a StatusNotifierItem/AppIndicator status icon while Regent runs, with Show/Hide and Quit. Stock GNOME needs the AppIndicator extension to display it; on most other desktops it is native.</description>
</key>
<key name="autostart" type="b">
<default>false</default>
<summary>Start at login</summary>
<description>Register Regent with the desktop's background portal so it starts at login, hidden, and can answer requests. Uses org.freedesktop.portal.Background; on GNOME this also lists Regent under Background Apps.</description>
</key>
<key name="relays" type="as">
<default>['wss://nostr.kosmos.org']</default>
<summary>Relays</summary>
+2
View File
@@ -27,6 +27,7 @@ cargo_build = custom_target(binary_name,
'src/application.rs',
'src/config.rs',
'src/headless.rs',
'src/portal.rs',
'src/runner.rs',
'src/runtime.rs',
'src/signer/approval.rs',
@@ -52,6 +53,7 @@ cargo_build = custom_target(binary_name,
'src/ui/preferences.rs',
'src/ui/qr.rs',
'src/ui/switcher.rs',
'src/ui/tray.rs',
'src/window.rs',
),
command: [
+15 -1
View File
@@ -1,5 +1,6 @@
//! Application object, actions and global setup.
use std::cell::Cell;
use std::rc::Rc;
use gtk::gio;
@@ -11,7 +12,7 @@ use crate::ui::approval;
use crate::window::Windows;
use crate::{APP_ID, RESOURCE_PATH};
pub fn run(args: &[String]) -> glib::ExitCode {
pub fn run(args: &[String], background: bool) -> glib::ExitCode {
// `HANDLES_OPEN` is what makes a `nostrconnect://` argument (the desktop's
// scheme handler runs `regent %u`) arrive in the `open` signal instead of
// being refused — and it is what lets a link reach an already-running
@@ -138,8 +139,21 @@ pub fn run(args: &[String]) -> glib::ExitCode {
app.connect_startup(|_| load_css());
{
let windows = Rc::clone(&windows);
// `--background` (an autostart launch) opens with no window, but only
// for the launch itself: a later activation — the app icon, a
// notification click — is the user asking for the window.
let first = Cell::new(true);
app.connect_activate(move |_| {
windows.build();
if first.replace(false) && background && windows.has_keys() {
// A `--background` launch is what autostart runs, but it is also
// a user-facing mode: register with the portal either way, so it
// is listed under Background Apps. `register_background` reads
// the autostart preference itself, so this writes an autostart
// entry only when the user asked for one.
windows.register_background();
return;
}
// First run has nothing to sign with and nothing to listen for, so the
// identities window is the whole app until a key exists. Activation can
// arrive more than once, which is why this presents rather than creates.
+80
View File
@@ -7,6 +7,37 @@ use nostr::prelude::PublicKey;
use crate::APP_ID;
/// What closing the main window does while the signer is listening.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CloseAction {
/// Show the "Close Regent?" dialog and let the user decide.
Ask,
/// Keep running in the background so requests can still be answered.
Background,
/// Quit the application.
Quit,
}
impl CloseAction {
/// Parse the stored string. An unknown value is treated as `Ask`: a
/// hand-edited setting must not silently turn closing into a quit.
fn from_setting(value: &str) -> Self {
match value {
"background" => Self::Background,
"quit" => Self::Quit,
_ => Self::Ask,
}
}
fn as_setting(self) -> &'static str {
match self {
Self::Ask => "ask",
Self::Background => "background",
Self::Quit => "quit",
}
}
}
pub struct Config {
settings: gio::Settings,
}
@@ -76,6 +107,39 @@ impl Config {
}
}
/// What closing the main window does while the signer is listening.
pub fn close_action(&self) -> CloseAction {
CloseAction::from_setting(&self.settings.string("close-action"))
}
pub fn set_close_action(&self, action: CloseAction) {
if let Err(error) = self.settings.set_string("close-action", action.as_setting()) {
eprintln!("regent: could not save the close action: {error}");
}
}
/// Whether to show the status-bar indicator while Regent runs.
pub fn show_tray_icon(&self) -> bool {
self.settings.boolean("show-tray-icon")
}
pub fn set_show_tray_icon(&self, show: bool) {
if let Err(error) = self.settings.set_boolean("show-tray-icon", show) {
eprintln!("regent: could not save the status-icon preference: {error}");
}
}
/// Whether Regent should start at login, in the background.
pub fn autostart(&self) -> bool {
self.settings.boolean("autostart")
}
pub fn set_autostart(&self, autostart: bool) {
if let Err(error) = self.settings.set_boolean("autostart", autostart) {
eprintln!("regent: could not save the autostart preference: {error}");
}
}
/// Relays Regent talks to. `REGENT_RELAYS` (comma separated) overrides the
/// setting, which is what headless tests and CI use.
pub fn relays(&self) -> Vec<String> {
@@ -103,3 +167,19 @@ impl Default for Config {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The stored strings round-trip, and anything unknown reads as "ask" — a
/// hand-edited setting must not silently turn closing into a quit.
#[test]
fn close_action_round_trips_and_defaults_to_ask() {
for action in [CloseAction::Ask, CloseAction::Background, CloseAction::Quit] {
assert_eq!(CloseAction::from_setting(action.as_setting()), action);
}
assert_eq!(CloseAction::from_setting(""), CloseAction::Ask);
assert_eq!(CloseAction::from_setting("nonsense"), CloseAction::Ask);
}
}
+7 -2
View File
@@ -23,7 +23,7 @@ use zeroize::Zeroizing;
use crate::config::Config;
use crate::runtime;
use crate::signer::approval::{Approver, Decision, Prompt};
use crate::signer::approval::{Approver, Decision, Notice, Prompt};
use crate::signer::{ClientPairing, Signer, SignerConfig, parse_client_uri};
use crate::store::apps::AppRegistry;
use crate::store::audit::ActivityLog;
@@ -134,9 +134,14 @@ async fn serve(
}
});
// No window, so a one-way notice is a line on stderr, not a notification.
// `RequestAnswered` is UI bookkeeping (hide a window shown for a prompt) and
// has nothing to report here.
tokio::spawn(async move {
while let Ok(notice) = notices.recv().await {
eprintln!("regent: {notice:?}");
match notice {
Notice::LoggedOut => eprintln!("regent: {notice:?}"),
Notice::RequestAnswered => {}
}
}
});
+17 -5
View File
@@ -6,6 +6,7 @@
mod application;
mod config;
mod headless;
mod portal;
mod runner;
mod runtime;
mod signer;
@@ -34,6 +35,8 @@ Options:
headless
--key <key> identity (npub or hex) that --pair binds the client to; the
current identity is used when omitted
--background start with no window, running in the background (used for
autostart); the tray or a second launch brings the window up
--passphrase-file <path>
read the key-vault passphrase from this file (mode 0400/0600)
so an unattended run can sign; a systemd credential named
@@ -70,10 +73,16 @@ fn main() -> glib::ExitCode {
}
register_resources();
// A `nostrconnect://` link (if any) is left in `args`: GApplication's `open`
// signal delivers it, so it works for a cold launch and for a link that
// arrives while Regent is already running.
application::run(&args)
// `--background` is Regent's own flag, not one GApplication knows: drop it
// from the argv it parses. A `nostrconnect://` link (if any) stays in the
// args, because GApplication's `open` signal delivers it — so it works for a
// cold launch and for a link that arrives while Regent is already running.
let gui_args: Vec<String> = args
.iter()
.filter(|arg| arg.as_str() != "--background")
.cloned()
.collect();
application::run(&gui_args, parsed.background)
}
/// The (few) arguments we accept.
@@ -81,22 +90,25 @@ struct Args {
headless: bool,
pair: Option<String>,
key: Option<String>,
background: bool,
passphrase_file: Option<String>,
}
/// Parse `--headless`, `--pair <uri>`, `--key <npub|hex>` and
/// Parse `--headless`, `--pair <uri>`, `--key <npub|hex>`, `--background` and
/// `--passphrase-file <path>`.
fn parse_args(args: &[String]) -> Result<Args, String> {
let mut parsed = Args {
headless: false,
pair: None,
key: None,
background: false,
passphrase_file: None,
};
let mut iter = args.iter();
while let Some(arg) = iter.next() {
match arg.as_str() {
"--headless" => parsed.headless = true,
"--background" => parsed.background = true,
"--pair" => parsed.pair = Some(value_for(&mut iter, "--pair", "a nostrconnect:// URI")?),
"--key" => parsed.key = Some(value_for(&mut iter, "--key", "an npub or hex key")?),
"--passphrase-file" => {
+95
View File
@@ -0,0 +1,95 @@
//! The desktop's Background portal: register Regent as a background app and,
//! optionally, as an autostart entry.
//!
//! GNOME 44+ lists window-less apps under "Background Apps" **only** when they
//! are registered through `org.freedesktop.portal.Background`; hiding the window
//! alone is not enough. The same call is how autostart is written, so there is
//! no hand-rolled `~/.config/autostart` file.
//!
//! Done with a raw `gio` D-Bus call rather than `ashpd`, which would drag a
//! second zbus major in beside ksni's.
use glib::prelude::ToVariant;
/// The reason the desktop shows for Regent running in the background.
const REASON: &str = "Regent answers signing requests from your applications";
/// What the desktop should run to start Regent in the background.
///
/// An absolute path matters: a session's PATH may not contain `~/.local/bin`,
/// which is exactly where a `~/.local` install puts the binary (the same reason
/// the desktop file's `Exec` is rewritten on deploy).
pub fn background_commandline() -> Vec<String> {
let program = std::env::current_exe()
.map(|path| path.to_string_lossy().into_owned())
.unwrap_or_else(|_| "regent".to_string());
vec![program, "--background".to_string()]
}
/// Register Regent with the Background portal.
///
/// `autostart` asks the desktop to start Regent at login; `commandline` is what
/// it runs then (Regent with `--background`, so the started instance has no
/// window). Best-effort: a desktop without the portal, or a refusal, is logged
/// and ignored — the app still runs and can still hide to the background.
pub fn request_background(autostart: bool, commandline: Vec<String>) {
if let Err(error) = request(autostart, commandline) {
eprintln!("regent: could not register with the background portal: {error}");
}
}
fn request(autostart: bool, commandline: Vec<String>) -> Result<(), String> {
let connection =
gtk::gio::bus_get_sync(gtk::gio::BusType::Session, gtk::gio::Cancellable::NONE)
.map_err(|error| error.to_string())?;
let arguments = background_arguments(autostart, &commandline);
let reply = connection
.call_sync(
Some("org.freedesktop.portal.Desktop"),
"/org/freedesktop/portal/desktop",
"org.freedesktop.portal.Background",
"RequestBackground",
Some(&arguments),
None,
gtk::gio::DBusCallFlags::NONE,
-1,
gtk::gio::Cancellable::NONE,
)
.map_err(|error| error.to_string())?;
let _: (String,) = reply
.get()
.ok_or("the portal returned an unexpected reply")?;
Ok(())
}
/// The `RequestBackground` arguments: `(s, a{sv})`.
///
/// An empty parent-window identifier (Regent is not sandboxed, so the portal
/// accepts it) and the options dict.
///
/// Pass the `VariantDict` itself, **not** the `Variant` from `end()`: a `Variant`
/// inside a tuple is wrapped as `v` (`impl ToVariant for Variant`), which makes
/// this `(s, v)` and the portal rejects it with
/// `Type of message, "(sv)", does not match expected type "(sa{sv})"`.
/// `VariantDict`'s own `ToVariant` yields `a{sv}`, so the tuple is correct.
fn background_arguments(autostart: bool, commandline: &[String]) -> glib::Variant {
let options = glib::VariantDict::new(None);
options.insert_value("reason", &REASON.to_variant());
options.insert_value("autostart", &autostart.to_variant());
options.insert_value("commandline", &commandline.to_vec().to_variant());
("", options).to_variant()
}
#[cfg(test)]
mod tests {
use super::*;
/// The portal wants `(s, a{sv})`; the bug this guards against shipped `(s, v)`.
#[test]
fn the_request_arguments_are_a_string_and_a_vardict() {
let arguments = background_arguments(false, &["regent".to_string()]);
assert_eq!(arguments.type_().as_str(), "(sa{sv})");
}
}
+42 -10
View File
@@ -18,6 +18,7 @@ use crate::runtime;
use crate::signer::approval::Approver;
use crate::signer::{Signer, SignerConfig};
use crate::state::AppState;
use crate::window::PrimaryHandle;
/// The responder's lifecycle. `Starting` matters: a second start (the dialog's
/// toggle, or a pairing while the first start is still in flight) would put two
@@ -33,9 +34,9 @@ type Listener = Rc<dyn Fn()>;
pub struct SignerRunner {
state: Rc<AppState>,
/// The widget the approval drain parents its dialogs to. It is the main
/// window, so a request can never arrive without somewhere to ask.
widget: gtk::Widget,
/// The main window: the drain presents it for a prompt and hides it again
/// when the request is answered.
primary: PrimaryHandle,
approver: Approver,
status: RefCell<Status>,
/// Bumped by every start and stop. An in-flight start whose generation is
@@ -49,33 +50,44 @@ pub struct SignerRunner {
/// Set when a stop arrives while a start is in flight. The start's
/// completion tears the responder down instead of publishing it.
stop_requested: Cell<bool>,
/// True while a prompt is on screen. Drives the tray's "needs attention".
pending: Cell<bool>,
listeners: RefCell<Vec<Listener>>,
}
impl SignerRunner {
/// Create the process's runner and install the approval drain. Call this
/// once, from the main window, after the window has its application.
pub fn new(state: Rc<AppState>, widget: gtk::Widget) -> Rc<Self> {
pub fn new(state: Rc<AppState>, primary: PrimaryHandle) -> Rc<Self> {
let (approver, prompts, notices) = Approver::new();
crate::ui::approval::install(prompts, widget.clone(), Rc::clone(&state));
crate::ui::approval::install_notices(notices, widget.clone());
let runner = Rc::new(Self {
state,
widget,
primary: primary.clone(),
approver,
status: RefCell::new(Status::Stopped),
generation: Cell::new(0),
starting: Cell::new(false),
stop_requested: Cell::new(false),
pending: Cell::new(false),
listeners: RefCell::new(Vec::new()),
});
// The drains are installed after the `Rc` exists, so a prompt can flip
// the pending flag and wake the tray listener.
crate::ui::approval::install(
prompts,
primary.clone(),
Rc::clone(&runner.state),
Rc::clone(&runner),
);
crate::ui::approval::install_notices(notices, primary);
// Follow the key list's *transitions*, not every `notify()`: a profile
// fetch or a lock must not restart a signer the user stopped. The first
// key starts the responder; removing the last one stops it, which is what
// keeps "the main window is visible exactly when the responder can ask"
// honest.
// keeps "the main window is presentable exactly when the responder can
// ask" honest.
{
let runner = Rc::clone(&runner);
let state = Rc::clone(&runner.state);
@@ -101,6 +113,18 @@ impl SignerRunner {
self.status.borrow().clone()
}
/// Whether a prompt is on screen. The tray turns this into "needs
/// attention"; it is flipped by the approval drain.
pub fn is_pending(&self) -> bool {
self.pending.get()
}
pub(crate) fn set_pending(&self, pending: bool) {
if self.pending.replace(pending) != pending {
self.notify();
}
}
pub fn bunker_uri(&self) -> Option<String> {
match &*self.status.borrow() {
Status::Running(signer) => Some(signer.bunker_uri().to_string()),
@@ -221,7 +245,15 @@ impl SignerRunner {
after(Err(error));
} else {
eprintln!("regent: could not start the signer: {error}");
crate::ui::plain::error_dialog(&runner.widget, &error);
// An `AdwDialog` parented to a hidden window is
// invisible; only raise it when the window is up.
// The stderr line is unconditional.
if runner.primary.is_visible() {
crate::ui::plain::error_dialog(
&runner.primary.widget(),
&error,
);
}
}
}
}
+6
View File
@@ -150,6 +150,12 @@ pub enum Prompt {
pub enum Notice {
/// A client asked to be forgotten (NIP-46 `logout`).
LoggedOut,
/// A request the user may have been asked about is fully answered.
///
/// The UI uses it to hide a window it presented only to show the prompt:
/// the hide must follow the *request*, not one dialog, because a locked
/// vault asks twice (approve, then unlock).
RequestAnswered,
}
/// The handle the responder uses to ask the user — and to tell them something.
+71 -3
View File
@@ -678,7 +678,7 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
identity: signing_key(config, identity),
rebind_from,
};
match config.approver.ask(question).await {
let outcome = match config.approver.ask(question).await {
Decision::Deny => {
record(
config,
@@ -712,7 +712,11 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
}
result
}
}
};
// A pairing is a request too: let the UI hide a window
// it presented for the prompt.
config.approver.notice(Notice::RequestAnswered);
outcome
}
}
}
@@ -940,6 +944,10 @@ async fn gate(
/// Records exactly one outcome. The vault is opened **before** the record, so a
/// request the vault refused is logged as `locked` and never as allowed or
/// silent: the activity log must not claim an answer that was never produced.
///
/// Wraps [`authorize_inner`] to send a [`Notice::RequestAnswered`] afterwards —
/// once for the whole request, so the UI hides a window it presented for the
/// prompt only after the approve/unlock pair is done, not between them.
#[allow(clippy::too_many_arguments)]
async fn authorize(
config: &SignerConfig,
@@ -950,6 +958,24 @@ async fn authorize(
method: &str,
kind: Option<u16>,
declined: &str,
) -> std::result::Result<Keys, String> {
let result =
authorize_inner(config, client, identity, request, permission, method, kind, declined)
.await;
config.approver.notice(Notice::RequestAnswered);
result
}
#[allow(clippy::too_many_arguments)]
async fn authorize_inner(
config: &SignerConfig,
client: &ClientInfo,
identity: PublicKey,
request: Request,
permission: Option<Permission>,
method: &str,
kind: Option<u16>,
declined: &str,
) -> std::result::Result<Keys, String> {
let verdict = gate(config, client, identity, request, permission).await;
if verdict == Verdict::Deny {
@@ -2188,7 +2214,13 @@ mod tests {
});
let config = config("ws://127.0.0.1:1", approver);
let device = pair(&client, &config).await;
assert!(notices.try_recv().is_err(), "pairing is not a notice");
// Pairing is answered with a `RequestAnswered` notice (so the UI can
// hide a window it presented for the prompt); it is not the logout
// announcement.
assert_eq!(
notices.try_recv().expect("the pairing notice"),
Notice::RequestAnswered,
);
let request = client_request(&client, &device, "logout", serde_json::json!([]));
let response = handle_request(&request, &config)
@@ -2205,6 +2237,42 @@ mod tests {
);
}
/// A sensitive request is answered with a `RequestAnswered` notice, so the
/// UI hides a window it presented for the prompt. One per request, so a
/// locked vault's approve/unlock pair hides only once, at the end.
#[tokio::test]
async fn an_answered_request_sends_a_notice() {
let client = Keys::generate();
let (approver, prompts, notices) = Approver::new();
let drain = tokio::spawn(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { reply, .. } => {
let _ = reply.send(Decision::Always).await;
}
Prompt::Unlock { reply, .. } => {
let _ = reply.send(false).await;
}
}
}
});
let config = config("ws://127.0.0.1:1", approver);
let device = pair(&client, &config).await;
assert_eq!(
notices.try_recv(),
Ok(Notice::RequestAnswered),
"pairing is answered"
);
assert!(sign_once(&client, &device, &config, "hi").await["result"].is_string());
drain.abort();
assert_eq!(
notices.try_recv(),
Ok(Notice::RequestAnswered),
"the signed request is answered"
);
}
/// A client can see what it may do without asking.
#[tokio::test]
async fn stored_permissions_are_reported_to_the_client() {
+36 -4
View File
@@ -20,10 +20,12 @@ use gtk::prelude::*;
use libadwaita as adw;
use crate::runtime;
use crate::runner::SignerRunner;
use crate::signer::approval::{ClientInfo, Decision, Notice, Prompt, Question, Request};
use crate::state::AppState;
use crate::store::keys::KeyStore;
use crate::ui::{content, kind, plain};
use crate::window::PrimaryHandle;
use crate::APP_ID;
/// One notification id, so a second prompt replaces the first rather than
@@ -40,7 +42,17 @@ const UNLOCK_BODY: &str = "Regent needs your passphrase to continue";
/// Start draining prompts: each one becomes a dialog, and the answer goes back
/// to the responder. Anything unanswered is a denial — and an unanswered unlock
/// leaves the vault locked.
pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::Rc<AppState>) {
///
/// The window may be hidden (Regent running in the background): the drain
/// presents it for the dialog and, once the whole request is answered, the
/// [`Notice::RequestAnswered`] arm hides it again.
pub fn install(
prompts: Receiver<Prompt>,
primary: PrimaryHandle,
state: Rc<AppState>,
runner: Rc<SignerRunner>,
) {
let widget = primary.widget();
glib::MainContext::default().spawn_local(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
@@ -56,9 +68,14 @@ pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::R
let _ = reply.send(Decision::Deny).await;
continue;
}
// Notify while the window is still hidden — the user is away
// by definition — then bring the window up for the dialog.
let notified = notify_pending(&widget, notification_body(&question.request));
primary.present_for_prompt();
runner.set_pending(true);
let decision =
present_question(&widget, &question, Some(deadline), &state).await;
runner.set_pending(false);
if notified {
withdraw_pending(&widget);
}
@@ -70,7 +87,10 @@ pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::R
continue;
}
let notified = notify_pending(&widget, UNLOCK_BODY);
primary.present_for_prompt();
runner.set_pending(true);
let unlocked = present_unlock(&widget, state.store(), Some(deadline)).await;
runner.set_pending(false);
if notified {
withdraw_pending(&widget);
}
@@ -87,14 +107,22 @@ pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::R
});
}
/// Drain one-way notices and turn each into a desktop notification.
/// Drain one-way notices and turn each into a desktop notification — or, for a
/// request that is finished, into hiding a window the drain presented.
///
/// The notice channel is separate from the prompt channel so this can never be
/// stuck behind an open approval dialog.
pub fn install_notices(notices: Receiver<Notice>, widget: gtk::Widget) {
pub fn install_notices(notices: Receiver<Notice>, primary: PrimaryHandle) {
let widget = primary.widget();
glib::MainContext::default().spawn_local(async move {
while let Ok(notice) = notices.recv().await {
notify_notice(&widget, notice_body(&notice));
match notice {
Notice::LoggedOut => notify_notice(&widget, notice_body(&notice)),
// Driven by the *request*, not one dialog: a locked vault asks
// twice (approve, then unlock), and hiding between them would
// flicker and strand the unlock dialog on a hidden window.
Notice::RequestAnswered => primary.restore_after_prompt(),
}
}
});
}
@@ -115,9 +143,13 @@ fn notification_body(request: &Request) -> &'static str {
/// The one line the desktop shows for a one-way notice. Our own words, so the
/// lock-screen rule holds here too.
///
/// `RequestAnswered` is not a notification — the drain uses it to hide a window
/// — so it has no body.
fn notice_body(notice: &Notice) -> &'static str {
match notice {
Notice::LoggedOut => "An application was disconnected",
Notice::RequestAnswered => "",
}
}
+1
View File
@@ -12,3 +12,4 @@ pub mod plain;
pub mod preferences;
pub mod qr;
pub mod switcher;
pub mod tray;
+113 -3
View File
@@ -17,7 +17,8 @@ use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use crate::config::Config;
use crate::config::{CloseAction, Config};
use crate::portal;
use crate::runner::{SignerRunner, Status};
use crate::runtime;
use crate::state::AppState;
@@ -34,6 +35,13 @@ const AUTO_LOCK: [(u32, &str); 6] = [
(0, "Never"),
];
/// The close-action choices, in the order the combo shows them.
const CLOSE_ACTIONS: [(CloseAction, &str); 3] = [
(CloseAction::Ask, "Ask every time"),
(CloseAction::Background, "Run in background"),
(CloseAction::Quit, "Quit Regent"),
];
/// The auto-approval limit, in requests per minute per application. `0` never
/// answers silently.
const AUTO_APPROVE_MAX: f64 = 600.0;
@@ -80,10 +88,17 @@ pub struct Preferences {
lock_button: gtk::Button,
auto_lock: adw::ComboRow,
auto_approve: adw::SpinRow,
close_action: adw::ComboRow,
tray_icon: adw::SwitchRow,
autostart: adw::SwitchRow,
}
impl Preferences {
pub fn new(state: Rc<AppState>, runner: Rc<SignerRunner>) -> Rc<Self> {
pub fn new(
state: Rc<AppState>,
runner: Rc<SignerRunner>,
on_tray_changed: Rc<dyn Fn()>,
) -> Rc<Self> {
// --- The signer's run state. ---
let signer_row = plain::row("Listen for requests", "—");
let toggle = gtk::Button::builder()
@@ -178,11 +193,45 @@ impl Preferences {
load_icons.set_subtitle("Fetch and show app icons when pairing");
appearance.add(&load_icons);
// --- Background. ---
let background = adw::PreferencesGroup::builder()
.title("Background")
.description(
"Regent can keep running without its window, so it can still ask you to \
sign incoming requests.",
)
.build();
let close_labels: Vec<&str> = CLOSE_ACTIONS.iter().map(|(_, label)| *label).collect();
let close_action = adw::ComboRow::builder()
.use_markup(false)
.title("When the window is closed")
.subtitle("Only offered while the signer is listening")
.model(&gtk::StringList::new(&close_labels))
.build();
let tray_icon = adw::SwitchRow::builder()
.use_markup(false)
.active(Config::new().show_tray_icon())
.build();
tray_icon.set_title("Show a status icon");
tray_icon.set_subtitle("A tray icon to show or hide the window, or quit");
let autostart = adw::SwitchRow::builder()
.use_markup(false)
.active(Config::new().autostart())
.build();
autostart.set_title("Start at login");
autostart.set_subtitle("Launch Regent in the background when you log in");
background.add(&close_action);
background.add(&tray_icon);
background.add(&autostart);
let page = adw::PreferencesPage::new();
page.add(&signer_group);
page.add(&vault);
page.add(&behaviour);
page.add(&background);
page.add(&appearance);
// "Requests" (the auto-approval limit) sits last: it is the most
// advanced setting, not something the common path needs.
page.add(&behaviour);
let dialog = adw::PreferencesDialog::new();
dialog.set_title("Preferences");
@@ -200,6 +249,9 @@ impl Preferences {
lock_button,
auto_lock,
auto_approve,
close_action,
tray_icon,
autostart,
});
{
@@ -285,6 +337,48 @@ impl Preferences {
preferences.state.notify_changes();
});
}
{
let preferences = Rc::clone(&preferences);
preferences.close_action.connect_selected_notify(move |row| {
if let Some((action, _)) = CLOSE_ACTIONS.get(row.selected() as usize) {
let config = Config::new();
// Idempotent: `refresh` sets the selection too.
if config.close_action() != *action {
config.set_close_action(*action);
}
}
});
}
{
let preferences = Rc::clone(&preferences);
preferences.tray_icon.connect_active_notify(move |row| {
let show = row.is_active();
let config = Config::new();
if config.show_tray_icon() != show {
config.set_show_tray_icon(show);
// Start or stop the icon to match.
on_tray_changed();
}
});
}
{
let preferences = Rc::clone(&preferences);
preferences.autostart.connect_active_notify(move |row| {
let autostart = row.is_active();
let config = Config::new();
if config.autostart() != autostart {
config.set_autostart(autostart);
// (Re)write the portal's autostart entry. Off the main loop:
// a portal-less desktop is not an error.
runtime::spawn_detached(async move {
let _ = tokio::task::spawn_blocking(move || {
portal::request_background(autostart, portal::background_commandline());
})
.await;
});
}
});
}
{
let preferences = Rc::clone(&preferences);
let state = preferences.state.clone();
@@ -296,7 +390,12 @@ impl Preferences {
}
/// Present it inside `parent` — the window it belongs to.
///
/// Refreshes first: the dialog is built once and re-presented, and the
/// settings it mirrors (the close action, the lock state, the signer's run
/// state) can have changed while it was closed.
pub fn present(&self, parent: Option<&impl IsA<gtk::Widget>>) {
self.refresh();
self.dialog.present(parent);
}
@@ -363,6 +462,17 @@ impl Preferences {
.position(|(value, _)| *value == seconds)
.unwrap_or(2);
self.auto_lock.set_selected(index as u32);
// Background settings: the combo is the only UI for the close action, so
// an unknown stored value shows as "Ask every time" rather than nothing.
let config = Config::new();
let close_index = CLOSE_ACTIONS
.iter()
.position(|(action, _)| *action == config.close_action())
.unwrap_or(0);
self.close_action.set_selected(close_index as u32);
self.tray_icon.set_active(config.show_tray_icon());
self.autostart.set_active(config.autostart());
}
/// Ask for a new passphrase and re-encrypt every key under it.
+244
View File
@@ -0,0 +1,244 @@
//! The status-bar indicator: a StatusNotifierItem/AppIndicator that lets the
//! user show or hide the window, open Preferences, or quit.
//!
//! Stock GNOME does not display SNI items without the AppIndicator extension;
//! everywhere else (KDE, XFCE, MATE, Cinnamon, …) it is native. A missing host
//! is therefore **not** an error: `watcher_offline` keeps the service alive so
//! enabling the extension later "just works", and the app runs on either way.
//!
//! The tray lives on the async runtime while its menu and window calls must
//! happen on the GTK main loop, so the two talk over a channel: the tray sends
//! [`TrayCmd`]s, and the main loop pushes visibility and signer state back into
//! the shared [`TrayModel`] through the ksni `Handle`.
use std::sync::{Arc, Mutex};
use async_channel::Sender;
use ksni::menu::{MenuItem, StandardItem};
use ksni::{ToolTip, Tray, TrayMethods};
/// The installed monochrome symbolic icon. Panels recolour symbolic names, so
/// the same file works on light and dark themes.
pub const ICON: &str = "org.kosmos.raucao.Regent-symbolic";
/// What a tray interaction asks the app to do. Deliberately tiny and `Copy`: the
/// menu callbacks run on the tray task and must never touch a GTK object.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrayCmd {
/// Show the window if hidden, hide it if shown.
Toggle,
/// Present the window and open Preferences.
Preferences,
/// Quit the application.
Quit,
}
/// The state the menu and tooltip are built from. The main loop writes it; the
/// tray task reads it.
#[derive(Default)]
pub struct TrayModel {
/// Whether the main window is currently visible (drives the Show/Hide label).
pub visible: bool,
/// A short signer-state line for the tooltip.
pub status: String,
/// Whether a prompt is waiting, so the icon asks for attention.
pub pending: bool,
}
/// The ksni tray. Holds only `Send` state: the model and the command channel.
pub struct RegentTray {
model: Arc<Mutex<TrayModel>>,
commands: Sender<TrayCmd>,
}
impl RegentTray {
pub fn new(model: Arc<Mutex<TrayModel>>, commands: Sender<TrayCmd>) -> Self {
Self { model, commands }
}
}
impl Tray for RegentTray {
/// Left-click opens the menu instead of calling `activate`.
///
/// The GNOME AppIndicator extension checks the introspection data for an
/// `Activate` method and, when one exists, waits out the double-click
/// interval before opening the menu on every click. Without `Activate` (this
/// const makes ksni serve the menu-only interface) the menu opens at once.
/// Show/Hide lives in the menu, so nothing is lost.
const MENU_ON_ACTIVATE: bool = true;
fn id(&self) -> String {
"regent".to_string()
}
fn title(&self) -> String {
"Regent".to_string()
}
fn icon_name(&self) -> String {
ICON.to_string()
}
fn attention_icon_name(&self) -> String {
ICON.to_string()
}
fn status(&self) -> ksni::Status {
if self.model.lock().unwrap().pending {
ksni::Status::NeedsAttention
} else {
ksni::Status::Active
}
}
fn tool_tip(&self) -> ToolTip {
let status = self.model.lock().unwrap().status.clone();
ToolTip {
title: "Regent".to_string(),
description: status,
..Default::default()
}
}
fn menu(&self) -> Vec<MenuItem<Self>> {
let visible = self.model.lock().unwrap().visible;
vec![
StandardItem {
label: if visible {
"Hide Regent"
} else {
"Show Regent"
}
.to_string(),
activate: Box::new(|tray: &mut Self| {
let _ = tray.commands.try_send(TrayCmd::Toggle);
}),
..Default::default()
}
.into(),
MenuItem::Separator,
StandardItem {
label: "Preferences…".to_string(),
icon_name: "preferences-system-symbolic".to_string(),
activate: Box::new(|tray: &mut Self| {
let _ = tray.commands.try_send(TrayCmd::Preferences);
}),
..Default::default()
}
.into(),
StandardItem {
label: "Quit Regent".to_string(),
icon_name: "application-exit-symbolic".to_string(),
activate: Box::new(|tray: &mut Self| {
let _ = tray.commands.try_send(TrayCmd::Quit);
}),
..Default::default()
}
.into(),
]
}
/// No host (stock GNOME, or the extension is off): keep the service running
/// so it appears the moment a host does. This can fire more than once (each
/// time the watcher goes away), so the line is not a one-shot.
fn watcher_offline(&self, _reason: ksni::OfflineReason) -> bool {
eprintln!(
"regent: no status-icon host found (on stock GNOME install the \
AppIndicator extension); the icon will appear if one shows up"
);
true
}
fn watcher_online(&self) {
eprintln!("regent: the status icon is now shown");
}
}
/// A running tray, from the main loop's side: the ksni handle plus the shared
/// model. `Handle` is `Clone + Send + Sync`, so updates can be handed to the
/// runtime.
pub struct TrayHandle {
handle: ksni::Handle<RegentTray>,
model: Arc<Mutex<TrayModel>>,
}
impl TrayHandle {
pub fn new(handle: ksni::Handle<RegentTray>, model: Arc<Mutex<TrayModel>>) -> Self {
Self { handle, model }
}
/// Apply `update` to the model and ask the host to re-read the item.
pub fn set(&self, update: impl FnOnce(&mut TrayModel)) {
update(&mut self.model.lock().unwrap());
let handle = self.handle.clone();
crate::runtime::spawn_detached(async move {
// `update` returns None once the service is gone; nothing to do then.
let _ = handle.update(|_| {}).await;
});
}
/// Stop the tray service. Used when the preference is turned off.
pub fn shutdown(&self) {
// Dropped on purpose: shutdown is initiated, and the awaiter only lets a
// caller wait for it. Nothing here needs to.
drop(self.handle.shutdown());
}
}
/// Start the tray on the async runtime and return its model + command channel.
///
/// The caller (the window registry) drains `commands` on the main loop and hands
/// the resulting `Handle` to a [`TrayHandle`] once the service is up.
///
/// `assume_sni_available(true)` turns a missing `StatusNotifierWatcher` (stock
/// GNOME, or the AppIndicator extension off) into a soft error routed to
/// [`RegentTray::watcher_offline`] instead of a `spawn` failure — so the service
/// keeps running and the icon appears the moment a host does.
pub fn spawn(
model: Arc<Mutex<TrayModel>>,
commands: Sender<TrayCmd>,
) -> impl std::future::Future<Output = Result<ksni::Handle<RegentTray>, String>> {
let tray = RegentTray::new(model, commands);
async move {
tray.assume_sni_available(true)
.spawn()
.await
.map_err(|error| error.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The tray never touches GTK: a menu item only ever sends a command.
#[test]
fn a_menu_item_sends_its_command() {
let model = Arc::new(Mutex::new(TrayModel {
visible: false,
status: "Stopped".to_string(),
pending: false,
}));
let (commands, received) = async_channel::unbounded();
let mut tray = RegentTray::new(model, commands);
// The toggle item's label follows visibility, and activating it sends
// exactly one command.
let labels: Vec<String> = tray
.menu()
.into_iter()
.filter_map(|item| match item {
MenuItem::Standard(item) => Some(item.label),
_ => None,
})
.collect();
assert!(labels.iter().any(|label| label == "Show Regent"));
assert!(labels.iter().any(|label| label == "Quit Regent"));
let mut items = tray.menu().into_iter();
if let Some(MenuItem::Standard(item)) = items.next() {
(item.activate)(&mut tray);
}
assert_eq!(received.try_recv(), Ok(TrayCmd::Toggle));
}
}
+427 -31
View File
@@ -7,30 +7,37 @@
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use gtk::gio;
use gtk::prelude::*;
use libadwaita as adw;
use adw::prelude::*;
use crate::runner::SignerRunner;
use crate::config::{CloseAction, Config};
use crate::runner::{SignerRunner, Status};
use crate::runtime;
use crate::state::AppState;
use crate::ui::about;
use crate::ui::activity_view::ActivityView;
use crate::ui::apps_view::AppsView;
use crate::ui::connect::ConnectDialog;
use crate::ui::keys_view::KeysView;
use crate::ui::plain;
use crate::ui::preferences::Preferences;
use crate::ui::switcher::IdentitySwitcher;
use crate::ui::tray::{self, TrayCmd, TrayHandle, TrayModel};
use crate::RESOURCE_PATH;
/// The windows this process owns, and the rule for which one is in front.
///
/// The invariant that keeps the two-window shape honest: **the main window is
/// visible exactly when the responder can serve prompts.** With no keys there is
/// nothing to sign with and nothing to listen for, so the identities window is
/// the whole app; the signer only runs once a key exists, and the approval
/// dialogs are parented to the main window, so a request can never arrive while
/// it is gone.
/// presentable exactly when the responder can serve prompts.** With no keys
/// there is nothing to sign with and nothing to listen for, so the identities
/// window is the whole app. With a key the main window exists and the responder
/// runs, but it may be hidden: the approval dialogs are parented to it, so the
/// drain presents it (see [`PrimaryHandle::present_for_prompt`]) before asking,
/// and hides it again once the request is answered.
pub struct Windows {
app: adw::Application,
state: Rc<AppState>,
@@ -42,6 +49,82 @@ pub struct Windows {
/// The main window's page stack, so the "Connect an app" dialog can bring
/// Apps forward after a pairing. `None` until the main window is built.
main_stack: RefCell<Option<adw::ViewStack>>,
/// The main window plus the "we opened it only for a prompt" bookkeeping.
primary: RefCell<Option<PrimaryHandle>>,
/// The status icon, when one is wanted and running.
tray: RefCell<Option<Rc<TrayHandle>>>,
/// True while a tray start is in flight, so a second activation cannot put
/// two SNI items on the bus (the handle only lands on completion).
tray_starting: Cell<bool>,
/// Guards the close-confirmation dialog against re-entry.
closing: Cell<bool>,
}
/// The main window, plus whether it is up only because a prompt needed it.
///
/// A window the user asked for (a menu item, the tray, a notification click) is
/// never hidden behind their back; a window the responder presented to show a
/// dialog is hidden again once the request is answered, so the app that asked
/// regains focus. The distinction is the single `auto` flag.
#[derive(Clone)]
pub struct PrimaryHandle {
window: adw::ApplicationWindow,
auto: Rc<Cell<bool>>,
}
impl PrimaryHandle {
pub fn new(window: adw::ApplicationWindow) -> Self {
Self {
window,
auto: Rc::new(Cell::new(false)),
}
}
/// The window as a widget, for parenting dialogs and notifications.
pub fn widget(&self) -> gtk::Widget {
self.window.clone().upcast()
}
pub fn is_visible(&self) -> bool {
self.window.is_visible()
}
/// Present the window at the user's request: clear the auto mark, so a later
/// answered request does not hide a window the user brought up.
pub fn present(&self) {
self.auto.set(false);
self.window.present();
}
/// Hide the window at the user's request.
pub fn hide(&self) {
self.auto.set(false);
self.window.set_visible(false);
}
pub fn toggle(&self) {
if self.is_visible() {
self.hide();
} else {
self.present();
}
}
/// A prompt needs the window: present it only if it is hidden, and remember
/// that we did.
pub fn present_for_prompt(&self) {
if !self.is_visible() {
self.auto.set(true);
self.window.present();
}
}
/// The request is over: hide the window if it was up only for the prompt.
pub fn restore_after_prompt(&self) {
if self.auto.replace(false) {
self.window.set_visible(false);
}
}
}
impl Windows {
@@ -55,6 +138,10 @@ impl Windows {
runner: RefCell::new(None),
connect: RefCell::new(None),
main_stack: RefCell::new(None),
primary: RefCell::new(None),
tray: RefCell::new(None),
tray_starting: Cell::new(false),
closing: Cell::new(false),
})
}
@@ -68,6 +155,11 @@ impl Windows {
let windows = Rc::clone(self);
let had_keys = Cell::new(self.state.has_keys());
self.state.listen(move || windows.follow_keys(&had_keys));
// The status icon's tooltip and attention state follow the signer.
if let Some(runner) = self.runner.borrow().clone() {
let windows = Rc::clone(self);
runner.listen(move || windows.refresh_tray());
}
// Say which mode the app came up in: it is the one thing about the
// launch that cannot be seen from the outside.
if self.state.has_keys() {
@@ -79,6 +171,17 @@ impl Windows {
if self.identities.borrow().is_none() {
*self.identities.borrow_mut() = Some(identities_window(&self.app, &self.state));
}
self.sync_tray();
}
/// Whether any identity key exists, i.e. whether the main window is the app.
pub fn has_keys(&self) -> bool {
self.state.has_keys()
}
/// The main window, when it exists.
fn handle(&self) -> Option<PrimaryHandle> {
self.primary.borrow().clone()
}
/// The window the app "is": the identities one while there are no keys,
@@ -91,12 +194,58 @@ impl Windows {
}
}
/// The window to parent a dialog to: the one the user is looking at, else
/// the window the app is.
///
/// Needed once the main window can be hidden in the background: parenting
/// an `AdwDialog` to a hidden window makes it silently invisible, so every
/// pointer route must fall back to a window that is actually on screen.
fn visible_parent(&self) -> Option<gtk::Window> {
self.app
.active_window()
.or_else(|| self.primary().map(|window| window.upcast::<gtk::Window>()))
}
/// Present the window the app is. A user-initiated present, so it clears the
/// auto mark.
pub fn present_primary(&self) {
if let Some(window) = self.primary() {
window.present();
if self.state.has_keys() {
if let Some(handle) = self.handle() {
handle.present();
}
} else {
self.present_identities();
}
}
/// Show the main window if hidden, hide it if shown — the tray's left click.
pub fn toggle_primary(&self) {
if self.state.has_keys() {
if let Some(handle) = self.handle() {
handle.toggle();
}
} else {
self.present_identities();
}
}
/// Hide the main window without ending the process.
pub fn hide_primary(&self) {
if let Some(handle) = self.handle() {
handle.hide();
}
}
/// Quit the application for real. Bypasses the close confirmation: this is
/// what the menu's Quit, Ctrl+Q and the tray's Quit do.
pub fn quit(&self) {
self.app.quit();
}
fn main_visible(&self) -> bool {
self.handle().map(|handle| handle.is_visible()).unwrap_or(false)
}
/// Open (or raise) the identities window — what the switcher's "Manage
/// identities…" does.
pub fn present_identities(&self) {
@@ -109,7 +258,7 @@ impl Windows {
/// without a parent. Built once: `AdwDialog` re-presents after being closed,
/// and its listeners must stay registered because the lock state changes
/// while it is open.
pub fn present_preferences(&self) {
pub fn present_preferences(self: &Rc<Self>) {
// Bind the clone to a local first: a `match` scrutinee is a temporary
// scope that lasts to the end of the match, so `borrow()`ing inline would
// still hold the `Ref` when the `None` arm takes `borrow_mut()` — and
@@ -123,18 +272,27 @@ impl Windows {
let Some(runner) = self.runner.borrow().clone() else {
return;
};
let preferences = Preferences::new(Rc::clone(&self.state), runner);
// Start or stop the status icon when its switch is flipped. Weak,
// so the preferences dialog does not keep the registry alive.
let weak = Rc::downgrade(self);
let on_tray_changed: Rc<dyn Fn()> = Rc::new(move || {
if let Some(windows) = weak.upgrade() {
windows.sync_tray();
}
});
let preferences =
Preferences::new(Rc::clone(&self.state), runner, on_tray_changed);
*self.preferences.borrow_mut() = Some(Rc::clone(&preferences));
preferences
}
};
preferences.present(self.primary().as_ref());
preferences.present(self.visible_parent().as_ref());
}
/// Present the About dialog inside the window the app "is". Built per
/// activation: it holds no state and registers no listeners.
pub fn present_about(&self) {
about::present(self.primary().as_ref());
about::present(self.visible_parent().as_ref());
}
/// Present the "Connect an app…" dialog inside the window the app "is".
@@ -142,7 +300,7 @@ impl Windows {
/// registered and the dialog re-presents after being closed.
pub fn present_connect(self: &Rc<Self>) {
if let Some(connect) = self.connect_dialog() {
connect.present(self.primary().as_ref());
connect.present(self.visible_parent().as_ref());
}
}
@@ -170,7 +328,13 @@ impl Windows {
let Some(connect) = self.connect_dialog() else {
return;
};
let Some(parent) = self.primary().map(|window| window.upcast::<gtk::Widget>()) else {
// A link can arrive while the window is hidden in the background, and a
// dialog parented to a hidden window is invisible.
self.present_primary();
let Some(parent) = self
.visible_parent()
.map(|window| window.upcast::<gtk::Widget>())
else {
return;
};
connect.begin_pairing(uri, &parent);
@@ -199,21 +363,246 @@ impl Windows {
had_keys.set(has_keys);
if has_keys {
if let Some(main) = self.main.borrow().as_ref() {
if !main.is_visible() {
main.present();
}
// The user just added a key, in the identities window: presenting
// the main window is expected even when it was backgrounded.
if let Some(handle) = self.handle().filter(|handle| !handle.is_visible()) {
handle.present();
}
return;
}
// Back to first run: nothing to sign with, so the main window has
// nothing to be.
if let Some(main) = self.main.borrow().as_ref() {
main.set_visible(false);
}
self.hide_primary();
self.present_identities();
}
/// The main window's close button: quit, hide to the background, or ask.
///
/// Always returns `Propagation::Stop` so the window is never destroyed by
/// GTK; quitting goes through `app.quit()` and hiding through the handle.
fn request_close(self: &Rc<Self>) -> glib::Propagation {
// A prompt is on screen: ignore the close rather than stack the ask
// dialog on top of it. An `AdwAlertDialog` blocks pointer closes, so only
// a keyboard/WM close reaches here; hiding the window would strand the
// prompt it lives in, and it times out to Deny on its own.
let pending = self
.runner
.borrow()
.as_ref()
.map(|runner| runner.is_pending())
.unwrap_or(false);
if pending {
return glib::Propagation::Stop;
}
// Keeping Regent alive only makes sense while it can answer. With no
// key, or a stopped signer, closing means quitting — a hidden window
// that can serve nothing is exactly the "signer that answers nothing"
// the two-window shape exists to avoid.
let running = matches!(
self.runner.borrow().as_ref().map(|runner| runner.status()),
Some(Status::Running(_))
);
if !running {
self.app.quit();
return glib::Propagation::Stop;
}
match Config::new().close_action() {
CloseAction::Quit => {
self.app.quit();
glib::Propagation::Stop
}
CloseAction::Background => {
self.enter_background();
glib::Propagation::Stop
}
CloseAction::Ask => {
self.ask_close();
glib::Propagation::Stop
}
}
}
/// Hide the window and tell the desktop Regent runs in the background.
///
/// The portal call is what makes GNOME list Regent under "Background Apps";
/// hiding the window alone does not.
fn enter_background(self: &Rc<Self>) {
self.hide_primary();
self.register_background();
}
/// Register Regent with the Background portal, honouring the autostart
/// preference. Best-effort and off the main loop: a portal-less desktop is
/// not an error.
pub(crate) fn register_background(&self) {
let autostart = Config::new().autostart();
let commandline = crate::portal::background_commandline();
runtime::spawn_detached(async move {
let _ = tokio::task::spawn_blocking(move || {
crate::portal::request_background(autostart, commandline);
})
.await;
});
}
/// Ask whether to keep running or quit, remembering the answer if asked to.
///
/// The dialog has a default response because the user opened it themselves —
/// unlike an approval prompt, where Enter must never answer.
fn ask_close(self: &Rc<Self>) {
if self.closing.replace(true) {
return;
}
let remember = gtk::CheckButton::builder()
.label("Remember this choice")
.build();
let dialog = adw::AlertDialog::builder()
.heading("Close Regent?")
.body(
"Regent can keep running in the background and ask you to sign incoming \
requests. If you quit, applications will not get signatures until you \
start Regent again.",
)
.extra_child(&remember)
.build();
plain::dialog(&dialog);
plain::alert_width(&dialog, plain::DIALOG_WIDTH);
dialog.add_response("cancel", "Cancel");
dialog.add_response("background", "Keep Running");
dialog.add_response("quit", "Quit");
dialog.set_response_appearance("background", adw::ResponseAppearance::Suggested);
dialog.set_response_appearance("quit", adw::ResponseAppearance::Destructive);
// The safe answer is the default. Escape and the dialog's own X mean
// "stay as you are", not "keep running".
dialog.set_default_response(Some("background"));
dialog.set_close_response("cancel");
{
let windows = Rc::clone(self);
dialog.connect_response(None, move |_, response| {
windows.closing.set(false);
let remember = remember.is_active();
match response {
"quit" => {
if remember {
Config::new().set_close_action(CloseAction::Quit);
}
windows.quit();
}
"background" => {
if remember {
Config::new().set_close_action(CloseAction::Background);
}
windows.enter_background();
}
_ => {}
}
});
}
dialog.present(self.visible_parent().as_ref());
}
/// Start or stop the status icon to match the preference.
///
/// A start is asynchronous, so `tray_starting` is the guard against a second
/// activation (or a toggle) racing the first: the handle only lands on
/// completion, and a second start would put two items on the bus.
fn sync_tray(self: &Rc<Self>) {
let wanted = Config::new().show_tray_icon();
if !wanted {
let tray = self.tray.borrow_mut().take();
if let Some(tray) = tray {
tray.shutdown();
}
return;
}
if self.tray.borrow().is_none() && !self.tray_starting.get() {
self.start_tray();
}
}
/// Start the status icon on the async runtime and drain its commands on the
/// main loop. The service is best-effort: no host just means no icon.
fn start_tray(self: &Rc<Self>) {
if self.tray_starting.replace(true) {
return;
}
let (commands, command_rx) = async_channel::unbounded();
let model = Arc::new(Mutex::new(TrayModel {
status: "Starting…".to_string(),
..Default::default()
}));
let start_model = Arc::clone(&model);
let windows = Rc::clone(self);
runtime::spawn(tray::spawn(start_model, commands), move |result| {
windows.tray_starting.set(false);
match result {
Ok(handle) => {
let tray = Rc::new(TrayHandle::new(handle, model));
// The preference may have been turned off while the service
// was starting: shut it down rather than show an icon the
// user just disabled.
if Config::new().show_tray_icon() {
*windows.tray.borrow_mut() = Some(tray);
windows.refresh_tray();
} else {
tray.shutdown();
}
}
Err(error) => eprintln!("regent: could not start the status icon: {error}"),
}
});
let windows = Rc::clone(self);
glib::MainContext::default().spawn_local(async move {
while let Ok(command) = command_rx.recv().await {
match command {
TrayCmd::Toggle => windows.toggle_primary(),
TrayCmd::Preferences => {
windows.present_primary();
windows.present_preferences();
}
TrayCmd::Quit => windows.quit(),
}
}
});
}
/// Push the window's visibility and the signer's state into the tray.
fn refresh_tray(&self) {
let Some(tray) = self.tray.borrow().clone() else {
return;
};
let visible = self.main_visible();
let (status, pending) = self.signer_state();
tray.set(|model| {
model.visible = visible;
model.status = status;
model.pending = pending;
});
}
/// A one-line signer state for the tray tooltip, and whether a prompt is
/// waiting (so the icon can ask for attention).
fn signer_state(&self) -> (String, bool) {
let runner = self.runner.borrow().clone();
let pending = runner
.as_ref()
.map(|runner| runner.is_pending())
.unwrap_or(false);
let status = match runner.as_ref().map(|runner| runner.status()) {
Some(Status::Running(signer)) => {
format!("Listening on {} relay(s)", signer.relay_count())
}
Some(Status::Starting) => "Starting…".to_string(),
_ => "Stopped".to_string(),
};
(status, pending)
}
}
/// The main window: what the app is for — pairing, approvals and the log.
@@ -237,9 +626,15 @@ fn main_window(
// approval drain: a notification without an application goes nowhere.
window.set_application(Some(app));
// The main window's handle: the registry uses it to present or hide the
// window, and the approval drain uses it to present a hidden window for a
// prompt and hide it again once the request is answered.
let primary = PrimaryHandle::new(window.clone());
*windows.primary.borrow_mut() = Some(primary.clone());
// The runner owns the process's only approval drain and the signer's
// lifecycle. Create it before the views so the Apps page can show its state.
let runner = SignerRunner::new(Rc::clone(state), window.clone().upcast());
let runner = SignerRunner::new(Rc::clone(state), primary);
*windows.runner.borrow_mut() = Some(Rc::clone(&runner));
let apps_view = AppsView::new(Rc::clone(state), Rc::clone(&runner));
@@ -326,16 +721,17 @@ fn main_window(
toolbar_view.set_content(Some(&stack));
// Closing the main window ends the session. The responder can only put a
// request to the user through this window, so leaving the process alive —
// the identities window would keep it alive — would mean a signer that
// answers nothing, behind a window the user believes they closed.
// Closing the main window asks, hides to the background, or quits — and
// never lets GTK destroy the window, so the process can stay alive with the
// responder running. See `Windows::request_close`.
{
let app = app.clone();
window.connect_close_request(move |_| {
app.quit();
glib::Propagation::Proceed
});
let windows = Rc::clone(windows);
window.connect_close_request(move |_| windows.request_close());
}
// The status icon's Show/Hide label follows the window.
{
let windows = Rc::clone(windows);
window.connect_visible_notify(move |_| windows.refresh_tray());
}
window