Add M10: identities in their own window, Preferences, first-run mode

This commit is contained in:
raucao committed 2026-11-24 16:30:12 +04:00
1 parent 3ee2d7a999
commit fa744e23f6
18 files changed
+758 -525

No files matched your search

+24
View File
@@ -179,6 +179,9 @@ sleep 6
grep -q 'signer listening' "$TMP_HOME/app.log"
check $? "the app started the signer ($(grep -m1 'signer listening' "$TMP_HOME/app.log" || echo 'no log line'))"
grep -q 'identity keys found, opening the main window' "$TMP_HOME/app.log"
check $? "with a key the main window is the app"
# The app must have generated and stored a device key of its own, in the vault.
grep -q '"device"' "$VAULT"
check $? "a device key was created in the vault"
@@ -277,6 +280,27 @@ kill "$HEADLESS" "$SUBSCRIBER" 2>/dev/null
HEADLESS=
SUBSCRIBER=
printf '\n== first run: no keys, so no signer ==\n'
# With no keys there is nothing to sign with and nothing to listen for, so the
# identities window is the whole app and the signer never starts. A fresh HOME is
# the only way to reach that state from here.
FIRST_HOME="$TMP_HOME/first-run"
mkdir -p "$FIRST_HOME/.local/share/applications"
sed "s|^Exec=regent|Exec=$ROOT/$BUILD/regent|" \
"$ROOT/data/$DATA_DIR.desktop" > "$FIRST_HOME/.local/share/applications/$DATA_DIR.desktop"
GDK_BACKEND=broadway BROADWAY_DISPLAY=:11 \
HOME="$FIRST_HOME" XDG_DATA_HOME="$FIRST_HOME/.local/share" XDG_CONFIG_HOME="$FIRST_HOME/.config" \
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" \
timeout 8 "$ROOT/$BUILD/regent" >"$TMP_HOME/first-run.log" 2>&1
grep -q 'no identity key yet, opening the identities window' "$TMP_HOME/first-run.log"
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'
if [ "$fails" = 0 ]; then
printf 'all checks passed\n'
-10
View File
@@ -1,16 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<schemalist gettext-domain="regent">
<schema id="org.kosmos.raucao.Regent" path="/org/kosmos/raucao/Regent/">
<key name="window-width" type="i">
<default>480</default>
<summary>Window width</summary>
<description>Width of the main window, in pixels.</description>
</key>
<key name="window-height" type="i">
<default>640</default>
<summary>Window height</summary>
<description>Height of the main window, in pixels.</description>
</key>
<key name="current-identity" type="s">
<default>''</default>
<summary>Current identity</summary>
+18 -10
View File
@@ -1,13 +1,21 @@
blueprints = custom_target('blueprints',
input: files('ui/window.blp'),
# `batch-compile` preserves paths relative to the source dir, so the output
# must be this directory itself (a named output would nest another level).
output: '.',
command: [
blueprint_compiler, 'batch-compile',
'@OUTPUT@', '@CURRENT_SOURCE_DIR@', '@INPUT@',
],
)
# One target per blueprint file, each writing exactly one .ui.
#
# The other obvious approach — a single `batch-compile` with `output: '.'` —
# makes the *directory* the target's output, which then becomes an input of the
# resource bundle: the bundle looks stale every time it writes into that
# directory (so it is regenerated on every build), and adding a file to the batch
# makes ninja fail to clean the stale output with "remove(...): Directory not
# empty". Meson forbids a path segment in `output`, so the .ui files land beside
# this file in the build directory and the resource paths are their plain names.
blueprints = []
foreach name : ['window', 'keys']
blueprints += custom_target(
name + '_ui',
input: 'ui' / (name + '.blp'),
output: name + '.ui',
command: [blueprint_compiler, 'compile', '--output', '@OUTPUT@', '@INPUT@'],
)
endforeach
gnome.compile_resources(app_id,
'resources.gresource.xml',
+2 -1
View File
@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
<gresource prefix="/org/kosmos/raucao/Regent">
<file preprocess="xml-stripblanks">ui/window.ui</file>
<file preprocess="xml-stripblanks">window.ui</file>
<file preprocess="xml-stripblanks">keys.ui</file>
<file>style.css</file>
</gresource>
</gresources>
+13
View File
@@ -0,0 +1,13 @@
using Gtk 4.0;
using Adw 1;
Adw.ApplicationWindow keys_window {
title: "Identities";
default-width: 420;
default-height: 640;
content: Adw.ToolbarView toolbar_view {
[top]
Adw.HeaderBar header_bar {}
};
}
+1
View File
@@ -43,6 +43,7 @@ cargo_build = custom_target(binary_name,
'src/ui/keys_view.rs',
'src/ui/mod.rs',
'src/ui/plain.rs',
'src/ui/preferences.rs',
'src/ui/qr.rs',
'src/ui/signer_view.rs',
'src/ui/switcher.rs',
+49 -26
View File
@@ -8,12 +8,27 @@ use libadwaita as adw;
use crate::state::AppState;
use crate::ui::approval;
use crate::window::Window;
use crate::window::Windows;
use crate::{APP_ID, RESOURCE_PATH};
pub fn run() -> glib::ExitCode {
let app = adw::Application::builder().application_id(APP_ID).build();
// One shared state per process, not per window: every window must see the
// same registry and signer. A vault that cannot be read is fatal — starting
// with an empty one would let the next save overwrite the real keys.
let state = match AppState::new() {
Ok(state) => state,
Err(error) => {
eprintln!("regent: could not read the key vault: {error}");
return glib::ExitCode::FAILURE;
}
};
warn_if_the_desktop_is_missing();
let windows = Windows::new(&app, Rc::clone(&state));
let quit = gio::SimpleAction::new("quit", None);
{
let app = app.clone();
@@ -22,12 +37,6 @@ pub fn run() -> glib::ExitCode {
app.add_action(&quit);
app.set_accels_for_action("app.quit", &["<primary>q"]);
// One shared state per process, not per window: every window must see the
// same registry and signer.
let state = AppState::new();
warn_if_the_desktop_is_missing();
// Lock or unlock the key vault. Unlocking asks for the passphrase; a locked
// vault fails closed, so this never signs anything. The user is present (they
// just clicked), so the dialog has no deadline.
@@ -35,21 +44,20 @@ pub fn run() -> glib::ExitCode {
{
let app = app.clone();
let state = Rc::clone(&state);
let windows = Rc::clone(&windows);
lock.connect_activate(move |_, _| {
let Some(store) = state.store() else {
return;
};
let store = state.store();
if !store.is_locked() {
store.lock();
eprintln!("regent: the key vault is locked");
state.notify();
return;
}
// `active_window()` is None when nothing is focused, which is also
// reachable through the accelerator, so fall back to the window.
// Parent it to the window the user is looking at, falling back to
// the window the app *is* so it is never parentless.
let widget = app
.active_window()
.or_else(|| app.windows().first().cloned())
.or_else(|| windows.primary().map(|window| window.upcast::<gtk::Window>()))
.map(|window| window.upcast::<gtk::Widget>());
let state = Rc::clone(&state);
glib::MainContext::default().spawn_local(async move {
@@ -66,6 +74,24 @@ pub fn run() -> glib::ExitCode {
app.add_action(&lock);
app.set_accels_for_action("app.lock", &["<primary>l"]);
// The identities window, always reachable: the switcher's own entry is
// hidden while there are no keys, which would otherwise leave no way back.
let identities = gio::SimpleAction::new("identities", None);
{
let windows = Rc::clone(&windows);
identities.connect_activate(move |_, _| windows.present_identities());
}
app.add_action(&identities);
// The vault's security and the request rate limit.
let preferences = gio::SimpleAction::new("preferences", None);
{
let windows = Rc::clone(&windows);
preferences.connect_activate(move |_, _| windows.present_preferences());
}
app.add_action(&preferences);
app.set_accels_for_action("app.preferences", &["<primary>comma"]);
// A notification body click lands here: GNOME Shell emits
// `ActionInvoked("default")` and GLib activates the notification's default
// action in-process (the `org.gtk.Notifications` path calls
@@ -73,26 +99,23 @@ pub fn run() -> glib::ExitCode {
// waiting on it — back to the front.
let focus = gio::SimpleAction::new("focus", None);
{
let app = app.clone();
let windows = Rc::clone(&windows);
focus.connect_activate(move |_, _| {
eprintln!("regent: bringing the window to the front");
for window in app.windows() {
window.present();
}
// Only the window the app *is*: presenting every window would un-hide
// the identities window on every notification click.
windows.present_primary();
});
}
app.add_action(&focus);
app.connect_startup(|_| load_css());
// Reuse the window: an activation can arrive while the app is already
// running (a notification click, or launching `regent` again), and a second
// window would share the state and show the same dialog twice.
app.connect_activate(move |app| {
if let Some(window) = app.windows().first() {
window.present();
return;
}
Window::new(app, Rc::clone(&state)).present();
app.connect_activate(move |_| {
windows.build();
// 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.
windows.present_primary();
});
// The resource file is passed through the environment, not argv, so that
+6 -8
View File
@@ -18,14 +18,6 @@ impl Config {
}
}
pub fn window_width(&self) -> i32 {
self.settings.int("window-width")
}
pub fn window_height(&self) -> i32 {
self.settings.int("window-height")
}
/// The identity selected in the UI: it scopes the Apps/Activity pages and
/// is the default for new pairings. `None` means "the first stored key".
pub fn current_identity(&self) -> Option<PublicKey> {
@@ -50,6 +42,12 @@ impl Config {
self.settings.int("auto-approve-limit").max(0) as u32
}
pub fn set_auto_approve_limit(&self, limit: u32) {
if let Err(error) = self.settings.set_int("auto-approve-limit", limit as i32) {
eprintln!("regent: could not save the auto-approval limit: {error}");
}
}
/// How long the key vault stays open after it is unlocked, in seconds.
/// Zero means never lock automatically.
///
+1 -3
View File
@@ -67,9 +67,7 @@ async fn serve(
// The passphrase is read once, here, and never logged.
let passphrase = read_passphrase(passphrase_file)?;
let store = KeyStore::connect()
.await
.map_err(|error| error.to_string())?;
let store = KeyStore::connect().map_err(|error| error.to_string())?;
let stored = store.list_user_keys();
if stored.is_empty() {
return Err(
+62 -77
View File
@@ -1,6 +1,6 @@
//! Shared application state: the key store once it is connected, the
//! application registry, the activity log, the selected identity, and a way for
//! views to be told that something changed.
//! Shared application state: the key vault, the application registry, the
//! activity log, the selected identity, and a way for views to be told that
//! something changed.
use std::cell::RefCell;
use std::collections::HashMap;
@@ -14,13 +14,15 @@ use crate::config::Config;
use crate::runtime;
use crate::store::apps::AppRegistry;
use crate::store::audit::ActivityLog;
use crate::store::keys::{KeyRef, KeyStore};
use crate::store::keys::{Error as KeyError, KeyRef, KeyStore};
use crate::store::profiles::Profiles;
type Listener = Rc<dyn Fn()>;
pub struct AppState {
store: RefCell<Option<Arc<KeyStore>>>,
/// Open once per process. A file, so it is read synchronously — the launch
/// decision needs the key list before any window exists.
store: Arc<KeyStore>,
/// Shared with the responder, which runs on tokio.
registry: Arc<Mutex<AppRegistry>>,
/// Shared with the responder; cloning shares the file lock too.
@@ -41,10 +43,15 @@ pub struct AppState {
impl AppState {
/// Build the one shared state. Called once per process, not per window.
pub fn new() -> Rc<Self> {
///
/// Fails when the vault exists but cannot be read. The caller must stop
/// rather than start with an empty vault: the next save would write that
/// empty vault over the real one.
pub fn new() -> Result<Rc<Self>, KeyError> {
let store = Arc::new(KeyStore::connect()?);
let (changes, changes_rx) = async_channel::bounded(1);
let state = Rc::new(Self {
store: RefCell::new(None),
store,
registry: Arc::new(Mutex::new(AppRegistry::load())),
activity: ActivityLog::new(),
current: Arc::new(Mutex::new(Config::new().current_identity())),
@@ -64,25 +71,16 @@ impl AppState {
});
}
let connecting = Rc::clone(&state);
runtime::spawn(KeyStore::connect(), move |result| match result {
Ok(store) => {
let store = Arc::new(store);
*connecting.store.borrow_mut() = Some(Arc::clone(&store));
connecting.refresh_identities();
}
Err(error) => eprintln!("regent: the key vault is unavailable: {error}"),
});
state.refresh_identities();
state.watch_auto_lock();
state
Ok(state)
}
/// Lock the vault once it has been open longer than the configured timeout.
///
/// A **hard** timeout measured from the unlock, not an idle timer that
/// request traffic resets: otherwise a client that keeps asking would hold
/// the keys open forever. The timer only ticks while a vault exists.
/// the keys open forever.
fn watch_auto_lock(self: &Rc<Self>) {
let state = Rc::clone(self);
glib::timeout_add_seconds_local(30, move || {
@@ -90,9 +88,7 @@ impl AppState {
if timeout == 0 {
return glib::ControlFlow::Continue;
}
let Some(store) = state.store() else {
return glib::ControlFlow::Continue;
};
let store = state.store();
let expired = store
.unlocked_at()
.map(|at| at.elapsed() >= std::time::Duration::from_secs(timeout as u64))
@@ -108,13 +104,16 @@ impl AppState {
/// Whether the vault still needs the passphrase.
pub fn is_locked(&self) -> bool {
self.store()
.map(|store| store.is_locked())
.unwrap_or(false)
self.store.is_locked()
}
pub fn store(&self) -> Option<Arc<KeyStore>> {
self.store.borrow().clone()
/// Whether any identity key is stored. Decides which window opens.
pub fn has_keys(&self) -> bool {
!self.names.lock().unwrap().is_empty()
}
pub fn store(&self) -> Arc<KeyStore> {
Arc::clone(&self.store)
}
/// The registry of approved applications, shared with the responder.
@@ -167,53 +166,41 @@ impl AppState {
self.notify_changes();
}
/// Re-read the identity list and selected key. Call after adding, renaming
/// or removing a key, and when the store becomes available.
/// Re-read the identity list and the selected key. Call after adding,
/// renaming or removing a key.
///
/// Synchronous: the vault is a file, and the launch decision needs the list
/// before any window exists. Only the kind-0 profile fetch stays async.
pub fn refresh_identities(self: &Rc<Self>) {
let Some(store) = self.store() else {
return;
};
let configured = Config::new().current_identity();
let state = Rc::clone(self);
runtime::spawn(
async move { Ok::<_, String>(store.list_user_keys()) },
move |result| match result {
Ok(keys) => {
// The **live** selection wins over the setting snapshot: a
// refresh started before the user picked a key must not
// clobber that pick when it lands.
let live = *state.current.lock().unwrap();
let selected = resolve_selection(live, configured, &keys);
let names = keys
.iter()
.map(|key| (key.public_key.to_hex(), key.name.clone()))
.collect();
*state.names.lock().unwrap() = names;
*state.current.lock().unwrap() = selected;
if selected != live {
Config::new().set_current_identity(selected);
}
let keys = self.store.list_user_keys();
// One-time migration: apps from before identities existed
// are bound to the selected key, so nothing resolves against
// a mutable default later.
if let Some(identity) = selected {
let registry = state.registry();
if let Err(error) = registry.lock().unwrap().bind_legacy(identity) {
eprintln!("regent: could not bind legacy applications: {error}");
}
}
state.notify();
state.notify_changes();
state.fetch_profiles(
keys.iter()
.filter(|key| state.profiles.needs_refresh(&key.public_key))
.map(|key| key.public_key)
.collect(),
);
}
Err(error) => eprintln!("regent: could not read the identity keys: {error}"),
},
// The live selection wins: it is what the UI is showing.
let live = *self.current.lock().unwrap();
let selected = resolve_selection(live, Config::new().current_identity(), &keys);
*self.names.lock().unwrap() = keys
.iter()
.map(|key| (key.public_key.to_hex(), key.name.clone()))
.collect();
*self.current.lock().unwrap() = selected;
if selected != live {
Config::new().set_current_identity(selected);
}
// One-time migration: apps from before identities existed are bound to
// the selected key, so nothing resolves against a mutable default later.
if let Some(identity) = selected {
let registry = self.registry();
if let Err(error) = registry.lock().unwrap().bind_legacy(identity) {
eprintln!("regent: could not bind legacy applications: {error}");
}
}
self.notify();
self.notify_changes();
self.fetch_profiles(
keys.iter()
.filter(|key| self.profiles.needs_refresh(&key.public_key))
.map(|key| key.public_key)
.collect(),
);
}
@@ -243,14 +230,12 @@ impl AppState {
self.changes.clone()
}
/// Register a listener for key/store changes; it runs immediately if the
/// store is already up.
/// Register a listener for key/store changes. It runs immediately: the
/// vault is already open by the time any view is built.
pub fn listen(&self, listener: impl Fn() + 'static) {
let listener: Listener = Rc::new(listener);
self.listeners.borrow_mut().push(Rc::clone(&listener));
if self.store.borrow().is_some() {
listener();
}
listener();
}
/// Announce that the keys (or the store) changed.
+5 -1
View File
@@ -104,7 +104,11 @@ impl KeyStore {
}
/// Open the vault this installation writes to.
pub async fn connect() -> Result<Self> {
///
/// Plain file I/O, and synchronous on purpose: startup needs the key list
/// before it can decide which window to open. The `async` this used to carry
/// went away with the keyring.
pub fn connect() -> Result<Self> {
Self::at(Self::default_path())
}
+3 -5
View File
@@ -64,16 +64,14 @@ pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::R
continue;
}
let notified = notify_pending(&widget, UNLOCK_BODY);
let unlocked = match state.store() {
Some(store) => present_unlock(&widget, store, Some(deadline)).await,
None => false,
};
let unlocked = present_unlock(&widget, state.store(), Some(deadline)).await;
if notified {
withdraw_pending(&widget);
}
if unlocked {
// Only `notify` reaches the header lock button and the
// keys page's vault rows; `notify_changes` does not.
// preferences dialog's vault rows; `notify_changes` does
// not.
state.notify();
}
let _ = reply.send(unlocked).await;
+16 -239
View File
@@ -1,9 +1,13 @@
//! The keys page: the identity keys (named, several of them) and the device key.
//! The identity keys: named, several of them.
//!
//! Creating, importing, renaming, exporting and removing a key all happen here;
//! the selected identity (used for new pairings and by the header switcher) is
//! chosen from the same list. The vault itself is managed here too: its
//! passphrase, the auto-lock timeout, and "Lock now".
//! Creating, importing, renaming, exporting and removing a key all happen here,
//! and the selected identity (used for new pairings and by the header switcher)
//! is chosen from the same list. This is the whole app on first run — there is
//! nothing to sign with and nothing to listen for until a key exists — and
//! afterwards it lives in its own window, reached from the identity switcher.
//!
//! The vault's passphrase, its auto-lock timeout and the device key are not key
//! *management* and live in Preferences (`ui/preferences.rs`).
use std::cell::RefCell;
use std::rc::Rc;
@@ -16,33 +20,15 @@ use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use crate::config::Config;
use crate::runtime;
use crate::state::AppState;
use crate::store::keys::KeyStore;
use crate::ui::{approval, plain};
/// The auto-lock choices: the timeout in seconds, and what to call it. `0` means
/// never lock, which is the user's call to make — but not the default.
const AUTO_LOCK: [(u32, &str); 6] = [
(60, "1 minute"),
(300, "5 minutes"),
(900, "15 minutes"),
(1800, "30 minutes"),
(3600, "1 hour"),
(0, "Never"),
];
/// Handles the callbacks need; cloned per closure.
#[derive(Clone)]
struct Handles {
stack: gtk::Stack,
list: adw::PreferencesGroup,
device: adw::ActionRow,
passphrase: adw::ActionRow,
passphrase_button: gtk::Button,
lock_button: gtk::Button,
auto_lock: adw::ComboRow,
}
/// The rows currently in the list, so a reload can remove exactly them.
@@ -61,12 +47,6 @@ impl KeysView {
pub fn new(state: Rc<AppState>) -> Self {
let stack = gtk::Stack::builder().vexpand(true).build();
let loading = adw::StatusPage::builder()
.title("Opening the key vault…")
.child(&adw::Spinner::new())
.build();
stack.add_named(&loading, Some("loading"));
let create = gtk::Button::builder()
.label("Create a key")
.css_classes(["pill", "suggested-action"])
@@ -99,14 +79,6 @@ impl KeysView {
the key it was paired with.",
)
.build();
let device = plain::row("Device key", "—");
let device_group = adw::PreferencesGroup::builder()
.title("Transport")
.description(
"Used for NIP-46 traffic only. Rotating it does not change any identity.",
)
.build();
device_group.add(&device);
let add_group = adw::PreferencesGroup::builder().title("Add a key").build();
let create_row = plain::row(
"Create a new identity key",
@@ -128,59 +100,12 @@ impl KeysView {
add_group.add(&create_row);
add_group.add(&import_row);
let vault_group = adw::PreferencesGroup::builder()
.title("Vault")
.description(
"Identity keys are encrypted with NIP-49 under one passphrase. Regent keeps \
the passphrase out of memory and locks the vault again after the timeout \
below.",
)
.build();
let passphrase = plain::row("Passphrase", "—");
let passphrase_button = gtk::Button::builder()
.label("Change…")
.valign(gtk::Align::Center)
.css_classes(["flat"])
.build();
passphrase.add_suffix(&passphrase_button);
let lock_row = plain::row(
"Lock now",
"Require the passphrase before the next signature",
);
let lock_button = gtk::Button::builder()
.label("Lock")
.valign(gtk::Align::Center)
.css_classes(["flat"])
.build();
lock_row.add_suffix(&lock_button);
let labels: Vec<&str> = AUTO_LOCK.iter().map(|(_, label)| *label).collect();
let auto_lock = adw::ComboRow::builder()
.title("Auto-lock after")
.subtitle("How long the vault stays open once it is unlocked")
.model(&gtk::StringList::new(&labels))
.build();
vault_group.add(&passphrase);
vault_group.add(&auto_lock);
vault_group.add(&lock_row);
let page = adw::PreferencesPage::new();
page.add(&list);
page.add(&add_group);
page.add(&vault_group);
page.add(&device_group);
stack.add_named(&page, Some("loaded"));
stack.set_visible_child_name("loading");
let handles = Handles {
stack,
list,
device,
passphrase,
passphrase_button,
lock_button,
auto_lock,
};
let handles = Handles { stack, list };
let rows: Rows = Rc::new(RefCell::new(Vec::new()));
let widget: gtk::Widget = handles.stack.clone().upcast();
@@ -193,35 +118,6 @@ impl KeysView {
button.connect_clicked(move |_| present_import(handles.clone(), Rc::clone(&state)));
}
{
let (state, handles) = (Rc::clone(&state), handles.clone());
handles.passphrase_button.clone().connect_clicked(move |_| {
present_change_passphrase(handles.clone(), Rc::clone(&state))
});
}
{
let state = Rc::clone(&state);
handles.lock_button.clone().connect_clicked(move |_| {
if let Some(store) = state.store() {
store.lock();
eprintln!("regent: the key vault is locked");
state.notify();
}
});
}
{
handles.auto_lock.clone().connect_selected_notify(move |row| {
if let Some((seconds, _)) = AUTO_LOCK.get(row.selected() as usize) {
let config = Config::new();
// Idempotent: reload sets the selection too, and writing the
// same value back must not loop.
if config.lock_timeout() != *seconds {
config.set_lock_timeout(*seconds);
}
}
});
}
// Reload on key changes and on a selection change.
{
let (listener_state, handles, rows) =
@@ -248,9 +144,6 @@ fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows) {
let names = names.lock().unwrap().clone();
let current = state.current_identity().map(|key| key.to_hex());
reload_vault(state, handles);
reload_device(handles.clone(), state.store());
if names.is_empty() {
handles.stack.set_visible_child_name("empty");
return;
@@ -276,46 +169,6 @@ fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows) {
}
}
/// Reflect the vault's state: which actions need it open, and the timeout.
fn reload_vault(state: &Rc<AppState>, handles: &Handles) {
let locked = state
.store()
.map(|store| store.is_locked())
.unwrap_or(false);
handles.passphrase_button.set_sensitive(!locked);
handles.lock_button.set_sensitive(!locked);
handles.passphrase.set_subtitle(if locked {
"Locked — unlock to change it"
} else {
"Encrypts every identity key"
});
let seconds = Config::new().lock_timeout();
// The combo is the only UI for this setting, so an out-of-range value (set
// by hand) falls back to the default rather than showing nothing selected.
let index = AUTO_LOCK
.iter()
.position(|(value, _)| *value == seconds)
.unwrap_or(2);
handles.auto_lock.set_selected(index as u32);
}
fn reload_device(handles: Handles, store: Option<Arc<KeyStore>>) {
let Some(store) = store else {
return;
};
runtime::spawn(
async move { store.device_key() },
move |result| match result {
Ok(keys) => set_public_key(&handles.device, &keys.public_key()),
Err(error) => {
handles.device.set_subtitle("unavailable");
report_error(&handles, &error);
}
},
);
}
fn key_row(
state: &Rc<AppState>,
handles: &Handles,
@@ -420,10 +273,6 @@ fn menu_button(label: &str) -> gtk::Button {
.build()
}
fn set_public_key(row: &adw::ActionRow, public_key: &PublicKey) {
row.set_subtitle(&public_key.to_bech32().unwrap_or_default());
}
/// A passphrase field for the add/import dialogs, plus a confirmation when this
/// is the call that *sets* the vault passphrase.
struct PassphraseFields {
@@ -476,9 +325,7 @@ const NEW_VAULT_NOTE: &str = "Choose a passphrase for the key vault. Every ident
stored encrypted under it, and it is needed to sign. There is no recovery if you forget it.";
fn present_create(handles: Handles, state: Rc<AppState>) {
let Some(store) = state.store() else {
return;
};
let store = state.store();
let first = !store.has_vault();
let count = state.names().lock().unwrap().len() + 1;
@@ -537,9 +384,7 @@ fn present_create(handles: Handles, state: Rc<AppState>) {
}
fn present_import(handles: Handles, state: Rc<AppState>) {
let Some(store) = state.store() else {
return;
};
let store = state.store();
let first = !store.has_vault();
let entry = adw::EntryRow::builder()
@@ -611,9 +456,7 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
/// Run `then` once the vault is open, asking for the passphrase first if needed.
fn with_unlocked<F: FnOnce() + 'static>(handles: &Handles, state: &Rc<AppState>, then: F) {
let Some(store) = state.store() else {
return;
};
let store = state.store();
if !store.is_locked() {
then();
return;
@@ -630,66 +473,6 @@ fn with_unlocked<F: FnOnce() + 'static>(handles: &Handles, state: &Rc<AppState>,
});
}
fn present_change_passphrase(handles: Handles, state: Rc<AppState>) {
let new = adw::PasswordEntryRow::builder().title("New passphrase").build();
let confirm = adw::PasswordEntryRow::builder()
.title("Confirm passphrase")
.build();
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
list.append(&new);
list.append(&confirm);
let dialog = adw::AlertDialog::builder()
.heading("Change the vault passphrase")
.body(
"Every identity key is re-encrypted under the new passphrase. There is no \
recovery if you forget it.",
)
.extra_child(&list)
.build();
plain::dialog(&dialog);
dialog.add_response("cancel", "Cancel");
dialog.add_response("change", "Change");
dialog.set_default_response(Some("change"));
dialog.set_response_appearance("change", adw::ResponseAppearance::Suggested);
dialog.set_close_response("cancel");
{
let (handles, state) = (handles.clone(), Rc::clone(&state));
dialog.connect_response(None, move |_, response| {
if response != "change" {
return;
}
let passphrase = new.text().to_string();
if passphrase.chars().count() < 8 {
return report_error(&handles, "Use a passphrase of at least 8 characters.");
}
if confirm.text().to_string() != passphrase {
return report_error(&handles, "The two passphrases do not match.");
}
let Some(store) = state.store() else {
return;
};
let after = Rc::clone(&state);
let handles = handles.clone();
runtime::spawn(
async move { store.change_passphrase(&passphrase).await },
move |result| match result {
Ok(()) => {
eprintln!("regent: the key vault passphrase was changed");
after.notify();
}
Err(error) => report_error(&handles, &error),
},
);
});
}
dialog.present(toplevel(&handles).as_ref());
}
fn present_rename(
handles: Handles,
state: Rc<AppState>,
@@ -715,9 +498,7 @@ fn present_rename(
if response != "rename" {
return;
}
let Some(store) = state.store() else {
return;
};
let store = state.store();
let name = defaulted_name(&entry.text().to_string());
let after = Rc::clone(&state);
let handles = handles.clone();
@@ -771,9 +552,7 @@ fn present_export_dialog(handles: Handles, state: Rc<AppState>, public_key: Publ
if response != "export" {
return;
}
let Some(store) = state.store() else {
return;
};
let store = state.store();
let (password, handles, window) =
(password.text().to_string(), handles.clone(), window.clone());
runtime::spawn(
@@ -849,9 +628,7 @@ fn present_remove(
if response != "remove" {
return;
}
let Some(store) = state.store() else {
return;
};
let store = state.store();
let registry = state.registry();
let after = Rc::clone(&state);
let handles = handles.clone();
+1
View File
@@ -6,6 +6,7 @@ pub mod apps_view;
pub mod kind;
pub mod keys_view;
pub mod plain;
pub mod preferences;
pub mod qr;
pub mod signer_view;
pub mod switcher;
+280
View File
@@ -0,0 +1,280 @@
//! Preferences: the vault's passphrase, its auto-lock timeout, and the
//! auto-approval rate limit.
//!
//! None of this is key *management* — that is the identities window — and none
//! of it is a window either: libadwaita replaces `AdwPreferencesWindow` with
//! `AdwPreferencesDialog`, which presents inside the main window.
//!
//! Built **once** and re-presented. `AdwDialog` re-presents after being closed,
//! and its listeners have to stay registered: the lock state genuinely changes
//! while it is open (the auto-lock timer, another window's "Lock now"), so
//! building it per activation would leak a listener every time.
use std::rc::Rc;
use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use crate::config::Config;
use crate::runtime;
use crate::state::AppState;
use crate::ui::plain;
/// The auto-lock choices: the timeout in seconds, and what to call it. `0` means
/// never lock, which is the user's call to make — but not the default.
const AUTO_LOCK: [(u32, &str); 6] = [
(60, "1 minute"),
(300, "5 minutes"),
(900, "15 minutes"),
(1800, "30 minutes"),
(3600, "1 hour"),
(0, "Never"),
];
/// The auto-approval limit, in requests per minute per application. `0` never
/// answers silently.
const AUTO_APPROVE_MAX: f64 = 600.0;
pub struct Preferences {
dialog: adw::PreferencesDialog,
state: Rc<AppState>,
passphrase: adw::ActionRow,
passphrase_button: gtk::Button,
lock_button: gtk::Button,
auto_lock: adw::ComboRow,
auto_approve: adw::SpinRow,
}
impl Preferences {
pub fn new(state: Rc<AppState>) -> Rc<Self> {
// --- Vault ---
let vault = adw::PreferencesGroup::builder()
.title("Vault")
.description(
"Identity keys are encrypted with NIP-49 under one passphrase. Regent keeps \
the passphrase out of memory and locks the vault again after the timeout \
below.",
)
.build();
let passphrase = plain::row("Passphrase", "—");
let passphrase_button = gtk::Button::builder()
.label("Change…")
.valign(gtk::Align::Center)
.css_classes(["flat"])
.build();
passphrase.add_suffix(&passphrase_button);
let labels: Vec<&str> = AUTO_LOCK.iter().map(|(_, label)| *label).collect();
let auto_lock = adw::ComboRow::builder()
.title("Auto-lock after")
.subtitle("How long the vault stays open once it is unlocked")
.model(&gtk::StringList::new(&labels))
.build();
let lock_row = plain::row(
"Lock now",
"Require the passphrase before the next signature",
);
let lock_button = gtk::Button::builder()
.label("Lock")
.valign(gtk::Align::Center)
.css_classes(["flat"])
.build();
lock_row.add_suffix(&lock_button);
vault.add(&passphrase);
vault.add(&auto_lock);
vault.add(&lock_row);
// --- Requests ---
let behaviour = adw::PreferencesGroup::builder()
.title("Requests")
.description(
"\"Allow always\" answers a request without asking. This caps how often it \
can do that, per application, so a runaway client turns back into prompts.",
)
.build();
let adjustment = gtk::Adjustment::new(
Config::new().auto_approve_limit() as f64,
0.0,
AUTO_APPROVE_MAX,
1.0,
10.0,
0.0,
);
let auto_approve = adw::SpinRow::new(Some(&adjustment), 1.0, 0);
auto_approve.set_use_markup(false);
auto_approve.set_title("Auto-approval limit");
auto_approve.set_subtitle("Requests per minute, per application. Zero never answers silently.");
behaviour.add(&auto_approve);
let page = adw::PreferencesPage::new();
page.add(&vault);
page.add(&behaviour);
let dialog = adw::PreferencesDialog::new();
dialog.set_title("Preferences");
dialog.add(&page);
let preferences = Rc::new(Self {
dialog,
state,
passphrase,
passphrase_button,
lock_button,
auto_lock,
auto_approve,
});
{
let button = preferences.passphrase_button.clone();
let preferences = Rc::clone(&preferences);
button.connect_clicked(move |_| preferences.change_passphrase());
}
{
let button = preferences.lock_button.clone();
let preferences = Rc::clone(&preferences);
button.connect_clicked(move |_| {
preferences.state.store().lock();
eprintln!("regent: the key vault is locked");
preferences.state.notify();
});
}
{
let preferences = Rc::clone(&preferences);
preferences.auto_lock.connect_selected_notify(move |row| {
if let Some((seconds, _)) = AUTO_LOCK.get(row.selected() as usize) {
let config = Config::new();
// Idempotent: the listener below sets the selection too, and
// writing the same value back must not loop.
if config.lock_timeout() != *seconds {
config.set_lock_timeout(*seconds);
}
}
});
}
{
let preferences = Rc::clone(&preferences);
preferences.auto_approve.connect_value_notify(move |row| {
let limit = row.value().max(0.0) as u32;
let config = Config::new();
if config.auto_approve_limit() != limit {
config.set_auto_approve_limit(limit);
}
});
}
{
let preferences = Rc::clone(&preferences);
let state = preferences.state.clone();
state.listen(move || preferences.refresh());
}
preferences.refresh();
preferences
}
/// Present it inside `parent` — the window it belongs to.
pub fn present(&self, parent: Option<&impl IsA<gtk::Widget>>) {
self.dialog.present(parent);
}
/// Reflect the vault's state: which actions need it open, and the timeout.
fn refresh(&self) {
let locked = self.state.is_locked();
self.passphrase_button.set_sensitive(!locked);
self.lock_button.set_sensitive(!locked);
self.passphrase.set_subtitle(if locked {
"Locked — unlock to change it"
} else {
"Encrypts every identity key"
});
let seconds = Config::new().lock_timeout();
// The combo is the only UI for this setting, so an out-of-range value
// (set by hand) falls back to the default rather than showing nothing.
let index = AUTO_LOCK
.iter()
.position(|(value, _)| *value == seconds)
.unwrap_or(2);
self.auto_lock.set_selected(index as u32);
}
/// Ask for a new passphrase and re-encrypt every key under it.
///
/// Only possible while unlocked: Regent holds the decrypted keys, so the
/// *old* passphrase is not needed.
fn change_passphrase(self: &Rc<Self>) {
let new = adw::PasswordEntryRow::builder().title("New passphrase").build();
let confirm = adw::PasswordEntryRow::builder()
.title("Confirm passphrase")
.build();
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
list.append(&new);
list.append(&confirm);
let dialog = adw::AlertDialog::builder()
.heading("Change the vault passphrase")
.body(
"Every identity key is re-encrypted under the new passphrase. There is no \
recovery if you forget it.",
)
.extra_child(&list)
.build();
plain::dialog(&dialog);
dialog.add_response("cancel", "Cancel");
dialog.add_response("change", "Change");
dialog.set_default_response(Some("change"));
dialog.set_response_appearance("change", adw::ResponseAppearance::Suggested);
dialog.set_close_response("cancel");
{
let (new, confirm) = (new.clone(), confirm.clone());
let preferences = Rc::clone(self);
dialog.connect_response(None, move |_, response| {
if response != "change" {
return;
}
let passphrase = new.text().to_string();
if passphrase.chars().count() < 8 {
return preferences.error("Use a passphrase of at least 8 characters.");
}
if confirm.text().to_string() != passphrase {
return preferences.error("The two passphrases do not match.");
}
let store = preferences.state.store();
let preferences = Rc::clone(&preferences);
runtime::spawn(
async move { store.change_passphrase(&passphrase).await },
move |result| match result {
Ok(()) => {
eprintln!("regent: the key vault passphrase was changed");
preferences.state.notify();
}
Err(error) => preferences.error(&error),
},
);
});
}
dialog.present(self.window().as_ref());
}
/// The window this dialog is presented in, for parenting another dialog.
fn window(&self) -> Option<gtk::Window> {
self.dialog.root().and_downcast::<gtk::Window>()
}
fn error(&self, message: &str) {
let dialog = adw::AlertDialog::builder()
.title("Something went wrong")
.body(message)
.build();
plain::dialog(&dialog);
dialog.add_response("close", "Close");
dialog.set_default_response(Some("close"));
dialog.present(self.window().as_ref());
}
}
+4 -15
View File
@@ -64,7 +64,7 @@ impl SignerView {
.icon_name("network-offline-symbolic")
.title("Nothing to listen for yet")
.description(
"Create or import an identity key on the Keys page, then come back here to \
"Add an identity key in the Identities window, then come back here to \
connect an application.",
)
.build();
@@ -225,9 +225,7 @@ impl SignerView {
let listener_state = Rc::clone(&state);
let listener_approver = approver.clone();
state.listen(move || {
let Some(store) = listener_state.store() else {
return;
};
let store = listener_state.store();
if !matches!(&*signer_running.borrow(), State::Stopped) {
return;
}
@@ -289,9 +287,7 @@ fn start(
if !matches!(&*running.borrow(), State::Stopped) {
return;
}
let Some(store) = state.store() else {
return;
};
let store = state.store();
*running.borrow_mut() = State::Starting;
let settings = Config::new();
@@ -452,7 +448,7 @@ fn begin_pairing(
let Some(identity) = state.current_identity() else {
report_error(
handles,
"Create an identity key on the Keys page first, then pair a client.",
"Add an identity key in the Identities window first, then pair a client.",
);
return;
};
@@ -507,13 +503,6 @@ fn begin_pairing(
match signer {
Some(signer) => pair_now(handles, state, &signer, pairing, identity),
None => {
if state.store().is_none() {
report_error(
&handles,
"The key vault is not ready yet; try again in a moment.",
);
return;
}
let extra = pairing
.relays
.iter()
+15 -21
View File
@@ -2,11 +2,13 @@
//!
//! Follows Fractal's account switcher — a header menu button opening a popover
//! with one row per identity (avatar, name, short npub, a check on the current
//! one), then "Manage identities…". It is hidden on the Keys page, which is the
//! identity manager, and when there are no keys.
//! one), then "Manage identities…", which opens the identities window. Hidden
//! while there are no keys.
//!
//! Holds the window registry **weakly**: the main window owns this switcher, so
//! a strong reference would be a cycle.
use std::cell::Cell;
use std::rc::Rc;
use std::rc::{Rc, Weak};
use nostr::nips::nip19::ToBech32;
use nostr::prelude::PublicKey;
@@ -16,19 +18,18 @@ use libadwaita as adw;
use crate::state::AppState;
use crate::ui::plain;
use crate::window::Windows;
pub struct IdentitySwitcher {
button: gtk::MenuButton,
popover: gtk::Popover,
content: gtk::Box,
state: Rc<AppState>,
stack: adw::ViewStack,
/// True unless the Keys page is showing; the switcher is hidden there.
on_other_page: Cell<bool>,
windows: Weak<Windows>,
}
impl IdentitySwitcher {
pub fn new(state: Rc<AppState>, stack: adw::ViewStack) -> Rc<Self> {
pub fn new(state: Rc<AppState>, windows: &Rc<Windows>) -> Rc<Self> {
let content = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(2)
@@ -46,8 +47,7 @@ impl IdentitySwitcher {
popover,
content,
state: Rc::clone(&state),
stack,
on_other_page: Cell::new(true),
windows: Rc::downgrade(windows),
});
// Rebuild on key changes and on a selection change.
@@ -68,13 +68,6 @@ impl IdentitySwitcher {
&self.button
}
/// Called when the visible page changes: the Keys page has no switcher.
pub fn set_previous_page_was_keys(&self, is_keys: bool) {
self.on_other_page.set(!is_keys);
let has_keys = !self.state.names().lock().unwrap().is_empty();
self.button.set_visible(has_keys && self.on_other_page.get());
}
fn rebuild(&self) {
while let Some(child) = self.content.first_child() {
self.content.remove(&child);
@@ -84,8 +77,7 @@ impl IdentitySwitcher {
let names = names.lock().unwrap().clone();
let current = self.state.current_identity();
let has_keys = !names.is_empty();
self.button
.set_visible(has_keys && self.on_other_page.get());
self.button.set_visible(has_keys);
let current_label = current
.map(|key| self.state.identity_label(&key))
@@ -116,10 +108,12 @@ impl IdentitySwitcher {
.css_classes(["flat"])
.build();
{
let (popover, stack) = (self.popover.clone(), self.stack.clone());
let (popover, windows) = (self.popover.clone(), self.windows.clone());
manage.connect_clicked(move |_| {
popover.popdown();
stack.set_visible_child_name("keys");
if let Some(windows) = windows.upgrade() {
windows.present_identities();
}
});
}
self.content.append(&manage);
+258 -109
View File
@@ -1,130 +1,279 @@
//! The main window: a view switcher over the pages.
//! The windows: the main one (Signer / Apps / Activity), the identities one, and
//! the registry that decides which of them the app "is".
//!
//! Pages are composed in Rust because they are built in code; Blueprint only
//! provides the window chrome.
//! Two windows rather than one plus a dialog, because a dialog presents *inside*
//! a parent window and so cannot be the whole visible app — and on first run,
//! with no keys, the identities window is exactly that.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use gtk::gio;
use gtk::prelude::*;
use libadwaita as adw;
use crate::config::Config;
use crate::state::AppState;
use crate::ui::activity_view::ActivityView;
use crate::ui::apps_view::AppsView;
use crate::ui::keys_view::KeysView;
use crate::ui::preferences::Preferences;
use crate::ui::signer_view::SignerView;
use crate::ui::switcher::IdentitySwitcher;
use crate::RESOURCE_PATH;
pub struct Window {
window: adw::ApplicationWindow,
/// 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.
pub struct Windows {
app: adw::Application,
state: Rc<AppState>,
main: RefCell<Option<adw::ApplicationWindow>>,
identities: RefCell<Option<adw::ApplicationWindow>>,
preferences: RefCell<Option<Rc<Preferences>>>,
}
impl Window {
/// `state` is created once per process and shared by every window.
pub fn new(app: &adw::Application, state: Rc<AppState>) -> Self {
let config = Config::new();
let builder = gtk::Builder::from_resource(&format!("{RESOURCE_PATH}/ui/window.ui"));
let window: adw::ApplicationWindow = builder
.object("window")
.expect("ui/window.blp must contain an object with id \"window\"");
let toolbar_view: adw::ToolbarView = builder
.object("toolbar_view")
.expect("ui/window.blp must contain an object with id \"toolbar_view\"");
let header_bar: adw::HeaderBar = builder
.object("header_bar")
.expect("ui/window.blp must contain an object with id \"header_bar\"");
let keys_view = KeysView::new(Rc::clone(&state));
let signer_view = SignerView::new(Rc::clone(&state));
let apps_view = AppsView::new(Rc::clone(&state));
let activity_view = ActivityView::new(Rc::clone(&state));
let stack = adw::ViewStack::new();
stack.add_titled_with_icon(
&keys_view.widget,
Some("keys"),
"Keys",
"dialog-password-symbolic",
);
stack.add_titled_with_icon(
&signer_view.widget,
Some("signer"),
"Signer",
"network-transmit-receive-symbolic",
);
stack.add_titled_with_icon(
&apps_view.widget,
Some("apps"),
"Apps",
"applications-system-symbolic",
);
stack.add_titled_with_icon(
&activity_view.widget,
Some("activity"),
"Activity",
"document-open-recent-symbolic",
);
let switcher = adw::ViewSwitcher::builder()
.stack(&stack)
.policy(adw::ViewSwitcherPolicy::Wide)
.build();
header_bar.set_title_widget(Some(&switcher));
// The identity switcher lives in the header; the Keys page is where
// identities are managed, so it is hidden there.
let identity_switcher = IdentitySwitcher::new(Rc::clone(&state), stack.clone());
header_bar.pack_end(identity_switcher.button());
// The vault's lock state, always visible, to the left of the switcher.
let lock_button = gtk::Button::builder()
.icon_name("changes-prevent-symbolic")
.tooltip_text("Lock the key vault")
.css_classes(["flat"])
.build();
lock_button.set_action_name(Some("app.lock"));
header_bar.pack_end(&lock_button);
{
let button = lock_button.clone();
let listener_state = Rc::clone(&state);
state.listen(move || {
let ready = listener_state.store().is_some();
let locked = listener_state.is_locked();
// Before the vault is open there is nothing to lock or unlock.
button.set_sensitive(ready);
button.set_icon_name(if locked {
"changes-allow-symbolic"
} else {
"changes-prevent-symbolic"
});
button.set_tooltip_text(Some(if locked {
"Unlock the key vault"
} else {
"Lock the key vault"
}));
});
}
{
let identity_switcher = Rc::clone(&identity_switcher);
stack.connect_visible_child_name_notify(move |stack| {
identity_switcher
.set_previous_page_was_keys(stack.visible_child_name().as_deref() == Some("keys"));
});
}
identity_switcher.set_previous_page_was_keys(true);
toolbar_view.set_content(Some(&stack));
window.set_application(Some(app));
window.set_default_size(config.window_width(), config.window_height());
Self { window }
impl Windows {
pub fn new(app: &adw::Application, state: Rc<AppState>) -> Rc<Self> {
Rc::new(Self {
app: app.clone(),
state,
main: RefCell::new(None),
identities: RefCell::new(None),
preferences: RefCell::new(None),
})
}
pub fn present(&self) {
self.window.present();
/// Create the windows if they do not exist yet. Activation can arrive more
/// than once, so this is idempotent.
pub fn build(self: &Rc<Self>) {
if self.main.borrow().is_none() {
*self.main.borrow_mut() = Some(main_window(&self.app, &self.state, self));
// The key list decides which window the app is, and it can change
// while the app runs.
let windows = Rc::clone(self);
let had_keys = Cell::new(self.state.has_keys());
self.state.listen(move || windows.follow_keys(&had_keys));
// 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() {
eprintln!("regent: identity keys found, opening the main window");
} else {
eprintln!("regent: no identity key yet, opening the identities window");
}
}
if self.identities.borrow().is_none() {
*self.identities.borrow_mut() = Some(identities_window(&self.app, &self.state));
}
}
/// The window the app "is": the identities one while there are no keys,
/// the main one afterwards.
pub fn primary(&self) -> Option<adw::ApplicationWindow> {
if self.state.has_keys() {
self.main.borrow().clone()
} else {
self.identities.borrow().clone()
}
}
pub fn present_primary(&self) {
if let Some(window) = self.primary() {
window.present();
}
}
/// Open (or raise) the identities window — what the switcher's "Manage
/// identities…" does.
pub fn present_identities(&self) {
if let Some(window) = self.identities.borrow().clone() {
window.present();
}
}
/// Present Preferences inside the window the app "is", so it is never left
/// 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) {
let preferences = match self.preferences.borrow().clone() {
Some(preferences) => preferences,
None => {
let preferences = Preferences::new(Rc::clone(&self.state));
*self.preferences.borrow_mut() = Some(Rc::clone(&preferences));
preferences
}
};
preferences.present(self.primary().as_ref());
}
/// Follow the key list: the main window is what the app is once a key
/// exists, and the identities window is what it is when the last key is
/// removed — the state the app starts in.
///
/// Acts on the **transition** only. A `notify()` for anything else (a
/// profile fetch, a lock) must not re-present a window the user has closed,
/// and the first key is what makes the main window meaningful.
fn follow_keys(&self, had_keys: &Cell<bool>) {
let has_keys = self.state.has_keys();
if has_keys == had_keys.get() {
return;
}
had_keys.set(has_keys);
if has_keys {
if let Some(main) = self.main.borrow().as_ref() {
if !main.is_visible() {
main.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.present_identities();
}
}
/// The main window: what the app is for — pairing, approvals and the log.
fn main_window(
app: &adw::Application,
state: &Rc<AppState>,
windows: &Rc<Windows>,
) -> adw::ApplicationWindow {
let builder = gtk::Builder::from_resource(&format!("{RESOURCE_PATH}/window.ui"));
let window: adw::ApplicationWindow = builder
.object("window")
.expect("ui/window.blp must contain an object with id \"window\"");
let toolbar_view: adw::ToolbarView = builder
.object("toolbar_view")
.expect("ui/window.blp must contain an object with id \"toolbar_view\"");
let header_bar: adw::HeaderBar = builder
.object("header_bar")
.expect("ui/window.blp must contain an object with id \"header_bar\"");
let signer_view = SignerView::new(Rc::clone(state));
let apps_view = AppsView::new(Rc::clone(state));
let activity_view = ActivityView::new(Rc::clone(state));
let stack = adw::ViewStack::new();
// Signer first: it is what the app is, and the switcher follows the stack.
stack.add_titled_with_icon(
&signer_view.widget,
Some("signer"),
"Signer",
"network-transmit-receive-symbolic",
);
stack.add_titled_with_icon(
&apps_view.widget,
Some("apps"),
"Apps",
"applications-system-symbolic",
);
stack.add_titled_with_icon(
&activity_view.widget,
Some("activity"),
"Activity",
"document-open-recent-symbolic",
);
let switcher = adw::ViewSwitcher::builder()
.stack(&stack)
.policy(adw::ViewSwitcherPolicy::Wide)
.build();
header_bar.set_title_widget(Some(&switcher));
// The primary menu. Locking stays on the header button, which doubles as the
// lock-state indicator, so it needs no menu entry.
let menu = gio::Menu::new();
menu.append(Some("Manage identities…"), Some("app.identities"));
menu.append(Some("Preferences…"), Some("app.preferences"));
menu.append(Some("Quit"), Some("app.quit"));
let menu_button = gtk::MenuButton::builder()
.icon_name("open-menu-symbolic")
.menu_model(&menu)
.tooltip_text("Main menu")
.css_classes(["flat"])
.build();
header_bar.pack_start(&menu_button);
// The identity switcher: which identity the app is looking at, and the way
// to the identities window.
let identity_switcher = IdentitySwitcher::new(Rc::clone(state), windows);
header_bar.pack_end(identity_switcher.button());
// The vault's lock state, always visible, to the left of the switcher.
let lock_button = gtk::Button::builder()
.icon_name("changes-prevent-symbolic")
.tooltip_text("Lock the key vault")
.css_classes(["flat"])
.build();
lock_button.set_action_name(Some("app.lock"));
header_bar.pack_end(&lock_button);
{
let button = lock_button.clone();
let listener_state = Rc::clone(state);
state.listen(move || {
let locked = listener_state.is_locked();
// Nothing to lock until a key — and so a passphrase — exists.
button.set_sensitive(listener_state.store().has_vault());
button.set_icon_name(if locked {
"changes-allow-symbolic"
} else {
"changes-prevent-symbolic"
});
button.set_tooltip_text(Some(if locked {
"Unlock the key vault"
} else {
"Lock the key vault"
}));
});
}
toolbar_view.set_content(Some(&stack));
window.set_application(Some(app));
// 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.
{
let app = app.clone();
window.connect_close_request(move |_| {
app.quit();
glib::Propagation::Proceed
});
}
window
}
/// The identities window: the whole app on first run, and a management window
/// afterwards, reached from the identity switcher.
fn identities_window(app: &adw::Application, state: &Rc<AppState>) -> adw::ApplicationWindow {
let builder = gtk::Builder::from_resource(&format!("{RESOURCE_PATH}/keys.ui"));
let window: adw::ApplicationWindow = builder
.object("keys_window")
.expect("ui/keys.blp must contain an object with id \"keys_window\"");
let toolbar_view: adw::ToolbarView = builder
.object("toolbar_view")
.expect("ui/keys.blp must contain an object with id \"toolbar_view\"");
let keys_view = KeysView::new(Rc::clone(state));
toolbar_view.set_content(Some(&keys_view.widget));
window.set_application(Some(app));
// Closing it only hides it: it is re-opened from the switcher, and the
// listeners `KeysView` registers capture its widgets, so destroying it would
// leave them pointing at dead ones.
window.set_hide_on_close(true);
window
}