Commit fdddc5c639

fdddc5c63994a83112c79d54fb9bc7a3225b3dba

parent: a507fea072

Unregistered key

Matthew Kabat <45803702+Nightchicken@users.noreply.github.com> · 2026-09-20 08:03 UTC
committer: <noreply@github.com>

Support pinned events (#692)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Ulyssa <git@ulyssa.dev>

Layout: unified · split

docs/iamb.1 +7
@@ -123,6 +123,10 @@ Remove your reaction from the selected message.
123When no arguments are given, remove all of your reactions from the message. 123When no arguments are given, remove all of your reactions from the message.
124.It Sy ":redact [reason]" 124.It Sy ":redact [reason]"
125Redact the selected message with the optional reason. 125Redact the selected message with the optional reason.
126.It Sy ":pin"
127Pin the selected message to the room.
128.It Sy ":unpin"
129Unpin the selected message from the room.
126.It Sy ":reply" 130.It Sy ":reply"
127Reply to the selected message. 131Reply to the selected message.
128.It Sy ":cancel" 132.It Sy ":cancel"
@@ -166,6 +170,9 @@ Send an invitation to a user to join the currently focused room with an optional
166Leave the currently focused room. 170Leave the currently focused room.
167.It Sy ":members" 171.It Sy ":members"
168View a list of members of the currently focused room. 172View a list of members of the currently focused room.
173.It Sy ":pinned"
174View a list of pinned messages in the currently focused room.
175Select a message to jump to it in the room.
169.It Sy ":room access set [rule]" 176.It Sy ":room access set [rule]"
170Set the join rules for the room to control who can access it. 177Set the join rules for the room to control who can access it.
171Possible values for the 178Possible values for the
src/base.rs +183 −2
@@ -102,6 +102,13 @@ pub enum VerifyAction {
102 Emoji, 102 Emoji,
103} 103}
104 104
105/// An action taken against a room's timeline.
106#[derive(Clone, Debug, Eq, PartialEq)]
107pub enum TimelineAction {
108 /// Jump to a loaded message in the scrollback.
109 GotoEvent(OwnedEventId),
110}
111
105/// An action taken against the currently selected message. 112/// An action taken against the currently selected message.
106#[derive(Clone, Debug, Eq, PartialEq)] 113#[derive(Clone, Debug, Eq, PartialEq)]
107pub enum MessageAction { 114pub enum MessageAction {
@@ -126,6 +133,9 @@ pub enum MessageAction {
126 /// when it is `true`. 133 /// when it is `true`.
127 React(String, bool), 134 React(String, bool),
128 135
136 /// Pin a message to the room.
137 Pin,
138
129 /// Redact a message, with an optional reason. 139 /// Redact a message, with an optional reason.
130 /// 140 ///
131 /// The [bool] argument indicates whether to skip confirmation. 141 /// The [bool] argument indicates whether to skip confirmation.
@@ -146,6 +156,9 @@ pub enum MessageAction {
146 /// and error when it doesn't recognize it. The second [bool] argument forces it to be 156 /// and error when it doesn't recognize it. The second [bool] argument forces it to be
147 /// interpreted literally when it is `true`. 157 /// interpreted literally when it is `true`.
148 Unreact(Option<String>, bool), 158 Unreact(Option<String>, bool),
159
160 /// Unpin a message from the room.
161 Unpin,
149} 162}
150 163
151/// An action taken in the currently selected space. 164/// An action taken in the currently selected space.
@@ -505,6 +518,9 @@ pub enum RoomAction {
505 /// Open the members window. 518 /// Open the members window.
506 Members(Box<CommandContext>), 519 Members(Box<CommandContext>),
507 520
521 /// Open the pinned messages window.
522 Pinned(Box<CommandContext>),
523
508 /// Set whether a room is a direct message. 524 /// Set whether a room is a direct message.
509 SetDirect(bool), 525 SetDirect(bool),
510 526
@@ -590,6 +606,9 @@ pub enum IambAction {
590 /// Perform an action against the homeserver. 606 /// Perform an action against the homeserver.
591 Homeserver(HomeserverAction), 607 Homeserver(HomeserverAction),
592 608
609 /// Perform an action against a room's timeline.
610 Timeline(TimelineAction),
611
593 /// Perform an action over room keys. 612 /// Perform an action over room keys.
594 Keys(KeysAction), 613 Keys(KeysAction),
595 614
@@ -661,6 +680,12 @@ impl From<SendAction> for IambAction {
661 } 680 }
662} 681}
663 682
683impl From<TimelineAction> for IambAction {
684 fn from(act: TimelineAction) -> Self {
685 IambAction::Timeline(act)
686 }
687}
688
664impl ApplicationAction for IambAction { 689impl ApplicationAction for IambAction {
665 fn is_edit_sequence(&self, _: &EditContext) -> SequenceStatus { 690 fn is_edit_sequence(&self, _: &EditContext) -> SequenceStatus {
666 match self { 691 match self {
@@ -672,6 +697,7 @@ impl ApplicationAction for IambAction {
672 IambAction::Room(..) => SequenceStatus::Break, 697 IambAction::Room(..) => SequenceStatus::Break,
673 IambAction::OpenLink(..) => SequenceStatus::Break, 698 IambAction::OpenLink(..) => SequenceStatus::Break,
674 IambAction::Send(..) => SequenceStatus::Break, 699 IambAction::Send(..) => SequenceStatus::Break,
700 IambAction::Timeline(..) => SequenceStatus::Break,
675 IambAction::ToggleScrollbackFocus => SequenceStatus::Break, 701 IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
676 IambAction::Verify(..) => SequenceStatus::Break, 702 IambAction::Verify(..) => SequenceStatus::Break,
677 IambAction::VerifyRequest(..) => SequenceStatus::Break, 703 IambAction::VerifyRequest(..) => SequenceStatus::Break,
@@ -689,6 +715,7 @@ impl ApplicationAction for IambAction {
689 IambAction::OpenLink(..) => SequenceStatus::Atom, 715 IambAction::OpenLink(..) => SequenceStatus::Atom,
690 IambAction::Room(..) => SequenceStatus::Atom, 716 IambAction::Room(..) => SequenceStatus::Atom,
691 IambAction::Send(..) => SequenceStatus::Atom, 717 IambAction::Send(..) => SequenceStatus::Atom,
718 IambAction::Timeline(..) => SequenceStatus::Atom,
692 IambAction::ToggleScrollbackFocus => SequenceStatus::Atom, 719 IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
693 IambAction::Verify(..) => SequenceStatus::Atom, 720 IambAction::Verify(..) => SequenceStatus::Atom,
694 IambAction::VerifyRequest(..) => SequenceStatus::Atom, 721 IambAction::VerifyRequest(..) => SequenceStatus::Atom,
@@ -706,6 +733,7 @@ impl ApplicationAction for IambAction {
706 IambAction::Room(..) => SequenceStatus::Ignore, 733 IambAction::Room(..) => SequenceStatus::Ignore,
707 IambAction::OpenLink(..) => SequenceStatus::Ignore, 734 IambAction::OpenLink(..) => SequenceStatus::Ignore,
708 IambAction::Send(..) => SequenceStatus::Ignore, 735 IambAction::Send(..) => SequenceStatus::Ignore,
736 IambAction::Timeline(..) => SequenceStatus::Ignore,
709 IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore, 737 IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
710 IambAction::Verify(..) => SequenceStatus::Ignore, 738 IambAction::Verify(..) => SequenceStatus::Ignore,
711 IambAction::VerifyRequest(..) => SequenceStatus::Ignore, 739 IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
@@ -723,6 +751,7 @@ impl ApplicationAction for IambAction {
723 IambAction::Keys(..) => false, 751 IambAction::Keys(..) => false,
724 IambAction::Send(..) => false, 752 IambAction::Send(..) => false,
725 IambAction::OpenLink(..) => false, 753 IambAction::OpenLink(..) => false,
754 IambAction::Timeline(..) => false,
726 IambAction::ToggleScrollbackFocus => false, 755 IambAction::ToggleScrollbackFocus => false,
727 IambAction::Verify(..) => false, 756 IambAction::Verify(..) => false,
728 IambAction::VerifyRequest(..) => false, 757 IambAction::VerifyRequest(..) => false,
@@ -743,6 +772,12 @@ impl From<SpaceAction> for ProgramAction {
743 } 772 }
744} 773}
745 774
775impl From<TimelineAction> for ProgramAction {
776 fn from(act: TimelineAction) -> Self {
777 IambAction::from(act).into()
778 }
779}
780
746impl From<IambAction> for ProgramAction { 781impl From<IambAction> for ProgramAction {
747 fn from(act: IambAction) -> Self { 782 fn from(act: IambAction) -> Self {
748 Action::Application(act) 783 Action::Application(act)
@@ -1185,6 +1220,15 @@ pub struct RoomInfo {
1185 1220
1186 /// The last time the room was rendered, used to detect if it is currently open. 1221 /// The last time the room was rendered, used to detect if it is currently open.
1187 pub draw_last: Option<Instant>, 1222 pub draw_last: Option<Instant>,
1223
1224 /// The room's pinned events, mirrored from the SDK's room state for rendering.
1225 pub pinned_events: Vec<OwnedEventId>,
1226
1227 /// Pinned events fetched for the `:pinned` window that aren't in the loaded scrollback.
1228 pub pinned_previews: HashMap<OwnedEventId, Message>,
1229
1230 /// How many times fetching each pinned event for the `:pinned` window has failed.
1231 pub pinned_failures: HashMap<OwnedEventId, u8>,
1188} 1232}
1189 1233
1190impl Default for RoomInfo { 1234impl Default for RoomInfo {
@@ -1206,6 +1250,9 @@ impl Default for RoomInfo {
1206 users_typing: Default::default(), 1250 users_typing: Default::default(),
1207 display_names: Default::default(), 1251 display_names: Default::default(),
1208 draw_last: Default::default(), 1252 draw_last: Default::default(),
1253 pinned_events: Default::default(),
1254 pinned_previews: Default::default(),
1255 pinned_failures: Default::default(),
1209 unloaded_edits: Default::default(), 1256 unloaded_edits: Default::default(),
1210 unloaded_polls: Default::default(), 1257 unloaded_polls: Default::default(),
1211 unloaded_unstable_polls: Default::default(), 1258 unloaded_unstable_polls: Default::default(),
@@ -1260,6 +1307,56 @@ impl RoomInfo {
1260 } 1307 }
1261 } 1308 }
1262 1309
1310 /// Whether a message is pinned to the room.
1311 pub fn is_pinned(&self, event_id: &EventId) -> bool {
1312 self.pinned_events.iter().any(|id| id == event_id)
1313 }
1314
1315 /// Get a pinned message, from the scrollback if it's loaded or else from the fetched previews.
1316 pub fn get_pinned(&self, event_id: &EventId) -> Option<&Message> {
1317 self.get_event(event_id).or_else(|| self.pinned_previews.get(event_id))
1318 }
1319
1320 /// Whether fetching a pinned event has failed too many times to keep retrying.
1321 pub fn pinned_unavailable(&self, event_id: &EventId) -> bool {
1322 self.pinned_failures
1323 .get(event_id)
1324 .is_some_and(|failures| *failures >= PINNED_FETCH_ATTEMPTS)
1325 }
1326
1327 /// Record the result of fetching a pinned event for the `:pinned` window.
1328 pub fn insert_pinned(&mut self, event_id: OwnedEventId, msg: Option<Message>) {
1329 match msg {
1330 Some(msg) => {
1331 self.pinned_failures.remove(&event_id);
1332 self.pinned_previews.insert(event_id, msg);
1333 },
1334 None => {
1335 let failures = self.pinned_failures.entry(event_id).or_default();
1336 *failures = failures.saturating_add(1);
1337 },
1338 }
1339 }
1340
1341 /// Pinned events that still need to be fetched for the `:pinned` window.
1342 pub fn missing_pinned(&self) -> Vec<OwnedEventId> {
1343 self.pinned_events
1344 .iter()
1345 .filter(|id| self.get_pinned(id).is_none() && !self.pinned_unavailable(id))
1346 .cloned()
1347 .collect()
1348 }
1349
1350 /// Get where a loaded message lives, as its thread root and key.
1351 pub fn get_message_location(
1352 &self,
1353 event_id: &EventId,
1354 ) -> Option<(Option<&EventId>, &MessageKey)> {
1355 let loc = self.keys.get(event_id)?;
1356
1357 Some((loc.to_thread_root(), loc.to_message_key()?))
1358 }
1359
1263 pub fn get_receipt_thread(&self, event_id: &EventId) -> Option<ReceiptThread> { 1360 pub fn get_receipt_thread(&self, event_id: &EventId) -> Option<ReceiptThread> {
1264 match self.keys.get(event_id)? { 1361 match self.keys.get(event_id)? {
1265 EventLocation::Message(None, _) | EventLocation::State(_) => Some(ReceiptThread::Main), 1362 EventLocation::Message(None, _) | EventLocation::State(_) => Some(ReceiptThread::Main),
@@ -2166,6 +2263,9 @@ impl SyncInfo {
2166 2263
2167static MESSAGE_NEED_TTL: u8 = 30; 2264static MESSAGE_NEED_TTL: u8 = 30;
2168 2265
2266/// How many failed fetches of a pinned event before the `:pinned` window stops retrying.
2267const PINNED_FETCH_ATTEMPTS: u8 = 10;
2268
2169#[derive(Debug, PartialEq)] 2269#[derive(Debug, PartialEq)]
2170/// Load messages until the event is loaded or `ttl` loads are exceeded 2270/// Load messages until the event is loaded or `ttl` loads are exceeded
2171pub struct MessageNeed { 2271pub struct MessageNeed {
@@ -2176,6 +2276,7 @@ pub struct MessageNeed {
2176#[derive(Default, Debug, PartialEq)] 2276#[derive(Default, Debug, PartialEq)]
2177pub struct Need { 2277pub struct Need {
2178 pub members: bool, 2278 pub members: bool,
2279 pub pinned: bool,
2179 pub messages: Option<Vec<MessageNeed>>, 2280 pub messages: Option<Vec<MessageNeed>>,
2180} 2281}
2181 2282
@@ -2191,6 +2292,11 @@ impl RoomNeeds {
2191 self.needs.entry(room_id).or_default().members = true; 2292 self.needs.entry(room_id).or_default().members = true;
2192 } 2293 }
2193 2294
2295 /// Mark a room for needing to fetch its pinned events.
2296 pub fn need_pinned(&mut self, room_id: OwnedRoomId) {
2297 self.needs.entry(room_id).or_default().pinned = true;
2298 }
2299
2194 /// Mark a room for needing to load messages. 2300 /// Mark a room for needing to load messages.
2195 pub fn need_messages(&mut self, room_id: OwnedRoomId) { 2301 pub fn need_messages(&mut self, room_id: OwnedRoomId) {
2196 self.needs.entry(room_id).or_default().messages.get_or_insert_default(); 2302 self.needs.entry(room_id).or_default().messages.get_or_insert_default();
@@ -2269,6 +2375,9 @@ pub struct ChatStore {
2269 /// Whether to ring the terminal bell on the next redraw. 2375 /// Whether to ring the terminal bell on the next redraw.
2270 pub ring_bell: bool, 2376 pub ring_bell: bool,
2271 2377
2378 /// An error raised while drawing, shown in the message bar on the next redraw.
2379 pub draw_error: Option<String>,
2380
2272 /// Whether the application is currently focused 2381 /// Whether the application is currently focused
2273 pub focused: bool, 2382 pub focused: bool,
2274 2383
@@ -2301,6 +2410,7 @@ impl ChatStore {
2301 sync_info: Default::default(), 2410 sync_info: Default::default(),
2302 draw_curr: None, 2411 draw_curr: None,
2303 ring_bell: false, 2412 ring_bell: false,
2413 draw_error: None,
2304 focused: true, 2414 focused: true,
2305 open_notifications: Default::default(), 2415 open_notifications: Default::default(),
2306 }; 2416 };
@@ -2366,6 +2476,9 @@ pub enum IambId {
2366 /// The `:members` window for a given Matrix room. 2476 /// The `:members` window for a given Matrix room.
2367 MemberList(OwnedRoomId), 2477 MemberList(OwnedRoomId),
2368 2478
2479 /// The `:pinned` window for a given Matrix room.
2480 PinnedList(OwnedRoomId),
2481
2369 /// The `:rooms` window. 2482 /// The `:rooms` window.
2370 RoomList, 2483 RoomList,
2371 2484
@@ -2427,6 +2540,9 @@ impl Display for IambId {
2427 IambId::MemberList(room_id) => { 2540 IambId::MemberList(room_id) => {
2428 write!(f, "iamb://members/{room_id}") 2541 write!(f, "iamb://members/{room_id}")
2429 }, 2542 },
2543 IambId::PinnedList(room_id) => {
2544 write!(f, "iamb://room/{room_id}/pinned")
2545 },
2430 IambId::DirectList => f.write_str("iamb://dms"), 2546 IambId::DirectList => f.write_str("iamb://dms"),
2431 IambId::RoomList => f.write_str("iamb://rooms"), 2547 IambId::RoomList => f.write_str("iamb://rooms"),
2432 IambId::SpaceList => f.write_str("iamb://spaces"), 2548 IambId::SpaceList => f.write_str("iamb://spaces"),
@@ -2507,7 +2623,14 @@ impl Visitor<'_> for IambIdVisitor {
2507 2623
2508 Ok(IambId::Room(room_id, Some(thread_root))) 2624 Ok(IambId::Room(room_id, Some(thread_root)))
2509 }, 2625 },
2510 _ => return Err(E::custom("Invalid members window URL")), 2626 [room_id, "pinned"] => {
2627 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
2628 return Err(E::custom("Invalid room identifier"));
2629 };
2630
2631 Ok(IambId::PinnedList(room_id))
2632 },
2633 _ => return Err(E::custom("Invalid iamb window URL")),
2511 } 2634 }
2512 }, 2635 },
2513 Some("joining") => { 2636 Some("joining") => {
@@ -2655,6 +2778,9 @@ pub enum IambBufferId {
2655 /// The `:members` window for a room. 2778 /// The `:members` window for a room.
2656 MemberList(OwnedRoomId), 2779 MemberList(OwnedRoomId),
2657 2780
2781 /// The `:pinned` window for a room.
2782 PinnedList(OwnedRoomId),
2783
2658 /// The `:rooms` window. 2784 /// The `:rooms` window.
2659 RoomList, 2785 RoomList,
2660 2786
@@ -2688,6 +2814,7 @@ impl IambBufferId {
2688 IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()), 2814 IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
2689 IambBufferId::DirectList => IambId::DirectList, 2815 IambBufferId::DirectList => IambId::DirectList,
2690 IambBufferId::MemberList(room) => IambId::MemberList(room.clone()), 2816 IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
2817 IambBufferId::PinnedList(room) => IambId::PinnedList(room.clone()),
2691 IambBufferId::RoomList => IambId::RoomList, 2818 IambBufferId::RoomList => IambId::RoomList,
2692 IambBufferId::SpaceList => IambId::SpaceList, 2819 IambBufferId::SpaceList => IambId::SpaceList,
2693 IambBufferId::VerifyList => IambId::VerifyList, 2820 IambBufferId::VerifyList => IambId::VerifyList,
@@ -3055,10 +3182,64 @@ pub mod tests {
3055 3182
3056 assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![( 3183 assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
3057 room_id, 3184 room_id,
3058 Need { members: true, messages: Some(Vec::new()) } 3185 Need {
3186 members: true,
3187 messages: Some(Vec::new()),
3188 pinned: false
3189 }
3059 )],); 3190 )],);
3060 } 3191 }
3061 3192
3193 #[test]
3194 fn test_pinned_lookup() {
3195 let mut info = mock_room();
3196 let unloaded = owned_event_id!("$unloaded");
3197
3198 info.pinned_events = vec![MSG3_EVID.clone(), unloaded.clone()];
3199
3200 assert!(info.is_pinned(&MSG3_EVID));
3201 assert!(!info.is_pinned(&MSG4_EVID));
3202
3203 // Loaded messages come from the scrollback, so only the unloaded one needs fetching.
3204 assert!(info.get_pinned(&MSG3_EVID).is_some());
3205 assert_eq!(info.missing_pinned(), vec![unloaded.clone()]);
3206
3207 info.insert_pinned(unloaded.clone(), mock_message1().into());
3208 assert!(info.get_pinned(&unloaded).is_some());
3209 assert!(info.missing_pinned().is_empty());
3210
3211 // Failed fetches are retried until they hit the limit.
3212 let broken = owned_event_id!("$broken");
3213 info.pinned_events.push(broken.clone());
3214
3215 for _ in 1..PINNED_FETCH_ATTEMPTS {
3216 info.insert_pinned(broken.clone(), None);
3217 }
3218 assert!(!info.pinned_unavailable(&broken));
3219 assert_eq!(info.missing_pinned(), vec![broken.clone()]);
3220
3221 info.insert_pinned(broken.clone(), None);
3222 assert!(info.pinned_unavailable(&broken));
3223 assert!(info.missing_pinned().is_empty());
3224
3225 let (thread, key) = info.get_message_location(&MSG3_EVID).unwrap();
3226 assert_eq!(thread, None);
3227 assert_eq!(key, &*MSG3_KEY);
3228 assert!(info.get_message_location(&unloaded).is_none());
3229 }
3230
3231 #[test]
3232 fn test_pinned_window_id() {
3233 let room_id = TEST_ROOM1_ID.clone();
3234 let id = IambId::PinnedList(room_id.clone());
3235 let url = format!("iamb://room/{room_id}/pinned");
3236
3237 assert_eq!(id.to_string(), url);
3238
3239 let parsed: IambId = serde_json::from_str(&format!("{url:?}")).unwrap();
3240 assert_eq!(parsed, id);
3241 }
3242
3062 #[test] 3243 #[test]
3063 fn test_ambiguous_displaynames() { 3244 fn test_ambiguous_displaynames() {
3064 let mut store = DisplayNameStore::default(); 3245 let mut store = DisplayNameStore::default();
src/commands.rs +67
@@ -344,6 +344,39 @@ fn iamb_unreact(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
344 return Ok(step); 344 return Ok(step);
345} 345}
346 346
347fn iamb_pinned(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
348 if !desc.arg.text.is_empty() {
349 return Result::Err(CommandError::InvalidArgument);
350 }
351
352 let open = IambAction::Room(RoomAction::Pinned(ctx.clone().into()));
353 let step = CommandStep::Continue(open.into(), ctx.context.clone());
354
355 return Ok(step);
356}
357
358fn iamb_pin(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
359 if !desc.arg.text.is_empty() {
360 return Result::Err(CommandError::InvalidArgument);
361 }
362
363 let mact = IambAction::from(MessageAction::Pin);
364 let step = CommandStep::Continue(mact.into(), ctx.context.clone());
365
366 return Ok(step);
367}
368
369fn iamb_unpin(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
370 if !desc.arg.text.is_empty() {
371 return Result::Err(CommandError::InvalidArgument);
372 }
373
374 let mact = IambAction::from(MessageAction::Unpin);
375 let step = CommandStep::Continue(mact.into(), ctx.context.clone());
376
377 return Ok(step);
378}
379
347fn iamb_redact(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult { 380fn iamb_redact(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
348 let args = desc.arg.strings()?; 381 let args = desc.arg.strings()?;
349 382
@@ -1092,6 +1125,12 @@ pub fn add_iamb_commands(cmds: &mut ProgramCommands) {
1092 aliases: vec![], 1125 aliases: vec![],
1093 f: iamb_react, 1126 f: iamb_react,
1094 }); 1127 });
1128 cmds.add_command(ProgramCommand { name: "pin".into(), aliases: vec![], f: iamb_pin });
1129 cmds.add_command(ProgramCommand {
1130 name: "pinned".into(),
1131 aliases: vec![],
1132 f: iamb_pinned,
1133 });
1095 cmds.add_command(ProgramCommand { 1134 cmds.add_command(ProgramCommand {
1096 name: "redact".into(), 1135 name: "redact".into(),
1097 aliases: vec![], 1136 aliases: vec![],
@@ -1144,6 +1183,11 @@ pub fn add_iamb_commands(cmds: &mut ProgramCommands) {
1144 aliases: vec![], 1183 aliases: vec![],
1145 f: iamb_unreact, 1184 f: iamb_unreact,
1146 }); 1185 });
1186 cmds.add_command(ProgramCommand {
1187 name: "unpin".into(),
1188 aliases: vec![],
1189 f: iamb_unpin,
1190 });
1147 cmds.add_command(ProgramCommand { 1191 cmds.add_command(ProgramCommand {
1148 name: "upload".into(), 1192 name: "upload".into(),
1149 aliases: vec![], 1193 aliases: vec![],
@@ -1787,6 +1831,29 @@ mod tests {
1787 assert_eq!(res, Err(CommandError::InvalidArgument)); 1831 assert_eq!(res, Err(CommandError::InvalidArgument));
1788 } 1832 }
1789 1833
1834 #[test]
1835 fn test_cmd_pin() {
1836 let mut cmds = setup_test_commands();
1837 let ctx = EditContext::default();
1838
1839 let res = cmds.input_cmd("pin", ctx.clone()).unwrap();
1840 let act = IambAction::Message(MessageAction::Pin);
1841 assert_eq!(res, vec![(act.into(), ctx.clone())]);
1842
1843 let res = cmds.input_cmd("unpin", ctx.clone()).unwrap();
1844 let act = IambAction::Message(MessageAction::Unpin);
1845 assert_eq!(res, vec![(act.into(), ctx.clone())]);
1846
1847 let res = cmds.input_cmd("pin foo", ctx.clone());
1848 assert_eq!(res, Err(CommandError::InvalidArgument));
1849
1850 let res = cmds.input_cmd("pinned foo", ctx.clone());
1851 assert_eq!(res, Err(CommandError::InvalidArgument));
1852
1853 let res = cmds.input_cmd("unpin foo", ctx.clone());
1854 assert_eq!(res, Err(CommandError::InvalidArgument));
1855 }
1856
1790 #[test] 1857 #[test]
1791 fn test_cmd_keys() { 1858 fn test_cmd_keys() {
1792 let mut cmds = setup_test_commands(); 1859 let mut cmds = setup_test_commands();
src/completions.rs +3 −1
@@ -623,7 +623,8 @@ fn complete_cmdarg(
623 623
624 // These have no arguments 624 // These have no arguments
625 "cancel" | "chats" | "dms" | "editor" | "edit" | "forget" | "invites" | "leave" | 625 "cancel" | "chats" | "dms" | "editor" | "edit" | "forget" | "invites" | "leave" |
626 "members" | "mentions" | "replied" | "reply" | "rooms" | "spaces" | "welcome" => vec![], 626 "members" | "mentions" | "pin" | "pinned" | "unpin" | "replied" | "reply" | "rooms" |
627 "spaces" | "welcome" => vec![],
627 628
628 "abo" | "aboveleft" | "bel" | "belowright" | "hor" | "horizontal" | "lefta" | 629 "abo" | "aboveleft" | "bel" | "belowright" | "hor" | "horizontal" | "lefta" |
629 "leftabove" | "rightb" | "rightbelow" | "tab" | "vert" | "vertical" => { 630 "leftabove" | "rightb" | "rightbelow" | "tab" | "vert" | "vertical" => {
@@ -786,6 +787,7 @@ impl Completer<IambInfo> for IambCompleter {
786 787
787 IambBufferId::DirectList => vec![], 788 IambBufferId::DirectList => vec![],
788 IambBufferId::MemberList(_) => vec![], 789 IambBufferId::MemberList(_) => vec![],
790 IambBufferId::PinnedList(_) => vec![],
789 IambBufferId::RoomList => vec![], 791 IambBufferId::RoomList => vec![],
790 IambBufferId::SpaceList => vec![], 792 IambBufferId::SpaceList => vec![],
791 IambBufferId::VerifyList => vec![], 793 IambBufferId::VerifyList => vec![],
src/main.rs +7
@@ -329,6 +329,10 @@ impl Application {
329 store.application.ring_bell = term.backend_mut().write_all(&[7]).is_err(); 329 store.application.ring_bell = term.backend_mut().write_all(&[7]).is_err();
330 } 330 }
331 331
332 if let Some(err) = store.application.draw_error.take() {
333 sstate.push_error(err);
334 }
335
332 if full { 336 if full {
333 term.clear()?; 337 term.clear()?;
334 } 338 }
@@ -627,6 +631,9 @@ impl Application {
627 IambAction::Space(act) => { 631 IambAction::Space(act) => {
628 self.screen.current_window_mut()?.space_command(act, ctx, store).await? 632 self.screen.current_window_mut()?.space_command(act, ctx, store).await?
629 }, 633 },
634 IambAction::Timeline(act) => {
635 self.screen.current_window_mut()?.timeline_command(act, ctx, store).await?
636 },
630 IambAction::Room(act) => { 637 IambAction::Room(act) => {
631 let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?; 638 let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
632 self.action_prepend(acts); 639 self.action_prepend(acts);
src/message/mod.rs +16 −3
@@ -234,6 +234,11 @@ impl MessageTimeStamp {
234 Span::styled(time, BOLD_STYLE) 234 Span::styled(time, BOLD_STYLE)
235 } 235 }
236 236
237 /// A compact date and time, for places without a date separator line.
238 pub fn show_datetime(self) -> String {
239 self.as_datetime().format("%Y-%m-%d %H:%M").to_string()
240 }
241
237 fn show_time(self) -> Span<'static> { 242 fn show_time(self) -> Span<'static> {
238 let time = self.as_datetime().format("%T"); 243 let time = self.as_datetime().format("%T");
239 let time = format!(" [{time}]"); 244 let time = format!(" [{time}]");
@@ -1291,11 +1296,19 @@ impl Message {
1291 fmt.push_spans(space_span(width, style).into(), style, &mut text); 1296 fmt.push_spans(space_span(width, style).into(), style, &mut text);
1292 } 1297 }
1293 1298
1294 if self.event.is_edited() { 1299 let pinned = self.event.event_id().is_some_and(|id| info.is_pinned(id));
1300 let label = match (self.event.is_edited(), pinned) {
1301 (true, true) => Some("(pinned, edited)"),
1302 (true, false) => Some("(edited)"),
1303 (false, true) => Some("(pinned)"),
1304 (false, false) => None,
1305 };
1306
1307 if let Some(label) = label {
1295 fmt.push_spans( 1308 fmt.push_spans(
1296 Line::from(vec![ 1309 Line::from(vec![
1297 Span::styled("(edited)", style.fg(Color::Gray)), 1310 Span::styled(label, style.fg(Color::Gray)),
1298 space_span(fmt.width().saturating_sub(8), style), 1311 space_span(fmt.width().saturating_sub(label.len()), style),
1299 ]), 1312 ]),
1300 style, 1313 style,
1301 &mut text, 1314 &mut text,
src/prelude.rs +1
@@ -87,6 +87,7 @@ pub use crate::base::{
87 RoomInfo, 87 RoomInfo,
88 SendAction, 88 SendAction,
89 SpaceAction, 89 SpaceAction,
90 TimelineAction,
90}; 91};
91pub use crate::config::{Aliases, ApplicationSettings}; 92pub use crate::config::{Aliases, ApplicationSettings};
92pub use crate::message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages}; 93pub use crate::message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages};
src/windows/mod.rs +169
@@ -290,6 +290,7 @@ macro_rules! delegate {
290 IambWindow::Room($id) => $e, 290 IambWindow::Room($id) => $e,
291 IambWindow::DirectList($id) => $e, 291 IambWindow::DirectList($id) => $e,
292 IambWindow::MemberList($id, _, _) => $e, 292 IambWindow::MemberList($id, _, _) => $e,
293 IambWindow::PinnedList($id, _, _) => $e,
293 IambWindow::RoomList($id) => $e, 294 IambWindow::RoomList($id) => $e,
294 IambWindow::SpaceList($id) => $e, 295 IambWindow::SpaceList($id) => $e,
295 IambWindow::VerifyList($id) => $e, 296 IambWindow::VerifyList($id) => $e,
@@ -305,6 +306,7 @@ macro_rules! delegate {
305pub enum IambWindow { 306pub enum IambWindow {
306 DirectList(RoomListState), 307 DirectList(RoomListState),
307 MemberList(MemberListState, OwnedRoomId, Option<Instant>), 308 MemberList(MemberListState, OwnedRoomId, Option<Instant>),
309 PinnedList(PinnedListState, OwnedRoomId, Option<Instant>),
308 Room(RoomState), 310 Room(RoomState),
309 VerifyList(VerifyListState), 311 VerifyList(VerifyListState),
310 RoomList(RoomListState), 312 RoomList(RoomListState),
@@ -325,6 +327,19 @@ impl IambWindow {
325 } 327 }
326 } 328 }
327 329
330 pub async fn timeline_command(
331 &mut self,
332 act: TimelineAction,
333 ctx: ProgramContext,
334 store: &mut ProgramStore,
335 ) -> IambResult<EditInfo> {
336 if let IambWindow::Room(w) = self {
337 w.timeline_command(act, ctx, store).await
338 } else {
339 Err(IambError::NoSelectedRoom.into())
340 }
341 }
342
328 pub async fn message_command( 343 pub async fn message_command(
329 &mut self, 344 &mut self,
330 act: MessageAction, 345 act: MessageAction,
@@ -360,6 +375,7 @@ impl IambWindow {
360 let id = match self { 375 let id = match self {
361 IambWindow::Room(state) => state.id(), 376 IambWindow::Room(state) => state.id(),
362 IambWindow::MemberList(_, room_id, _) => Some(&**room_id), 377 IambWindow::MemberList(_, room_id, _) => Some(&**room_id),
378 IambWindow::PinnedList(_, room_id, _) => Some(&**room_id),
363 379
364 IambWindow::DirectList(state) => state.get().map(|state| state.room_id()), 380 IambWindow::DirectList(state) => state.get().map(|state| state.room_id()),
365 IambWindow::RoomList(state) => state.get().map(|state| state.room_id()), 381 IambWindow::RoomList(state) => state.get().map(|state| state.room_id()),
@@ -393,6 +409,7 @@ impl IambWindow {
393} 409}
394 410
395pub type MemberListState = ListState<MemberItem, IambInfo>; 411pub type MemberListState = ListState<MemberItem, IambInfo>;
412pub type PinnedListState = ListState<PinnedItem, IambInfo>;
396pub type RoomListState = ListState<GenericRoomItem, IambInfo>; 413pub type RoomListState = ListState<GenericRoomItem, IambInfo>;
397pub type VerifyListState = ListState<VerifyItem, IambInfo>; 414pub type VerifyListState = ListState<VerifyItem, IambInfo>;
398 415
@@ -527,6 +544,33 @@ impl WindowOps<IambInfo> for IambWindow {
527 .focus(focused) 544 .focus(focused)
528 .render(area, buf, state); 545 .render(area, buf, state);
529 }, 546 },
547 IambWindow::PinnedList(state, room_id, last_fetch) => {
548 let info = store.application.rooms.get_or_default(room_id.clone());
549
550 // Most recently pinned first.
551 let items = info
552 .pinned_events
553 .iter()
554 .rev()
555 .map(|event_id| PinnedItem::new(room_id.clone(), event_id.clone()))
556 .collect::<Vec<_>>();
557
558 let need_fetch = last_fetch.is_none_or(|i| i.elapsed() >= MEMBER_FETCH_DEBOUNCE);
559
560 if need_fetch && !info.missing_pinned().is_empty() {
561 store.application.need_load.need_pinned(room_id.clone());
562 *last_fetch = Some(Instant::now());
563 }
564
565 state.set(items);
566 state.set_ignorecase(store.application.settings.tunables.ignorecase);
567
568 List::new(store)
569 .empty_message("No pinned messages in this room")
570 .empty_alignment(Alignment::Center)
571 .focus(focused)
572 .render(area, buf, state);
573 },
530 IambWindow::RoomList(state) => { 574 IambWindow::RoomList(state) => {
531 let mut items = sync_info 575 let mut items = sync_info
532 .rooms 576 .rooms
@@ -680,6 +724,9 @@ impl WindowOps<IambInfo> for IambWindow {
680 IambWindow::MemberList(w, room_id, last_fetch) => { 724 IambWindow::MemberList(w, room_id, last_fetch) => {
681 IambWindow::MemberList(w.dup(store), room_id.clone(), *last_fetch) 725 IambWindow::MemberList(w.dup(store), room_id.clone(), *last_fetch)
682 }, 726 },
727 IambWindow::PinnedList(w, room_id, last_fetch) => {
728 IambWindow::PinnedList(w.dup(store), room_id.clone(), *last_fetch)
729 },
683 IambWindow::RoomList(w) => Self::RoomList(w.dup(store)), 730 IambWindow::RoomList(w) => Self::RoomList(w.dup(store)),
684 IambWindow::SpaceList(w) => Self::SpaceList(w.dup(store)), 731 IambWindow::SpaceList(w) => Self::SpaceList(w.dup(store)),
685 IambWindow::VerifyList(w) => w.dup(store).into(), 732 IambWindow::VerifyList(w) => w.dup(store).into(),
@@ -723,6 +770,7 @@ impl Window<IambInfo> for IambWindow {
723 IambWindow::Room(room) => room.window_id(), 770 IambWindow::Room(room) => room.window_id(),
724 IambWindow::DirectList(_) => IambId::DirectList, 771 IambWindow::DirectList(_) => IambId::DirectList,
725 IambWindow::MemberList(_, room_id, _) => IambId::MemberList(room_id.clone()), 772 IambWindow::MemberList(_, room_id, _) => IambId::MemberList(room_id.clone()),
773 IambWindow::PinnedList(_, room_id, _) => IambId::PinnedList(room_id.clone()),
726 IambWindow::RoomList(_) => IambId::RoomList, 774 IambWindow::RoomList(_) => IambId::RoomList,
727 IambWindow::SpaceList(_) => IambId::SpaceList, 775 IambWindow::SpaceList(_) => IambId::SpaceList,
728 IambWindow::VerifyList(_) => IambId::VerifyList, 776 IambWindow::VerifyList(_) => IambId::VerifyList,
@@ -757,6 +805,16 @@ impl Window<IambInfo> for IambWindow {
757 ]; 805 ];
758 Line::from(v) 806 Line::from(v)
759 }, 807 },
808 IambWindow::PinnedList(state, room_id, _) => {
809 let title = store.application.get_room_title(room_id.as_ref());
810 let n = state.len();
811 let v = vec![
812 bold_span("Pinned Messages "),
813 Span::styled(format!("({n}): "), bold_style()),
814 title.into(),
815 ];
816 Line::from(v)
817 },
760 } 818 }
761 } 819 }
762 820
@@ -783,6 +841,16 @@ impl Window<IambInfo> for IambWindow {
783 ]; 841 ];
784 Line::from(v) 842 Line::from(v)
785 }, 843 },
844 IambWindow::PinnedList(state, room_id, _) => {
845 let title = store.application.get_room_title(room_id.as_ref());
846 let n = state.len();
847 let v = vec![
848 bold_span("Pinned Messages "),
849 Span::styled(format!("({n}): "), bold_style()),
850 title.into(),
851 ];
852 Line::from(v)
853 },
786 } 854 }
787 } 855 }
788 856
@@ -816,6 +884,13 @@ impl Window<IambInfo> for IambWindow {
816 884
817 return Ok(win); 885 return Ok(win);
818 }, 886 },
887 IambId::PinnedList(room_id) => {
888 let id = IambBufferId::PinnedList(room_id.clone());
889 let list = PinnedListState::new(id, vec![]);
890 let win = IambWindow::PinnedList(list, room_id, None);
891
892 return Ok(win);
893 },
819 IambId::RoomList => { 894 IambId::RoomList => {
820 let list = RoomListState::new(IambBufferId::RoomList, vec![]); 895 let list = RoomListState::new(IambBufferId::RoomList, vec![]);
821 896
@@ -1188,6 +1263,100 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
1188 } 1263 }
1189} 1264}
1190 1265
1266#[derive(Clone)]
1267pub struct PinnedItem {
1268 room_id: OwnedRoomId,
1269 event_id: OwnedEventId,
1270}
1271
1272impl PinnedItem {
1273 fn new(room_id: OwnedRoomId, event_id: OwnedEventId) -> Self {
1274 Self { room_id, event_id }
1275 }
1276}
1277
1278impl Display for PinnedItem {
1279 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1280 write!(f, "{}", self.event_id)
1281 }
1282}
1283
1284impl ListItem<IambInfo> for PinnedItem {
1285 fn show(
1286 &self,
1287 selected: bool,
1288 _: &ViewportContext<ListCursor>,
1289 store: &mut ProgramStore,
1290 ) -> Text<'_> {
1291 let info = store.application.rooms.get_or_default(self.room_id.clone());
1292 let settings = &store.application.settings;
1293
1294 let style = if selected {
1295 Style::default().add_modifier(StyleModifier::REVERSED)
1296 } else {
1297 Style::default()
1298 };
1299
1300 let Some(msg) = info.get_pinned(&self.event_id) else {
1301 let text = if info.pinned_unavailable(&self.event_id) {
1302 "Unable to load message"
1303 } else {
1304 "Loading pinned message..."
1305 };
1306
1307 return Span::styled(text, style.fg(Color::Gray)).into();
1308 };
1309
1310 let sender = settings.get_user_span(&msg.sender, info);
1311 let sender = Span::styled(sender.content.into_owned(), sender.style.patch(style));
1312 let time = format!(" [{}]: ", msg.timestamp.show_datetime());
1313 let body = msg.event.body().lines().next().unwrap_or_default().to_string();
1314
1315 Line::from(vec![sender, Span::styled(time, style), Span::styled(body, style)]).into()
1316 }
1317
1318 fn get_word(&self) -> Option<String> {
1319 self.event_id.to_string().into()
1320 }
1321}
1322
1323impl Promptable<ProgramContext, ProgramStore, IambInfo> for PinnedItem {
1324 fn prompt(
1325 &mut self,
1326 act: &PromptAction,
1327 ctx: &ProgramContext,
1328 store: &mut ProgramStore,
1329 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1330 match act {
1331 PromptAction::Submit => {
1332 let info = store.application.rooms.get_or_default(self.room_id.clone());
1333 let thread = info
1334 .get_message_location(&self.event_id)
1335 .and_then(|(thread, _)| thread)
1336 .map(ToOwned::to_owned);
1337
1338 let room = IambId::Room(self.room_id.clone(), thread);
1339 let open = WindowAction::Switch(OpenTarget::Application(room));
1340 let jump = IambAction::from(TimelineAction::GotoEvent(self.event_id.clone()));
1341
1342 Ok(vec![(open.into(), ctx.clone()), (jump.into(), ctx.clone())])
1343 },
1344 PromptAction::Abort(_) => {
1345 let msg = "Cannot abort entry inside a list";
1346 let err = EditError::Failure(msg.into());
1347
1348 Err(err)
1349 },
1350 PromptAction::Recall(..) => {
1351 let msg = "Cannot recall history inside a list";
1352 let err = EditError::Failure(msg.into());
1353
1354 Err(err)
1355 },
1356 }
1357 }
1358}
1359
1191#[cfg(test)] 1360#[cfg(test)]
1192mod tests { 1361mod tests {
1193 use super::*; 1362 use super::*;
src/windows/room/chat.rs +149 −1
@@ -12,6 +12,7 @@ use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo};
12use matrix_sdk::media::{MediaFormat, MediaRequestParameters}; 12use matrix_sdk::media::{MediaFormat, MediaRequestParameters};
13use matrix_sdk::room::reply::{EnforceThread, Reply}; 13use matrix_sdk::room::reply::{EnforceThread, Reply};
14use matrix_sdk::ruma::events::Mentions; 14use matrix_sdk::ruma::events::Mentions;
15use matrix_sdk::ruma::events::StateEventType;
15use matrix_sdk::ruma::events::reaction::ReactionEventContent; 16use matrix_sdk::ruma::events::reaction::ReactionEventContent;
16use matrix_sdk::ruma::events::relation::Annotation; 17use matrix_sdk::ruma::events::relation::Annotation;
17use matrix_sdk::ruma::events::room::message::{ 18use matrix_sdk::ruma::events::room::message::{
@@ -21,6 +22,7 @@ use matrix_sdk::ruma::events::room::message::{
21 ReplyWithinThread, 22 ReplyWithinThread,
22 TextMessageEventContent, 23 TextMessageEventContent,
23}; 24};
25use matrix_sdk::ruma::events::room::pinned_events::RoomPinnedEventsEventContent;
24use matrix_sdk::send_queue::RoomSendQueueError; 26use matrix_sdk::send_queue::RoomSendQueueError;
25use modalkit::editing::history::{self, HistoryList}; 27use modalkit::editing::history::{self, HistoryList};
26use modalkit::editing::store::RegisterError; 28use modalkit::editing::store::RegisterError;
@@ -30,7 +32,7 @@ use modalkit_ratatui::textbox::{TextBox, TextBoxState};
30use ratatui::prelude::Stylize; 32use ratatui::prelude::Stylize;
31use regex::Regex; 33use regex::Regex;
32 34
33use crate::base::{DownloadFlags, EchoLocation}; 35use crate::base::{DownloadFlags, EchoLocation, RoomFetchStatus};
34use crate::config::EncryptionIndicatorLocation; 36use crate::config::EncryptionIndicatorLocation;
35use crate::message::{ 37use crate::message::{
36 MessageId, 38 MessageId,
@@ -42,6 +44,11 @@ use crate::prelude::*;
42use crate::util::SuspendedTty; 44use crate::util::SuspendedTty;
43use crate::windows::room::scrollback::{Scrollback, ScrollbackState}; 45use crate::windows::room::scrollback::{Scrollback, ScrollbackState};
44 46
47/// How long to wait for a message to load before giving up on jumping to it.
48///
49/// History loads one page roughly every two seconds, for up to `MESSAGE_NEED_TTL` pages.
50const PENDING_JUMP_TIMEOUT: Duration = Duration::from_secs(120);
51
45/// State needed for rendering [Chat]. 52/// State needed for rendering [Chat].
46pub struct ChatState { 53pub struct ChatState {
47 room_id: OwnedRoomId, 54 room_id: OwnedRoomId,
@@ -56,6 +63,9 @@ pub struct ChatState {
56 63
57 reply_to: Option<MessageKey>, 64 reply_to: Option<MessageKey>,
58 editing: Option<MessageKey>, 65 editing: Option<MessageKey>,
66
67 /// A message to jump to once it has been loaded, and when the jump was requested.
68 pending_jump: Option<(OwnedEventId, Instant)>,
59} 69}
60 70
61impl ChatState { 71impl ChatState {
@@ -79,6 +89,7 @@ impl ChatState {
79 89
80 reply_to: None, 90 reply_to: None,
81 editing: None, 91 editing: None,
92 pending_jump: None,
82 } 93 }
83 } 94 }
84 95
@@ -122,6 +133,77 @@ impl ChatState {
122 } 133 }
123 } 134 }
124 135
136 /// Where to put the cursor for a loaded message.
137 ///
138 /// A thread reply can't be shown in the main timeline, so that lands on its thread root.
139 fn jump_target(&self, info: &RoomInfo, event_id: &EventId) -> Option<MessageKey> {
140 let (thread, key) = info.get_message_location(event_id)?;
141
142 match thread {
143 Some(root) if self.thread().is_none() => info.get_message_key(root).cloned(),
144 _ => Some(key.clone()),
145 }
146 }
147
148 fn jump_to_message(
149 &mut self,
150 event_id: OwnedEventId,
151 store: &mut ProgramStore,
152 ) -> IambResult<EditInfo> {
153 let info = store.application.rooms.get_or_default(self.room_id.clone());
154
155 if let Some(key) = self.jump_target(info, &event_id) {
156 self.pending_jump = None;
157 self.scrollback.goto_message(key);
158 self.focus = RoomFocus::Scrollback;
159
160 return Ok(None);
161 }
162
163 store
164 .application
165 .need_load
166 .need_message(self.room_id.clone(), event_id.clone());
167 self.pending_jump = Some((event_id, Instant::now()));
168
169 let msg = "Loading message; will jump to it once it arrives";
170 Ok(Some(InfoMessage::from(msg)))
171 }
172
173 /// Finish a jump that was waiting on its message to load.
174 fn complete_pending_jump(&mut self, store: &mut ProgramStore) {
175 let Some((event_id, requested)) = &self.pending_jump else {
176 return;
177 };
178
179 let info = store.application.rooms.get_or_default(self.room_id.clone());
180
181 if let Some(key) = self.jump_target(info, event_id) {
182 self.pending_jump = None;
183 self.scrollback.goto_message(key);
184 self.focus = RoomFocus::Scrollback;
185 } else if matches!(info.fetch_id, RoomFetchStatus::Done) ||
186 requested.elapsed() >= PENDING_JUMP_TIMEOUT
187 {
188 // The whole history is loaded without it, or it's too far back to find.
189 self.pending_jump = None;
190
191 let msg = "Unable to jump to message: it's too far back in the room's history";
192 store.application.draw_error = Some(msg.into());
193 }
194 }
195
196 pub async fn timeline_command(
197 &mut self,
198 act: TimelineAction,
199 _: ProgramContext,
200 store: &mut ProgramStore,
201 ) -> IambResult<EditInfo> {
202 match act {
203 TimelineAction::GotoEvent(event_id) => self.jump_to_message(event_id, store),
204 }
205 }
206
125 pub async fn message_command( 207 pub async fn message_command(
126 &mut self, 208 &mut self,
127 act: MessageAction, 209 act: MessageAction,
@@ -354,6 +436,69 @@ impl ChatState {
354 436
355 Ok(None) 437 Ok(None)
356 }, 438 },
439 MessageAction::Pin | MessageAction::Unpin => {
440 let pin = act == MessageAction::Pin;
441
442 let event_id = match &msg.event {
443 MessageEvent::Local(..) => {
444 let msg = "Cannot pin a message that hasn't been sent yet";
445 return Err(UIError::Failure(msg.into()));
446 },
447 MessageEvent::Redacted(..) | MessageEvent::EncryptedRedacted(_) if pin => {
448 let msg = "Cannot pin a redacted message";
449 return Err(UIError::Failure(msg.into()));
450 },
451 event => {
452 event
453 .event_id()
454 .map(ToOwned::to_owned)
455 .ok_or(IambError::NoSelectedMessage)?
456 },
457 };
458
459 let room = self.get_joined(&store.application.worker)?;
460
461 let can_pin = room
462 .power_levels()
463 .await
464 .map_err(matrix_sdk::Error::from)
465 .map_err(IambError::from)?
466 .user_can_send_state(
467 &settings.profile.user_id,
468 StateEventType::RoomPinnedEvents,
469 );
470
471 if !can_pin {
472 return Err(IambError::InsufficientPermission.into());
473 }
474
475 // The state event holds the whole list, so rebuild it from the SDK's latest copy.
476 let mut pinned = room.pinned_event_ids().unwrap_or_default();
477 let position = pinned.iter().position(|id| *id == event_id);
478
479 match (pin, position) {
480 (true, Some(_)) => {
481 let msg = "This message is already pinned";
482 return Err(UIError::Failure(msg.into()));
483 },
484 (false, None) => {
485 let msg = "This message is not pinned";
486 return Err(UIError::Failure(msg.into()));
487 },
488 (true, None) => {
489 pinned.push(event_id);
490 },
491 (false, Some(idx)) => {
492 pinned.remove(idx);
493 },
494 }
495
496 room.send_state_event(RoomPinnedEventsEventContent::new(pinned))
497 .await
498 .map_err(IambError::from)?;
499
500 Ok(None)
501 },
357 MessageAction::Redact(reason, skip_confirm) => { 502 MessageAction::Redact(reason, skip_confirm) => {
358 if !skip_confirm { 503 if !skip_confirm {
359 let msg = "Are you sure you want to redact this message?"; 504 let msg = "Are you sure you want to redact this message?";
@@ -874,6 +1019,7 @@ impl WindowOps<IambInfo> for ChatState {
874 1019
875 reply_to: None, 1020 reply_to: None,
876 editing: None, 1021 editing: None,
1022 pending_jump: None,
877 } 1023 }
878 } 1024 }
879 1025
@@ -1108,6 +1254,8 @@ impl StatefulWidget for Chat<'_> {
1108 type State = ChatState; 1254 type State = ChatState;
1109 1255
1110 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { 1256 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1257 state.complete_pending_jump(self.store);
1258
1111 let settings = &self.store.application.settings; 1259 let settings = &self.store.application.settings;
1112 1260
1113 // Determine whether we have a description to show for the message bar. 1261 // Determine whether we have a description to show for the message bar.
src/windows/room/mod.rs +20
@@ -209,6 +209,13 @@ pub async fn room_command(
209 209
210 Ok(vec![(act, cmd.context.clone())]) 210 Ok(vec![(act, cmd.context.clone())])
211 }, 211 },
212 RoomAction::Pinned(cmd) => {
213 let id = IambId::PinnedList(id.to_owned());
214 let target = OpenTarget::Application(id);
215 let act = cmd.switch(target);
216
217 Ok(vec![(act, cmd.context.clone())])
218 },
212 RoomAction::SetAccess(rule) => { 219 RoomAction::SetAccess(rule) => {
213 let Some(room) = store.application.worker.client.get_room(id) else { 220 let Some(room) = store.application.worker.client.get_room(id) else {
214 return Err(IambError::NotJoined.into()); 221 return Err(IambError::NotJoined.into());
@@ -832,6 +839,19 @@ impl RoomState {
832 return; 839 return;
833 } 840 }
834 841
842 pub async fn timeline_command(
843 &mut self,
844 act: TimelineAction,
845 ctx: ProgramContext,
846 store: &mut ProgramStore,
847 ) -> IambResult<EditInfo> {
848 if let RoomState::Chat(chat) = self {
849 chat.timeline_command(act, ctx, store).await
850 } else {
851 Err(IambError::NoSelectedRoom.into())
852 }
853 }
854
835 pub async fn message_command( 855 pub async fn message_command(
836 &mut self, 856 &mut self,
837 act: MessageAction, 857 act: MessageAction,
src/windows/room/scrollback.rs +5 −1
@@ -1555,7 +1555,11 @@ mod tests {
1555 std::mem::take(&mut store.application.need_load) 1555 std::mem::take(&mut store.application.need_load)
1556 .into_iter() 1556 .into_iter()
1557 .collect::<Vec<(OwnedRoomId, Need)>>(), 1557 .collect::<Vec<(OwnedRoomId, Need)>>(),
1558 vec![(room_id.clone(), Need { messages: Some(Vec::new()), members: false })] 1558 vec![(room_id.clone(), Need {
1559 messages: Some(Vec::new()),
1560 members: false,
1561 pinned: false
1562 })]
1559 ); 1563 );
1560 1564
1561 // Search forward twice to MSG1. 1565 // Search forward twice to MSG1.
src/worker.rs +79
@@ -52,6 +52,7 @@ use matrix_sdk::ruma::events::receipt::{ReceiptEventContent, ReceiptType};
52use matrix_sdk::ruma::events::room::encryption::RoomEncryptionEventContent; 52use matrix_sdk::ruma::events::room::encryption::RoomEncryptionEventContent;
53use matrix_sdk::ruma::events::room::member::{MembershipState, OriginalSyncRoomMemberEvent}; 53use matrix_sdk::ruma::events::room::member::{MembershipState, OriginalSyncRoomMemberEvent};
54use matrix_sdk::ruma::events::room::name::RoomNameEventContent; 54use matrix_sdk::ruma::events::room::name::RoomNameEventContent;
55use matrix_sdk::ruma::events::room::pinned_events::SyncRoomPinnedEventsEvent;
55use matrix_sdk::ruma::events::room::redaction::OriginalSyncRoomRedactionEvent; 56use matrix_sdk::ruma::events::room::redaction::OriginalSyncRoomRedactionEvent;
56use matrix_sdk::ruma::events::sticker::StickerEventContent; 57use matrix_sdk::ruma::events::sticker::StickerEventContent;
57use matrix_sdk::ruma::events::typing::SyncTypingEvent; 58use matrix_sdk::ruma::events::typing::SyncTypingEvent;
@@ -179,6 +180,7 @@ async fn update_event_receipts(info: &mut RoomInfo, room: &MatrixRoom, event_id:
179enum Plan { 180enum Plan {
180 Messages(OwnedRoomId, Option<String>, Vec<MessageNeed>), 181 Messages(OwnedRoomId, Option<String>, Vec<MessageNeed>),
181 Members(OwnedRoomId), 182 Members(OwnedRoomId),
183 Pinned(OwnedRoomId, Vec<OwnedEventId>),
182} 184}
183 185
184async fn load_plans(store: &AsyncProgramStore) -> Vec<Plan> { 186async fn load_plans(store: &AsyncProgramStore) -> Vec<Plan> {
@@ -187,6 +189,13 @@ async fn load_plans(store: &AsyncProgramStore) -> Vec<Plan> {
187 let mut plan = Vec::with_capacity(need_load.rooms() * 2); 189 let mut plan = Vec::with_capacity(need_load.rooms() * 2);
188 190
189 for (room_id, need) in std::mem::take(need_load).into_iter() { 191 for (room_id, need) in std::mem::take(need_load).into_iter() {
192 if need.pinned {
193 let missing = rooms.get_or_default(room_id.clone()).missing_pinned();
194
195 if !missing.is_empty() {
196 plan.push(Plan::Pinned(room_id.to_owned(), missing));
197 }
198 }
190 if let Some(message_need) = need.messages { 199 if let Some(message_need) = need.messages {
191 let info = rooms.get_or_default(room_id.clone()); 200 let info = rooms.get_or_default(room_id.clone());
192 201
@@ -227,10 +236,60 @@ async fn run_plan(client: &Client, store: &AsyncProgramStore, plan: Plan, permit
227 let mut locked = store.lock().await; 236 let mut locked = store.lock().await;
228 members_insert(room_id, res, locked.deref_mut()); 237 members_insert(room_id, res, locked.deref_mut());
229 }, 238 },
239 Plan::Pinned(room_id, event_ids) => {
240 let msgs = pinned_load(client, &room_id, event_ids).await;
241 let mut locked = store.lock().await;
242 let info = locked.application.get_room_info(room_id);
243
244 for (event_id, msg) in msgs {
245 info.insert_pinned(event_id, msg);
246 }
247 },
230 } 248 }
231 drop(permit); 249 drop(permit);
232} 250}
233 251
252async fn pinned_load(
253 client: &Client,
254 room_id: &RoomId,
255 event_ids: Vec<OwnedEventId>,
256) -> Vec<(OwnedEventId, Option<Message>)> {
257 let Some(room) = client.get_room(room_id) else {
258 return vec![];
259 };
260
261 let mut msgs = vec![];
262
263 for event_id in event_ids {
264 let msg = pinned_load_one(&room, room_id, &event_id).await;
265 msgs.push((event_id, msg));
266 }
267
268 msgs
269}
270
271async fn pinned_load_one(
272 room: &MatrixRoom,
273 room_id: &RoomId,
274 event_id: &EventId,
275) -> Option<Message> {
276 let ev = room
277 .load_or_fetch_event(event_id, None)
278 .await
279 .inspect_err(|e| warn!(?event_id, "failed to fetch pinned event: {e}"))
280 .ok()?;
281
282 let msg = match ev.into_raw().deserialize().ok()?.into_full_event(room_id.to_owned()) {
283 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(ev)) => ev.into(),
284 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomEncrypted(ev)) => ev.into(),
285 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => ev.into(),
286 AnyTimelineEvent::MessageLike(_) => return None,
287 AnyTimelineEvent::State(ev) => Message::from(AnySyncStateEvent::from(ev)),
288 };
289
290 Some(msg)
291}
292
234async fn load_older_one( 293async fn load_older_one(
235 client: &Client, 294 client: &Client,
236 room_id: &RoomId, 295 room_id: &RoomId,
@@ -440,6 +499,7 @@ async fn load_older_forever(client: &Client, store: &AsyncProgramStore) {
440} 499}
441 500
442async fn refresh_rooms(client: &Client, store: &AsyncProgramStore, first_sync: bool) { 501async fn refresh_rooms(client: &Client, store: &AsyncProgramStore, first_sync: bool) {
502 let mut pinned = vec![];
443 let mut names_and_tags = vec![]; 503 let mut names_and_tags = vec![];
444 504
445 let mut spaces = vec![]; 505 let mut spaces = vec![];
@@ -465,6 +525,7 @@ async fn refresh_rooms(client: &Client, store: &AsyncProgramStore, first_sync: b
465 let name = display.to_string(); 525 let name = display.to_string();
466 let tags = room.tags().await.unwrap_or_default(); 526 let tags = room.tags().await.unwrap_or_default();
467 527
528 pinned.push((room.room_id().to_owned(), room.pinned_event_ids().unwrap_or_default()));
468 names_and_tags.push((room.room_id().to_owned(), name, tags)); 529 names_and_tags.push((room.room_id().to_owned(), name, tags));
469 530
470 if room.is_direct().await.unwrap_or_default() { 531 if room.is_direct().await.unwrap_or_default() {
@@ -484,6 +545,10 @@ async fn refresh_rooms(client: &Client, store: &AsyncProgramStore, first_sync: b
484 for (room_id, name, tags) in names_and_tags { 545 for (room_id, name, tags) in names_and_tags {
485 locked.application.set_room_info(room_id, name, tags); 546 locked.application.set_room_info(room_id, name, tags);
486 } 547 }
548
549 for (room_id, pinned_events) in pinned {
550 locked.application.get_room_info(room_id).pinned_events = pinned_events;
551 }
487} 552}
488 553
489async fn refresh_rooms_forever(client: &Client, store: &AsyncProgramStore) { 554async fn refresh_rooms_forever(client: &Client, store: &AsyncProgramStore) {
@@ -1565,6 +1630,20 @@ impl ClientWorker {
1565 }, 1630 },
1566 ); 1631 );
1567 1632
1633 let _ = self.client.add_event_handler(
1634 |_: SyncRoomPinnedEventsEvent, room: MatrixRoom, store: Ctx<AsyncProgramStore>| {
1635 async move {
1636 // The SDK has already applied the event to its room state by the time
1637 // handlers run, and it also copes with redacted pin lists.
1638 let pinned = room.pinned_event_ids().unwrap_or_default();
1639
1640 let mut locked = store.lock().await;
1641 let info = locked.application.get_room_info(room.room_id().to_owned());
1642 info.pinned_events = pinned;
1643 }
1644 },
1645 );
1646
1568 let _ = self.client.add_event_handler( 1647 let _ = self.client.add_event_handler(
1569 |ev: OriginalSyncRoomMemberEvent, room: MatrixRoom, store: Ctx<AsyncProgramStore>| { 1648 |ev: OriginalSyncRoomMemberEvent, room: MatrixRoom, store: Ctx<AsyncProgramStore>| {
1570 async move { 1649 async move {