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