src/windows/mod.rs

1194 lines · 35033 bytes

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