From a36245bd9f5961ded55482ea0da27348aed25715 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 7 Oct 2026 07:56:43 +0000 Subject: [PATCH] ui: a New line above the first unread message, and read markers kept on disk Messages count as read only while their chat is on screen (Nav.chat-shown) in the focused window: winit's focus events, through slint's unstable-winit-030 on the desktop; Android counts a chat on screen as read. A tab keeps the newest message read and counts what came after it, not our own. Entering a tab with new messages puts a red New line above the first one until the tab is left (so does a stored or gateway page that brings them while the tab is on screen), and while that line is above the view a bar over the list counts them, with Jump and Mark as read. voelin-store migration 5 adds chat_reads (Store::chat_read, set_chat_read, chat_reads). Markers are loaded once a session's server is known and written when a tab is left, marked read, its session ends and on exit, never per message; a restart counts what came while away again, gateway pages included. Dev switch VOELIN_OPEN=unread[:end]. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ --- CHANGELOG.md | 4 + Cargo.lock | 1 + crates/voelin-store/src/chat.rs | 94 ++++++++- crates/voelin-store/src/lib.rs | 2 +- crates/voelin-store/src/store.rs | 43 ++++ crates/voelin-ui/Cargo.toml | 4 +- crates/voelin-ui/src/app.rs | 117 ++++++++++- crates/voelin-ui/src/bind/chat.rs | 6 + crates/voelin-ui/src/chat.rs | 242 ++++++++++++++++++++-- crates/voelin-ui/src/dev.rs | 59 +++++- crates/voelin-ui/src/servers.rs | 3 + crates/voelin-ui/src/social.rs | 17 +- crates/voelin-ui/src/studio.rs | 5 +- crates/voelin-ui/src/vm/chat.rs | 93 ++++++++- crates/voelin-ui/ui/app.slint | 4 + crates/voelin-ui/ui/bridge.slint | 14 ++ crates/voelin-ui/ui/nav.slint | 5 + crates/voelin-ui/ui/screens/chat.slint | 276 +++++++++++++++++-------- docs/architecture.md | 2 +- docs/ui.md | 14 +- 20 files changed, 877 insertions(+), 128 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba76a22..647622a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,10 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - Every message can be quoted into the composer (`> ` lines) and its text copied, from the actions on hover or a right-click menu, also on servers without a gateway. +- A "New" line above the first unread message of a chat, and a bar that + counts the new messages with a jump to the first; unread counts survive + restarts. Messages count as read only while their chat is on screen in + the focused window. ### Changed diff --git a/Cargo.lock b/Cargo.lock index 47951aa..4303409 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7869,6 +7869,7 @@ dependencies = [ "i-slint-backend-android-activity", "i-slint-backend-linuxkms", "i-slint-backend-selector", + "i-slint-backend-winit", "i-slint-common", "i-slint-core", "i-slint-core-macros", diff --git a/crates/voelin-store/src/chat.rs b/crates/voelin-store/src/chat.rs index 3b1353b..adde3d4 100644 --- a/crates/voelin-store/src/chat.rs +++ b/crates/voelin-store/src/chat.rs @@ -16,7 +16,8 @@ //! of the other, or (without both unique ids) the same nickname. //! //! Pages are by time: `(ts_ms, id)` orders a chat ([`PageQuery`]). A -//! [`ChatCursor`] remembers how far a chat is synced with a gateway. +//! [`ChatCursor`] remembers how far a chat is synced with a gateway, a +//! [`ChatRead`] how far it was read on this device. use rusqlite::{OptionalExtension, Row, Transaction, params}; use serde::{Deserialize, Serialize}; @@ -226,6 +227,31 @@ pub struct ChatCursor { pub updated_ms: i64, } +/// How far a chat was read on this device: the newest message read, by +/// `(ts_ms, id)` as a chat is ordered. TeamSpeak has no read receipts, so +/// this stays on the device. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChatRead { + /// Unix milliseconds of the message. + pub ts_ms: i64, + /// Its local id ([`StoredMessage::id`]). + pub id: i64, + /// Unix milliseconds of the last change. + pub updated_ms: i64, +} + +/// Version 5: how far each chat was read ([`ChatRead`]). +pub(crate) const SCHEMA_5: &str = r#" + CREATE TABLE chat_reads ( + server_uid TEXT NOT NULL, + target TEXT NOT NULL, + read_ms INTEGER NOT NULL, + read_id INTEGER NOT NULL DEFAULT 0, + updated_ms INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (server_uid, target) + ) WITHOUT ROWID; +"#; + /// Version 2: times in milliseconds, sources, gateway ids and metadata, /// dedupe keys, sync cursors and server aliases. Old messages keep their /// data (source `local`, their second times in milliseconds). @@ -686,6 +712,53 @@ impl Store { Ok(()) } + /// How far a chat was read on this device. + pub fn chat_read(&self, server_uid: &str, target: &ChatTarget) -> Result> { + Ok(self + .db + .prepare_cached( + "SELECT read_ms, read_id, updated_ms FROM chat_reads + WHERE server_uid = ?1 AND target = ?2", + )? + .query_row(params![server_uid, target.key()], |r| { + Ok(ChatRead { ts_ms: r.get(0)?, id: r.get(1)?, updated_ms: r.get(2)? }) + }) + .optional()?) + } + + /// How far each chat of a server was read on this device. + pub fn chat_reads(&self, server_uid: &str) -> Result> { + let mut stmt = self.db.prepare_cached( + "SELECT target, read_ms, read_id, updated_ms FROM chat_reads + WHERE server_uid = ?1 ORDER BY target", + )?; + let rows = stmt.query_map([server_uid], |r| { + let target: String = r.get(0)?; + let read = ChatRead { ts_ms: r.get(1)?, id: r.get(2)?, updated_ms: r.get(3)? }; + Ok((ChatTarget::from_key(&target), read)) + })?; + Ok(rows.collect::>()?) + } + + /// Remember how far a chat was read on this device (replacing what was + /// there). + pub fn set_chat_read( + &self, + server_uid: &str, + target: &ChatTarget, + read: &ChatRead, + ) -> Result<()> { + self.db + .prepare_cached( + "INSERT INTO chat_reads (server_uid, target, read_ms, read_id, updated_ms) + VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT (server_uid, target) DO UPDATE SET read_ms = excluded.read_ms, + read_id = excluded.read_id, updated_ms = excluded.updated_ms", + )? + .execute(params![server_uid, target.key(), read.ts_ms, read.id, read.updated_ms])?; + Ok(()) + } + /// Forget the gateway ids of a chat (another gateway numbers its /// messages differently) and its cursor; the rows stay, as seen by this /// device, and are matched again with the new gateway's copies. @@ -962,6 +1035,25 @@ mod tests { assert_eq!(store.server_alias("voice:host").unwrap().as_deref(), Some("uid2")); } + #[test] + fn read_markers() { + let store = Store::open_in_memory().unwrap(); + let (channel, dm) = (ChatTarget::Channel(1), ChatTarget::Private("uid-b".into())); + assert_eq!(store.chat_read(SRV, &channel).unwrap(), None); + assert!(store.chat_reads(SRV).unwrap().is_empty()); + let read = ChatRead { ts_ms: 1_000, id: 7, updated_ms: 5 }; + store.set_chat_read(SRV, &channel, &read).unwrap(); + assert_eq!(store.chat_read(SRV, &channel).unwrap(), Some(read)); + // Set again: the same row, moved. + let later = ChatRead { ts_ms: 2_000, id: 9, updated_ms: 6 }; + store.set_chat_read(SRV, &channel, &later).unwrap(); + assert_eq!(store.chat_read(SRV, &channel).unwrap(), Some(later)); + store.set_chat_read(SRV, &dm, &read).unwrap(); + store.set_chat_read("other", &channel, &read).unwrap(); + assert_eq!(store.chat_reads(SRV).unwrap(), [(channel.clone(), later), (dm, read)]); + assert_eq!(store.chat_reads("other").unwrap(), [(channel, read)]); + } + /// A database of version 1 with messages is upgraded in place. #[test] fn migrates_version_1_with_data() { diff --git a/crates/voelin-store/src/lib.rs b/crates/voelin-store/src/lib.rs index 7c80437..d420d5d 100644 --- a/crates/voelin-store/src/lib.rs +++ b/crates/voelin-store/src/lib.rs @@ -14,7 +14,7 @@ mod secrets; mod store; pub use chat::{ - ChatCursor, ChatTarget, MessageSource, NewMessage, PageQuery, Reaction, RemoteInfo, + ChatCursor, ChatRead, ChatTarget, MessageSource, NewMessage, PageQuery, Reaction, RemoteInfo, StoredMessage, SyncState, WriteOutcome, Written, }; pub use contacts::{Contact, ContactSeen, Relation}; diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index f8d4352..5839d7f 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -23,6 +23,7 @@ const MIGRATIONS: &[Migration] = &[ Migration::Code(crate::chat::migrate_2), Migration::Sql(crate::contacts::SCHEMA_3), Migration::Sql(SCHEMA_4), + Migration::Sql(crate::chat::SCHEMA_5), ]; /// Version 4: where each identity came from ([`IdentityOrigin`]) and which @@ -531,6 +532,48 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// A database of version 4 learns where its chats were read, keeping + /// its messages; nothing is read yet. + #[test] + fn migrates_version_4_read_markers() { + use crate::{ChatRead, ChatTarget, PageQuery}; + let dir = std::env::temp_dir().join(format!("voelin-store-v4-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("client.db"); + { + let mut db = rusqlite::Connection::open(&path).unwrap(); + db.execute_batch(SCHEMA_1).unwrap(); + let tx = db.transaction().unwrap(); + crate::chat::migrate_2(&tx).unwrap(); + tx.commit().unwrap(); + db.execute_batch(crate::contacts::SCHEMA_3).unwrap(); + db.execute_batch(SCHEMA_4).unwrap(); + db.pragma_update(None, "user_version", 4).unwrap(); + db.execute( + "INSERT INTO messages (server_uid, target, ts, ts_ms, author_name, text) + VALUES ('srv', 'channel/1', 1, 1000, 'a', 'kept')", + [], + ) + .unwrap(); + } + let store = Store::open(&path).unwrap(); + assert_eq!(Store::SCHEMA_VERSION, 5); + assert_eq!(store.schema_version().unwrap(), Store::SCHEMA_VERSION); + let channel = ChatTarget::Channel(1); + let rows = store.messages("srv", &channel, PageQuery::default()).unwrap(); + assert_eq!(rows.len(), 1); + assert!(store.chat_reads("srv").unwrap().is_empty()); + let read = ChatRead { ts_ms: rows[0].ts_ms, id: rows[0].id, updated_ms: 1 }; + store.set_chat_read("srv", &channel, &read).unwrap(); + drop(store); + // Opened again: the marker is there and nothing runs twice. + let store = Store::open(&path).unwrap(); + assert_eq!(store.chat_read("srv", &channel).unwrap(), Some(read)); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn bookmarks_keep_order_and_fields() { let store = Store::open_in_memory().unwrap(); diff --git a/crates/voelin-ui/Cargo.toml b/crates/voelin-ui/Cargo.toml index 10427a8..6449da4 100644 --- a/crates/voelin-ui/Cargo.toml +++ b/crates/voelin-ui/Cargo.toml @@ -50,7 +50,9 @@ tsclientlib = { path = "../proto/tsclientlib" } # and PipeWire, global hotkeys through the portal and X11. [target.'cfg(not(target_os = "android"))'.dependencies] voelin-myts = { path = "../voelin-myts" } -slint = { version = "1.18", features = ["renderer-software"] } +# winit's focus events (an unstable API, so this minor version only): +# messages are read only while the window has the focus (`app::watch_focus`). +slint = { version = "~1.18", features = ["renderer-software", "unstable-winit-030"] } voelin-core = { path = "../voelin-core", default-features = false, features = ["media-desktop"] } voelin-platform = { path = "../voelin-platform" } voelin-store = { path = "../voelin-store", features = ["keyring"] } diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index ff312ee..4bdeede 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -24,9 +24,10 @@ use voelin_core::settings::{ }; use voelin_core::stream::StreamInfo; use voelin_core::{ - AudioSettings, Command, Engine, Event, History, HistoryMessage, SessionState, VoiceState, + AudioSettings, Command, Engine, Event, History, HistoryMessage, ObserveState, SessionState, + VoiceState, }; -use voelin_model::{Capabilities, ChannelId, ChatTarget, GroupInfo, Presence}; +use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence}; use voelin_platform::crash; use voelin_store::{Bookmark, MemorySecrets, Secrets, Store}; @@ -144,7 +145,17 @@ pub(crate) struct Tab { /// Live messages of a session that keeps no history (no server unique /// id yet): grouped from the message before, without ids. pub last: Option, + /// Messages not read, not ours: those after `read` (without stored + /// history, those that came while the tab was not on screen). pub unread: i32, + /// The newest message read, by `(ts_ms, id)`: kept in the store + /// (`chat_reads`) when the tab is left, the session closes and on exit + /// (`App::save_read`). `stored_read` is what the store has. + pub read: Option<(i64, i64)>, + pub stored_read: Option<(i64, i64)>, + /// The message the "New" divider is above: the first that was new when + /// the tab came on screen. It stays until the tab is left. + pub divider: Option, /// Nothing older exists as far as the engine can tell. pub complete: bool, /// A gateway page arrived: the chat is not only what we saw. @@ -176,6 +187,9 @@ impl Tab { messages: Vec::new(), last: None, unread: 0, + read: None, + stored_read: None, + divider: None, complete: false, synced: false, loading: false, @@ -200,6 +214,50 @@ impl Tab { pub fn message(&self, key: i32) -> Option<&HistoryMessage> { self.messages.iter().chain(&self.topic_messages).find(|m| m.key == key).map(|m| &m.message) } + + /// Where each message is and whether it is ours (`own`), for the read + /// markers ([`crate::vm::chat::first_unread`]). + pub fn positions(&self, own: impl Fn(&ChatMessage) -> bool) -> Vec<(i64, i64, bool)> { + self.messages + .iter() + .map(|m| (m.message.message.ts_ms, m.message.id, own(&m.message.message))) + .collect() + } + + /// Where the newest message is. + pub fn newest(&self) -> Option<(i64, i64)> { + self.messages.last().map(|m| (m.message.message.ts_ms, m.message.id)) + } + + /// The tab came on screen: the first new message gets the divider + /// (unless one shows), and everything is read. + pub fn enter(&mut self, own: impl Fn(&ChatMessage) -> bool) { + if self.unread > 0 && self.divider.is_none() { + let first = crate::vm::chat::first_unread(&self.positions(own), self.read); + self.divider = first.map(|i| self.messages[i].message.id); + } + self.catch_up(); + } + + /// Everything in the tab is read (it is on screen). + pub fn catch_up(&mut self) { + self.read = self.read.max(self.newest()); + self.unread = 0; + } + + /// Count what is not read: what came after `read`, not ours. + pub fn count_unread(&mut self, own: impl Fn(&ChatMessage) -> bool) { + self.unread = crate::vm::chat::unread_count(&self.positions(own), self.read); + } + + /// Start from where the store says the chat was read (`reads`: by the + /// store's name of the chat). + pub fn read_from(&mut self, reads: &HashMap) { + if let Some(&read) = reads.get(&crate::chat::store_target(&self.target).key()) { + self.read = self.read.max(Some(read)); + self.stored_read = Some(read); + } + } } /// What we know about one server session. @@ -251,6 +309,10 @@ pub(crate) struct SessionView { pub next_transfer: u64, /// What the home, messages and events screens keep of the session. pub extra: crate::social::SessionExtra, + /// Where its chats were read, from the store (by the store's name of + /// the chat), for the server unique id `reads_of`. + pub reads: HashMap, + pub reads_of: Option, } impl Default for SessionView { @@ -281,6 +343,8 @@ impl Default for SessionView { downloads: HashMap::new(), next_transfer: 1, extra: Default::default(), + reads: HashMap::new(), + reads_of: None, } } } @@ -317,6 +381,13 @@ impl SessionView { self.tabs.iter().map(|t| t.unread).sum() } + /// A new tab for `target`, read as far as the store says. + pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab { + let mut tab = Tab::new(target, title); + tab.read_from(&self.reads); + tab + } + /// The session's gateway offers this feature /// (`voelin_gateway_proto::feature`). pub fn gateway_has(&self, feature: &str) -> bool { @@ -469,6 +540,12 @@ pub(crate) struct App { pub join_target: Option<(i64, ChannelId)>, /// Who the poke dialog pokes: session, client, nickname. pub poke_target: Option<(i64, u16, String)>, + /// The window has the focus (desktop: winit tells; elsewhere assumed): + /// messages are read only then. + pub focused: bool, + /// The chat whose messages are on screen (session, target): when it is + /// left, it is stored and loses its divider (`App::track_reading`). + pub reading: Option<(i64, ChatTarget)>, pub mic_test: bool, pub ptt: GlobalPtt, pub video: Video, @@ -662,6 +739,8 @@ pub fn run(options: RunOptions) -> Result<()> { bridge.set_app_name(voelin_platform::APP_NAME.into()); bridge.set_app_version(env!("CARGO_PKG_VERSION").into()); bridge.set_desktop(cfg!(not(target_os = "android"))); + #[cfg(not(target_os = "android"))] + watch_focus(&ui); let models = Models::new(&bridge); // Wayland and X11 find the desktop file (and icon) by this id. #[cfg(not(target_os = "android"))] @@ -712,6 +791,8 @@ pub fn run(options: RunOptions) -> Result<()> { playback_dialog: None, join_target: None, poke_target: None, + focused: true, + reading: None, mic_test: false, ptt, video, @@ -786,6 +867,10 @@ pub fn run(options: RunOptions) -> Result<()> { if let Err(e) = app.prefs.flush() { warn!(%e, "could not store settings"); } + let ids: Vec = app.sessions.keys().copied().collect(); + for id in ids { + app.save_reads(id); + } app.watch = None; app.share = None; if own && !app.demo_ui { @@ -805,6 +890,20 @@ pub fn run(options: RunOptions) -> Result<()> { Ok(()) } +/// Tell the app when the window gains or loses the focus: messages are read +/// only while it has it. (winit's focus events; without them, as on +/// Android, the window counts as focused.) +#[cfg(not(target_os = "android"))] +fn watch_focus(ui: &MainWindow) { + use slint::winit_030::{EventResult, WinitWindowAccessor, winit::event::WindowEvent}; + ui.window().on_winit_window_event(|_, event| { + if let WindowEvent::Focused(focused) = *event { + later(move |app| app.window_focused(focused)); + } + EventResult::Propagate + }); +} + /// Open a file or folder with the desktop's default application. pub(crate) fn open_path(path: &Path) -> std::io::Result<()> { open_target(path.as_os_str()) @@ -922,6 +1021,7 @@ impl App { let id = session as i64; let view = self.sessions.entry(id).or_default(); let was_voice = view.state.voice; + let was_observe = view.state.observe; view.state = state.clone(); if state.voice != VoiceState::Connected { view.focused_own_channel = false; @@ -935,11 +1035,24 @@ impl App { // A new connection: volumes are sent again. view.applied_playback.clear(); } + // Where its chats were read, once the server is known; kept + // when the session ends. + self.load_reads(id); + let off = |voice: VoiceState, observe: ObserveState| { + voice == VoiceState::Disconnected && observe == ObserveState::Off + }; + if off(state.voice, state.observe) && !off(was_voice, was_observe) { + self.save_reads(id); + } + let view = self.sessions.entry(id).or_default(); let focus = !view.focused_own_channel; if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected { self.set_status("Connected"); } if self.current == Some(id) { + if self.track_reading() { + self.refresh_chat(); + } // The voice channel's chat is always at hand, and focused // once per connection. if let (Some(cid), VoiceState::Connected) = (state.own_channel, state.voice) { diff --git a/crates/voelin-ui/src/bind/chat.rs b/crates/voelin-ui/src/bind/chat.rs index 23a9d8a..925ccfb 100644 --- a/crates/voelin-ui/src/bind/chat.rs +++ b/crates/voelin-ui/src/bind/chat.rs @@ -25,6 +25,12 @@ pub(super) fn wire(ui: &MainWindow) { bridge.on_load_older(|| { with_app(App::load_older); }); + bridge.on_mark_read(|| { + with_app(App::mark_read); + }); + bridge.on_chat_shown_changed(|| { + with_app(App::chat_shown_changed); + }); bridge.on_react(|key, emoji| { with_app(|app| app.react(key, emoji.to_string())); }); diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index ac1610b..2e3211f 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -7,6 +7,12 @@ //! the selected tab are rebuilt from them with [`vm::list::sync`], which //! touches only the rows that changed. Sessions the engine keeps no history //! for (it does not know the server yet) fall back to [`Event::Chat`]. +//! +//! Messages are read while their tab is on screen in the focused window +//! ([`App::track_reading`]). A tab remembers the newest message read +//! (`Tab::read`, kept in the store's `chat_reads`), counts what came after +//! it, and when it comes on screen shows a "New" divider above the first +//! of those until it is left. use std::collections::HashMap; use std::path::PathBuf; @@ -20,6 +26,7 @@ use voelin_core::{ }; use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails}; +use voelin_store::ChatRead; use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, Nav, PinItem, SessionView, Tab}; use crate::settings::UI_IMAGE_PREVIEW_KB; @@ -52,6 +59,15 @@ pub(crate) fn server_text<'a>(view: &'a SessionView, tab: &Tab, key: i32) -> Opt server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text) } +/// The store's name of a chat. +pub(crate) fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget { + match target { + ChatTarget::Server => voelin_store::ChatTarget::Server, + ChatTarget::Channel(cid) => voelin_store::ChatTarget::Channel(*cid), + ChatTarget::Private(uid) => voelin_store::ChatTarget::Private(uid.clone()), + } +} + /// A file being downloaded from a chat message. pub(crate) struct Download { /// The message's handle and which of its links this is. @@ -103,7 +119,8 @@ impl App { let index = match view.tabs.iter().position(|t| t.target == target) { Some(i) => i, None => { - view.tabs.push(Tab::new(target.clone(), title)); + let tab = view.new_tab(target.clone(), title); + view.tabs.push(tab); if !self.demo_ui { self.engine.send(Command::OpenChat { session: id as u64, target }); } @@ -112,7 +129,7 @@ impl App { }; if focus { view.current_tab = index; - view.tabs[index].unread = 0; + self.track_reading(); } self.refresh_chat(); self.refresh_servers(); @@ -123,12 +140,12 @@ impl App { && index < view.tabs.len() { view.current_tab = index; - view.tabs[index].unread = 0; view.tabs[index].topic = None; } if let Some(id) = self.current { self.fetch_previews(id); } + self.track_reading(); self.refresh_chat(); self.refresh_servers(); } @@ -139,10 +156,14 @@ impl App { if index == 0 || index >= view.tabs.len() { return; } + self.save_read(id, index); + let view = self.sessions.entry(id).or_default(); let tab = view.tabs.remove(index); view.current_tab = view.current_tab.min(view.tabs.len() - 1); self.engine.send(Command::CloseChat { session: id as u64, target: tab.target }); + self.track_reading(); self.refresh_chat(); + self.refresh_servers(); } pub(crate) fn send_message(&mut self, text: String) { @@ -161,7 +182,8 @@ impl App { match view.tabs.iter().position(|t| t.target == *target) { Some(i) => i, None => { - view.tabs.push(Tab::new(target.clone(), title())); + let tab = view.new_tab(target.clone(), title()); + view.tabs.push(tab); view.tabs.len() - 1 } } @@ -186,21 +208,24 @@ impl App { /// comes, without an id. pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) { let current = self.current == Some(id); + let reading = self.reads_now(id); + let new = !self.is_own(id, &message); let view = self.sessions.entry(id).or_default(); let title = Self::tab_title(view, &message.target, &message.author_name); let index = Self::tab_for(view, &message.target, || title); - let shown = current && view.current_tab == index; + let seen = reading && view.current_tab == index; let tab = &mut view.tabs[index]; let line = vm::chat::line(&message, tab.last.as_ref()); tab.last = Some(Previous::of(&message)); tab.lines.push(line); - if !shown { + let counted = new && !seen; + if counted { tab.unread += 1; } if current { self.refresh_chat(); } - if !shown { + if counted { self.refresh_servers(); } self.studio_chat_changed(id, &message.target); @@ -216,6 +241,7 @@ impl App { complete: bool, ) { let current = self.current == Some(id); + let reading = self.reads_now(id); // A private chat is named after the peer, whoever wrote first. let peer = match target { ChatTarget::Private(uid) => Some(format!( @@ -231,7 +257,8 @@ impl App { let author = messages.first().map_or("", |m| m.message.author_name.as_str()); let title = peer.unwrap_or_else(|| Self::tab_title(view, target, author)); let index = Self::tab_for(view, target, || title); - let shown = current && view.current_tab == index; + let seen = reading && view.current_tab == index; + let own_client = view.state.own_client; let tab = &mut view.tabs[index]; if source == HistorySource::Gateway { tab.synced = true; @@ -240,28 +267,49 @@ impl App { tab.loading = false; tab.complete = tab.complete || complete; } - let mut fresh = 0; + // Without a marker, what the tab holds was read. + if tab.read.is_none() { + tab.read = tab.newest(); + } for message in messages { match tab.messages.iter().position(|m| m.message.id == message.id) { Some(i) => tab.messages[i].message = message, None => { let key = tab.take_key(); - if source == HistorySource::Live { - fresh += 1; - } tab.messages.push(Msg { key, message }); } } } tab.messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id)); - if !shown { - tab.unread += fresh; + // ...and so is a first stored page; a first live message is new. + if tab.read.is_none() { + tab.read = match source { + HistorySource::Live => tab + .messages + .first() + .map(|m| (m.message.message.ts_ms, m.message.id.saturating_sub(1))), + _ => tab.newest(), + }; } + let unread = tab.unread; + let own = + |m: &ChatMessage| crate::social::own_message(&self.social.own_uids, own_client, m); + if seen && source == HistorySource::Live { + tab.catch_up(); + } else { + tab.count_unread(own); + // What came while away (a stored or gateway page) gets the + // divider also when its chat is on screen already. + if seen { + tab.enter(own); + } + } + let counted = tab.unread != unread; if current { self.fetch_previews(id); self.refresh_chat(); } - if fresh > 0 && !shown { + if counted { self.refresh_servers(); } self.studio_chat_changed(id, target); @@ -332,6 +380,7 @@ impl App { previews, pictures, cache, + unread_start: main && tab.divider == Some(m.message.id), }; lines.push(( m.message.message.ts_ms, @@ -434,6 +483,7 @@ impl App { if bridge.get_messages() != empty { bridge.set_messages(empty); } + bridge.set_unread_index(-1); return; }; let tabs: Vec = view @@ -483,13 +533,31 @@ impl App { } let tab = &view.tabs[view.current_tab]; // Sessions without stored history push their lines themselves. + let mut divider = None; if view.has_history() { - vm::list::sync(&tab.lines, &self.lines_of(view, tab, true)); + let lines = self.lines_of(view, tab, true); + divider = lines.iter().position(|l| l.unread_start); + vm::list::sync(&tab.lines, &lines); } let lines = ModelRc::from(tab.lines.clone()); if bridge.get_messages() != lines { bridge.set_messages(lines); } + // The "New" divider: how many came from there on, and when. + let new = tab + .divider + .and_then(|d| tab.messages.iter().position(|m| m.message.id == d)) + .map_or(&[][..], |i| &tab.messages[i..]); + let session = self.current.unwrap_or_default(); + let count = new.iter().filter(|m| !self.is_own(session, &m.message.message)).count(); + bridge.set_unread_index(divider.map_or(-1, |i| i as i32)); + bridge.set_unread_count(count as i32); + bridge.set_unread_since( + new.first() + .map(|m| vm::chat::since_time(m.message.message.ts_ms)) + .unwrap_or_default() + .into(), + ); bridge.set_more_history(view.has_history() && !tab.complete); bridge.set_loading_history(tab.loading); bridge.set_local_history( @@ -584,6 +652,148 @@ impl App { } } + // What is read. + + /// The current chat's messages are on screen (`Nav.chat-shown`). + fn chat_shown(&self) -> bool { + self.ui.upgrade().is_some_and(|ui| ui.global::