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