src/windows/mod.rs

987 lines · 28864 bytes

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