src/windows/mod.rs
1791 lines · 54498 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 accessible and resettable.
9use std::cmp::{Ord, Ordering, PartialOrd};
10use std::fmt::{self, Display};
11use std::ops::Deref;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use matrix_sdk::{
16 encryption::verification::{format_emojis, SasVerification},
17 room::{Room as MatrixRoom, RoomMember},
18 ruma::{
19 events::room::member::MembershipState,
20 events::tag::{TagName, Tags},
21 OwnedRoomAliasId,
22 OwnedRoomId,
23 RoomAliasId,
24 RoomId,
25 },
26 RoomState as MatrixRoomState,
27};
28
29use ratatui::{
30 buffer::Buffer,
31 layout::{Alignment, Rect},
32 style::{Modifier as StyleModifier, Style},
33 text::{Line, Span, Text},
34 widgets::StatefulWidget,
35};
36
37use modalkit::{
38 actions::{
39 Action,
40 Editable,
41 EditorAction,
42 Jumpable,
43 PromptAction,
44 Promptable,
45 Scrollable,
46 WindowAction,
47 },
48 editing::completion::CompletionList,
49 errors::{EditError, EditResult, UIError},
50 prelude::*,
51};
52
53use modalkit_ratatui::{
54 list::{List, ListCursor, ListItem, ListState},
55 TermOffset,
56 TerminalCursor,
57 Window,
58 WindowOps,
59};
60
61use crate::base::{
62 ChatStore,
63 IambBufferId,
64 IambError,
65 IambId,
66 IambInfo,
67 IambResult,
68 MessageAction,
69 Need,
70 ProgramAction,
71 ProgramContext,
72 ProgramStore,
73 RoomAction,
74 SendAction,
75 SortColumn,
76 SortFieldRoom,
77 SortFieldUser,
78 SortOrder,
79 SpaceAction,
80 UnreadInfo,
81};
82
83use self::{room::RoomState, welcome::WelcomeState};
84use crate::message::MessageTimeStamp;
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
127fn name_and_labels(name: &str, unread: bool, style: Style) -> (Span<'_>, Vec<Vec<Span<'_>>>) {
128 let name_style = if unread {
129 style.add_modifier(StyleModifier::BOLD)
130 } else {
131 style
132 };
133
134 let name = Span::styled(name, name_style);
135 let labels = if unread {
136 vec![vec![Span::styled("Unread", style)]]
137 } else {
138 vec![]
139 };
140
141 (name, labels)
142}
143
144/// Sort `Some` to be less than `None` so that list items with values come before those without.
145#[inline]
146fn some_cmp<T, F>(a: Option<T>, b: Option<T>, f: F) -> Ordering
147where
148 F: Fn(&T, &T) -> Ordering,
149{
150 match (a, b) {
151 (Some(a), Some(b)) => f(&a, &b),
152 (None, None) => Ordering::Equal,
153 (None, Some(_)) => Ordering::Greater,
154 (Some(_), None) => Ordering::Less,
155 }
156}
157
158fn user_cmp(a: &MemberItem, b: &MemberItem, field: &SortFieldUser) -> Ordering {
159 let a_id = a.member.user_id();
160 let b_id = b.member.user_id();
161
162 match field {
163 SortFieldUser::UserId => a_id.cmp(b_id),
164 SortFieldUser::LocalPart => a_id.localpart().cmp(b_id.localpart()),
165 SortFieldUser::Server => a_id.server_name().cmp(b_id.server_name()),
166 SortFieldUser::PowerLevel => {
167 // Sort higher power levels towards the top of the list.
168 b.member.power_level().cmp(&a.member.power_level())
169 },
170 }
171}
172
173fn room_cmp<T: RoomLikeItem>(a: &T, b: &T, field: &SortFieldRoom) -> Ordering {
174 match field {
175 SortFieldRoom::Favorite => {
176 let fava = a.has_tag(TagName::Favorite);
177 let favb = b.has_tag(TagName::Favorite);
178
179 // If a has Favorite and b doesn't, it should sort earlier in room list.
180 favb.cmp(&fava)
181 },
182 SortFieldRoom::LowPriority => {
183 let lowa = a.has_tag(TagName::LowPriority);
184 let lowb = b.has_tag(TagName::LowPriority);
185
186 // If a has LowPriority and b doesn't, it should sort later in room list.
187 lowa.cmp(&lowb)
188 },
189 SortFieldRoom::Name => a.name().cmp(b.name()),
190 SortFieldRoom::Alias => some_cmp(a.alias(), b.alias(), Ord::cmp),
191 SortFieldRoom::RoomId => a.room_id().cmp(b.room_id()),
192 SortFieldRoom::Unread => {
193 // Sort true (unread) before false (read)
194 b.is_unread().cmp(&a.is_unread())
195 },
196 SortFieldRoom::Recent => {
197 // sort larger timestamps towards the top.
198 some_cmp(a.recent_ts(), b.recent_ts(), |a, b| b.cmp(a))
199 },
200 SortFieldRoom::Invite => {
201 // sort invites before other rooms.
202 b.is_invite().cmp(&a.is_invite())
203 },
204 }
205}
206
207/// Compare two rooms according the configured sort criteria.
208fn room_fields_cmp<T: RoomLikeItem>(
209 a: &T,
210 b: &T,
211 fields: &[SortColumn<SortFieldRoom>],
212) -> Ordering {
213 for SortColumn(field, order) in fields {
214 match (room_cmp(a, b, field), order) {
215 (Ordering::Equal, _) => continue,
216 (o, SortOrder::Ascending) => return o,
217 (o, SortOrder::Descending) => return o.reverse(),
218 }
219 }
220
221 // Break ties on ascending room id.
222 room_cmp(a, b, &SortFieldRoom::RoomId)
223}
224
225fn user_fields_cmp(
226 a: &MemberItem,
227 b: &MemberItem,
228 fields: &[SortColumn<SortFieldUser>],
229) -> Ordering {
230 for SortColumn(field, order) in fields {
231 match (user_cmp(a, b, field), order) {
232 (Ordering::Equal, _) => continue,
233 (o, SortOrder::Ascending) => return o,
234 (o, SortOrder::Descending) => return o.reverse(),
235 }
236 }
237
238 // Break ties on ascending user id.
239 user_cmp(a, b, &SortFieldUser::UserId)
240}
241
242fn tag_to_span(tag: &TagName, style: Style) -> Vec<Span<'_>> {
243 match tag {
244 TagName::Favorite => vec![Span::styled("Favorite", style)],
245 TagName::LowPriority => vec![Span::styled("Low Priority", style)],
246 TagName::ServerNotice => vec![Span::styled("Server Notice", style)],
247 TagName::User(tag) => {
248 vec![
249 Span::styled("User Tag: ", style),
250 Span::styled(tag.as_ref(), style),
251 ]
252 },
253 tag => vec![Span::styled(format!("{tag:?}"), style)],
254 }
255}
256
257fn append_tags<'a>(tags: Vec<Vec<Span<'a>>>, spans: &mut Vec<Span<'a>>, style: Style) {
258 if tags.is_empty() {
259 return;
260 }
261
262 spans.push(Span::styled(" (", style));
263
264 for (i, tag) in tags.into_iter().enumerate() {
265 if i > 0 {
266 spans.push(Span::styled(", ", style));
267 }
268
269 spans.extend(tag);
270 }
271
272 spans.push(Span::styled(")", style));
273}
274
275trait RoomLikeItem {
276 fn room_id(&self) -> &RoomId;
277 fn has_tag(&self, tag: TagName) -> bool;
278 fn is_unread(&self) -> bool;
279 fn recent_ts(&self) -> Option<&MessageTimeStamp>;
280 fn alias(&self) -> Option<&RoomAliasId>;
281 fn name(&self) -> &str;
282 fn is_invite(&self) -> bool;
283}
284
285#[inline]
286fn room_prompt(
287 room_id: &RoomId,
288 act: &PromptAction,
289 ctx: &ProgramContext,
290) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
291 match act {
292 PromptAction::Submit => {
293 let room = IambId::Room(room_id.to_owned(), None);
294 let open = WindowAction::Switch(OpenTarget::Application(room));
295 let acts = vec![(open.into(), ctx.clone())];
296
297 Ok(acts)
298 },
299 PromptAction::Abort(_) => {
300 let msg = "Cannot abort entry inside a list";
301 let err = EditError::Failure(msg.into());
302
303 Err(err)
304 },
305 PromptAction::Recall(..) => {
306 let msg = "Cannot recall history inside a list";
307 let err = EditError::Failure(msg.into());
308
309 Err(err)
310 },
311 }
312}
313
314macro_rules! delegate {
315 ($s: expr, $id: ident => $e: expr) => {
316 match $s {
317 IambWindow::Room($id) => $e,
318 IambWindow::DirectList($id) => $e,
319 IambWindow::MemberList($id, _, _) => $e,
320 IambWindow::RoomList($id) => $e,
321 IambWindow::SpaceList($id) => $e,
322 IambWindow::VerifyList($id) => $e,
323 IambWindow::Welcome($id) => $e,
324 IambWindow::ChatList($id) => $e,
325 IambWindow::UnreadList($id) => $e,
326 }
327 };
328}
329
330pub enum IambWindow {
331 DirectList(DirectListState),
332 MemberList(MemberListState, OwnedRoomId, Option<Instant>),
333 Room(RoomState),
334 VerifyList(VerifyListState),
335 RoomList(RoomListState),
336 SpaceList(SpaceListState),
337 Welcome(WelcomeState),
338 ChatList(ChatListState),
339 UnreadList(UnreadListState),
340}
341
342impl IambWindow {
343 pub fn focus_toggle(&mut self) {
344 if let IambWindow::Room(w) = self {
345 w.focus_toggle()
346 } else {
347 return;
348 }
349 }
350
351 pub async fn message_command(
352 &mut self,
353 act: MessageAction,
354 ctx: ProgramContext,
355 store: &mut ProgramStore,
356 ) -> IambResult<EditInfo> {
357 if let IambWindow::Room(w) = self {
358 w.message_command(act, ctx, store).await
359 } else {
360 return Err(IambError::NoSelectedRoom.into());
361 }
362 }
363
364 pub async fn space_command(
365 &mut self,
366 act: SpaceAction,
367 ctx: ProgramContext,
368 store: &mut ProgramStore,
369 ) -> IambResult<EditInfo> {
370 if let IambWindow::Room(w) = self {
371 w.space_command(act, ctx, store).await
372 } else {
373 return Err(IambError::NoSelectedRoom.into());
374 }
375 }
376
377 pub async fn room_command(
378 &mut self,
379 act: RoomAction,
380 ctx: ProgramContext,
381 store: &mut ProgramStore,
382 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
383 if let IambWindow::Room(w) = self {
384 w.room_command(act, ctx, store).await
385 } else {
386 return Err(IambError::NoSelectedRoomOrSpace.into());
387 }
388 }
389
390 pub async fn send_command(
391 &mut self,
392 act: SendAction,
393 ctx: ProgramContext,
394 store: &mut ProgramStore,
395 ) -> IambResult<EditInfo> {
396 if let IambWindow::Room(w) = self {
397 w.send_command(act, ctx, store).await
398 } else {
399 return Err(IambError::NoSelectedRoom.into());
400 }
401 }
402}
403
404pub type DirectListState = ListState<DirectItem, IambInfo>;
405pub type MemberListState = ListState<MemberItem, IambInfo>;
406pub type RoomListState = ListState<RoomItem, IambInfo>;
407pub type ChatListState = ListState<GenericChatItem, IambInfo>;
408pub type UnreadListState = ListState<GenericChatItem, IambInfo>;
409pub type SpaceListState = ListState<SpaceItem, IambInfo>;
410pub type VerifyListState = ListState<VerifyItem, IambInfo>;
411
412impl From<ChatListState> for IambWindow {
413 fn from(list: ChatListState) -> Self {
414 IambWindow::ChatList(list)
415 }
416}
417
418impl From<RoomState> for IambWindow {
419 fn from(room: RoomState) -> Self {
420 IambWindow::Room(room)
421 }
422}
423
424impl From<VerifyListState> for IambWindow {
425 fn from(list: VerifyListState) -> Self {
426 IambWindow::VerifyList(list)
427 }
428}
429
430impl From<DirectListState> for IambWindow {
431 fn from(list: DirectListState) -> Self {
432 IambWindow::DirectList(list)
433 }
434}
435
436impl From<RoomListState> for IambWindow {
437 fn from(list: RoomListState) -> Self {
438 IambWindow::RoomList(list)
439 }
440}
441
442impl From<SpaceListState> for IambWindow {
443 fn from(list: SpaceListState) -> Self {
444 IambWindow::SpaceList(list)
445 }
446}
447
448impl From<WelcomeState> for IambWindow {
449 fn from(win: WelcomeState) -> Self {
450 IambWindow::Welcome(win)
451 }
452}
453
454impl Editable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
455 fn editor_command(
456 &mut self,
457 act: &EditorAction,
458 ctx: &ProgramContext,
459 store: &mut ProgramStore,
460 ) -> EditResult<EditInfo, IambInfo> {
461 delegate!(self, w => w.editor_command(act, ctx, store))
462 }
463}
464
465impl Jumpable<ProgramContext, IambInfo> for IambWindow {
466 fn jump(
467 &mut self,
468 list: PositionList,
469 dir: MoveDir1D,
470 count: usize,
471 ctx: &ProgramContext,
472 ) -> IambResult<usize> {
473 delegate!(self, w => w.jump(list, dir, count, ctx))
474 }
475}
476
477impl Scrollable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
478 fn scroll(
479 &mut self,
480 style: &ScrollStyle,
481 ctx: &ProgramContext,
482 store: &mut ProgramStore,
483 ) -> EditResult<EditInfo, IambInfo> {
484 delegate!(self, w => w.scroll(style, ctx, store))
485 }
486}
487
488impl Promptable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
489 fn prompt(
490 &mut self,
491 act: &PromptAction,
492 ctx: &ProgramContext,
493 store: &mut ProgramStore,
494 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
495 delegate!(self, w => w.prompt(act, ctx, store))
496 }
497}
498
499impl TerminalCursor for IambWindow {
500 fn get_term_cursor(&self) -> Option<TermOffset> {
501 delegate!(self, w => w.get_term_cursor())
502 }
503}
504
505impl WindowOps<IambInfo> for IambWindow {
506 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
507 match self {
508 IambWindow::Room(state) => state.draw(area, buf, focused, store),
509 IambWindow::DirectList(state) => {
510 let mut items = store
511 .application
512 .sync_info
513 .dms
514 .clone()
515 .into_iter()
516 .map(|room_info| DirectItem::new(room_info, store))
517 .collect::<Vec<_>>();
518 let fields = &store.application.settings.tunables.sort.dms;
519 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
520
521 state.set(items);
522
523 List::new(store)
524 .empty_message("No direct messages yet!")
525 .empty_alignment(Alignment::Center)
526 .focus(focused)
527 .render(area, buf, state);
528 },
529 IambWindow::MemberList(state, room_id, last_fetch) => {
530 let need_fetch = match last_fetch {
531 Some(i) => i.elapsed() >= MEMBER_FETCH_DEBOUNCE,
532 None => true,
533 };
534
535 if need_fetch {
536 if let Ok(mems) = store.application.worker.members(room_id.clone()) {
537 let mut items = mems
538 .into_iter()
539 .map(|m| MemberItem::new(m, room_id.clone()))
540 .collect::<Vec<_>>();
541 let fields = &store.application.settings.tunables.sort.members;
542 items.sort_by(|a, b| user_fields_cmp(a, b, fields));
543 state.set(items);
544 *last_fetch = Some(Instant::now());
545 }
546 }
547
548 List::new(store)
549 .empty_message("No users here yet!")
550 .empty_alignment(Alignment::Center)
551 .focus(focused)
552 .render(area, buf, state);
553 },
554 IambWindow::RoomList(state) => {
555 let mut items = store
556 .application
557 .sync_info
558 .rooms
559 .clone()
560 .into_iter()
561 .map(|room_info| RoomItem::new(room_info, store))
562 .collect::<Vec<_>>();
563 let fields = &store.application.settings.tunables.sort.rooms;
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 rooms yet")
570 .empty_alignment(Alignment::Center)
571 .focus(focused)
572 .render(area, buf, state);
573 },
574 IambWindow::ChatList(state) => {
575 let mut items = store
576 .application
577 .sync_info
578 .rooms
579 .clone()
580 .into_iter()
581 .map(|room_info| GenericChatItem::new(room_info, store, false))
582 .collect::<Vec<_>>();
583
584 let dms = store
585 .application
586 .sync_info
587 .dms
588 .clone()
589 .into_iter()
590 .map(|room_info| GenericChatItem::new(room_info, store, true));
591
592 items.extend(dms);
593
594 let fields = &store.application.settings.tunables.sort.chats;
595 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
596
597 state.set(items);
598
599 List::new(store)
600 .empty_message("You do not have rooms or dms yet")
601 .empty_alignment(Alignment::Center)
602 .focus(focused)
603 .render(area, buf, state);
604 },
605 IambWindow::UnreadList(state) => {
606 let mut items = store
607 .application
608 .sync_info
609 .rooms
610 .clone()
611 .into_iter()
612 .map(|room_info| GenericChatItem::new(room_info, store, false))
613 .filter(RoomLikeItem::is_unread)
614 .collect::<Vec<_>>();
615
616 let dms = store
617 .application
618 .sync_info
619 .dms
620 .clone()
621 .into_iter()
622 .map(|room_info| GenericChatItem::new(room_info, store, true))
623 .filter(RoomLikeItem::is_unread);
624
625 items.extend(dms);
626
627 let fields = &store.application.settings.tunables.sort.chats;
628 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
629
630 state.set(items);
631
632 List::new(store)
633 .empty_message("You do not have rooms or dms yet")
634 .empty_alignment(Alignment::Center)
635 .focus(focused)
636 .render(area, buf, state);
637 },
638 IambWindow::SpaceList(state) => {
639 let mut items = store
640 .application
641 .sync_info
642 .spaces
643 .clone()
644 .into_iter()
645 .map(|room| SpaceItem::new(room, store))
646 .collect::<Vec<_>>();
647 let fields = &store.application.settings.tunables.sort.spaces;
648 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
649
650 state.set(items);
651
652 List::new(store)
653 .empty_message("You haven't joined any spaces yet")
654 .empty_alignment(Alignment::Center)
655 .focus(focused)
656 .render(area, buf, state);
657 },
658 IambWindow::VerifyList(state) => {
659 let verifications = &store.application.verifications;
660 let mut items = verifications.iter().map(VerifyItem::from).collect::<Vec<_>>();
661
662 // Sort the active verifications towards the top.
663 items.sort();
664
665 state.set(items);
666
667 List::new(store)
668 .empty_message("No in-progress verifications")
669 .empty_alignment(Alignment::Center)
670 .focus(focused)
671 .render(area, buf, state);
672 },
673 IambWindow::Welcome(state) => state.draw(area, buf, focused, store),
674 }
675 }
676
677 fn dup(&self, store: &mut ProgramStore) -> Self {
678 match self {
679 IambWindow::Room(w) => w.dup(store).into(),
680 IambWindow::DirectList(w) => w.dup(store).into(),
681 IambWindow::MemberList(w, room_id, last_fetch) => {
682 IambWindow::MemberList(w.dup(store), room_id.clone(), *last_fetch)
683 },
684 IambWindow::RoomList(w) => w.dup(store).into(),
685 IambWindow::SpaceList(w) => w.dup(store).into(),
686 IambWindow::VerifyList(w) => w.dup(store).into(),
687 IambWindow::Welcome(w) => w.dup(store).into(),
688 IambWindow::ChatList(w) => w.dup(store).into(),
689 IambWindow::UnreadList(w) => w.dup(store).into(),
690 }
691 }
692
693 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
694 delegate!(self, w => w.close(flags, store))
695 }
696
697 fn write(
698 &mut self,
699 path: Option<&str>,
700 flags: WriteFlags,
701 store: &mut ProgramStore,
702 ) -> IambResult<EditInfo> {
703 delegate!(self, w => w.write(path, flags, store))
704 }
705
706 fn get_completions(&self) -> Option<CompletionList> {
707 delegate!(self, w => w.get_completions())
708 }
709
710 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
711 delegate!(self, w => w.get_cursor_word(style))
712 }
713
714 fn get_selected_word(&self) -> Option<String> {
715 delegate!(self, w => w.get_selected_word())
716 }
717}
718
719impl Window<IambInfo> for IambWindow {
720 fn id(&self) -> IambId {
721 match self {
722 IambWindow::Room(room) => IambId::Room(room.id().to_owned(), room.thread().cloned()),
723 IambWindow::DirectList(_) => IambId::DirectList,
724 IambWindow::MemberList(_, room_id, _) => IambId::MemberList(room_id.clone()),
725 IambWindow::RoomList(_) => IambId::RoomList,
726 IambWindow::SpaceList(_) => IambId::SpaceList,
727 IambWindow::VerifyList(_) => IambId::VerifyList,
728 IambWindow::Welcome(_) => IambId::Welcome,
729 IambWindow::ChatList(_) => IambId::ChatList,
730 IambWindow::UnreadList(_) => IambId::UnreadList,
731 }
732 }
733
734 fn get_tab_title(&self, store: &mut ProgramStore) -> Line {
735 match self {
736 IambWindow::DirectList(_) => bold_spans("Direct Messages"),
737 IambWindow::RoomList(_) => bold_spans("Rooms"),
738 IambWindow::SpaceList(_) => bold_spans("Spaces"),
739 IambWindow::VerifyList(_) => bold_spans("Verifications"),
740 IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
741 IambWindow::ChatList(_) => bold_spans("DMs & Rooms"),
742 IambWindow::UnreadList(_) => bold_spans("Unread Messages"),
743
744 IambWindow::Room(w) => {
745 let title = store.application.get_room_title(w.id());
746
747 Line::from(title)
748 },
749 IambWindow::MemberList(state, room_id, _) => {
750 let title = store.application.get_room_title(room_id.as_ref());
751 let n = state.len();
752 let v = vec![
753 bold_span("Room Members "),
754 Span::styled(format!("({n}): "), bold_style()),
755 title.into(),
756 ];
757 Line::from(v)
758 },
759 }
760 }
761
762 fn get_win_title(&self, store: &mut ProgramStore) -> Line {
763 match self {
764 IambWindow::DirectList(_) => bold_spans("Direct Messages"),
765 IambWindow::RoomList(_) => bold_spans("Rooms"),
766 IambWindow::SpaceList(_) => bold_spans("Spaces"),
767 IambWindow::VerifyList(_) => bold_spans("Verifications"),
768 IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
769 IambWindow::ChatList(_) => bold_spans("DMs & Rooms"),
770 IambWindow::UnreadList(_) => bold_spans("Unread Messages"),
771
772 IambWindow::Room(w) => w.get_title(store),
773 IambWindow::MemberList(state, room_id, _) => {
774 let title = store.application.get_room_title(room_id.as_ref());
775 let n = state.len();
776 let v = vec![
777 bold_span("Room Members "),
778 Span::styled(format!("({n}): "), bold_style()),
779 title.into(),
780 ];
781 Line::from(v)
782 },
783 }
784 }
785
786 fn open(id: IambId, store: &mut ProgramStore) -> IambResult<Self> {
787 match id {
788 IambId::Room(room_id, thread) => {
789 let (room, name, tags) = store.application.worker.get_room(room_id)?;
790 let room = RoomState::new(room, thread, name, tags, store);
791
792 store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
793 return Ok(room.into());
794 },
795 IambId::DirectList => {
796 let list = DirectListState::new(IambBufferId::DirectList, vec![]);
797
798 return Ok(list.into());
799 },
800 IambId::MemberList(room_id) => {
801 let id = IambBufferId::MemberList(room_id.clone());
802 let list = MemberListState::new(id, vec![]);
803 let win = IambWindow::MemberList(list, room_id, None);
804
805 return Ok(win);
806 },
807 IambId::RoomList => {
808 let list = RoomListState::new(IambBufferId::RoomList, vec![]);
809
810 return Ok(list.into());
811 },
812 IambId::SpaceList => {
813 let list = SpaceListState::new(IambBufferId::SpaceList, vec![]);
814
815 return Ok(list.into());
816 },
817 IambId::VerifyList => {
818 let list = VerifyListState::new(IambBufferId::VerifyList, vec![]);
819
820 return Ok(list.into());
821 },
822 IambId::Welcome => {
823 let win = WelcomeState::new(store);
824
825 return Ok(win.into());
826 },
827 IambId::ChatList => {
828 let list = ChatListState::new(IambBufferId::ChatList, vec![]);
829
830 Ok(list.into())
831 },
832 IambId::UnreadList => {
833 let list = UnreadListState::new(IambBufferId::UnreadList, vec![]);
834
835 Ok(IambWindow::UnreadList(list))
836 },
837 }
838 }
839
840 fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
841 let ChatStore { names, worker, .. } = &mut store.application;
842
843 if let Some(room) = names.get_mut(&name) {
844 let id = IambId::Room(room.clone(), None);
845
846 IambWindow::open(id, store)
847 } else {
848 let room_id = worker.join_room(name.clone())?;
849 names.insert(name, room_id.clone());
850
851 let (room, name, tags) = store.application.worker.get_room(room_id)?;
852 let room = RoomState::new(room, None, name, tags, store);
853
854 store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
855 Ok(room.into())
856 }
857 }
858
859 fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
860 let msg = format!("Cannot find indexed buffer (index = {index})");
861 let err = UIError::Unimplemented(msg);
862
863 Err(err)
864 }
865
866 fn unnamed(store: &mut ProgramStore) -> IambResult<Self> {
867 Self::open(IambId::RoomList, store)
868 }
869}
870
871#[derive(Clone)]
872pub struct GenericChatItem {
873 room_info: MatrixRoomInfo,
874 name: String,
875 alias: Option<OwnedRoomAliasId>,
876 unread: UnreadInfo,
877 is_dm: bool,
878}
879
880impl GenericChatItem {
881 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore, is_dm: bool) -> Self {
882 let room = &room_info.deref().0;
883 let room_id = room.room_id();
884
885 let info = store.application.rooms.get_or_default(room_id.to_owned());
886 let name = info.name.clone().unwrap_or_default();
887 let alias = room.canonical_alias();
888 let unread = info.unreads(&store.application.settings);
889 info.tags.clone_from(&room_info.deref().1);
890
891 if let Some(alias) = &alias {
892 store.application.names.insert(alias.to_string(), room_id.to_owned());
893 }
894
895 GenericChatItem { room_info, name, alias, is_dm, unread }
896 }
897
898 #[inline]
899 fn room(&self) -> &MatrixRoom {
900 &self.room_info.deref().0
901 }
902
903 #[inline]
904 fn tags(&self) -> &Option<Tags> {
905 &self.room_info.deref().1
906 }
907}
908
909impl RoomLikeItem for GenericChatItem {
910 fn name(&self) -> &str {
911 self.name.as_str()
912 }
913
914 fn alias(&self) -> Option<&RoomAliasId> {
915 self.alias.as_deref()
916 }
917
918 fn room_id(&self) -> &RoomId {
919 self.room().room_id()
920 }
921
922 fn has_tag(&self, tag: TagName) -> bool {
923 if let Some(tags) = &self.room_info.deref().1 {
924 tags.contains_key(&tag)
925 } else {
926 false
927 }
928 }
929
930 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
931 self.unread.latest()
932 }
933
934 fn is_unread(&self) -> bool {
935 self.unread.is_unread()
936 }
937
938 fn is_invite(&self) -> bool {
939 self.room().state() == MatrixRoomState::Invited
940 }
941}
942
943impl Display for GenericChatItem {
944 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
945 write!(f, "{}", self.name)
946 }
947}
948
949impl ListItem<IambInfo> for GenericChatItem {
950 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
951 let unread = self.unread.is_unread();
952 let style = selected_style(selected);
953 let (name, mut labels) = name_and_labels(&self.name, unread, style);
954 let mut spans = vec![name];
955
956 labels.push(if self.is_dm {
957 vec![Span::styled("DM", style)]
958 } else {
959 vec![Span::styled("Room", style)]
960 });
961
962 if let Some(tags) = &self.tags() {
963 labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
964 }
965
966 append_tags(labels, &mut spans, style);
967 Text::from(Line::from(spans))
968 }
969
970 fn get_word(&self) -> Option<String> {
971 self.room_id().to_string().into()
972 }
973}
974
975impl Promptable<ProgramContext, ProgramStore, IambInfo> for GenericChatItem {
976 fn prompt(
977 &mut self,
978 act: &PromptAction,
979 ctx: &ProgramContext,
980 _: &mut ProgramStore,
981 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
982 room_prompt(self.room_id(), act, ctx)
983 }
984}
985
986#[derive(Clone)]
987pub struct RoomItem {
988 room_info: MatrixRoomInfo,
989 name: String,
990 alias: Option<OwnedRoomAliasId>,
991 unread: UnreadInfo,
992}
993
994impl RoomItem {
995 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
996 let room = &room_info.deref().0;
997 let room_id = room.room_id();
998
999 let info = store.application.rooms.get_or_default(room_id.to_owned());
1000 let name = info.name.clone().unwrap_or_default();
1001 let alias = room.canonical_alias();
1002 let unread = info.unreads(&store.application.settings);
1003 info.tags.clone_from(&room_info.deref().1);
1004
1005 if let Some(alias) = &alias {
1006 store.application.names.insert(alias.to_string(), room_id.to_owned());
1007 }
1008
1009 RoomItem { room_info, name, alias, unread }
1010 }
1011
1012 #[inline]
1013 fn room(&self) -> &MatrixRoom {
1014 &self.room_info.deref().0
1015 }
1016
1017 #[inline]
1018 fn tags(&self) -> &Option<Tags> {
1019 &self.room_info.deref().1
1020 }
1021}
1022
1023impl RoomLikeItem for RoomItem {
1024 fn name(&self) -> &str {
1025 self.name.as_str()
1026 }
1027
1028 fn alias(&self) -> Option<&RoomAliasId> {
1029 self.alias.as_deref()
1030 }
1031
1032 fn room_id(&self) -> &RoomId {
1033 self.room().room_id()
1034 }
1035
1036 fn has_tag(&self, tag: TagName) -> bool {
1037 if let Some(tags) = &self.room_info.deref().1 {
1038 tags.contains_key(&tag)
1039 } else {
1040 false
1041 }
1042 }
1043
1044 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1045 self.unread.latest()
1046 }
1047
1048 fn is_unread(&self) -> bool {
1049 self.unread.is_unread()
1050 }
1051
1052 fn is_invite(&self) -> bool {
1053 self.room().state() == MatrixRoomState::Invited
1054 }
1055}
1056
1057impl Display for RoomItem {
1058 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1059 write!(f, "{}", self.name)
1060 }
1061}
1062
1063impl ListItem<IambInfo> for RoomItem {
1064 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1065 let unread = self.unread.is_unread();
1066 let style = selected_style(selected);
1067 let (name, mut labels) = name_and_labels(&self.name, unread, style);
1068 let mut spans = vec![name];
1069
1070 if let Some(tags) = &self.tags() {
1071 labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
1072 }
1073
1074 append_tags(labels, &mut spans, style);
1075
1076 Text::from(Line::from(spans))
1077 }
1078
1079 fn get_word(&self) -> Option<String> {
1080 self.room_id().to_string().into()
1081 }
1082}
1083
1084impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomItem {
1085 fn prompt(
1086 &mut self,
1087 act: &PromptAction,
1088 ctx: &ProgramContext,
1089 _: &mut ProgramStore,
1090 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1091 room_prompt(self.room_id(), act, ctx)
1092 }
1093}
1094
1095#[derive(Clone)]
1096pub struct DirectItem {
1097 room_info: MatrixRoomInfo,
1098 name: String,
1099 alias: Option<OwnedRoomAliasId>,
1100 unread: UnreadInfo,
1101}
1102
1103impl DirectItem {
1104 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
1105 let room_id = room_info.0.room_id().to_owned();
1106 let alias = room_info.0.canonical_alias();
1107
1108 let info = store.application.rooms.get_or_default(room_id);
1109 let name = info.name.clone().unwrap_or_default();
1110 let unread = info.unreads(&store.application.settings);
1111 info.tags.clone_from(&room_info.deref().1);
1112
1113 DirectItem { room_info, name, alias, unread }
1114 }
1115
1116 #[inline]
1117 fn room(&self) -> &MatrixRoom {
1118 &self.room_info.deref().0
1119 }
1120
1121 #[inline]
1122 fn tags(&self) -> &Option<Tags> {
1123 &self.room_info.deref().1
1124 }
1125}
1126
1127impl RoomLikeItem for DirectItem {
1128 fn name(&self) -> &str {
1129 self.name.as_str()
1130 }
1131
1132 fn alias(&self) -> Option<&RoomAliasId> {
1133 self.alias.as_deref()
1134 }
1135
1136 fn has_tag(&self, tag: TagName) -> bool {
1137 if let Some(tags) = &self.room_info.deref().1 {
1138 tags.contains_key(&tag)
1139 } else {
1140 false
1141 }
1142 }
1143
1144 fn room_id(&self) -> &RoomId {
1145 self.room().room_id()
1146 }
1147
1148 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1149 self.unread.latest()
1150 }
1151
1152 fn is_unread(&self) -> bool {
1153 self.unread.is_unread()
1154 }
1155
1156 fn is_invite(&self) -> bool {
1157 self.room().state() == MatrixRoomState::Invited
1158 }
1159}
1160
1161impl Display for DirectItem {
1162 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1163 write!(f, ":verify request {}", self.name)
1164 }
1165}
1166
1167impl ListItem<IambInfo> for DirectItem {
1168 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1169 let unread = self.unread.is_unread();
1170 let style = selected_style(selected);
1171 let (name, mut labels) = name_and_labels(&self.name, unread, style);
1172 let mut spans = vec![name];
1173
1174 if let Some(tags) = &self.tags() {
1175 labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
1176 }
1177
1178 append_tags(labels, &mut spans, style);
1179
1180 Text::from(Line::from(spans))
1181 }
1182
1183 fn get_word(&self) -> Option<String> {
1184 self.room_id().to_string().into()
1185 }
1186}
1187
1188impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
1189 fn prompt(
1190 &mut self,
1191 act: &PromptAction,
1192 ctx: &ProgramContext,
1193 _: &mut ProgramStore,
1194 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1195 room_prompt(self.room_id(), act, ctx)
1196 }
1197}
1198
1199#[derive(Clone)]
1200pub struct SpaceItem {
1201 room_info: MatrixRoomInfo,
1202 name: String,
1203 alias: Option<OwnedRoomAliasId>,
1204}
1205
1206impl SpaceItem {
1207 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
1208 let room_id = room_info.0.room_id();
1209 let name = store
1210 .application
1211 .get_room_info(room_id.to_owned())
1212 .name
1213 .clone()
1214 .unwrap_or_default();
1215 let alias = room_info.0.canonical_alias();
1216
1217 if let Some(alias) = &alias {
1218 store.application.names.insert(alias.to_string(), room_id.to_owned());
1219 }
1220
1221 SpaceItem { room_info, name, alias }
1222 }
1223
1224 #[inline]
1225 fn room(&self) -> &MatrixRoom {
1226 &self.room_info.deref().0
1227 }
1228}
1229
1230impl RoomLikeItem for SpaceItem {
1231 fn name(&self) -> &str {
1232 self.name.as_str()
1233 }
1234
1235 fn room_id(&self) -> &RoomId {
1236 self.room().room_id()
1237 }
1238
1239 fn alias(&self) -> Option<&RoomAliasId> {
1240 self.alias.as_deref()
1241 }
1242
1243 fn has_tag(&self, _: TagName) -> bool {
1244 // I think that spaces can technically have tags, but afaik no client
1245 // exposes them, so we'll just always return false here for now.
1246 false
1247 }
1248
1249 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1250 // XXX: this needs to determine the room with most recent message and return its timestamp.
1251 None
1252 }
1253
1254 fn is_unread(&self) -> bool {
1255 // XXX: this needs to check whether the space contains rooms with unread messages
1256 false
1257 }
1258
1259 fn is_invite(&self) -> bool {
1260 self.room().state() == MatrixRoomState::Invited
1261 }
1262}
1263
1264impl Display for SpaceItem {
1265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1266 write!(f, "{}", self.name)
1267 }
1268}
1269
1270impl ListItem<IambInfo> for SpaceItem {
1271 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1272 selected_text(self.name.as_str(), selected)
1273 }
1274
1275 fn get_word(&self) -> Option<String> {
1276 self.room_id().to_string().into()
1277 }
1278}
1279
1280impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
1281 fn prompt(
1282 &mut self,
1283 act: &PromptAction,
1284 ctx: &ProgramContext,
1285 _: &mut ProgramStore,
1286 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1287 room_prompt(self.room_id(), act, ctx)
1288 }
1289}
1290
1291#[derive(Clone)]
1292pub struct VerifyItem {
1293 user_dev: String,
1294 sasv1: SasVerification,
1295}
1296
1297impl VerifyItem {
1298 fn new(user_dev: String, sasv1: SasVerification) -> Self {
1299 VerifyItem { user_dev, sasv1 }
1300 }
1301
1302 fn show_item(&self) -> String {
1303 let state = if self.sasv1.is_done() {
1304 "done"
1305 } else if self.sasv1.is_cancelled() {
1306 "cancelled"
1307 } else if self.sasv1.emoji().is_some() {
1308 "accepted"
1309 } else {
1310 "not accepted"
1311 };
1312
1313 if self.sasv1.is_self_verification() {
1314 let device = self.sasv1.other_device();
1315
1316 if let Some(display_name) = device.display_name() {
1317 format!("Device verification with {display_name} ({state})")
1318 } else {
1319 format!("Device verification with device {} ({})", device.device_id(), state)
1320 }
1321 } else {
1322 format!("User Verification with {} ({})", self.sasv1.other_user_id(), state)
1323 }
1324 }
1325}
1326
1327impl PartialEq for VerifyItem {
1328 fn eq(&self, other: &Self) -> bool {
1329 self.user_dev == other.user_dev
1330 }
1331}
1332
1333impl Eq for VerifyItem {}
1334
1335impl Ord for VerifyItem {
1336 fn cmp(&self, other: &Self) -> Ordering {
1337 fn state_val(sas: &SasVerification) -> usize {
1338 if sas.is_done() {
1339 return 3;
1340 } else if sas.is_cancelled() {
1341 return 2;
1342 } else {
1343 return 1;
1344 }
1345 }
1346
1347 fn device_val(sas: &SasVerification) -> usize {
1348 if sas.is_self_verification() {
1349 return 1;
1350 } else {
1351 return 2;
1352 }
1353 }
1354
1355 let state1 = state_val(&self.sasv1);
1356 let state2 = state_val(&other.sasv1);
1357
1358 let dev1 = device_val(&self.sasv1);
1359 let dev2 = device_val(&other.sasv1);
1360
1361 let scmp = state1.cmp(&state2);
1362 let dcmp = dev1.cmp(&dev2);
1363
1364 scmp.then(dcmp).then_with(|| {
1365 let did1 = self.sasv1.other_device().device_id();
1366 let did2 = other.sasv1.other_device().device_id();
1367
1368 did1.cmp(did2)
1369 })
1370 }
1371}
1372
1373impl PartialOrd for VerifyItem {
1374 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1375 Some(self.cmp(other))
1376 }
1377}
1378
1379impl From<(&String, &SasVerification)> for VerifyItem {
1380 fn from((user_dev, sasv1): (&String, &SasVerification)) -> Self {
1381 VerifyItem::new(user_dev.clone(), sasv1.clone())
1382 }
1383}
1384
1385impl Display for VerifyItem {
1386 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1387 if self.sasv1.is_done() {
1388 return Ok(());
1389 }
1390
1391 if self.sasv1.is_cancelled() {
1392 write!(f, ":verify request {}", self.sasv1.other_user_id())
1393 } else if self.sasv1.emoji().is_some() {
1394 write!(f, ":verify confirm {}", self.user_dev)
1395 } else {
1396 write!(f, ":verify accept {}", self.user_dev)
1397 }
1398 }
1399}
1400
1401impl ListItem<IambInfo> for VerifyItem {
1402 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1403 let mut lines = vec![];
1404
1405 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1406 let item = Span::styled(self.show_item(), selected_style(selected));
1407 lines.push(Line::from(item));
1408
1409 if self.sasv1.is_done() {
1410 // Print nothing.
1411 } else if self.sasv1.is_cancelled() {
1412 if let Some(info) = self.sasv1.cancel_info() {
1413 lines.push(Line::from(format!(" Cancelled: {}", info.reason())));
1414 lines.push(Line::from(""));
1415 }
1416
1417 lines.push(Line::from(" You can start a new verification request with:"));
1418 } else if let Some(emoji) = self.sasv1.emoji() {
1419 lines.push(Line::from(
1420 " Both devices should see the following Emoji sequence:".to_string(),
1421 ));
1422 lines.push(Line::from(""));
1423
1424 for line in format_emojis(emoji).lines() {
1425 lines.push(Line::from(format!(" {line}")));
1426 }
1427
1428 lines.push(Line::from(""));
1429 lines.push(Line::from(" If they don't match, run:"));
1430 lines.push(Line::from(""));
1431 lines.push(Line::from(Span::styled(
1432 format!(":verify mismatch {}", self.user_dev),
1433 bold,
1434 )));
1435 lines.push(Line::from(""));
1436 lines.push(Line::from(" If everything looks right, you can confirm with:"));
1437 } else {
1438 lines.push(Line::from(" To accept this request, run:"));
1439 }
1440
1441 let cmd = self.to_string();
1442
1443 if !cmd.is_empty() {
1444 lines.push(Line::from(""));
1445 lines.push(Line::from(vec![Span::from(" "), Span::styled(cmd, bold)]));
1446 lines.push(Line::from(""));
1447 lines.push(Line::from(vec![
1448 Span::from("You can copy the above command with "),
1449 Span::styled("yy", bold),
1450 Span::from(" and then execute it with "),
1451 Span::styled("@\"", bold),
1452 ]));
1453 }
1454
1455 Text::from(lines)
1456 }
1457
1458 fn get_word(&self) -> Option<String> {
1459 None
1460 }
1461}
1462
1463impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
1464 fn prompt(
1465 &mut self,
1466 act: &PromptAction,
1467 _: &ProgramContext,
1468 _: &mut ProgramStore,
1469 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1470 match act {
1471 PromptAction::Submit => Ok(vec![]),
1472 PromptAction::Abort(_) => {
1473 let msg = "Cannot abort entry inside a list";
1474 let err = EditError::Failure(msg.into());
1475
1476 Err(err)
1477 },
1478 PromptAction::Recall(..) => {
1479 let msg = "Cannot recall history inside a list";
1480 let err = EditError::Failure(msg.into());
1481
1482 Err(err)
1483 },
1484 }
1485 }
1486}
1487
1488#[derive(Clone)]
1489pub struct MemberItem {
1490 member: RoomMember,
1491 room_id: OwnedRoomId,
1492}
1493
1494impl MemberItem {
1495 fn new(member: RoomMember, room_id: OwnedRoomId) -> Self {
1496 Self { member, room_id }
1497 }
1498}
1499
1500impl Display for MemberItem {
1501 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1502 write!(f, "{}", self.member.user_id())
1503 }
1504}
1505
1506impl ListItem<IambInfo> for MemberItem {
1507 fn show(
1508 &self,
1509 selected: bool,
1510 _: &ViewportContext<ListCursor>,
1511 store: &mut ProgramStore,
1512 ) -> Text {
1513 let info = store.application.rooms.get_or_default(self.room_id.clone());
1514 let user_id = self.member.user_id();
1515
1516 let (color, name) = store.application.settings.get_user_overrides(self.member.user_id());
1517 let color = color.unwrap_or_else(|| super::config::user_color(user_id.as_str()));
1518 let mut style = super::config::user_style_from_color(color);
1519
1520 if selected {
1521 style = style.add_modifier(StyleModifier::REVERSED);
1522 }
1523
1524 let mut spans = vec![];
1525 let mut parens = false;
1526
1527 if let Some(name) = name {
1528 spans.push(Span::styled(name, style));
1529 parens = true;
1530 } else if let Some(display) = info.display_names.get(user_id) {
1531 spans.push(Span::styled(display.clone(), style));
1532 parens = true;
1533 }
1534
1535 spans.extend(parens.then_some(Span::styled(" (", style)));
1536 spans.push(Span::styled(user_id.as_str(), style));
1537 spans.extend(parens.then_some(Span::styled(")", style)));
1538
1539 let state = match self.member.membership() {
1540 MembershipState::Ban => Span::raw(" (banned)").into(),
1541 MembershipState::Invite => Span::raw(" (invited)").into(),
1542 MembershipState::Knock => Span::raw(" (wants to join)").into(),
1543 MembershipState::Leave => Span::raw(" (left)").into(),
1544 MembershipState::Join => None,
1545 _ => None,
1546 };
1547
1548 spans.extend(state);
1549
1550 return Line::from(spans).into();
1551 }
1552
1553 fn get_word(&self) -> Option<String> {
1554 self.member.user_id().to_string().into()
1555 }
1556}
1557
1558impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
1559 fn prompt(
1560 &mut self,
1561 act: &PromptAction,
1562 _: &ProgramContext,
1563 _: &mut ProgramStore,
1564 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1565 match act {
1566 PromptAction::Submit => Ok(vec![]),
1567 PromptAction::Abort(_) => {
1568 let msg = "Cannot abort entry inside a list";
1569 let err = EditError::Failure(msg.into());
1570
1571 Err(err)
1572 },
1573 PromptAction::Recall(..) => {
1574 let msg = "Cannot recall history inside a list";
1575 let err = EditError::Failure(msg.into());
1576
1577 Err(err)
1578 },
1579 }
1580 }
1581}
1582
1583#[cfg(test)]
1584mod tests {
1585 use super::*;
1586 use matrix_sdk::ruma::{room_alias_id, server_name};
1587
1588 #[derive(Debug, Eq, PartialEq)]
1589 struct TestRoomItem {
1590 room_id: OwnedRoomId,
1591 tags: Vec<TagName>,
1592 alias: Option<OwnedRoomAliasId>,
1593 name: &'static str,
1594 unread: UnreadInfo,
1595 invite: bool,
1596 }
1597
1598 impl RoomLikeItem for &TestRoomItem {
1599 fn room_id(&self) -> &RoomId {
1600 self.room_id.as_ref()
1601 }
1602
1603 fn has_tag(&self, tag: TagName) -> bool {
1604 self.tags.contains(&tag)
1605 }
1606
1607 fn alias(&self) -> Option<&RoomAliasId> {
1608 self.alias.as_deref()
1609 }
1610
1611 fn name(&self) -> &str {
1612 self.name
1613 }
1614
1615 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1616 self.unread.latest()
1617 }
1618
1619 fn is_unread(&self) -> bool {
1620 self.unread.is_unread()
1621 }
1622
1623 fn is_invite(&self) -> bool {
1624 self.invite
1625 }
1626 }
1627
1628 #[test]
1629 fn test_sort_rooms() {
1630 let server = server_name!("example.com");
1631
1632 let room1 = TestRoomItem {
1633 room_id: RoomId::new(server).to_owned(),
1634 tags: vec![TagName::Favorite],
1635 alias: Some(room_alias_id!("#room1:example.com").to_owned()),
1636 name: "Z",
1637 unread: UnreadInfo::default(),
1638 invite: false,
1639 };
1640
1641 let room2 = TestRoomItem {
1642 room_id: RoomId::new(server).to_owned(),
1643 tags: vec![],
1644 alias: Some(room_alias_id!("#a:example.com").to_owned()),
1645 name: "Unnamed Room",
1646 unread: UnreadInfo::default(),
1647 invite: false,
1648 };
1649
1650 let room3 = TestRoomItem {
1651 room_id: RoomId::new(server).to_owned(),
1652 tags: vec![],
1653 alias: None,
1654 name: "Cool Room",
1655 unread: UnreadInfo::default(),
1656 invite: false,
1657 };
1658
1659 // Sort by Name ascending.
1660 let mut rooms = vec![&room1, &room2, &room3];
1661 let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Ascending)];
1662 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1663 assert_eq!(rooms, vec![&room3, &room2, &room1]);
1664
1665 // Sort by Name descending.
1666 let mut rooms = vec![&room1, &room2, &room3];
1667 let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Descending)];
1668 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1669 assert_eq!(rooms, vec![&room1, &room2, &room3]);
1670
1671 // Sort by Favorite and Alias before Name to show order matters.
1672 let mut rooms = vec![&room1, &room2, &room3];
1673 let fields = &[
1674 SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
1675 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1676 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1677 ];
1678 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1679 assert_eq!(rooms, vec![&room1, &room2, &room3]);
1680
1681 // Now flip order of Favorite with Descending
1682 let mut rooms = vec![&room1, &room2, &room3];
1683 let fields = &[
1684 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1685 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1686 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1687 ];
1688 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1689 assert_eq!(rooms, vec![&room2, &room3, &room1]);
1690 }
1691
1692 #[test]
1693 fn test_sort_room_recents() {
1694 let server = server_name!("example.com");
1695
1696 let room1 = TestRoomItem {
1697 room_id: RoomId::new(server).to_owned(),
1698 tags: vec![],
1699 alias: None,
1700 name: "Room 1",
1701 unread: UnreadInfo { unread: false, latest: None },
1702 invite: false,
1703 };
1704
1705 let room2 = TestRoomItem {
1706 room_id: RoomId::new(server).to_owned(),
1707 tags: vec![],
1708 alias: None,
1709 name: "Room 2",
1710 unread: UnreadInfo {
1711 unread: false,
1712 latest: Some(MessageTimeStamp::OriginServer(40u32.into())),
1713 },
1714 invite: false,
1715 };
1716
1717 let room3 = TestRoomItem {
1718 room_id: RoomId::new(server).to_owned(),
1719 tags: vec![],
1720 alias: None,
1721 name: "Room 3",
1722 unread: UnreadInfo {
1723 unread: false,
1724 latest: Some(MessageTimeStamp::OriginServer(20u32.into())),
1725 },
1726 invite: false,
1727 };
1728
1729 // Sort by Recent ascending.
1730 let mut rooms = vec![&room1, &room2, &room3];
1731 let fields = &[SortColumn(SortFieldRoom::Recent, SortOrder::Ascending)];
1732 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1733 assert_eq!(rooms, vec![&room2, &room3, &room1]);
1734
1735 // Sort by Recent descending.
1736 let mut rooms = vec![&room1, &room2, &room3];
1737 let fields = &[SortColumn(SortFieldRoom::Recent, SortOrder::Descending)];
1738 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1739 assert_eq!(rooms, vec![&room1, &room3, &room2]);
1740 }
1741
1742 #[test]
1743 fn test_sort_room_invites() {
1744 let server = server_name!("example.com");
1745
1746 let room1 = TestRoomItem {
1747 room_id: RoomId::new(server).to_owned(),
1748 tags: vec![],
1749 alias: None,
1750 name: "Old room 1",
1751 unread: UnreadInfo::default(),
1752 invite: false,
1753 };
1754
1755 let room2 = TestRoomItem {
1756 room_id: RoomId::new(server).to_owned(),
1757 tags: vec![],
1758 alias: None,
1759 name: "Old room 2",
1760 unread: UnreadInfo::default(),
1761 invite: false,
1762 };
1763
1764 let room3 = TestRoomItem {
1765 room_id: RoomId::new(server).to_owned(),
1766 tags: vec![],
1767 alias: None,
1768 name: "New Fancy Room",
1769 unread: UnreadInfo::default(),
1770 invite: true,
1771 };
1772
1773 // Sort invites first
1774 let mut rooms = vec![&room1, &room2, &room3];
1775 let fields = &[
1776 SortColumn(SortFieldRoom::Invite, SortOrder::Ascending),
1777 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1778 ];
1779 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1780 assert_eq!(rooms, vec![&room3, &room1, &room2]);
1781
1782 // Sort invites after
1783 let mut rooms = vec![&room1, &room2, &room3];
1784 let fields = &[
1785 SortColumn(SortFieldRoom::Invite, SortOrder::Descending),
1786 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1787 ];
1788 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1789 assert_eq!(rooms, vec![&room1, &room2, &room3]);
1790 }
1791}