src/windows/mod.rs
1368 lines · 41473 bytes
1//! # Windows for the User Interface
2//!
3//! This module contains the logic for rendering windows, and handling UI actions that get
4//! delegated to individual windows/UI elements (e.g., typing text or selecting a list item).
5//!
6//! Additionally, some of the iamb commands delegate behaviour to the current UI element. For
7//! example, [sending messages][crate::base::SendAction] delegate to the [room window][RoomState],
8//! where we have the message bar and room ID easily accesible and resetable.
9use std::cmp::{Ord, Ordering, PartialOrd};
10use std::ops::Deref;
11use std::sync::Arc;
12use std::time::{Duration, Instant};
13
14use matrix_sdk::{
15 encryption::verification::{format_emojis, SasVerification},
16 room::{Room as MatrixRoom, RoomMember},
17 ruma::{
18 events::room::member::MembershipState,
19 events::tag::{TagName, Tags},
20 OwnedRoomAliasId,
21 OwnedRoomId,
22 RoomAliasId,
23 RoomId,
24 },
25};
26
27use modalkit::tui::{
28 buffer::Buffer,
29 layout::{Alignment, Rect},
30 style::{Modifier as StyleModifier, Style},
31 text::{Line, Span, Text},
32 widgets::StatefulWidget,
33};
34
35use modalkit::{
36 editing::{
37 action::{
38 Action,
39 EditError,
40 EditInfo,
41 EditResult,
42 Editable,
43 EditorAction,
44 Jumpable,
45 PromptAction,
46 Promptable,
47 Scrollable,
48 UIError,
49 WindowAction,
50 },
51 base::{
52 CloseFlags,
53 MoveDir1D,
54 OpenTarget,
55 PositionList,
56 ScrollStyle,
57 ViewportContext,
58 WordStyle,
59 WriteFlags,
60 },
61 completion::CompletionList,
62 },
63 widgets::{
64 list::{List, ListCursor, ListItem, ListState},
65 TermOffset,
66 TerminalCursor,
67 Window,
68 WindowOps,
69 },
70};
71
72use crate::base::{
73 ChatStore,
74 IambBufferId,
75 IambError,
76 IambId,
77 IambInfo,
78 IambResult,
79 MessageAction,
80 Need,
81 ProgramAction,
82 ProgramContext,
83 ProgramStore,
84 RoomAction,
85 SendAction,
86 SortColumn,
87 SortFieldRoom,
88 SortFieldUser,
89 SortOrder,
90};
91
92use self::{room::RoomState, welcome::WelcomeState};
93
94pub mod room;
95pub mod welcome;
96
97type MatrixRoomInfo = Arc<(MatrixRoom, Option<Tags>)>;
98
99const MEMBER_FETCH_DEBOUNCE: Duration = Duration::from_secs(5);
100
101#[inline]
102fn bold_style() -> Style {
103 Style::default().add_modifier(StyleModifier::BOLD)
104}
105
106#[inline]
107fn bold_span(s: &str) -> Span {
108 Span::styled(s, bold_style())
109}
110
111#[inline]
112fn bold_spans(s: &str) -> Line {
113 bold_span(s).into()
114}
115
116#[inline]
117fn selected_style(selected: bool) -> Style {
118 if selected {
119 Style::default().add_modifier(StyleModifier::REVERSED)
120 } else {
121 Style::default()
122 }
123}
124
125#[inline]
126fn selected_span(s: &str, selected: bool) -> Span {
127 Span::styled(s, selected_style(selected))
128}
129
130#[inline]
131fn selected_text(s: &str, selected: bool) -> Text {
132 Text::from(selected_span(s, selected))
133}
134
135/// Sort `Some` to be less than `None` so that list items with values come before those without.
136#[inline]
137fn some_cmp<T: Ord>(a: Option<T>, b: Option<T>) -> Ordering {
138 match (a, b) {
139 (Some(a), Some(b)) => a.cmp(&b),
140 (None, None) => Ordering::Equal,
141 (None, Some(_)) => Ordering::Greater,
142 (Some(_), None) => Ordering::Less,
143 }
144}
145
146fn user_cmp(a: &MemberItem, b: &MemberItem, field: &SortFieldUser) -> Ordering {
147 let a_id = a.member.user_id();
148 let b_id = b.member.user_id();
149
150 match field {
151 SortFieldUser::UserId => a_id.cmp(b_id),
152 SortFieldUser::LocalPart => a_id.localpart().cmp(b_id.localpart()),
153 SortFieldUser::Server => a_id.server_name().cmp(b_id.server_name()),
154 SortFieldUser::PowerLevel => {
155 // Sort higher power levels towards the top of the list.
156 b.member.power_level().cmp(&a.member.power_level())
157 },
158 }
159}
160
161fn room_cmp<T: RoomLikeItem>(a: &T, b: &T, field: &SortFieldRoom) -> Ordering {
162 match field {
163 SortFieldRoom::Favorite => {
164 let fava = a.has_tag(TagName::Favorite);
165 let favb = b.has_tag(TagName::Favorite);
166
167 // If a has Favorite and b doesn't, it should sort earlier in room list.
168 favb.cmp(&fava)
169 },
170 SortFieldRoom::LowPriority => {
171 let lowa = a.has_tag(TagName::LowPriority);
172 let lowb = b.has_tag(TagName::LowPriority);
173
174 // If a has LowPriority and b doesn't, it should sort later in room list.
175 lowa.cmp(&lowb)
176 },
177 SortFieldRoom::Name => a.name().cmp(b.name()),
178 SortFieldRoom::Alias => some_cmp(a.alias(), b.alias()),
179 SortFieldRoom::RoomId => a.room_id().cmp(b.room_id()),
180 }
181}
182
183/// Compare two rooms according the configured sort criteria.
184fn room_fields_cmp<T: RoomLikeItem>(
185 a: &T,
186 b: &T,
187 fields: &[SortColumn<SortFieldRoom>],
188) -> Ordering {
189 for SortColumn(field, order) in fields {
190 match (room_cmp(a, b, field), order) {
191 (Ordering::Equal, _) => continue,
192 (o, SortOrder::Ascending) => return o,
193 (o, SortOrder::Descending) => return o.reverse(),
194 }
195 }
196
197 // Break ties on ascending room id.
198 room_cmp(a, b, &SortFieldRoom::RoomId)
199}
200
201fn user_fields_cmp(
202 a: &MemberItem,
203 b: &MemberItem,
204 fields: &[SortColumn<SortFieldUser>],
205) -> Ordering {
206 for SortColumn(field, order) in fields {
207 match (user_cmp(a, b, field), order) {
208 (Ordering::Equal, _) => continue,
209 (o, SortOrder::Ascending) => return o,
210 (o, SortOrder::Descending) => return o.reverse(),
211 }
212 }
213
214 // Break ties on ascending user id.
215 user_cmp(a, b, &SortFieldUser::UserId)
216}
217
218fn append_tags<'a>(tags: &'a Tags, spans: &mut Vec<Span<'a>>, style: Style) {
219 if tags.is_empty() {
220 return;
221 }
222
223 spans.push(Span::styled(" (", style));
224
225 for (i, tag) in tags.keys().enumerate() {
226 if i > 0 {
227 spans.push(Span::styled(", ", style));
228 }
229
230 match tag {
231 TagName::Favorite => spans.push(Span::styled("Favorite", style)),
232 TagName::LowPriority => spans.push(Span::styled("Low Priority", style)),
233 TagName::ServerNotice => spans.push(Span::styled("Server Notice", style)),
234 TagName::User(tag) => {
235 spans.push(Span::styled("User Tag: ", style));
236 spans.push(Span::styled(tag.as_ref(), style));
237 },
238 tag => spans.push(Span::styled(format!("{tag:?}"), style)),
239 }
240 }
241
242 spans.push(Span::styled(")", style));
243}
244
245trait RoomLikeItem {
246 fn room_id(&self) -> &RoomId;
247 fn has_tag(&self, tag: TagName) -> bool;
248 fn alias(&self) -> Option<&RoomAliasId>;
249 fn name(&self) -> &str;
250}
251
252#[inline]
253fn room_prompt(
254 room_id: &RoomId,
255 act: &PromptAction,
256 ctx: &ProgramContext,
257) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
258 match act {
259 PromptAction::Submit => {
260 let room = IambId::Room(room_id.to_owned());
261 let open = WindowAction::Switch(OpenTarget::Application(room));
262 let acts = vec![(open.into(), ctx.clone())];
263
264 Ok(acts)
265 },
266 PromptAction::Abort(_) => {
267 let msg = "Cannot abort entry inside a list";
268 let err = EditError::Failure(msg.into());
269
270 Err(err)
271 },
272 PromptAction::Recall(..) => {
273 let msg = "Cannot recall history inside a list";
274 let err = EditError::Failure(msg.into());
275
276 Err(err)
277 },
278 _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
279 }
280}
281
282macro_rules! delegate {
283 ($s: expr, $id: ident => $e: expr) => {
284 match $s {
285 IambWindow::Room($id) => $e,
286 IambWindow::DirectList($id) => $e,
287 IambWindow::MemberList($id, _, _) => $e,
288 IambWindow::RoomList($id) => $e,
289 IambWindow::SpaceList($id) => $e,
290 IambWindow::VerifyList($id) => $e,
291 IambWindow::Welcome($id) => $e,
292 }
293 };
294}
295
296pub enum IambWindow {
297 DirectList(DirectListState),
298 MemberList(MemberListState, OwnedRoomId, Option<Instant>),
299 Room(RoomState),
300 VerifyList(VerifyListState),
301 RoomList(RoomListState),
302 SpaceList(SpaceListState),
303 Welcome(WelcomeState),
304}
305
306impl IambWindow {
307 pub fn focus_toggle(&mut self) {
308 if let IambWindow::Room(w) = self {
309 w.focus_toggle()
310 } else {
311 return;
312 }
313 }
314
315 pub async fn message_command(
316 &mut self,
317 act: MessageAction,
318 ctx: ProgramContext,
319 store: &mut ProgramStore,
320 ) -> IambResult<EditInfo> {
321 if let IambWindow::Room(w) = self {
322 w.message_command(act, ctx, store).await
323 } else {
324 return Err(IambError::NoSelectedRoom.into());
325 }
326 }
327
328 pub async fn room_command(
329 &mut self,
330 act: RoomAction,
331 ctx: ProgramContext,
332 store: &mut ProgramStore,
333 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
334 if let IambWindow::Room(w) = self {
335 w.room_command(act, ctx, store).await
336 } else {
337 return Err(IambError::NoSelectedRoomOrSpace.into());
338 }
339 }
340
341 pub async fn send_command(
342 &mut self,
343 act: SendAction,
344 ctx: ProgramContext,
345 store: &mut ProgramStore,
346 ) -> IambResult<EditInfo> {
347 if let IambWindow::Room(w) = self {
348 w.send_command(act, ctx, store).await
349 } else {
350 return Err(IambError::NoSelectedRoom.into());
351 }
352 }
353}
354
355pub type DirectListState = ListState<DirectItem, IambInfo>;
356pub type MemberListState = ListState<MemberItem, IambInfo>;
357pub type RoomListState = ListState<RoomItem, IambInfo>;
358pub type SpaceListState = ListState<SpaceItem, IambInfo>;
359pub type VerifyListState = ListState<VerifyItem, IambInfo>;
360
361impl From<RoomState> for IambWindow {
362 fn from(room: RoomState) -> Self {
363 IambWindow::Room(room)
364 }
365}
366
367impl From<VerifyListState> for IambWindow {
368 fn from(list: VerifyListState) -> Self {
369 IambWindow::VerifyList(list)
370 }
371}
372
373impl From<DirectListState> for IambWindow {
374 fn from(list: DirectListState) -> Self {
375 IambWindow::DirectList(list)
376 }
377}
378
379impl From<RoomListState> for IambWindow {
380 fn from(list: RoomListState) -> Self {
381 IambWindow::RoomList(list)
382 }
383}
384
385impl From<SpaceListState> for IambWindow {
386 fn from(list: SpaceListState) -> Self {
387 IambWindow::SpaceList(list)
388 }
389}
390
391impl From<WelcomeState> for IambWindow {
392 fn from(win: WelcomeState) -> Self {
393 IambWindow::Welcome(win)
394 }
395}
396
397impl Editable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
398 fn editor_command(
399 &mut self,
400 act: &EditorAction,
401 ctx: &ProgramContext,
402 store: &mut ProgramStore,
403 ) -> EditResult<EditInfo, IambInfo> {
404 delegate!(self, w => w.editor_command(act, ctx, store))
405 }
406}
407
408impl Jumpable<ProgramContext, IambInfo> for IambWindow {
409 fn jump(
410 &mut self,
411 list: PositionList,
412 dir: MoveDir1D,
413 count: usize,
414 ctx: &ProgramContext,
415 ) -> IambResult<usize> {
416 delegate!(self, w => w.jump(list, dir, count, ctx))
417 }
418}
419
420impl Scrollable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
421 fn scroll(
422 &mut self,
423 style: &ScrollStyle,
424 ctx: &ProgramContext,
425 store: &mut ProgramStore,
426 ) -> EditResult<EditInfo, IambInfo> {
427 delegate!(self, w => w.scroll(style, ctx, store))
428 }
429}
430
431impl Promptable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
432 fn prompt(
433 &mut self,
434 act: &PromptAction,
435 ctx: &ProgramContext,
436 store: &mut ProgramStore,
437 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
438 delegate!(self, w => w.prompt(act, ctx, store))
439 }
440}
441
442impl TerminalCursor for IambWindow {
443 fn get_term_cursor(&self) -> Option<TermOffset> {
444 delegate!(self, w => w.get_term_cursor())
445 }
446}
447
448impl WindowOps<IambInfo> for IambWindow {
449 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
450 match self {
451 IambWindow::Room(state) => state.draw(area, buf, focused, store),
452 IambWindow::DirectList(state) => {
453 let mut items = store
454 .application
455 .sync_info
456 .dms
457 .clone()
458 .into_iter()
459 .map(|room_info| DirectItem::new(room_info, store))
460 .collect::<Vec<_>>();
461 let fields = &store.application.settings.tunables.sort.dms;
462 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
463
464 state.set(items);
465
466 List::new(store)
467 .empty_message("No direct messages yet!")
468 .empty_alignment(Alignment::Center)
469 .focus(focused)
470 .render(area, buf, state);
471 },
472 IambWindow::MemberList(state, room_id, last_fetch) => {
473 let need_fetch = match last_fetch {
474 Some(i) => i.elapsed() >= MEMBER_FETCH_DEBOUNCE,
475 None => true,
476 };
477
478 if need_fetch {
479 if let Ok(mems) = store.application.worker.members(room_id.clone()) {
480 let mut items = mems
481 .into_iter()
482 .map(|m| MemberItem::new(m, room_id.clone()))
483 .collect::<Vec<_>>();
484 let fields = &store.application.settings.tunables.sort.members;
485 items.sort_by(|a, b| user_fields_cmp(a, b, fields));
486 state.set(items);
487 *last_fetch = Some(Instant::now());
488 }
489 }
490
491 List::new(store)
492 .empty_message("No users here yet!")
493 .empty_alignment(Alignment::Center)
494 .focus(focused)
495 .render(area, buf, state);
496 },
497 IambWindow::RoomList(state) => {
498 let mut items = store
499 .application
500 .sync_info
501 .rooms
502 .clone()
503 .into_iter()
504 .map(|room_info| RoomItem::new(room_info, store))
505 .collect::<Vec<_>>();
506 let fields = &store.application.settings.tunables.sort.rooms;
507 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
508
509 state.set(items);
510
511 List::new(store)
512 .empty_message("You haven't joined any rooms yet")
513 .empty_alignment(Alignment::Center)
514 .focus(focused)
515 .render(area, buf, state);
516 },
517 IambWindow::SpaceList(state) => {
518 let mut items = store
519 .application
520 .sync_info
521 .spaces
522 .clone()
523 .into_iter()
524 .map(|room| SpaceItem::new(room, store))
525 .collect::<Vec<_>>();
526 let fields = &store.application.settings.tunables.sort.spaces;
527 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
528
529 state.set(items);
530
531 List::new(store)
532 .empty_message("You haven't joined any spaces yet")
533 .empty_alignment(Alignment::Center)
534 .focus(focused)
535 .render(area, buf, state);
536 },
537 IambWindow::VerifyList(state) => {
538 let verifications = &store.application.verifications;
539 let mut items = verifications.iter().map(VerifyItem::from).collect::<Vec<_>>();
540
541 // Sort the active verifications towards the top.
542 items.sort();
543
544 state.set(items);
545
546 List::new(store)
547 .empty_message("No in-progress verifications")
548 .empty_alignment(Alignment::Center)
549 .focus(focused)
550 .render(area, buf, state);
551 },
552 IambWindow::Welcome(state) => state.draw(area, buf, focused, store),
553 }
554 }
555
556 fn dup(&self, store: &mut ProgramStore) -> Self {
557 match self {
558 IambWindow::Room(w) => w.dup(store).into(),
559 IambWindow::DirectList(w) => w.dup(store).into(),
560 IambWindow::MemberList(w, room_id, last_fetch) => {
561 IambWindow::MemberList(w.dup(store), room_id.clone(), *last_fetch)
562 },
563 IambWindow::RoomList(w) => w.dup(store).into(),
564 IambWindow::SpaceList(w) => w.dup(store).into(),
565 IambWindow::VerifyList(w) => w.dup(store).into(),
566 IambWindow::Welcome(w) => w.dup(store).into(),
567 }
568 }
569
570 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
571 delegate!(self, w => w.close(flags, store))
572 }
573
574 fn write(
575 &mut self,
576 path: Option<&str>,
577 flags: WriteFlags,
578 store: &mut ProgramStore,
579 ) -> IambResult<EditInfo> {
580 delegate!(self, w => w.write(path, flags, store))
581 }
582
583 fn get_completions(&self) -> Option<CompletionList> {
584 delegate!(self, w => w.get_completions())
585 }
586
587 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
588 delegate!(self, w => w.get_cursor_word(style))
589 }
590
591 fn get_selected_word(&self) -> Option<String> {
592 delegate!(self, w => w.get_selected_word())
593 }
594}
595
596impl Window<IambInfo> for IambWindow {
597 fn id(&self) -> IambId {
598 match self {
599 IambWindow::Room(room) => IambId::Room(room.id().to_owned()),
600 IambWindow::DirectList(_) => IambId::DirectList,
601 IambWindow::MemberList(_, room_id, _) => IambId::MemberList(room_id.clone()),
602 IambWindow::RoomList(_) => IambId::RoomList,
603 IambWindow::SpaceList(_) => IambId::SpaceList,
604 IambWindow::VerifyList(_) => IambId::VerifyList,
605 IambWindow::Welcome(_) => IambId::Welcome,
606 }
607 }
608
609 fn get_tab_title(&self, store: &mut ProgramStore) -> Line {
610 match self {
611 IambWindow::DirectList(_) => bold_spans("Direct Messages"),
612 IambWindow::RoomList(_) => bold_spans("Rooms"),
613 IambWindow::SpaceList(_) => bold_spans("Spaces"),
614 IambWindow::VerifyList(_) => bold_spans("Verifications"),
615 IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
616
617 IambWindow::Room(w) => {
618 let title = store.application.get_room_title(w.id());
619
620 Line::from(title)
621 },
622 IambWindow::MemberList(state, room_id, _) => {
623 let title = store.application.get_room_title(room_id.as_ref());
624 let n = state.len();
625 let v = vec![
626 bold_span("Room Members "),
627 Span::styled(format!("({n}): "), bold_style()),
628 title.into(),
629 ];
630 Line::from(v)
631 },
632 }
633 }
634
635 fn get_win_title(&self, store: &mut ProgramStore) -> Line {
636 match self {
637 IambWindow::DirectList(_) => bold_spans("Direct Messages"),
638 IambWindow::RoomList(_) => bold_spans("Rooms"),
639 IambWindow::SpaceList(_) => bold_spans("Spaces"),
640 IambWindow::VerifyList(_) => bold_spans("Verifications"),
641 IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
642
643 IambWindow::Room(w) => w.get_title(store),
644 IambWindow::MemberList(state, room_id, _) => {
645 let title = store.application.get_room_title(room_id.as_ref());
646 let n = state.len();
647 let v = vec![
648 bold_span("Room Members "),
649 Span::styled(format!("({n}): "), bold_style()),
650 title.into(),
651 ];
652 Line::from(v)
653 },
654 }
655 }
656
657 fn open(id: IambId, store: &mut ProgramStore) -> IambResult<Self> {
658 match id {
659 IambId::Room(room_id) => {
660 let (room, name, tags) = store.application.worker.get_room(room_id)?;
661 let room = RoomState::new(room, name, tags, store);
662
663 store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
664 return Ok(room.into());
665 },
666 IambId::DirectList => {
667 let list = DirectListState::new(IambBufferId::DirectList, vec![]);
668
669 return Ok(list.into());
670 },
671 IambId::MemberList(room_id) => {
672 let id = IambBufferId::MemberList(room_id.clone());
673 let list = MemberListState::new(id, vec![]);
674 let win = IambWindow::MemberList(list, room_id, None);
675
676 return Ok(win);
677 },
678 IambId::RoomList => {
679 let list = RoomListState::new(IambBufferId::RoomList, vec![]);
680
681 return Ok(list.into());
682 },
683 IambId::SpaceList => {
684 let list = SpaceListState::new(IambBufferId::SpaceList, vec![]);
685
686 return Ok(list.into());
687 },
688 IambId::VerifyList => {
689 let list = VerifyListState::new(IambBufferId::VerifyList, vec![]);
690
691 return Ok(list.into());
692 },
693 IambId::Welcome => {
694 let win = WelcomeState::new(store);
695
696 return Ok(win.into());
697 },
698 }
699 }
700
701 fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
702 let ChatStore { names, worker, .. } = &mut store.application;
703
704 if let Some(room) = names.get_mut(&name) {
705 let id = IambId::Room(room.clone());
706
707 IambWindow::open(id, store)
708 } else {
709 let room_id = worker.join_room(name.clone())?;
710 names.insert(name, room_id.clone());
711
712 let (room, name, tags) = store.application.worker.get_room(room_id)?;
713 let room = RoomState::new(room, name, tags, store);
714
715 store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
716 Ok(room.into())
717 }
718 }
719
720 fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
721 let msg = format!("Cannot find indexed buffer (index = {index})");
722 let err = UIError::Unimplemented(msg);
723
724 Err(err)
725 }
726
727 fn unnamed(store: &mut ProgramStore) -> IambResult<Self> {
728 Self::open(IambId::RoomList, store)
729 }
730}
731
732#[derive(Clone)]
733pub struct RoomItem {
734 room_info: MatrixRoomInfo,
735 name: String,
736 alias: Option<OwnedRoomAliasId>,
737}
738
739impl RoomItem {
740 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
741 let room = &room_info.deref().0;
742 let room_id = room.room_id();
743
744 let info = store.application.get_room_info(room_id.to_owned());
745 let name = info.name.clone().unwrap_or_default();
746 let alias = room.canonical_alias();
747 info.tags = room_info.deref().1.clone();
748
749 if let Some(alias) = &alias {
750 store.application.names.insert(alias.to_string(), room_id.to_owned());
751 }
752
753 RoomItem { room_info, name, alias }
754 }
755
756 #[inline]
757 fn room(&self) -> &MatrixRoom {
758 &self.room_info.deref().0
759 }
760
761 #[inline]
762 fn tags(&self) -> &Option<Tags> {
763 &self.room_info.deref().1
764 }
765}
766
767impl RoomLikeItem for RoomItem {
768 fn name(&self) -> &str {
769 self.name.as_str()
770 }
771
772 fn alias(&self) -> Option<&RoomAliasId> {
773 self.alias.as_deref()
774 }
775
776 fn room_id(&self) -> &RoomId {
777 self.room().room_id()
778 }
779
780 fn has_tag(&self, tag: TagName) -> bool {
781 if let Some(tags) = &self.room_info.deref().1 {
782 tags.contains_key(&tag)
783 } else {
784 false
785 }
786 }
787}
788
789impl ToString for RoomItem {
790 fn to_string(&self) -> String {
791 return self.name.clone();
792 }
793}
794
795impl ListItem<IambInfo> for RoomItem {
796 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
797 if let Some(tags) = &self.tags() {
798 let style = selected_style(selected);
799 let mut spans = vec![Span::styled(self.name.as_str(), style)];
800
801 append_tags(tags, &mut spans, style);
802
803 Text::from(Line::from(spans))
804 } else {
805 selected_text(self.name.as_str(), selected)
806 }
807 }
808
809 fn get_word(&self) -> Option<String> {
810 self.room_id().to_string().into()
811 }
812}
813
814impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomItem {
815 fn prompt(
816 &mut self,
817 act: &PromptAction,
818 ctx: &ProgramContext,
819 _: &mut ProgramStore,
820 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
821 room_prompt(self.room_id(), act, ctx)
822 }
823}
824
825#[derive(Clone)]
826pub struct DirectItem {
827 room_info: MatrixRoomInfo,
828 name: String,
829 alias: Option<OwnedRoomAliasId>,
830}
831
832impl DirectItem {
833 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
834 let room_id = room_info.0.room_id().to_owned();
835 let name = store.application.get_room_info(room_id).name.clone().unwrap_or_default();
836 let alias = room_info.0.canonical_alias();
837
838 DirectItem { room_info, name, alias }
839 }
840
841 #[inline]
842 fn room(&self) -> &MatrixRoom {
843 &self.room_info.deref().0
844 }
845
846 #[inline]
847 fn tags(&self) -> &Option<Tags> {
848 &self.room_info.deref().1
849 }
850}
851
852impl RoomLikeItem for DirectItem {
853 fn name(&self) -> &str {
854 self.name.as_str()
855 }
856
857 fn alias(&self) -> Option<&RoomAliasId> {
858 self.alias.as_deref()
859 }
860
861 fn has_tag(&self, tag: TagName) -> bool {
862 if let Some(tags) = &self.room_info.deref().1 {
863 tags.contains_key(&tag)
864 } else {
865 false
866 }
867 }
868
869 fn room_id(&self) -> &RoomId {
870 self.room().room_id()
871 }
872}
873
874impl ToString for DirectItem {
875 fn to_string(&self) -> String {
876 return self.name.clone();
877 }
878}
879
880impl ListItem<IambInfo> for DirectItem {
881 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
882 if let Some(tags) = &self.tags() {
883 let style = selected_style(selected);
884 let mut spans = vec![Span::styled(self.name.as_str(), style)];
885
886 append_tags(tags, &mut spans, style);
887
888 Text::from(Line::from(spans))
889 } else {
890 selected_text(self.name.as_str(), selected)
891 }
892 }
893
894 fn get_word(&self) -> Option<String> {
895 self.room_id().to_string().into()
896 }
897}
898
899impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
900 fn prompt(
901 &mut self,
902 act: &PromptAction,
903 ctx: &ProgramContext,
904 _: &mut ProgramStore,
905 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
906 room_prompt(self.room_id(), act, ctx)
907 }
908}
909
910#[derive(Clone)]
911pub struct SpaceItem {
912 room_info: MatrixRoomInfo,
913 name: String,
914 alias: Option<OwnedRoomAliasId>,
915}
916
917impl SpaceItem {
918 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
919 let room_id = room_info.0.room_id();
920 let name = store
921 .application
922 .get_room_info(room_id.to_owned())
923 .name
924 .clone()
925 .unwrap_or_default();
926 let alias = room_info.0.canonical_alias();
927
928 if let Some(alias) = &alias {
929 store.application.names.insert(alias.to_string(), room_id.to_owned());
930 }
931
932 SpaceItem { room_info, name, alias }
933 }
934
935 #[inline]
936 fn room(&self) -> &MatrixRoom {
937 &self.room_info.deref().0
938 }
939}
940
941impl RoomLikeItem for SpaceItem {
942 fn name(&self) -> &str {
943 self.name.as_str()
944 }
945
946 fn room_id(&self) -> &RoomId {
947 self.room().room_id()
948 }
949
950 fn alias(&self) -> Option<&RoomAliasId> {
951 self.alias.as_deref()
952 }
953
954 fn has_tag(&self, _: TagName) -> bool {
955 // I think that spaces can technically have tags, but afaik no client
956 // exposes them, so we'll just always return false here for now.
957 false
958 }
959}
960
961impl ToString for SpaceItem {
962 fn to_string(&self) -> String {
963 return self.room_id().to_string();
964 }
965}
966
967impl ListItem<IambInfo> for SpaceItem {
968 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
969 selected_text(self.name.as_str(), selected)
970 }
971
972 fn get_word(&self) -> Option<String> {
973 self.room_id().to_string().into()
974 }
975}
976
977impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
978 fn prompt(
979 &mut self,
980 act: &PromptAction,
981 ctx: &ProgramContext,
982 _: &mut ProgramStore,
983 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
984 room_prompt(self.room_id(), act, ctx)
985 }
986}
987
988#[derive(Clone)]
989pub struct VerifyItem {
990 user_dev: String,
991 sasv1: SasVerification,
992}
993
994impl VerifyItem {
995 fn new(user_dev: String, sasv1: SasVerification) -> Self {
996 VerifyItem { user_dev, sasv1 }
997 }
998
999 fn show_item(&self) -> String {
1000 let state = if self.sasv1.is_done() {
1001 "done"
1002 } else if self.sasv1.is_cancelled() {
1003 "cancelled"
1004 } else if self.sasv1.emoji().is_some() {
1005 "accepted"
1006 } else {
1007 "not accepted"
1008 };
1009
1010 if self.sasv1.is_self_verification() {
1011 let device = self.sasv1.other_device();
1012
1013 if let Some(display_name) = device.display_name() {
1014 format!("Device verification with {display_name} ({state})")
1015 } else {
1016 format!("Device verification with device {} ({})", device.device_id(), state)
1017 }
1018 } else {
1019 format!("User Verification with {} ({})", self.sasv1.other_user_id(), state)
1020 }
1021 }
1022}
1023
1024impl PartialEq for VerifyItem {
1025 fn eq(&self, other: &Self) -> bool {
1026 self.user_dev == other.user_dev
1027 }
1028}
1029
1030impl Eq for VerifyItem {}
1031
1032impl Ord for VerifyItem {
1033 fn cmp(&self, other: &Self) -> Ordering {
1034 fn state_val(sas: &SasVerification) -> usize {
1035 if sas.is_done() {
1036 return 3;
1037 } else if sas.is_cancelled() {
1038 return 2;
1039 } else {
1040 return 1;
1041 }
1042 }
1043
1044 fn device_val(sas: &SasVerification) -> usize {
1045 if sas.is_self_verification() {
1046 return 1;
1047 } else {
1048 return 2;
1049 }
1050 }
1051
1052 let state1 = state_val(&self.sasv1);
1053 let state2 = state_val(&other.sasv1);
1054
1055 let dev1 = device_val(&self.sasv1);
1056 let dev2 = device_val(&other.sasv1);
1057
1058 let scmp = state1.cmp(&state2);
1059 let dcmp = dev1.cmp(&dev2);
1060
1061 scmp.then(dcmp).then_with(|| {
1062 let did1 = self.sasv1.other_device().device_id();
1063 let did2 = other.sasv1.other_device().device_id();
1064
1065 did1.cmp(did2)
1066 })
1067 }
1068}
1069
1070impl PartialOrd for VerifyItem {
1071 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1072 self.cmp(other).into()
1073 }
1074}
1075
1076impl From<(&String, &SasVerification)> for VerifyItem {
1077 fn from((user_dev, sasv1): (&String, &SasVerification)) -> Self {
1078 VerifyItem::new(user_dev.clone(), sasv1.clone())
1079 }
1080}
1081
1082impl ToString for VerifyItem {
1083 fn to_string(&self) -> String {
1084 if self.sasv1.is_done() {
1085 String::new()
1086 } else if self.sasv1.is_cancelled() {
1087 format!(":verify request {}", self.sasv1.other_user_id())
1088 } else if self.sasv1.emoji().is_some() {
1089 format!(":verify confirm {}", self.user_dev)
1090 } else {
1091 format!(":verify accept {}", self.user_dev)
1092 }
1093 }
1094}
1095
1096impl ListItem<IambInfo> for VerifyItem {
1097 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1098 let mut lines = vec![];
1099
1100 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1101 let item = Span::styled(self.show_item(), selected_style(selected));
1102 lines.push(Line::from(item));
1103
1104 if self.sasv1.is_done() {
1105 // Print nothing.
1106 } else if self.sasv1.is_cancelled() {
1107 if let Some(info) = self.sasv1.cancel_info() {
1108 lines.push(Line::from(format!(" Cancelled: {}", info.reason())));
1109 lines.push(Line::from(""));
1110 }
1111
1112 lines.push(Line::from(" You can start a new verification request with:"));
1113 } else if let Some(emoji) = self.sasv1.emoji() {
1114 lines.push(Line::from(
1115 " Both devices should see the following Emoji sequence:".to_string(),
1116 ));
1117 lines.push(Line::from(""));
1118
1119 for line in format_emojis(emoji).lines() {
1120 lines.push(Line::from(format!(" {line}")));
1121 }
1122
1123 lines.push(Line::from(""));
1124 lines.push(Line::from(" If they don't match, run:"));
1125 lines.push(Line::from(""));
1126 lines.push(Line::from(Span::styled(
1127 format!(":verify mismatch {}", self.user_dev),
1128 bold,
1129 )));
1130 lines.push(Line::from(""));
1131 lines.push(Line::from(" If everything looks right, you can confirm with:"));
1132 } else {
1133 lines.push(Line::from(" To accept this request, run:"));
1134 }
1135
1136 let cmd = self.to_string();
1137
1138 if !cmd.is_empty() {
1139 lines.push(Line::from(""));
1140 lines.push(Line::from(vec![Span::from(" "), Span::styled(cmd, bold)]));
1141 lines.push(Line::from(""));
1142 lines.push(Line::from(vec![
1143 Span::from("You can copy the above command with "),
1144 Span::styled("yy", bold),
1145 Span::from(" and then execute it with "),
1146 Span::styled("@\"", bold),
1147 ]));
1148 }
1149
1150 Text { lines }
1151 }
1152
1153 fn get_word(&self) -> Option<String> {
1154 None
1155 }
1156}
1157
1158impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
1159 fn prompt(
1160 &mut self,
1161 act: &PromptAction,
1162 _: &ProgramContext,
1163 _: &mut ProgramStore,
1164 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1165 match act {
1166 PromptAction::Submit => Ok(vec![]),
1167 PromptAction::Abort(_) => {
1168 let msg = "Cannot abort entry inside a list";
1169 let err = EditError::Failure(msg.into());
1170
1171 Err(err)
1172 },
1173 PromptAction::Recall(..) => {
1174 let msg = "Cannot recall history inside a list";
1175 let err = EditError::Failure(msg.into());
1176
1177 Err(err)
1178 },
1179 _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
1180 }
1181 }
1182}
1183
1184#[derive(Clone)]
1185pub struct MemberItem {
1186 member: RoomMember,
1187 room_id: OwnedRoomId,
1188}
1189
1190impl MemberItem {
1191 fn new(member: RoomMember, room_id: OwnedRoomId) -> Self {
1192 Self { member, room_id }
1193 }
1194}
1195
1196impl ToString for MemberItem {
1197 fn to_string(&self) -> String {
1198 self.member.user_id().to_string()
1199 }
1200}
1201
1202impl ListItem<IambInfo> for MemberItem {
1203 fn show(
1204 &self,
1205 selected: bool,
1206 _: &ViewportContext<ListCursor>,
1207 store: &mut ProgramStore,
1208 ) -> Text {
1209 let info = store.application.rooms.get_or_default(self.room_id.clone());
1210 let user_id = self.member.user_id();
1211
1212 let (color, name) = store.application.settings.get_user_overrides(self.member.user_id());
1213 let color = color.unwrap_or_else(|| super::config::user_color(user_id.as_str()));
1214 let mut style = super::config::user_style_from_color(color);
1215
1216 if selected {
1217 style = style.add_modifier(StyleModifier::REVERSED);
1218 }
1219
1220 let mut spans = vec![];
1221 let mut parens = false;
1222
1223 if let Some(name) = name {
1224 spans.push(Span::styled(name, style));
1225 parens = true;
1226 } else if let Some(display) = info.display_names.get(user_id) {
1227 spans.push(Span::styled(display.clone(), style));
1228 parens = true;
1229 }
1230
1231 spans.extend(parens.then_some(Span::styled(" (", style)));
1232 spans.push(Span::styled(user_id.as_str(), style));
1233 spans.extend(parens.then_some(Span::styled(")", style)));
1234
1235 let state = match self.member.membership() {
1236 MembershipState::Ban => Span::raw(" (banned)").into(),
1237 MembershipState::Invite => Span::raw(" (invited)").into(),
1238 MembershipState::Knock => Span::raw(" (wants to join)").into(),
1239 MembershipState::Leave => Span::raw(" (left)").into(),
1240 MembershipState::Join => None,
1241 _ => None,
1242 };
1243
1244 spans.extend(state);
1245
1246 return Line::from(spans).into();
1247 }
1248
1249 fn get_word(&self) -> Option<String> {
1250 self.member.user_id().to_string().into()
1251 }
1252}
1253
1254impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
1255 fn prompt(
1256 &mut self,
1257 act: &PromptAction,
1258 _: &ProgramContext,
1259 _: &mut ProgramStore,
1260 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1261 match act {
1262 PromptAction::Submit => Ok(vec![]),
1263 PromptAction::Abort(_) => {
1264 let msg = "Cannot abort entry inside a list";
1265 let err = EditError::Failure(msg.into());
1266
1267 Err(err)
1268 },
1269 PromptAction::Recall(..) => {
1270 let msg = "Cannot recall history inside a list";
1271 let err = EditError::Failure(msg.into());
1272
1273 Err(err)
1274 },
1275 _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
1276 }
1277 }
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282 use super::*;
1283 use matrix_sdk::ruma::{room_alias_id, server_name};
1284
1285 #[derive(Debug, Eq, PartialEq)]
1286 struct TestRoomItem {
1287 room_id: OwnedRoomId,
1288 tags: Vec<TagName>,
1289 alias: Option<OwnedRoomAliasId>,
1290 name: &'static str,
1291 }
1292
1293 impl RoomLikeItem for &TestRoomItem {
1294 fn room_id(&self) -> &RoomId {
1295 self.room_id.as_ref()
1296 }
1297
1298 fn has_tag(&self, tag: TagName) -> bool {
1299 self.tags.contains(&tag)
1300 }
1301
1302 fn alias(&self) -> Option<&RoomAliasId> {
1303 self.alias.as_deref()
1304 }
1305
1306 fn name(&self) -> &str {
1307 self.name
1308 }
1309 }
1310
1311 #[test]
1312 fn test_sort_rooms() {
1313 let server = server_name!("example.com");
1314
1315 let room1 = TestRoomItem {
1316 room_id: RoomId::new(server).to_owned(),
1317 tags: vec![TagName::Favorite],
1318 alias: Some(room_alias_id!("#room1:example.com").to_owned()),
1319 name: "Z",
1320 };
1321
1322 let room2 = TestRoomItem {
1323 room_id: RoomId::new(server).to_owned(),
1324 tags: vec![],
1325 alias: Some(room_alias_id!("#a:example.com").to_owned()),
1326 name: "Unnamed Room",
1327 };
1328
1329 let room3 = TestRoomItem {
1330 room_id: RoomId::new(server).to_owned(),
1331 tags: vec![],
1332 alias: None,
1333 name: "Cool Room",
1334 };
1335
1336 // Sort by Name ascending.
1337 let mut rooms = vec![&room1, &room2, &room3];
1338 let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Ascending)];
1339 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1340 assert_eq!(rooms, vec![&room3, &room2, &room1]);
1341
1342 // Sort by Name descending.
1343 let mut rooms = vec![&room1, &room2, &room3];
1344 let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Descending)];
1345 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1346 assert_eq!(rooms, vec![&room1, &room2, &room3]);
1347
1348 // Sort by Favorite and Alias before Name to show order matters.
1349 let mut rooms = vec![&room1, &room2, &room3];
1350 let fields = &[
1351 SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
1352 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1353 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1354 ];
1355 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1356 assert_eq!(rooms, vec![&room1, &room2, &room3]);
1357
1358 // Now flip order of Favorite with Descending
1359 let mut rooms = vec![&room1, &room2, &room3];
1360 let fields = &[
1361 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1362 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1363 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1364 ];
1365 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1366 assert_eq!(rooms, vec![&room2, &room3, &room1]);
1367 }
1368}