Add the multi-identity UI: switcher, scoping and profiles

This commit is contained in:
raucao committed 2026-11-14 14:34:30 +04:00
1 parent 27ec8d351d
commit 34f0fdccd1
13 files changed
+676 -40

No files matched your search

+2
View File
@@ -35,6 +35,7 @@ cargo_build = custom_target(binary_name,
'src/store/audit.rs',
'src/store/mod.rs',
'src/store/keys.rs',
'src/store/profiles.rs',
'src/ui/activity_view.rs',
'src/ui/apps_view.rs',
'src/ui/approval.rs',
@@ -44,6 +45,7 @@ cargo_build = custom_target(binary_name,
'src/ui/plain.rs',
'src/ui/qr.rs',
'src/ui/signer_view.rs',
'src/ui/switcher.rs',
'src/window.rs',
),
command: [
+45
View File
@@ -15,6 +15,7 @@ use crate::runtime;
use crate::store::apps::AppRegistry;
use crate::store::audit::ActivityLog;
use crate::store::keys::{KeyRef, KeyStore};
use crate::store::profiles::Profiles;
type Listener = Rc<dyn Fn()>;
@@ -30,6 +31,8 @@ pub struct AppState {
current: Arc<Mutex<Option<PublicKey>>>,
/// Display names for the identity keys (hex → name), kept for dialogs.
names: Arc<Mutex<HashMap<String, String>>>,
/// Cached kind-0 display names, read-only.
profiles: Profiles,
listeners: RefCell<Vec<Listener>>,
change_listeners: RefCell<Vec<Listener>>,
/// The responder pings this after it changes the registry or the log.
@@ -46,6 +49,7 @@ impl AppState {
activity: ActivityLog::new(),
current: Arc::new(Mutex::new(Config::new().current_identity())),
names: Arc::new(Mutex::new(HashMap::new())),
profiles: Profiles::new(),
listeners: RefCell::new(Vec::new()),
change_listeners: RefCell::new(Vec::new()),
changes,
@@ -102,6 +106,20 @@ impl AppState {
Arc::clone(&self.names)
}
/// Cached kind-0 profiles (read-only display hints).
pub fn profiles(&self) -> Profiles {
self.profiles.clone()
}
/// What to call an identity: its kind-0 `display_name` if one was fetched,
/// else the user's label for the key.
pub fn identity_label(&self, key: &PublicKey) -> String {
self.profiles
.display_name(key)
.or_else(|| self.names.lock().unwrap().get(&key.to_hex()).cloned())
.unwrap_or_else(|| "Identity key".to_string())
}
/// Select an identity: it scopes the UI and becomes the pairing default.
pub fn set_current_identity(&self, identity: PublicKey) {
*self.current.lock().unwrap() = Some(identity);
@@ -151,12 +169,39 @@ impl AppState {
}
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}"),
},
);
}
/// Fetch kind-0 profiles for keys that lack a fresh one. Best effort and
/// safe to call often; the cached names arrive via a later notify.
fn fetch_profiles(self: &Rc<Self>, keys: Vec<PublicKey>) {
if keys.is_empty() {
return;
}
let relays = Config::new().relays();
let profiles = self.profiles.clone();
let state = Rc::clone(self);
runtime::spawn(
async move { crate::store::profiles::fetch(relays, keys, profiles).await },
move |result| {
if let Err(error) = result {
eprintln!("regent: could not fetch profiles: {error}");
}
state.notify();
state.notify_changes();
},
);
}
/// A sender the responder uses to announce registry or log changes.
pub fn changes(&self) -> async_channel::Sender<()> {
self.changes.clone()
+4 -7
View File
@@ -303,12 +303,9 @@ impl AppRegistry {
self.save()
}
/// Forget every application. Permissions go with them.
pub fn clear(&mut self) -> Result<()> {
self.apps.clear();
self.save()
}
/// Every application, across identities. Scoped views use
/// [`AppRegistry::list_for`].
#[cfg(test)]
pub fn list(&self) -> &[App] {
&self.apps
}
@@ -390,7 +387,7 @@ mod tests {
assert!(!reloaded.permits(&keys.public_key(), &kind));
assert!(reloaded.permits(&keys.public_key(), &method));
registry.clear().unwrap();
registry.clear_for(keys.public_key()).unwrap();
assert!(registry.list().is_empty());
assert!(AppRegistry::at(path.clone()).list().is_empty());
+44
View File
@@ -160,6 +160,27 @@ impl ActivityLog {
let _ = std::fs::remove_file(&self.path);
}
/// Forget the entries answered as one identity, keeping the rest.
pub fn clear_for(&self, identity: &str) {
let _guard = self.lock.lock().unwrap();
if self.path.as_os_str().is_empty() {
return;
}
let Ok(file) = File::open(&self.path) else {
return;
};
let kept: Vec<String> = BufReader::new(file)
.lines()
.map_while(std::result::Result::ok)
.filter(|line| match serde_json::from_str::<Entry>(line) {
Ok(entry) => entry.identity.as_deref() != Some(identity),
// Keep lines we cannot parse rather than silently drop history.
Err(_) => true,
})
.collect();
let _ = rewrite(&self.path, kept.iter());
}
fn size(&self) -> u64 {
std::fs::metadata(&self.path).map(|data| data.len()).unwrap_or(0)
}
@@ -270,6 +291,29 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn clearing_one_identity_keeps_the_others() {
let (dir, log) = scratch();
let mut mine = entry(1, "aa");
mine.identity = Some("mine".to_string());
let mut theirs = entry(2, "bb");
theirs.identity = Some("theirs".to_string());
let mut legacy = entry(3, "cc");
legacy.identity = None;
log.record(&mine);
log.record(&theirs);
log.record(&legacy);
log.clear_for("mine");
let recent = log.recent(10);
assert_eq!(recent.len(), 2);
assert!(recent
.iter()
.all(|entry| entry.identity.as_deref() != Some("mine")));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn trimming_keeps_the_newest_entries() {
let (dir, log) = scratch();
+1
View File
@@ -3,3 +3,4 @@
pub mod apps;
pub mod audit;
pub mod keys;
pub mod profiles;
+252
View File
@@ -0,0 +1,252 @@
//! Cached kind-0 profiles (read-only).
//!
//! A profile's `display_name` is attacker-publishable text: it is shown as a
//! hint only, never as verified identity (nip05 is deliberately not shown), and
//! only through plain labels.
//!
//! Fetches use a **fresh ephemeral** client — never the device or identity key —
//! so a relay cannot link an identity to this signer's transport key.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use nostr::prelude::*;
use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize};
use crate::store::audit;
use crate::APP_ID;
/// A cached profile is refreshed after a day.
const REFRESH_AFTER: i64 = 24 * 60 * 60;
/// How long to listen for kind-0 answers.
const FETCH_WINDOW: Duration = Duration::from_secs(3);
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Profile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
/// Unix time the profile was last fetched.
#[serde(default)]
pub fetched_at: i64,
}
#[derive(Clone)]
pub struct Profiles {
path: PathBuf,
entries: Arc<Mutex<HashMap<String, Profile>>>,
}
impl Profiles {
pub fn new() -> Self {
Self::at(glib::user_data_dir().join(APP_ID).join("profiles.json"))
}
pub fn at(path: PathBuf) -> Self {
let entries = std::fs::read_to_string(&path)
.ok()
.and_then(|contents| serde_json::from_str(&contents).ok())
.unwrap_or_default();
Self {
path,
entries: Arc::new(Mutex::new(entries)),
}
}
pub fn get(&self, key: &PublicKey) -> Option<Profile> {
self.entries.lock().unwrap().get(&key.to_hex()).cloned()
}
/// The profile name for display, if one was fetched.
pub fn display_name(&self, key: &PublicKey) -> Option<String> {
self.get(key)
.and_then(|profile| profile.display_name)
.map(|name| name.trim().to_string())
.filter(|name| !name.is_empty())
}
/// Whether this key has no profile or an old one.
pub fn needs_refresh(&self, key: &PublicKey) -> bool {
match self.get(key) {
None => true,
Some(profile) => audit::now() - profile.fetched_at > REFRESH_AFTER,
}
}
fn put(&self, key: &PublicKey, mut profile: Profile) {
profile.fetched_at = audit::now();
self.entries
.lock()
.unwrap()
.insert(key.to_hex(), profile);
self.save();
}
fn save(&self) {
if self.path.as_os_str().is_empty() {
return;
}
if let Some(parent) = self.path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let entries = self.entries.lock().unwrap().clone();
let Ok(contents) = serde_json::to_string_pretty(&entries) else {
return;
};
let temporary = self.path.with_extension("json.tmp");
if write_private(&temporary, contents.as_bytes()).is_ok() {
let _ = std::fs::rename(&temporary, &self.path);
}
}
}
impl Default for Profiles {
fn default() -> Self {
Self::new()
}
}
/// Fetch the latest kind-0 for `keys` from `relays`, best effort.
///
/// Our relays are NIP-46 relays, so profiles are often absent — that is normal,
/// not an error.
pub async fn fetch(
relays: Vec<String>,
keys: Vec<PublicKey>,
profiles: Profiles,
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
if keys.is_empty() {
return Ok(());
}
let urls: Vec<RelayUrl> = relays
.iter()
.filter_map(|relay| RelayUrl::parse(relay).ok())
.collect();
if urls.is_empty() {
return Ok(());
}
// Deliberately ephemeral: reads must not use the signer's device key.
let client = Client::new();
for url in &urls {
client.add_relay(url.clone()).await?;
}
client.connect().await;
client.connect().and_wait(Duration::from_secs(10)).await;
let filter = Filter::new()
.kind(Kind::Metadata)
.authors(keys.iter().copied())
.limit(0);
let targets: Vec<(RelayUrl, Vec<Filter>)> = urls
.iter()
.cloned()
.map(|url| (url, vec![filter.clone()]))
.collect();
let mut notifications = client.notifications();
client.subscribe(targets).await?;
let mut newest: HashMap<PublicKey, (Timestamp, Profile)> = HashMap::new();
let deadline = tokio::time::Instant::now() + FETCH_WINDOW;
loop {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
break;
}
match tokio::time::timeout(remaining, notifications.next()).await {
Ok(Some(ClientNotification::Event { event, .. }))
if event.kind == Kind::Metadata =>
{
let Ok(metadata) = serde_json::from_str::<Metadata>(&event.content) else {
continue;
};
let profile = Profile {
display_name: metadata
.display_name
.map(|name| name.trim().to_string())
.filter(|name| !name.is_empty()),
fetched_at: 0,
};
match newest.get(&event.pubkey) {
Some((at, _)) if *at >= event.created_at => {}
_ => {
newest.insert(event.pubkey, (event.created_at, profile));
}
}
}
Ok(Some(_)) => continue,
Ok(None) | Err(_) => break,
}
}
let _ = client.disconnect().await;
for (key, (_, profile)) in newest {
profiles.put(&key, profile);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn profiles_round_trip_and_refresh_after_a_day() {
let dir = std::env::temp_dir().join(format!("regent-profiles-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("profiles.json");
let store = Profiles::at(path.clone());
let key = Keys::generate().public_key();
assert!(store.display_name(&key).is_none());
assert!(store.needs_refresh(&key));
store.put(
&key,
Profile {
display_name: Some(" Alice ".to_string()),
fetched_at: 0,
},
);
assert_eq!(store.display_name(&key).as_deref(), Some("Alice"));
assert!(!store.needs_refresh(&key), "just fetched");
// Survives a reload.
let reloaded = Profiles::at(path);
assert_eq!(reloaded.display_name(&key).as_deref(), Some("Alice"));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_blank_display_name_is_ignored() {
let store = Profiles::at(PathBuf::new());
let key = Keys::generate().public_key();
store.put(
&key,
Profile {
display_name: Some(" ".to_string()),
fetched_at: 0,
},
);
assert!(store.display_name(&key).is_none());
}
}
fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path)?;
file.write_all(bytes)?;
file.sync_all()?;
Ok(())
}
+36 -4
View File
@@ -79,7 +79,29 @@ impl ActivityView {
impl Ui {
fn refresh(self: &Rc<Self>) {
let entries = self.log.recent(RECENT);
let current = self.state.current_identity();
let identity_hex = current.map(|key| key.to_hex());
// Scoped to the selected identity. Entries from before identities
// existed (no identity) show under every scope so the history is not
// silently lost.
let entries: Vec<Entry> = self
.log
.recent(RECENT)
.into_iter()
.filter(|entry| match (&identity_hex, &entry.identity) {
(Some(selected), Some(entry_identity)) => entry_identity == selected,
(Some(_), None) => true,
(None, _) => true,
})
.collect();
let identity_name = current.and_then(|key| {
self.state
.names()
.lock()
.unwrap()
.get(&key.to_hex())
.cloned()
});
while let Some(child) = self.content.first_child() {
self.content.remove(&child);
@@ -91,8 +113,12 @@ impl Ui {
}
self.stack.set_visible_child_name("list");
let title = match &identity_name {
Some(name) if !name.trim().is_empty() => format!("Recent activity · {name}"),
_ => "Recent activity".to_string(),
};
let group = adw::PreferencesGroup::builder()
.title("Recent activity")
.title(&title)
.description("Metadata only — no message content is recorded.")
.build();
for entry in &entries {
@@ -118,7 +144,10 @@ impl Ui {
fn clear_group(self: &Rc<Self>) -> adw::PreferencesGroup {
let group = adw::PreferencesGroup::new();
let row = plain::row("Clear activity", "Forget everything recorded so far.");
let row = plain::row(
"Clear this identity's activity",
"Forget the entries answered as the selected identity.",
);
let clear = gtk::Button::builder()
.label("Clear")
.valign(gtk::Align::Center)
@@ -126,7 +155,10 @@ impl Ui {
.build();
let ui = Rc::clone(self);
clear.connect_clicked(move |_| {
ui.log.clear();
match ui.state.current_identity() {
Some(identity) => ui.log.clear_for(&identity.to_hex()),
None => ui.log.clear(),
}
ui.state.notify_changes();
});
row.add_suffix(&clear);
+47 -27
View File
@@ -20,8 +20,13 @@ use crate::store::apps::{App, Permission, Policy};
use crate::ui::{kind, plain};
/// What the page currently shows, so a log-only change does not rebuild it and
/// collapse the expanders.
type Shown = Vec<(String, Option<String>, Policy)>;
/// collapse the expanders. The selected identity is part of it: switching
/// identities rescopes the page.
type Shown = (
Option<String>,
Option<String>,
Vec<(String, Option<String>, Policy)>,
);
pub struct AppsView {
pub widget: gtk::Widget,
@@ -87,20 +92,37 @@ impl AppsView {
impl Ui {
fn refresh(self: &Rc<Self>) {
// Snapshot under a short lock; build the UI after it is dropped.
let apps: Vec<App> = {
let registry = self.state.registry();
let guard = registry.lock().unwrap();
guard.list().to_vec()
// The page is scoped to the selected identity.
let current = self.state.current_identity();
let apps: Vec<App> = match current {
Some(identity) => {
// Snapshot under a short lock; build the UI after it is dropped.
let registry = self.state.registry();
let guard = registry.lock().unwrap();
guard.list_for(identity)
}
None => Vec::new(),
};
let identity_hex = current.map(|key| key.to_hex());
let identity_name = current.and_then(|key| {
self.state
.names()
.lock()
.unwrap()
.get(&key.to_hex())
.cloned()
});
// The shared change channel also fires for activity-log entries. Only
// rebuild when the apps themselves changed, or every answered request
// rebuild when what this page shows changed, or every answered request
// would collapse the expanders.
let signature: Shown = apps
.iter()
.map(|app| (app.public_key.clone(), app.name.clone(), app.policy.clone()))
.collect();
let signature: Shown = (
identity_hex,
identity_name.clone(),
apps.iter()
.map(|app| (app.public_key.clone(), app.name.clone(), app.policy.clone()))
.collect(),
);
if self.shown.borrow().as_ref() == Some(&signature) {
return;
}
@@ -116,8 +138,12 @@ impl Ui {
}
self.stack.set_visible_child_name("apps");
let title = match &identity_name {
Some(name) if !name.trim().is_empty() => format!("Applications · {name}"),
_ => "Applications".to_string(),
};
let group = adw::PreferencesGroup::builder()
.title("Approved applications")
.title(&title)
.description(
"Each one can ask for signatures and encryption. It only skips the prompt \
for what you allowed with “Allow always”.",
@@ -148,17 +174,7 @@ impl Ui {
let signing_as = match bound {
Some(identity) => {
let key_npub = identity.to_bech32().unwrap_or_else(|_| identity.to_hex());
let key_name = self
.state
.names()
.lock()
.unwrap()
.get(&identity.to_hex())
.cloned();
match key_name {
Some(name) if !name.trim().is_empty() => format!("{name} ({key_npub})"),
_ => key_npub,
}
format!("{} ({key_npub})", self.state.identity_label(&identity))
}
None => "unknown (paired before identities existed)".to_string(),
};
@@ -247,8 +263,8 @@ impl Ui {
fn forget_all_group(self: &Rc<Self>) -> adw::PreferencesGroup {
let group = adw::PreferencesGroup::new();
let row = plain::row(
"Forget all applications",
"Remove every approval and everything it was allowed to do.",
"Forget all applications for this identity",
"Remove their approvals and everything they were allowed to do.",
);
let forget = gtk::Button::builder()
.label("Forget all")
@@ -257,8 +273,12 @@ impl Ui {
.build();
let ui = Rc::clone(self);
forget.connect_clicked(move |_| {
// Scoped to the selected identity, like the rest of the page.
let Some(identity) = ui.state.current_identity() else {
return;
};
let registry = ui.state.registry();
if let Err(error) = registry.lock().unwrap().clear() {
if let Err(error) = registry.lock().unwrap().clear_for(identity) {
eprintln!("regent: could not forget applications: {error}");
}
ui.state.notify_changes();
+19 -2
View File
@@ -166,7 +166,17 @@ fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows) {
let mut listed: Vec<(String, String)> = names.into_iter().collect();
listed.sort_by_key(|(_, name)| name.to_lowercase());
for (hex, name) in listed {
let row = key_row(state, handles, &hex, &name, current.as_deref() == Some(hex.as_str()));
let profile = PublicKey::from_hex(&hex)
.ok()
.and_then(|key| state.profiles().display_name(&key));
let row = key_row(
state,
handles,
&hex,
&name,
profile.as_deref(),
current.as_deref() == Some(hex.as_str()),
);
handles.list.add(&row);
rows.borrow_mut().push(row);
}
@@ -195,13 +205,20 @@ fn key_row(
handles: &Handles,
hex: &str,
name: &str,
profile: Option<&str>,
current: bool,
) -> adw::ActionRow {
let public_key = PublicKey::from_hex(hex).ok();
let npub = public_key
.map(|key| key.to_bech32().unwrap_or_default())
.unwrap_or_else(|| hex.to_string());
let row = plain::row(name, &plain::shorten(&npub, 12, 6));
let subtitle = match profile {
Some(profile) => format!("{profile} · {}", plain::shorten(&npub, 12, 6)),
None => plain::shorten(&npub, 12, 6),
};
let row = plain::row(name, &subtitle);
// Initials avatar, from the kind-0 name when there is one.
row.add_prefix(&adw::Avatar::new(32, Some(profile.unwrap_or(name)), true));
if current {
let badge = gtk::Label::builder()
+1
View File
@@ -8,3 +8,4 @@ pub mod keys_view;
pub mod plain;
pub mod qr;
pub mod signer_view;
pub mod switcher;
+23
View File
@@ -33,6 +33,7 @@ struct Handles {
picture: gtk::Picture,
toggle: gtk::Button,
pair: gtk::Button,
signing_as: adw::ActionRow,
}
/// The toplevel, resolved lazily: a view is not in a window when it is built.
@@ -79,6 +80,7 @@ impl SignerView {
.build();
uri.add_suffix(&copy);
let device = plain::row("Device key", "—");
let signing_as = plain::row("New connections", "—");
let group = adw::PreferencesGroup::builder()
.title("Pairing")
@@ -87,6 +89,7 @@ impl SignerView {
group.add(&status);
group.add(&uri);
group.add(&device);
group.add(&signing_as);
// The client-initiated direction: the application shows a
// `nostrconnect://` string and waits for the signer to answer it.
@@ -143,10 +146,17 @@ impl SignerView {
picture,
toggle,
pair,
signing_as,
};
let widget: gtk::Widget = handles.stack.clone().upcast();
update_signing_as(&handles, &state);
{
let (listener_handles, listener_state) = (handles.clone(), Rc::clone(&state));
state.listen_changes(move || update_signing_as(&listener_handles, &listener_state));
}
// Approval questions are answered on the main loop; the responder waits
// on the other end of this channel.
let (approver, questions) = Approver::new();
@@ -236,6 +246,19 @@ impl SignerView {
}
}
/// Show which identity a new pairing would use.
fn update_signing_as(handles: &Handles, state: &Rc<AppState>) {
let subtitle = match state.current_identity() {
Some(key) => {
let name = state.identity_label(&key);
let npub = key.to_bech32().unwrap_or_else(|_| key.to_hex());
format!("{name} ({npub})")
}
None => "no identity key yet".to_string(),
};
handles.signing_as.set_subtitle(&subtitle);
}
fn show_empty(handles: &Handles) {
handles.stack.set_visible_child_name("empty");
handles.status.set_subtitle("Stopped");
+188
View File
@@ -0,0 +1,188 @@
//! The header identity switcher: which identity the app is looking at.
//!
//! 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.
use std::cell::Cell;
use std::rc::Rc;
use nostr::nips::nip19::ToBech32;
use nostr::prelude::PublicKey;
use gtk::prelude::*;
use libadwaita as adw;
use crate::state::AppState;
use crate::ui::plain;
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>,
}
impl IdentitySwitcher {
pub fn new(state: Rc<AppState>, stack: adw::ViewStack) -> Rc<Self> {
let content = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(2)
.build();
let popover = gtk::Popover::new();
popover.set_child(Some(&content));
let button = gtk::MenuButton::builder()
.tooltip_text("Identity")
.popover(&popover)
.css_classes(["flat"])
.build();
let switcher = Rc::new(Self {
button,
popover,
content,
state: Rc::clone(&state),
stack,
on_other_page: Cell::new(true),
});
// Rebuild on key changes and on a selection change.
{
let switcher = Rc::clone(&switcher);
state.listen(move || switcher.rebuild());
}
{
let switcher = Rc::clone(&switcher);
state.listen_changes(move || switcher.rebuild());
}
switcher.rebuild();
switcher
}
pub fn button(&self) -> &gtk::MenuButton {
&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);
}
let names = self.state.names();
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());
let current_label = current
.map(|key| self.state.identity_label(&key))
.unwrap_or_else(|| "?".to_string());
let avatar = adw::Avatar::new(24, Some(&current_label), true);
self.button.set_child(Some(&avatar));
self.button
.set_tooltip_text(Some(&format!("Identity: {current_label}")));
let mut listed: Vec<(String, String)> = names.into_iter().collect();
listed.sort_by_key(|(_, name)| name.to_lowercase());
for (hex, name) in listed {
let row = self.row(&hex, &name, current);
self.content.append(&row);
}
if has_keys {
self.content
.append(&gtk::Separator::new(gtk::Orientation::Horizontal));
let manage = gtk::Button::builder()
.child(
&gtk::Label::builder()
.label("Manage identities…")
.xalign(0.0)
.use_markup(false)
.halign(gtk::Align::Start)
.build(),
)
.css_classes(["flat"])
.build();
{
let (popover, stack) = (self.popover.clone(), self.stack.clone());
manage.connect_clicked(move |_| {
popover.popdown();
stack.set_visible_child_name("keys");
});
}
self.content.append(&manage);
}
}
fn row(&self, hex: &str, name: &str, current: Option<PublicKey>) -> gtk::Button {
let key = PublicKey::from_hex(hex).ok();
let label = key
.map(|key| self.state.identity_label(&key))
.unwrap_or_else(|| name.to_string());
let row = gtk::Button::builder()
.css_classes(["flat"])
.halign(gtk::Align::Fill)
.build();
let line = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(10)
.build();
line.append(&adw::Avatar::new(32, Some(&label), true));
let texts = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(2)
.hexpand(true)
.halign(gtk::Align::Start)
.build();
texts.append(
&gtk::Label::builder()
.label(&label)
.use_markup(false)
.xalign(0.0)
.ellipsize(gtk::pango::EllipsizeMode::End)
.build(),
);
if let Some(key) = key {
texts.append(
&gtk::Label::builder()
.label(plain::shorten(
&key.to_bech32().unwrap_or_else(|_| key.to_hex()),
12,
6,
))
.use_markup(false)
.xalign(0.0)
.css_classes(["dim-label"])
.build(),
);
}
line.append(&texts);
if current.is_some_and(|current| current.to_hex() == hex) {
line.append(&gtk::Image::from_icon_name("object-select-symbolic"));
}
row.set_child(Some(&line));
if let Some(key) = key {
let (state, popover) = (Rc::clone(&self.state), self.popover.clone());
row.connect_clicked(move |_| {
state.set_current_identity(key);
popover.popdown();
});
}
row
}
}
+14
View File
@@ -15,6 +15,7 @@ use crate::ui::apps_view::AppsView;
use crate::ui::keys_view::KeysView;
use crate::ui::plain;
use crate::ui::signer_view::SignerView;
use crate::ui::switcher::IdentitySwitcher;
use crate::RESOURCE_PATH;
pub struct Window {
@@ -78,6 +79,19 @@ impl Window {
.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());
{
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));