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