src/windows/mod.rs

1142 lines · 33500 bytes

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