8000 fix(composer): keep contact lookups off the UI thread by aheinze · Pull Request #484 · hyprlab/hylki · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

## Unreleased

- **Fixed: Reply and New Message froze when the contact service stopped
answering.** The composer opens before loading recipient suggestions.
Contact lookups run in the background and give up after three seconds
without an answer, using cached contacts and mail history instead.

- **Changed: one Contacts page in Settings.** Settings → Contacts lists
every address book Hylki reads, as Mail Accounts lists mail accounts: the
Hylki book, the books on this computer, each GNOME Online Accounts account
Expand Down
2 changes: 1 addition & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18013,7 +18013,7 @@ impl AppModel {
prefill,
accounts,
selected,
suggestions: crate::contacts::suggestions(&own),
own_addresses: own,
windowed,
can_toggle,
compact: false,
Expand Down
66 changes: 51 additions & 15 deletions src/contacts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1538,29 +1538,47 @@ fn registry_books() -> Option<HashMap<String, String>> {
/// Every source the EDS registry holds: (object path, UID, key file).
/// `None` when the registry can't be reached.
pub(crate) fn registry_sources() -> Option<Vec<(String, String, String)>> {
use gtk::gio;

let dest = sources_dest()?;
let conn = zbus::blocking::Connection::session().ok()?;
let reply = conn
.call_method(
Some(dest.as_str()),
"/org/gnome/evolution/dataserver/SourceManager",
Some("org.freedesktop.DBus.ObjectManager"),
"GetManagedObjects",
&(),
)
.ok()?;
type Props = HashMap<String, zbus::zvariant::OwnedValue>;
type Objects = HashMap<zbus::zvariant::OwnedObjectPath, HashMap<String, Props>>;
let (objects,): (Objects,) = reply.body().deserialize().ok()?;
let conn = gio::bus_get_sync(gio::BusType::Session, gio::Cancellable::NONE).ok()?;
// zbus 4's blocking call has no deadline. A deadlocked source registry
// used to strand every composer lookup forever. GIO bounds the actual
// request, so the worker can fall back to cached books and mail history
// instead of leaving another blocked thread behind on every open.
let reply = match conn.call_sync(
Some(dest.as_str()),
"/org/gnome/evolution/dataserver/SourceManager",
"org.freedesktop.DBus.ObjectManager",
"GetManagedObjects",
None,
None,
gio::DBusCallFlags::NONE,
3000,
gio::Cancellable::NONE,
) {
Ok(reply) => reply,
Err(e) => {
tracing::warn!("EDS source registry unavailable: {e}");
return None;
}
};
sources_from_reply(&reply)
}

fn sources_from_reply(reply: &gtk::glib::Variant) -> Option<Vec<(String, String, String)>> {
type Props = HashMap<String, gtk::glib::Variant>;
type Objects = HashMap<gtk::glib::variant::ObjectPath, HashMap<String, Props>>;
let (objects,): (Objects,) = reply.get()?;
let mut sources = Vec::new();
for (path, ifaces) in &objects {
let Some(props) = ifaces.get("org.gnome.evolution.dataserver.Source") else {
continue;
};
let uid =
props.get("UID").and_then(|v| v.downcast_ref::<&str>().ok()).map(str::to_string);
props.get("UID").and_then(|v| v.str()).map(str::to_string);
let data =
props.get("Data").and_then(|v| v.downcast_ref::<&str>().ok()).map(str::to_string);
props.get("Data").and_then(|v| v.str()).map(str::to_string);
if let (Some(uid), Some(data)) = (uid, data) {
sources.push((path.to_string(), uid, data));
}
Expand Down Expand Up @@ -2351,6 +2369,24 @@ pub fn delete_contact(book_uid: &str, uid: &str) -> Result<(), String> {

#[cfg(test)]
mod tests {
#[test]
fn registry_reply_keeps_sources_and_skips_unrelated_objects() {
use gtk::glib::{variant::ObjectPath, variant::ToVariant};
use std::collections::HashMap;
let path = ObjectPath::try_from("/org/gnome/evolution/dataserver/Source/test").unwrap();
let data = "[Data Source]\nDisplayName=Test\n[Address Book]\nBackendName=local\n";
let objects = HashMap::from([
(path.clone(), HashMap::from([("org.gnome.evolution.dataserver.Source", HashMap::from([
("UID", "test".to_variant()), ("Data", data.to_variant()),
]))])),
(ObjectPath::try_from("/unrelated").unwrap(), HashMap::new()),
]);
assert_eq!(super::sources_from_reply(&(objects,).to_variant()), Some(vec![
(path.to_string(), "test".into(), data.into()),
]));
assert!(super::sources_from_reply(&"wrong reply type".to_variant()).is_none());
}

use super::{
details_from_local_vcards, is_local_book, prefer_book, Book, merge_target, vcard_display_name, vcard_photo,
vcard_photo_with,
Expand Down
88 changes: 84 additions & 4 deletions src/ui/compose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,8 @@ pub struct ComposeInit {
pub accounts: Vec<ComposeAccount>,
/// Index into `accounts` of the account to send from by default.
pub selected: usize,
/// Recipient autocomplete suggestions (Contacts + mail history).
pub suggestions: Vec<Suggestion>,
/// Own addresses to include in the suggestions loaded after opening.
pub own_addresses: Vec<(String, String)>,
/// Whether the pane starts hosted in a standalone window (vs. inline).
pub windowed: bool,
/// Whether the inline/window toggle button is offered (reply/forward only).
Expand Down Expand Up @@ -665,6 +665,8 @@ pub enum ComposeInput {
/// The accounts whose organization directory is searched (#410), and
/// the addresses in the mail of those that suggest only their own.
DirectoriesKnown { graph: Vec<crate::config::AccountConfig>, own_mail: OwnMail },
/// Contacts and mail history loaded off the UI thread.
SuggestionsLoaded(Vec<Suggestion>),
/// The typing paused: ask the directories, unless it went on since.
DirectoryLookup { field: Field, token: String, generation: u64 },
/// What the directories answered, and the failures not shown before.
Expand Down Expand Up @@ -1145,7 +1147,7 @@ impl Component for Compose {
prefill,
accounts,
selected,
suggestions,
own_addresses,
windowed,
can_toggle,
compact,
Expand Down Expand Up @@ -1352,7 +1354,7 @@ impl Component for Compose {
signature_position,
attachments: prefill_attachments,
attach_thumbs: Default::default(),
suggestions,
suggestions: Vec::new(),
graph_directories: Default::default(),
own_mail: Default::default(),
from_account: 0,
Expand Down Expand Up @@ -1713,6 +1715,10 @@ impl Component for Compose {
_ => OwnMail::new(),
};
let _ = s.send(ComposeInput::DirectoriesKnown { graph, own_mail });
// EDS can stop answering, and a large mail cache takes time
// to scan. Neither is a prerequisite for writing a message.
let suggestions = crate::contacts::suggestions(&own_addresses);
let _ = s.send(ComposeInput::SuggestionsLoaded(suggestions));
});
}

Expand Down Expand Up @@ -2506,6 +2512,23 @@ impl Component for Compose {
self.own_mail = own_mail;
}

ComposeInput::SuggestionsLoaded(loaded) => {
tracing::debug!("composer suggestions loaded: {}", loaded.len());
merge_loaded_suggestions(&mut self.suggestions, loaded);
// The user may already be typing. Update that field's
// matches without touching its text, caret or dirty state.
for (field, row) in [
(Field::To, &widgets.to_row),
(Field::Cc, &widgets.cc_row),
(Field::Bcc, &widgets.bcc_row),
] {
if recipient_focused(row) {
self.show_completion(field, row, &widgets.bcc_row);
break;
}
}
}

ComposeInput::DirectoryLookup { field, token, generation } => {
if generation == self.directory_generation {
let s = sender.input_sender().clone();
Expand Down Expand Up @@ -3303,6 +3326,26 @@ impl Component for Compose {
/// How often an edited message is saved to Drafts on its own (#340).
const AUTOSAVE_SECS: u32 = 30;

/// Keep addresses sent from another composer while the initial lookup was
/// running. The loaded contact metadata (including groups and own-address
/// ranking) wins; addresses added during the lookup must not disappear.
fn merge_loaded_suggestions(current: &mut Vec<Suggestion>, mut loaded: Vec<Suggestion>) {
for recent in current.drain(..) {
if let Some(s) = loaded.iter_mut().find(|s| {
s.group.is_none() && s.email.eq_ignore_ascii_case(&recent.email)
}) {
// The snapshot may already include that send: do not count it twice.
s.score = s.score.max(recent.score);
if s.name.trim().is_empty() || s.name == s.email {
s.name = recent.name;
}
} else {
loaded.push(recent);
}
}
*current = loaded;
}

/// An identity's From as the composer writes it out: "Name <address>".
fn identity_display(a: &ComposeAccount) -> String {
a.alias_from.clone().unwrap_or_else(|| a.label.clone()).trim().to_string()
Expand Down Expand Up @@ -4824,6 +4867,43 @@ var t=document.getElementById('src');if(t)t.readOnly=false;window.__hylkiTr=null

#[cfg(test)]
mod tests {
use crate::contacts::{Suggestion, SuggestedGroup};

fn suggestion(name: &str, email: &str, score: u32) -> Suggestion {
Suggestion {
name: name.into(), email: email.into(), score,
from_contacts: false, from_directory: false, own: false, group: None,
}
}

#[test]
fn initial_suggestions_keep_addresses_added_while_loading() {
let mut current = vec![suggestion("Ann", "ANN@example.org", 2), suggestion("Bob", "bob@example.org", 1)];
let mut contact = suggestion("Ann Contact", "ann@example.org", 5);
contact.from_contacts = true;
contact.own = true;
let mut group = suggestion("Book Club", "", 0);
group.group = Some(std::sync::Arc::new(SuggestedGroup { members: Vec::new(), hide_addresses: true }));
super::merge_loaded_suggestions(&mut current, vec![contact, group]);
assert_eq!(current.len(), 3);
let ann = &current[0];
assert_eq!(ann.name, "Ann Contact");
assert_eq!(ann.score, 5);
assert!(ann.from_contacts && ann.own);
assert!(current[1].group.is_some());
assert_eq!(current[2].email, "bob@example.org");
}

#[test]
fn initial_suggestions_keep_newer_names_and_frequency() {
let mut current = vec![suggestion("Ann", "ann@example.org", 3)];
super::merge_loaded_suggestions(&mut current, vec![suggestion("ann@example.org", "ann@example.org", 1)]);
assert_eq!(current.len(), 1);
assert_eq!(current[0].name, "Ann");
assert_eq!(current[0].score, 3);
super::merge_loaded_suggestions(&mut current, Vec::new());
assert_eq!(current[0].name, "Ann");
}

#[test]
fn a_markdown_reply_has_a_line_to_write_on_above_the_quote() {
Expand Down
Loading
0