src/windows/mod.rs

1132 lines · 33120 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(_, room_id, _) => {
 533                let title = store.application.get_room_title(room_id.as_ref());
 534
 535                Spans(vec![bold_span("Room Members: "), title.into()])
 536            },
 537        }
 538    }
 539
 540    fn get_win_title(&self, store: &mut ProgramStore) -> Spans {
 541        match self {
 542            IambWindow::DirectList(_) => bold_spans("Direct Messages"),
 543            IambWindow::RoomList(_) => bold_spans("Rooms"),
 544            IambWindow::SpaceList(_) => bold_spans("Spaces"),
 545            IambWindow::VerifyList(_) => bold_spans("Verifications"),
 546            IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
 547
 548            IambWindow::Room(w) => w.get_title(store),
 549            IambWindow::MemberList(_, room_id, _) => {
 550                let title = store.application.get_room_title(room_id.as_ref());
 551
 552                Spans(vec![bold_span("Room Members: "), title.into()])
 553            },
 554        }
 555    }
 556
 557    fn open(id: IambId, store: &mut ProgramStore) -> IambResult<Self> {
 558        match id {
 559            IambId::Room(room_id) => {
 560                let (room, name, tags) = store.application.worker.get_room(room_id)?;
 561                let room = RoomState::new(room, name, tags, store);
 562
 563                return Ok(room.into());
 564            },
 565            IambId::DirectList => {
 566                let list = DirectListState::new(IambBufferId::DirectList, vec![]);
 567
 568                return Ok(list.into());
 569            },
 570            IambId::MemberList(room_id) => {
 571                let id = IambBufferId::MemberList(room_id.clone());
 572                let list = MemberListState::new(id, vec![]);
 573                let win = IambWindow::MemberList(list, room_id, None);
 574
 575                return Ok(win);
 576            },
 577            IambId::RoomList => {
 578                let list = RoomListState::new(IambBufferId::RoomList, vec![]);
 579
 580                return Ok(list.into());
 581            },
 582            IambId::SpaceList => {
 583                let list = SpaceListState::new(IambBufferId::SpaceList, vec![]);
 584
 585                return Ok(list.into());
 586            },
 587            IambId::VerifyList => {
 588                let list = VerifyListState::new(IambBufferId::VerifyList, vec![]);
 589
 590                return Ok(list.into());
 591            },
 592            IambId::Welcome => {
 593                let win = WelcomeState::new(store);
 594
 595                return Ok(win.into());
 596            },
 597        }
 598    }
 599
 600    fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
 601        let ChatStore { names, worker, .. } = &mut store.application;
 602
 603        if let Some(room) = names.get_mut(&name) {
 604            let id = IambId::Room(room.clone());
 605
 606            IambWindow::open(id, store)
 607        } else {
 608            let room_id = worker.join_room(name.clone())?;
 609            names.insert(name, room_id.clone());
 610
 611            let (room, name, tags) = store.application.worker.get_room(room_id)?;
 612            let room = RoomState::new(room, name, tags, store);
 613
 614            Ok(room.into())
 615        }
 616    }
 617
 618    fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
 619        let msg = format!("Cannot find indexed buffer (index = {index})");
 620        let err = UIError::Unimplemented(msg);
 621
 622        Err(err)
 623    }
 624
 625    fn unnamed(store: &mut ProgramStore) -> IambResult<Self> {
 626        Self::open(IambId::RoomList, store)
 627    }
 628}
 629
 630#[derive(Clone)]
 631pub struct RoomItem {
 632    room: MatrixRoom,
 633    tags: Option<Tags>,
 634    name: String,
 635}
 636
 637impl RoomItem {
 638    fn new(
 639        room: MatrixRoom,
 640        name: DisplayName,
 641        tags: Option<Tags>,
 642        store: &mut ProgramStore,
 643    ) -> Self {
 644        let name = name.to_string();
 645        let room_id = room.room_id();
 646
 647        let info = store.application.get_room_info(room_id.to_owned());
 648        info.name = name.clone().into();
 649        info.tags = tags.clone();
 650
 651        if let Some(alias) = room.canonical_alias() {
 652            store.application.names.insert(alias.to_string(), room_id.to_owned());
 653        }
 654
 655        RoomItem { room, tags, name }
 656    }
 657}
 658
 659impl PartialEq for RoomItem {
 660    fn eq(&self, other: &Self) -> bool {
 661        self.room.room_id() == other.room.room_id()
 662    }
 663}
 664
 665impl Eq for RoomItem {}
 666
 667impl Ord for RoomItem {
 668    fn cmp(&self, other: &Self) -> Ordering {
 669        tag_cmp(&self.tags, &other.tags).then_with(|| room_cmp(&self.room, &other.room))
 670    }
 671}
 672
 673impl PartialOrd for RoomItem {
 674    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 675        self.cmp(other).into()
 676    }
 677}
 678
 679impl ToString for RoomItem {
 680    fn to_string(&self) -> String {
 681        return self.name.clone();
 682    }
 683}
 684
 685impl ListItem<IambInfo> for RoomItem {
 686    fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
 687        if let Some(tags) = &self.tags {
 688            let style = selected_style(selected);
 689            let mut spans = vec![Span::styled(self.name.as_str(), style)];
 690
 691            append_tags(tags, &mut spans, style);
 692
 693            Text::from(Spans(spans))
 694        } else {
 695            selected_text(self.name.as_str(), selected)
 696        }
 697    }
 698
 699    fn get_word(&self) -> Option<String> {
 700        self.room.room_id().to_string().into()
 701    }
 702}
 703
 704impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomItem {
 705    fn prompt(
 706        &mut self,
 707        act: &PromptAction,
 708        ctx: &ProgramContext,
 709        _: &mut ProgramStore,
 710    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 711        room_prompt(self.room.room_id(), act, ctx)
 712    }
 713}
 714
 715#[derive(Clone)]
 716pub struct DirectItem {
 717    room: MatrixRoom,
 718    tags: Option<Tags>,
 719    name: String,
 720}
 721
 722impl DirectItem {
 723    fn new(
 724        room: MatrixRoom,
 725        name: DisplayName,
 726        tags: Option<Tags>,
 727        store: &mut ProgramStore,
 728    ) -> Self {
 729        let name = name.to_string();
 730
 731        store.application.set_room_name(room.room_id(), name.as_str());
 732
 733        DirectItem { room, tags, name }
 734    }
 735}
 736
 737impl ToString for DirectItem {
 738    fn to_string(&self) -> String {
 739        return self.name.clone();
 740    }
 741}
 742
 743impl ListItem<IambInfo> for DirectItem {
 744    fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
 745        if let Some(tags) = &self.tags {
 746            let style = selected_style(selected);
 747            let mut spans = vec![Span::styled(self.name.as_str(), style)];
 748
 749            append_tags(tags, &mut spans, style);
 750
 751            Text::from(Spans(spans))
 752        } else {
 753            selected_text(self.name.as_str(), selected)
 754        }
 755    }
 756
 757    fn get_word(&self) -> Option<String> {
 758        self.room.room_id().to_string().into()
 759    }
 760}
 761
 762impl PartialEq for DirectItem {
 763    fn eq(&self, other: &Self) -> bool {
 764        self.room.room_id() == other.room.room_id()
 765    }
 766}
 767
 768impl Eq for DirectItem {}
 769
 770impl Ord for DirectItem {
 771    fn cmp(&self, other: &Self) -> Ordering {
 772        tag_cmp(&self.tags, &other.tags).then_with(|| room_cmp(&self.room, &other.room))
 773    }
 774}
 775
 776impl PartialOrd for DirectItem {
 777    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 778        self.cmp(other).into()
 779    }
 780}
 781
 782impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
 783    fn prompt(
 784        &mut self,
 785        act: &PromptAction,
 786        ctx: &ProgramContext,
 787        _: &mut ProgramStore,
 788    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 789        room_prompt(self.room.room_id(), act, ctx)
 790    }
 791}
 792
 793#[derive(Clone)]
 794pub struct SpaceItem {
 795    room: MatrixRoom,
 796    name: String,
 797}
 798
 799impl SpaceItem {
 800    fn new(room: MatrixRoom, name: DisplayName, store: &mut ProgramStore) -> Self {
 801        let name = name.to_string();
 802        let room_id = room.room_id();
 803
 804        store.application.set_room_name(room_id, name.as_str());
 805
 806        if let Some(alias) = room.canonical_alias() {
 807            store.application.names.insert(alias.to_string(), room_id.to_owned());
 808        }
 809
 810        SpaceItem { room, name }
 811    }
 812}
 813
 814impl PartialEq for SpaceItem {
 815    fn eq(&self, other: &Self) -> bool {
 816        self.room.room_id() == other.room.room_id()
 817    }
 818}
 819
 820impl Eq for SpaceItem {}
 821
 822impl Ord for SpaceItem {
 823    fn cmp(&self, other: &Self) -> Ordering {
 824        room_cmp(&self.room, &other.room)
 825    }
 826}
 827
 828impl PartialOrd for SpaceItem {
 829    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 830        self.cmp(other).into()
 831    }
 832}
 833
 834impl ToString for SpaceItem {
 835    fn to_string(&self) -> String {
 836        return self.room.room_id().to_string();
 837    }
 838}
 839
 840impl ListItem<IambInfo> for SpaceItem {
 841    fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
 842        selected_text(self.name.as_str(), selected)
 843    }
 844
 845    fn get_word(&self) -> Option<String> {
 846        self.room.room_id().to_string().into()
 847    }
 848}
 849
 850impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
 851    fn prompt(
 852        &mut self,
 853        act: &PromptAction,
 854        ctx: &ProgramContext,
 855        _: &mut ProgramStore,
 856    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 857        room_prompt(self.room.room_id(), act, ctx)
 858    }
 859}
 860
 861#[derive(Clone)]
 862pub struct VerifyItem {
 863    user_dev: String,
 864    sasv1: SasVerification,
 865}
 866
 867impl VerifyItem {
 868    fn new(user_dev: String, sasv1: SasVerification) -> Self {
 869        VerifyItem { user_dev, sasv1 }
 870    }
 871
 872    fn show_item(&self) -> String {
 873        let state = if self.sasv1.is_done() {
 874            "done"
 875        } else if self.sasv1.is_cancelled() {
 876            "cancelled"
 877        } else if self.sasv1.emoji().is_some() {
 878            "accepted"
 879        } else {
 880            "not accepted"
 881        };
 882
 883        if self.sasv1.is_self_verification() {
 884            let device = self.sasv1.other_device();
 885
 886            if let Some(display_name) = device.display_name() {
 887                format!("Device verification with {display_name} ({state})")
 888            } else {
 889                format!("Device verification with device {} ({})", device.device_id(), state)
 890            }
 891        } else {
 892            format!("User Verification with {} ({})", self.sasv1.other_user_id(), state)
 893        }
 894    }
 895}
 896
 897impl PartialEq for VerifyItem {
 898    fn eq(&self, other: &Self) -> bool {
 899        self.user_dev == other.user_dev
 900    }
 901}
 902
 903impl Eq for VerifyItem {}
 904
 905impl Ord for VerifyItem {
 906    fn cmp(&self, other: &Self) -> Ordering {
 907        fn state_val(sas: &SasVerification) -> usize {
 908            if sas.is_done() {
 909                return 3;
 910            } else if sas.is_cancelled() {
 911                return 2;
 912            } else {
 913                return 1;
 914            }
 915        }
 916
 917        fn device_val(sas: &SasVerification) -> usize {
 918            if sas.is_self_verification() {
 919                return 1;
 920            } else {
 921                return 2;
 922            }
 923        }
 924
 925        let state1 = state_val(&self.sasv1);
 926        let state2 = state_val(&other.sasv1);
 927
 928        let dev1 = device_val(&self.sasv1);
 929        let dev2 = device_val(&other.sasv1);
 930
 931        let scmp = state1.cmp(&state2);
 932        let dcmp = dev1.cmp(&dev2);
 933
 934        scmp.then(dcmp).then_with(|| {
 935            let did1 = self.sasv1.other_device().device_id();
 936            let did2 = other.sasv1.other_device().device_id();
 937
 938            did1.cmp(did2)
 939        })
 940    }
 941}
 942
 943impl PartialOrd for VerifyItem {
 944    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 945        self.cmp(other).into()
 946    }
 947}
 948
 949impl From<(&String, &SasVerification)> for VerifyItem {
 950    fn from((user_dev, sasv1): (&String, &SasVerification)) -> Self {
 951        VerifyItem::new(user_dev.clone(), sasv1.clone())
 952    }
 953}
 954
 955impl ToString for VerifyItem {
 956    fn to_string(&self) -> String {
 957        if self.sasv1.is_done() {
 958            String::new()
 959        } else if self.sasv1.is_cancelled() {
 960            format!(":verify request {}", self.sasv1.other_user_id())
 961        } else if self.sasv1.emoji().is_some() {
 962            format!(":verify confirm {}", self.user_dev)
 963        } else {
 964            format!(":verify accept {}", self.user_dev)
 965        }
 966    }
 967}
 968
 969impl ListItem<IambInfo> for VerifyItem {
 970    fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
 971        let mut lines = vec![];
 972
 973        let bold = Style::default().add_modifier(StyleModifier::BOLD);
 974        let item = Span::styled(self.show_item(), selected_style(selected));
 975        lines.push(Spans::from(item));
 976
 977        if self.sasv1.is_done() {
 978            // Print nothing.
 979        } else if self.sasv1.is_cancelled() {
 980            if let Some(info) = self.sasv1.cancel_info() {
 981                lines.push(Spans::from(format!("    Cancelled: {}", info.reason())));
 982                lines.push(Spans::from(""));
 983            }
 984
 985            lines.push(Spans::from("    You can start a new verification request with:"));
 986        } else if let Some(emoji) = self.sasv1.emoji() {
 987            lines.push(Spans::from(
 988                "    Both devices should see the following Emoji sequence:".to_string(),
 989            ));
 990            lines.push(Spans::from(""));
 991
 992            for line in format_emojis(emoji).lines() {
 993                lines.push(Spans::from(format!("    {line}")));
 994            }
 995
 996            lines.push(Spans::from(""));
 997            lines.push(Spans::from("    If they don't match, run:"));
 998            lines.push(Spans::from(""));
 999            lines.push(Spans::from(Span::styled(
1000                format!(":verify mismatch {}", self.user_dev),
1001                bold,
1002            )));
1003            lines.push(Spans::from(""));
1004            lines.push(Spans::from("    If everything looks right, you can confirm with:"));
1005        } else {
1006            lines.push(Spans::from("    To accept this request, run:"));
1007        }
1008
1009        let cmd = self.to_string();
1010
1011        if !cmd.is_empty() {
1012            lines.push(Spans::from(""));
1013            lines.push(Spans(vec![Span::from("        "), Span::styled(cmd, bold)]));
1014            lines.push(Spans::from(""));
1015            lines.push(Spans(vec![
1016                Span::from("You can copy the above command with "),
1017                Span::styled("yy", bold),
1018                Span::from(" and then execute it with "),
1019                Span::styled("@\"", bold),
1020            ]));
1021        }
1022
1023        Text { lines }
1024    }
1025
1026    fn get_word(&self) -> Option<String> {
1027        None
1028    }
1029}
1030
1031impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
1032    fn prompt(
1033        &mut self,
1034        act: &PromptAction,
1035        _: &ProgramContext,
1036        _: &mut ProgramStore,
1037    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1038        match act {
1039            PromptAction::Submit => Ok(vec![]),
1040            PromptAction::Abort(_) => {
1041                let msg = "Cannot abort entry inside a list";
1042                let err = EditError::Failure(msg.into());
1043
1044                Err(err)
1045            },
1046            PromptAction::Recall(_, _) => {
1047                let msg = "Cannot recall history inside a list";
1048                let err = EditError::Failure(msg.into());
1049
1050                Err(err)
1051            },
1052            _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
1053        }
1054    }
1055}
1056
1057#[derive(Clone)]
1058pub struct MemberItem {
1059    member: RoomMember,
1060}
1061
1062impl MemberItem {
1063    fn new(member: RoomMember) -> Self {
1064        Self { member }
1065    }
1066}
1067
1068impl ToString for MemberItem {
1069    fn to_string(&self) -> String {
1070        self.member.user_id().to_string()
1071    }
1072}
1073
1074impl ListItem<IambInfo> for MemberItem {
1075    fn show(
1076        &self,
1077        selected: bool,
1078        _: &ViewportContext<ListCursor>,
1079        store: &mut ProgramStore,
1080    ) -> Text {
1081        let mut user = store.application.settings.get_user_span(self.member.user_id());
1082
1083        if selected {
1084            user.style = user.style.add_modifier(StyleModifier::REVERSED);
1085        }
1086
1087        let state = match self.member.membership() {
1088            MembershipState::Ban => Span::raw(" (banned)").into(),
1089            MembershipState::Invite => Span::raw(" (invited)").into(),
1090            MembershipState::Knock => Span::raw(" (wants to join)").into(),
1091            MembershipState::Leave => Span::raw(" (left)").into(),
1092            MembershipState::Join => None,
1093            _ => None,
1094        };
1095
1096        if let Some(state) = state {
1097            Spans(vec![user, state]).into()
1098        } else {
1099            user.into()
1100        }
1101    }
1102
1103    fn get_word(&self) -> Option<String> {
1104        self.member.user_id().to_string().into()
1105    }
1106}
1107
1108impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
1109    fn prompt(
1110        &mut self,
1111        act: &PromptAction,
1112        _: &ProgramContext,
1113        _: &mut ProgramStore,
1114    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1115        match act {
1116            PromptAction::Submit => Ok(vec![]),
1117            PromptAction::Abort(_) => {
1118                let msg = "Cannot abort entry inside a list";
1119                let err = EditError::Failure(msg.into());
1120
1121                Err(err)
1122            },
1123            PromptAction::Recall(_, _) => {
1124                let msg = "Cannot recall history inside a list";
1125                let err = EditError::Failure(msg.into());
1126
1127                Err(err)
1128            },
1129            _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
1130        }
1131    }
1132}