src/windows/mod.rs

1524 lines · 46057 bytes

   1//! # Windows for the User Interface
   2//!
   3//! This module contains the logic for rendering windows, and handling UI actions that get
   4//! delegated to individual windows/UI elements (e.g., typing text or selecting a list item).
   5//!
   6//! Additionally, some of the iamb commands delegate behaviour to the current UI element. For
   7//! example, [sending messages][crate::base::SendAction] delegate to the [room window][RoomState],
   8//! where we have the message bar and room ID easily accesible and resetable.
   9use std::cmp::{Ord, Ordering, PartialOrd};
  10use std::ops::Deref;
  11use std::sync::Arc;
  12use std::time::{Duration, Instant};
  13
  14use matrix_sdk::{
  15    encryption::verification::{format_emojis, SasVerification},
  16    room::{Room as MatrixRoom, RoomMember},
  17    ruma::{
  18        events::room::member::MembershipState,
  19        events::tag::{TagName, Tags},
  20        OwnedRoomAliasId,
  21        OwnedRoomId,
  22        RoomAliasId,
  23        RoomId,
  24    },
  25};
  26
  27use modalkit::tui::{
  28    buffer::Buffer,
  29    layout::{Alignment, Rect},
  30    style::{Modifier as StyleModifier, Style},
  31    text::{Line, Span, Text},
  32    widgets::StatefulWidget,
  33};
  34
  35use modalkit::{
  36    editing::{
  37        action::{
  38            Action,
  39            EditError,
  40            EditInfo,
  41            EditResult,
  42            Editable,
  43            EditorAction,
  44            Jumpable,
  45            PromptAction,
  46            Promptable,
  47            Scrollable,
  48            UIError,
  49            WindowAction,
  50        },
  51        base::{
  52            CloseFlags,
  53            MoveDir1D,
  54            OpenTarget,
  55            PositionList,
  56            ScrollStyle,
  57            ViewportContext,
  58            WordStyle,
  59            WriteFlags,
  60        },
  61        completion::CompletionList,
  62    },
  63    widgets::{
  64        list::{List, ListCursor, ListItem, ListState},
  65        TermOffset,
  66        TerminalCursor,
  67        Window,
  68        WindowOps,
  69    },
  70};
  71
  72use crate::base::{
  73    ChatStore,
  74    IambBufferId,
  75    IambError,
  76    IambId,
  77    IambInfo,
  78    IambResult,
  79    MessageAction,
  80    Need,
  81    ProgramAction,
  82    ProgramContext,
  83    ProgramStore,
  84    RoomAction,
  85    SendAction,
  86    SortColumn,
  87    SortFieldRoom,
  88    SortFieldUser,
  89    SortOrder,
  90};
  91
  92use self::{room::RoomState, welcome::WelcomeState};
  93
  94pub mod room;
  95pub mod welcome;
  96
  97type MatrixRoomInfo = Arc<(MatrixRoom, Option<Tags>)>;
  98
  99const MEMBER_FETCH_DEBOUNCE: Duration = Duration::from_secs(5);
 100
 101#[inline]
 102fn bold_style() -> Style {
 103    Style::default().add_modifier(StyleModifier::BOLD)
 104}
 105
 106#[inline]
 107fn bold_span(s: &str) -> Span {
 108    Span::styled(s, bold_style())
 109}
 110
 111#[inline]
 112fn bold_spans(s: &str) -> Line {
 113    bold_span(s).into()
 114}
 115
 116#[inline]
 117fn selected_style(selected: bool) -> Style {
 118    if selected {
 119        Style::default().add_modifier(StyleModifier::REVERSED)
 120    } else {
 121        Style::default()
 122    }
 123}
 124
 125#[inline]
 126fn selected_span(s: &str, selected: bool) -> Span {
 127    Span::styled(s, selected_style(selected))
 128}
 129
 130#[inline]
 131fn selected_text(s: &str, selected: bool) -> Text {
 132    Text::from(selected_span(s, selected))
 133}
 134
 135/// Sort `Some` to be less than `None` so that list items with values come before those without.
 136#[inline]
 137fn some_cmp<T: Ord>(a: Option<T>, b: Option<T>) -> Ordering {
 138    match (a, b) {
 139        (Some(a), Some(b)) => a.cmp(&b),
 140        (None, None) => Ordering::Equal,
 141        (None, Some(_)) => Ordering::Greater,
 142        (Some(_), None) => Ordering::Less,
 143    }
 144}
 145
 146fn user_cmp(a: &MemberItem, b: &MemberItem, field: &SortFieldUser) -> Ordering {
 147    let a_id = a.member.user_id();
 148    let b_id = b.member.user_id();
 149
 150    match field {
 151        SortFieldUser::UserId => a_id.cmp(b_id),
 152        SortFieldUser::LocalPart => a_id.localpart().cmp(b_id.localpart()),
 153        SortFieldUser::Server => a_id.server_name().cmp(b_id.server_name()),
 154        SortFieldUser::PowerLevel => {
 155            // Sort higher power levels towards the top of the list.
 156            b.member.power_level().cmp(&a.member.power_level())
 157        },
 158    }
 159}
 160
 161fn room_cmp<T: RoomLikeItem>(a: &T, b: &T, field: &SortFieldRoom) -> Ordering {
 162    match field {
 163        SortFieldRoom::Favorite => {
 164            let fava = a.has_tag(TagName::Favorite);
 165            let favb = b.has_tag(TagName::Favorite);
 166
 167            // If a has Favorite and b doesn't, it should sort earlier in room list.
 168            favb.cmp(&fava)
 169        },
 170        SortFieldRoom::LowPriority => {
 171            let lowa = a.has_tag(TagName::LowPriority);
 172            let lowb = b.has_tag(TagName::LowPriority);
 173
 174            // If a has LowPriority and b doesn't, it should sort later in room list.
 175            lowa.cmp(&lowb)
 176        },
 177        SortFieldRoom::Name => a.name().cmp(b.name()),
 178        SortFieldRoom::Alias => some_cmp(a.alias(), b.alias()),
 179        SortFieldRoom::RoomId => a.room_id().cmp(b.room_id()),
 180    }
 181}
 182
 183/// Compare two rooms according the configured sort criteria.
 184fn room_fields_cmp<T: RoomLikeItem>(
 185    a: &T,
 186    b: &T,
 187    fields: &[SortColumn<SortFieldRoom>],
 188) -> Ordering {
 189    for SortColumn(field, order) in fields {
 190        match (room_cmp(a, b, field), order) {
 191            (Ordering::Equal, _) => continue,
 192            (o, SortOrder::Ascending) => return o,
 193            (o, SortOrder::Descending) => return o.reverse(),
 194        }
 195    }
 196
 197    // Break ties on ascending room id.
 198    room_cmp(a, b, &SortFieldRoom::RoomId)
 199}
 200
 201fn user_fields_cmp(
 202    a: &MemberItem,
 203    b: &MemberItem,
 204    fields: &[SortColumn<SortFieldUser>],
 205) -> Ordering {
 206    for SortColumn(field, order) in fields {
 207        match (user_cmp(a, b, field), order) {
 208            (Ordering::Equal, _) => continue,
 209            (o, SortOrder::Ascending) => return o,
 210            (o, SortOrder::Descending) => return o.reverse(),
 211        }
 212    }
 213
 214    // Break ties on ascending user id.
 215    user_cmp(a, b, &SortFieldUser::UserId)
 216}
 217
 218fn tag_to_span(tag: &TagName, style: Style) -> Vec<Span<'_>> {
 219    match tag {
 220        TagName::Favorite => vec![Span::styled("Favorite", style)],
 221        TagName::LowPriority => vec![Span::styled("Low Priority", style)],
 222        TagName::ServerNotice => vec![Span::styled("Server Notice", style)],
 223        TagName::User(tag) => {
 224            vec![
 225                Span::styled("User Tag: ", style),
 226                Span::styled(tag.as_ref(), style),
 227            ]
 228        },
 229        tag => vec![Span::styled(format!("{tag:?}"), style)],
 230    }
 231}
 232
 233fn append_tags<'a>(tags: Vec<Vec<Span<'a>>>, spans: &mut Vec<Span<'a>>, style: Style) {
 234    if tags.is_empty() {
 235        return;
 236    }
 237
 238    spans.push(Span::styled(" (", style));
 239
 240    for (i, tag) in tags.into_iter().enumerate() {
 241        if i > 0 {
 242            spans.push(Span::styled(", ", style));
 243        }
 244
 245        spans.extend(tag);
 246    }
 247
 248    spans.push(Span::styled(")", style));
 249}
 250
 251trait RoomLikeItem {
 252    fn room_id(&self) -> &RoomId;
 253    fn has_tag(&self, tag: TagName) -> bool;
 254    fn alias(&self) -> Option<&RoomAliasId>;
 255    fn name(&self) -> &str;
 256}
 257
 258#[inline]
 259fn room_prompt(
 260    room_id: &RoomId,
 261    act: &PromptAction,
 262    ctx: &ProgramContext,
 263) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 264    match act {
 265        PromptAction::Submit => {
 266            let room = IambId::Room(room_id.to_owned());
 267            let open = WindowAction::Switch(OpenTarget::Application(room));
 268            let acts = vec![(open.into(), ctx.clone())];
 269
 270            Ok(acts)
 271        },
 272        PromptAction::Abort(_) => {
 273            let msg = "Cannot abort entry inside a list";
 274            let err = EditError::Failure(msg.into());
 275
 276            Err(err)
 277        },
 278        PromptAction::Recall(..) => {
 279            let msg = "Cannot recall history inside a list";
 280            let err = EditError::Failure(msg.into());
 281
 282            Err(err)
 283        },
 284        _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
 285    }
 286}
 287
 288macro_rules! delegate {
 289    ($s: expr, $id: ident => $e: expr) => {
 290        match $s {
 291            IambWindow::Room($id) => $e,
 292            IambWindow::DirectList($id) => $e,
 293            IambWindow::MemberList($id, _, _) => $e,
 294            IambWindow::RoomList($id) => $e,
 295            IambWindow::SpaceList($id) => $e,
 296            IambWindow::VerifyList($id) => $e,
 297            IambWindow::Welcome($id) => $e,
 298            IambWindow::ChatList($id) => $e,
 299        }
 300    };
 301}
 302
 303pub enum IambWindow {
 304    DirectList(DirectListState),
 305    MemberList(MemberListState, OwnedRoomId, Option<Instant>),
 306    Room(RoomState),
 307    VerifyList(VerifyListState),
 308    RoomList(RoomListState),
 309    SpaceList(SpaceListState),
 310    Welcome(WelcomeState),
 311    ChatList(ChatListState),
 312}
 313
 314impl IambWindow {
 315    pub fn focus_toggle(&mut self) {
 316        if let IambWindow::Room(w) = self {
 317            w.focus_toggle()
 318        } else {
 319            return;
 320        }
 321    }
 322
 323    pub async fn message_command(
 324        &mut self,
 325        act: MessageAction,
 326        ctx: ProgramContext,
 327        store: &mut ProgramStore,
 328    ) -> IambResult<EditInfo> {
 329        if let IambWindow::Room(w) = self {
 330            w.message_command(act, ctx, store).await
 331        } else {
 332            return Err(IambError::NoSelectedRoom.into());
 333        }
 334    }
 335
 336    pub async fn room_command(
 337        &mut self,
 338        act: RoomAction,
 339        ctx: ProgramContext,
 340        store: &mut ProgramStore,
 341    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
 342        if let IambWindow::Room(w) = self {
 343            w.room_command(act, ctx, store).await
 344        } else {
 345            return Err(IambError::NoSelectedRoomOrSpace.into());
 346        }
 347    }
 348
 349    pub async fn send_command(
 350        &mut self,
 351        act: SendAction,
 352        ctx: ProgramContext,
 353        store: &mut ProgramStore,
 354    ) -> IambResult<EditInfo> {
 355        if let IambWindow::Room(w) = self {
 356            w.send_command(act, ctx, store).await
 357        } else {
 358            return Err(IambError::NoSelectedRoom.into());
 359        }
 360    }
 361}
 362
 363pub type DirectListState = ListState<DirectItem, IambInfo>;
 364pub type MemberListState = ListState<MemberItem, IambInfo>;
 365pub type RoomListState = ListState<RoomItem, IambInfo>;
 366pub type ChatListState = ListState<GenericChatItem, IambInfo>;
 367pub type SpaceListState = ListState<SpaceItem, IambInfo>;
 368pub type VerifyListState = ListState<VerifyItem, IambInfo>;
 369
 370impl From<ChatListState> for IambWindow {
 371    fn from(list: ChatListState) -> Self {
 372        IambWindow::ChatList(list)
 373    }
 374}
 375
 376impl From<RoomState> for IambWindow {
 377    fn from(room: RoomState) -> Self {
 378        IambWindow::Room(room)
 379    }
 380}
 381
 382impl From<VerifyListState> for IambWindow {
 383    fn from(list: VerifyListState) -> Self {
 384        IambWindow::VerifyList(list)
 385    }
 386}
 387
 388impl From<DirectListState> for IambWindow {
 389    fn from(list: DirectListState) -> Self {
 390        IambWindow::DirectList(list)
 391    }
 392}
 393
 394impl From<RoomListState> for IambWindow {
 395    fn from(list: RoomListState) -> Self {
 396        IambWindow::RoomList(list)
 397    }
 398}
 399
 400impl From<SpaceListState> for IambWindow {
 401    fn from(list: SpaceListState) -> Self {
 402        IambWindow::SpaceList(list)
 403    }
 404}
 405
 406impl From<WelcomeState> for IambWindow {
 407    fn from(win: WelcomeState) -> Self {
 408        IambWindow::Welcome(win)
 409    }
 410}
 411
 412impl Editable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
 413    fn editor_command(
 414        &mut self,
 415        act: &EditorAction,
 416        ctx: &ProgramContext,
 417        store: &mut ProgramStore,
 418    ) -> EditResult<EditInfo, IambInfo> {
 419        delegate!(self, w => w.editor_command(act, ctx, store))
 420    }
 421}
 422
 423impl Jumpable<ProgramContext, IambInfo> for IambWindow {
 424    fn jump(
 425        &mut self,
 426        list: PositionList,
 427        dir: MoveDir1D,
 428        count: usize,
 429        ctx: &ProgramContext,
 430    ) -> IambResult<usize> {
 431        delegate!(self, w => w.jump(list, dir, count, ctx))
 432    }
 433}
 434
 435impl Scrollable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
 436    fn scroll(
 437        &mut self,
 438        style: &ScrollStyle,
 439        ctx: &ProgramContext,
 440        store: &mut ProgramStore,
 441    ) -> EditResult<EditInfo, IambInfo> {
 442        delegate!(self, w => w.scroll(style, ctx, store))
 443    }
 444}
 445
 446impl Promptable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
 447    fn prompt(
 448        &mut self,
 449        act: &PromptAction,
 450        ctx: &ProgramContext,
 451        store: &mut ProgramStore,
 452    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 453        delegate!(self, w => w.prompt(act, ctx, store))
 454    }
 455}
 456
 457impl TerminalCursor for IambWindow {
 458    fn get_term_cursor(&self) -> Option<TermOffset> {
 459        delegate!(self, w => w.get_term_cursor())
 460    }
 461}
 462
 463impl WindowOps<IambInfo> for IambWindow {
 464    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
 465        match self {
 466            IambWindow::Room(state) => state.draw(area, buf, focused, store),
 467            IambWindow::DirectList(state) => {
 468                let mut items = store
 469                    .application
 470                    .sync_info
 471                    .dms
 472                    .clone()
 473                    .into_iter()
 474                    .map(|room_info| DirectItem::new(room_info, store))
 475                    .collect::<Vec<_>>();
 476                let fields = &store.application.settings.tunables.sort.dms;
 477                items.sort_by(|a, b| room_fields_cmp(a, b, fields));
 478
 479                state.set(items);
 480
 481                List::new(store)
 482                    .empty_message("No direct messages yet!")
 483                    .empty_alignment(Alignment::Center)
 484                    .focus(focused)
 485                    .render(area, buf, state);
 486            },
 487            IambWindow::MemberList(state, room_id, last_fetch) => {
 488                let need_fetch = match last_fetch {
 489                    Some(i) => i.elapsed() >= MEMBER_FETCH_DEBOUNCE,
 490                    None => true,
 491                };
 492
 493                if need_fetch {
 494                    if let Ok(mems) = store.application.worker.members(room_id.clone()) {
 495                        let mut items = mems
 496                            .into_iter()
 497                            .map(|m| MemberItem::new(m, room_id.clone()))
 498                            .collect::<Vec<_>>();
 499                        let fields = &store.application.settings.tunables.sort.members;
 500                        items.sort_by(|a, b| user_fields_cmp(a, b, fields));
 501                        state.set(items);
 502                        *last_fetch = Some(Instant::now());
 503                    }
 504                }
 505
 506                List::new(store)
 507                    .empty_message("No users here yet!")
 508                    .empty_alignment(Alignment::Center)
 509                    .focus(focused)
 510                    .render(area, buf, state);
 511            },
 512            IambWindow::RoomList(state) => {
 513                let mut items = store
 514                    .application
 515                    .sync_info
 516                    .rooms
 517                    .clone()
 518                    .into_iter()
 519                    .map(|room_info| RoomItem::new(room_info, store))
 520                    .collect::<Vec<_>>();
 521                let fields = &store.application.settings.tunables.sort.rooms;
 522                items.sort_by(|a, b| room_fields_cmp(a, b, fields));
 523
 524                state.set(items);
 525
 526                List::new(store)
 527                    .empty_message("You haven't joined any rooms yet")
 528                    .empty_alignment(Alignment::Center)
 529                    .focus(focused)
 530                    .render(area, buf, state);
 531            },
 532            IambWindow::ChatList(state) => {
 533                let mut items = store
 534                    .application
 535                    .sync_info
 536                    .rooms
 537                    .clone()
 538                    .into_iter()
 539                    .map(|room_info| GenericChatItem::new(room_info, store, false))
 540                    .collect::<Vec<_>>();
 541
 542                let dms = store
 543                    .application
 544                    .sync_info
 545                    .dms
 546                    .clone()
 547                    .into_iter()
 548                    .map(|room_info| GenericChatItem::new(room_info, store, true));
 549
 550                items.extend(dms);
 551
 552                let fields = &store.application.settings.tunables.sort.chats;
 553                items.sort_by(|a, b| room_fields_cmp(a, b, fields));
 554
 555                state.set(items);
 556
 557                List::new(store)
 558                    .empty_message("You do not have rooms or dms yet")
 559                    .empty_alignment(Alignment::Center)
 560                    .focus(focused)
 561                    .render(area, buf, state);
 562            },
 563            IambWindow::SpaceList(state) => {
 564                let mut items = store
 565                    .application
 566                    .sync_info
 567                    .spaces
 568                    .clone()
 569                    .into_iter()
 570                    .map(|room| SpaceItem::new(room, store))
 571                    .collect::<Vec<_>>();
 572                let fields = &store.application.settings.tunables.sort.spaces;
 573                items.sort_by(|a, b| room_fields_cmp(a, b, fields));
 574
 575                state.set(items);
 576
 577                List::new(store)
 578                    .empty_message("You haven't joined any spaces yet")
 579                    .empty_alignment(Alignment::Center)
 580                    .focus(focused)
 581                    .render(area, buf, state);
 582            },
 583            IambWindow::VerifyList(state) => {
 584                let verifications = &store.application.verifications;
 585                let mut items = verifications.iter().map(VerifyItem::from).collect::<Vec<_>>();
 586
 587                // Sort the active verifications towards the top.
 588                items.sort();
 589
 590                state.set(items);
 591
 592                List::new(store)
 593                    .empty_message("No in-progress verifications")
 594                    .empty_alignment(Alignment::Center)
 595                    .focus(focused)
 596                    .render(area, buf, state);
 597            },
 598            IambWindow::Welcome(state) => state.draw(area, buf, focused, store),
 599        }
 600    }
 601
 602    fn dup(&self, store: &mut ProgramStore) -> Self {
 603        match self {
 604            IambWindow::Room(w) => w.dup(store).into(),
 605            IambWindow::DirectList(w) => w.dup(store).into(),
 606            IambWindow::MemberList(w, room_id, last_fetch) => {
 607                IambWindow::MemberList(w.dup(store), room_id.clone(), *last_fetch)
 608            },
 609            IambWindow::RoomList(w) => w.dup(store).into(),
 610            IambWindow::SpaceList(w) => w.dup(store).into(),
 611            IambWindow::VerifyList(w) => w.dup(store).into(),
 612            IambWindow::Welcome(w) => w.dup(store).into(),
 613            IambWindow::ChatList(w) => w.dup(store).into(),
 614        }
 615    }
 616
 617    fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
 618        delegate!(self, w => w.close(flags, store))
 619    }
 620
 621    fn write(
 622        &mut self,
 623        path: Option<&str>,
 624        flags: WriteFlags,
 625        store: &mut ProgramStore,
 626    ) -> IambResult<EditInfo> {
 627        delegate!(self, w => w.write(path, flags, store))
 628    }
 629
 630    fn get_completions(&self) -> Option<CompletionList> {
 631        delegate!(self, w => w.get_completions())
 632    }
 633
 634    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
 635        delegate!(self, w => w.get_cursor_word(style))
 636    }
 637
 638    fn get_selected_word(&self) -> Option<String> {
 639        delegate!(self, w => w.get_selected_word())
 640    }
 641}
 642
 643impl Window<IambInfo> for IambWindow {
 644    fn id(&self) -> IambId {
 645        match self {
 646            IambWindow::Room(room) => IambId::Room(room.id().to_owned()),
 647            IambWindow::DirectList(_) => IambId::DirectList,
 648            IambWindow::MemberList(_, room_id, _) => IambId::MemberList(room_id.clone()),
 649            IambWindow::RoomList(_) => IambId::RoomList,
 650            IambWindow::SpaceList(_) => IambId::SpaceList,
 651            IambWindow::VerifyList(_) => IambId::VerifyList,
 652            IambWindow::Welcome(_) => IambId::Welcome,
 653            IambWindow::ChatList(_) => IambId::ChatList,
 654        }
 655    }
 656
 657    fn get_tab_title(&self, store: &mut ProgramStore) -> Line {
 658        match self {
 659            IambWindow::DirectList(_) => bold_spans("Direct Messages"),
 660            IambWindow::RoomList(_) => bold_spans("Rooms"),
 661            IambWindow::SpaceList(_) => bold_spans("Spaces"),
 662            IambWindow::VerifyList(_) => bold_spans("Verifications"),
 663            IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
 664            IambWindow::ChatList(_) => bold_spans("DMs & Rooms"),
 665
 666            IambWindow::Room(w) => {
 667                let title = store.application.get_room_title(w.id());
 668
 669                Line::from(title)
 670            },
 671            IambWindow::MemberList(state, room_id, _) => {
 672                let title = store.application.get_room_title(room_id.as_ref());
 673                let n = state.len();
 674                let v = vec![
 675                    bold_span("Room Members "),
 676                    Span::styled(format!("({n}): "), bold_style()),
 677                    title.into(),
 678                ];
 679                Line::from(v)
 680            },
 681        }
 682    }
 683
 684    fn get_win_title(&self, store: &mut ProgramStore) -> Line {
 685        match self {
 686            IambWindow::DirectList(_) => bold_spans("Direct Messages"),
 687            IambWindow::RoomList(_) => bold_spans("Rooms"),
 688            IambWindow::SpaceList(_) => bold_spans("Spaces"),
 689            IambWindow::VerifyList(_) => bold_spans("Verifications"),
 690            IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
 691            IambWindow::ChatList(_) => bold_spans("DMs & Rooms"),
 692
 693            IambWindow::Room(w) => w.get_title(store),
 694            IambWindow::MemberList(state, room_id, _) => {
 695                let title = store.application.get_room_title(room_id.as_ref());
 696                let n = state.len();
 697                let v = vec![
 698                    bold_span("Room Members "),
 699                    Span::styled(format!("({n}): "), bold_style()),
 700                    title.into(),
 701                ];
 702                Line::from(v)
 703            },
 704        }
 705    }
 706
 707    fn open(id: IambId, store: &mut ProgramStore) -> IambResult<Self> {
 708        match id {
 709            IambId::Room(room_id) => {
 710                let (room, name, tags) = store.application.worker.get_room(room_id)?;
 711                let room = RoomState::new(room, name, tags, store);
 712
 713                store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
 714                return Ok(room.into());
 715            },
 716            IambId::DirectList => {
 717                let list = DirectListState::new(IambBufferId::DirectList, vec![]);
 718
 719                return Ok(list.into());
 720            },
 721            IambId::MemberList(room_id) => {
 722                let id = IambBufferId::MemberList(room_id.clone());
 723                let list = MemberListState::new(id, vec![]);
 724                let win = IambWindow::MemberList(list, room_id, None);
 725
 726                return Ok(win);
 727            },
 728            IambId::RoomList => {
 729                let list = RoomListState::new(IambBufferId::RoomList, vec![]);
 730
 731                return Ok(list.into());
 732            },
 733            IambId::SpaceList => {
 734                let list = SpaceListState::new(IambBufferId::SpaceList, vec![]);
 735
 736                return Ok(list.into());
 737            },
 738            IambId::VerifyList => {
 739                let list = VerifyListState::new(IambBufferId::VerifyList, vec![]);
 740
 741                return Ok(list.into());
 742            },
 743            IambId::Welcome => {
 744                let win = WelcomeState::new(store);
 745
 746                return Ok(win.into());
 747            },
 748            IambId::ChatList => {
 749                let list = ChatListState::new(IambBufferId::ChatList, vec![]);
 750
 751                Ok(list.into())
 752            },
 753        }
 754    }
 755
 756    fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
 757        let ChatStore { names, worker, .. } = &mut store.application;
 758
 759        if let Some(room) = names.get_mut(&name) {
 760            let id = IambId::Room(room.clone());
 761
 762            IambWindow::open(id, store)
 763        } else {
 764            let room_id = worker.join_room(name.clone())?;
 765            names.insert(name, room_id.clone());
 766
 767            let (room, name, tags) = store.application.worker.get_room(room_id)?;
 768            let room = RoomState::new(room, name, tags, store);
 769
 770            store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
 771            Ok(room.into())
 772        }
 773    }
 774
 775    fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
 776        let msg = format!("Cannot find indexed buffer (index = {index})");
 777        let err = UIError::Unimplemented(msg);
 778
 779        Err(err)
 780    }
 781
 782    fn unnamed(store: &mut ProgramStore) -> IambResult<Self> {
 783        Self::open(IambId::RoomList, store)
 784    }
 785}
 786
 787#[derive(Clone)]
 788pub struct GenericChatItem {
 789    room_info: MatrixRoomInfo,
 790    name: String,
 791    alias: Option<OwnedRoomAliasId>,
 792    is_dm: bool,
 793}
 794
 795impl GenericChatItem {
 796    fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore, is_dm: bool) -> Self {
 797        let room = &room_info.deref().0;
 798        let room_id = room.room_id();
 799
 800        let info = store.application.get_room_info(room_id.to_owned());
 801
 802        let name = info.name.clone().unwrap_or_default();
 803        let alias = room.canonical_alias();
 804        info.tags = room_info.deref().1.clone();
 805
 806        if let Some(alias) = &alias {
 807            store.application.names.insert(alias.to_string(), room_id.to_owned());
 808        }
 809
 810        GenericChatItem { room_info, name, alias, is_dm }
 811    }
 812
 813    #[inline]
 814    fn room(&self) -> &MatrixRoom {
 815        &self.room_info.deref().0
 816    }
 817
 818    #[inline]
 819    fn tags(&self) -> &Option<Tags> {
 820        &self.room_info.deref().1
 821    }
 822}
 823
 824impl RoomLikeItem for GenericChatItem {
 825    fn name(&self) -> &str {
 826        self.name.as_str()
 827    }
 828
 829    fn alias(&self) -> Option<&RoomAliasId> {
 830        self.alias.as_deref()
 831    }
 832
 833    fn room_id(&self) -> &RoomId {
 834        self.room().room_id()
 835    }
 836
 837    fn has_tag(&self, tag: TagName) -> bool {
 838        if let Some(tags) = &self.room_info.deref().1 {
 839            tags.contains_key(&tag)
 840        } else {
 841            false
 842        }
 843    }
 844}
 845
 846impl ToString for GenericChatItem {
 847    fn to_string(&self) -> String {
 848        return self.name.clone();
 849    }
 850}
 851
 852impl ListItem<IambInfo> for GenericChatItem {
 853    fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
 854        let style = selected_style(selected);
 855        let mut spans = vec![Span::styled(self.name.as_str(), style)];
 856        let mut labels = if self.is_dm {
 857            vec![vec![Span::styled("DM", style)]]
 858        } else {
 859            vec![vec![Span::styled("Room", style)]]
 860        };
 861
 862        if let Some(tags) = &self.tags() {
 863            labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
 864        }
 865
 866        append_tags(labels, &mut spans, style);
 867        Text::from(Line::from(spans))
 868    }
 869
 870    fn get_word(&self) -> Option<String> {
 871        self.room_id().to_string().into()
 872    }
 873}
 874
 875impl Promptable<ProgramContext, ProgramStore, IambInfo> for GenericChatItem {
 876    fn prompt(
 877        &mut self,
 878        act: &PromptAction,
 879        ctx: &ProgramContext,
 880        _: &mut ProgramStore,
 881    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 882        room_prompt(self.room_id(), act, ctx)
 883    }
 884}
 885
 886#[derive(Clone)]
 887pub struct RoomItem {
 888    room_info: MatrixRoomInfo,
 889    name: String,
 890    alias: Option<OwnedRoomAliasId>,
 891}
 892
 893impl RoomItem {
 894    fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
 895        let room = &room_info.deref().0;
 896        let room_id = room.room_id();
 897
 898        let info = store.application.get_room_info(room_id.to_owned());
 899        let name = info.name.clone().unwrap_or_default();
 900        let alias = room.canonical_alias();
 901        info.tags = room_info.deref().1.clone();
 902
 903        if let Some(alias) = &alias {
 904            store.application.names.insert(alias.to_string(), room_id.to_owned());
 905        }
 906
 907        RoomItem { room_info, name, alias }
 908    }
 909
 910    #[inline]
 911    fn room(&self) -> &MatrixRoom {
 912        &self.room_info.deref().0
 913    }
 914
 915    #[inline]
 916    fn tags(&self) -> &Option<Tags> {
 917        &self.room_info.deref().1
 918    }
 919}
 920
 921impl RoomLikeItem for RoomItem {
 922    fn name(&self) -> &str {
 923        self.name.as_str()
 924    }
 925
 926    fn alias(&self) -> Option<&RoomAliasId> {
 927        self.alias.as_deref()
 928    }
 929
 930    fn room_id(&self) -> &RoomId {
 931        self.room().room_id()
 932    }
 933
 934    fn has_tag(&self, tag: TagName) -> bool {
 935        if let Some(tags) = &self.room_info.deref().1 {
 936            tags.contains_key(&tag)
 937        } else {
 938            false
 939        }
 940    }
 941}
 942
 943impl ToString for RoomItem {
 944    fn to_string(&self) -> String {
 945        return self.name.clone();
 946    }
 947}
 948
 949impl ListItem<IambInfo> for RoomItem {
 950    fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
 951        if let Some(tags) = &self.tags() {
 952            let style = selected_style(selected);
 953            let mut spans = vec![Span::styled(self.name.as_str(), style)];
 954            let tags = tags.keys().map(|t| tag_to_span(t, style)).collect();
 955
 956            append_tags(tags, &mut spans, style);
 957
 958            Text::from(Line::from(spans))
 959        } else {
 960            selected_text(self.name.as_str(), selected)
 961        }
 962    }
 963
 964    fn get_word(&self) -> Option<String> {
 965        self.room_id().to_string().into()
 966    }
 967}
 968
 969impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomItem {
 970    fn prompt(
 971        &mut self,
 972        act: &PromptAction,
 973        ctx: &ProgramContext,
 974        _: &mut ProgramStore,
 975    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 976        room_prompt(self.room_id(), act, ctx)
 977    }
 978}
 979
 980#[derive(Clone)]
 981pub struct DirectItem {
 982    room_info: MatrixRoomInfo,
 983    name: String,
 984    alias: Option<OwnedRoomAliasId>,
 985}
 986
 987impl DirectItem {
 988    fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
 989        let room_id = room_info.0.room_id().to_owned();
 990        let name = store.application.get_room_info(room_id).name.clone().unwrap_or_default();
 991        let alias = room_info.0.canonical_alias();
 992
 993        DirectItem { room_info, name, alias }
 994    }
 995
 996    #[inline]
 997    fn room(&self) -> &MatrixRoom {
 998        &self.room_info.deref().0
 999    }
1000
1001    #[inline]
1002    fn tags(&self) -> &Option<Tags> {
1003        &self.room_info.deref().1
1004    }
1005}
1006
1007impl RoomLikeItem for DirectItem {
1008    fn name(&self) -> &str {
1009        self.name.as_str()
1010    }
1011
1012    fn alias(&self) -> Option<&RoomAliasId> {
1013        self.alias.as_deref()
1014    }
1015
1016    fn has_tag(&self, tag: TagName) -> bool {
1017        if let Some(tags) = &self.room_info.deref().1 {
1018            tags.contains_key(&tag)
1019        } else {
1020            false
1021        }
1022    }
1023
1024    fn room_id(&self) -> &RoomId {
1025        self.room().room_id()
1026    }
1027}
1028
1029impl ToString for DirectItem {
1030    fn to_string(&self) -> String {
1031        return self.name.clone();
1032    }
1033}
1034
1035impl ListItem<IambInfo> for DirectItem {
1036    fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1037        if let Some(tags) = &self.tags() {
1038            let style = selected_style(selected);
1039            let mut spans = vec![Span::styled(self.name.as_str(), style)];
1040            let tags = tags.keys().map(|t| tag_to_span(t, style)).collect();
1041
1042            append_tags(tags, &mut spans, style);
1043
1044            Text::from(Line::from(spans))
1045        } else {
1046            selected_text(self.name.as_str(), selected)
1047        }
1048    }
1049
1050    fn get_word(&self) -> Option<String> {
1051        self.room_id().to_string().into()
1052    }
1053}
1054
1055impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
1056    fn prompt(
1057        &mut self,
1058        act: &PromptAction,
1059        ctx: &ProgramContext,
1060        _: &mut ProgramStore,
1061    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1062        room_prompt(self.room_id(), act, ctx)
1063    }
1064}
1065
1066#[derive(Clone)]
1067pub struct SpaceItem {
1068    room_info: MatrixRoomInfo,
1069    name: String,
1070    alias: Option<OwnedRoomAliasId>,
1071}
1072
1073impl SpaceItem {
1074    fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
1075        let room_id = room_info.0.room_id();
1076        let name = store
1077            .application
1078            .get_room_info(room_id.to_owned())
1079            .name
1080            .clone()
1081            .unwrap_or_default();
1082        let alias = room_info.0.canonical_alias();
1083
1084        if let Some(alias) = &alias {
1085            store.application.names.insert(alias.to_string(), room_id.to_owned());
1086        }
1087
1088        SpaceItem { room_info, name, alias }
1089    }
1090
1091    #[inline]
1092    fn room(&self) -> &MatrixRoom {
1093        &self.room_info.deref().0
1094    }
1095}
1096
1097impl RoomLikeItem for SpaceItem {
1098    fn name(&self) -> &str {
1099        self.name.as_str()
1100    }
1101
1102    fn room_id(&self) -> &RoomId {
1103        self.room().room_id()
1104    }
1105
1106    fn alias(&self) -> Option<&RoomAliasId> {
1107        self.alias.as_deref()
1108    }
1109
1110    fn has_tag(&self, _: TagName) -> bool {
1111        // I think that spaces can technically have tags, but afaik no client
1112        // exposes them, so we'll just always return false here for now.
1113        false
1114    }
1115}
1116
1117impl ToString for SpaceItem {
1118    fn to_string(&self) -> String {
1119        return self.room_id().to_string();
1120    }
1121}
1122
1123impl ListItem<IambInfo> for SpaceItem {
1124    fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1125        selected_text(self.name.as_str(), selected)
1126    }
1127
1128    fn get_word(&self) -> Option<String> {
1129        self.room_id().to_string().into()
1130    }
1131}
1132
1133impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
1134    fn prompt(
1135        &mut self,
1136        act: &PromptAction,
1137        ctx: &ProgramContext,
1138        _: &mut ProgramStore,
1139    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1140        room_prompt(self.room_id(), act, ctx)
1141    }
1142}
1143
1144#[derive(Clone)]
1145pub struct VerifyItem {
1146    user_dev: String,
1147    sasv1: SasVerification,
1148}
1149
1150impl VerifyItem {
1151    fn new(user_dev: String, sasv1: SasVerification) -> Self {
1152        VerifyItem { user_dev, sasv1 }
1153    }
1154
1155    fn show_item(&self) -> String {
1156        let state = if self.sasv1.is_done() {
1157            "done"
1158        } else if self.sasv1.is_cancelled() {
1159            "cancelled"
1160        } else if self.sasv1.emoji().is_some() {
1161            "accepted"
1162        } else {
1163            "not accepted"
1164        };
1165
1166        if self.sasv1.is_self_verification() {
1167            let device = self.sasv1.other_device();
1168
1169            if let Some(display_name) = device.display_name() {
1170                format!("Device verification with {display_name} ({state})")
1171            } else {
1172                format!("Device verification with device {} ({})", device.device_id(), state)
1173            }
1174        } else {
1175            format!("User Verification with {} ({})", self.sasv1.other_user_id(), state)
1176        }
1177    }
1178}
1179
1180impl PartialEq for VerifyItem {
1181    fn eq(&self, other: &Self) -> bool {
1182        self.user_dev == other.user_dev
1183    }
1184}
1185
1186impl Eq for VerifyItem {}
1187
1188impl Ord for VerifyItem {
1189    fn cmp(&self, other: &Self) -> Ordering {
1190        fn state_val(sas: &SasVerification) -> usize {
1191            if sas.is_done() {
1192                return 3;
1193            } else if sas.is_cancelled() {
1194                return 2;
1195            } else {
1196                return 1;
1197            }
1198        }
1199
1200        fn device_val(sas: &SasVerification) -> usize {
1201            if sas.is_self_verification() {
1202                return 1;
1203            } else {
1204                return 2;
1205            }
1206        }
1207
1208        let state1 = state_val(&self.sasv1);
1209        let state2 = state_val(&other.sasv1);
1210
1211        let dev1 = device_val(&self.sasv1);
1212        let dev2 = device_val(&other.sasv1);
1213
1214        let scmp = state1.cmp(&state2);
1215        let dcmp = dev1.cmp(&dev2);
1216
1217        scmp.then(dcmp).then_with(|| {
1218            let did1 = self.sasv1.other_device().device_id();
1219            let did2 = other.sasv1.other_device().device_id();
1220
1221            did1.cmp(did2)
1222        })
1223    }
1224}
1225
1226impl PartialOrd for VerifyItem {
1227    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1228        Some(self.cmp(other))
1229    }
1230}
1231
1232impl From<(&String, &SasVerification)> for VerifyItem {
1233    fn from((user_dev, sasv1): (&String, &SasVerification)) -> Self {
1234        VerifyItem::new(user_dev.clone(), sasv1.clone())
1235    }
1236}
1237
1238impl ToString for VerifyItem {
1239    fn to_string(&self) -> String {
1240        if self.sasv1.is_done() {
1241            String::new()
1242        } else if self.sasv1.is_cancelled() {
1243            format!(":verify request {}", self.sasv1.other_user_id())
1244        } else if self.sasv1.emoji().is_some() {
1245            format!(":verify confirm {}", self.user_dev)
1246        } else {
1247            format!(":verify accept {}", self.user_dev)
1248        }
1249    }
1250}
1251
1252impl ListItem<IambInfo> for VerifyItem {
1253    fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1254        let mut lines = vec![];
1255
1256        let bold = Style::default().add_modifier(StyleModifier::BOLD);
1257        let item = Span::styled(self.show_item(), selected_style(selected));
1258        lines.push(Line::from(item));
1259
1260        if self.sasv1.is_done() {
1261            // Print nothing.
1262        } else if self.sasv1.is_cancelled() {
1263            if let Some(info) = self.sasv1.cancel_info() {
1264                lines.push(Line::from(format!("    Cancelled: {}", info.reason())));
1265                lines.push(Line::from(""));
1266            }
1267
1268            lines.push(Line::from("    You can start a new verification request with:"));
1269        } else if let Some(emoji) = self.sasv1.emoji() {
1270            lines.push(Line::from(
1271                "    Both devices should see the following Emoji sequence:".to_string(),
1272            ));
1273            lines.push(Line::from(""));
1274
1275            for line in format_emojis(emoji).lines() {
1276                lines.push(Line::from(format!("    {line}")));
1277            }
1278
1279            lines.push(Line::from(""));
1280            lines.push(Line::from("    If they don't match, run:"));
1281            lines.push(Line::from(""));
1282            lines.push(Line::from(Span::styled(
1283                format!(":verify mismatch {}", self.user_dev),
1284                bold,
1285            )));
1286            lines.push(Line::from(""));
1287            lines.push(Line::from("    If everything looks right, you can confirm with:"));
1288        } else {
1289            lines.push(Line::from("    To accept this request, run:"));
1290        }
1291
1292        let cmd = self.to_string();
1293
1294        if !cmd.is_empty() {
1295            lines.push(Line::from(""));
1296            lines.push(Line::from(vec![Span::from("        "), Span::styled(cmd, bold)]));
1297            lines.push(Line::from(""));
1298            lines.push(Line::from(vec![
1299                Span::from("You can copy the above command with "),
1300                Span::styled("yy", bold),
1301                Span::from(" and then execute it with "),
1302                Span::styled("@\"", bold),
1303            ]));
1304        }
1305
1306        Text { lines }
1307    }
1308
1309    fn get_word(&self) -> Option<String> {
1310        None
1311    }
1312}
1313
1314impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
1315    fn prompt(
1316        &mut self,
1317        act: &PromptAction,
1318        _: &ProgramContext,
1319        _: &mut ProgramStore,
1320    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1321        match act {
1322            PromptAction::Submit => Ok(vec![]),
1323            PromptAction::Abort(_) => {
1324                let msg = "Cannot abort entry inside a list";
1325                let err = EditError::Failure(msg.into());
1326
1327                Err(err)
1328            },
1329            PromptAction::Recall(..) => {
1330                let msg = "Cannot recall history inside a list";
1331                let err = EditError::Failure(msg.into());
1332
1333                Err(err)
1334            },
1335            _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
1336        }
1337    }
1338}
1339
1340#[derive(Clone)]
1341pub struct MemberItem {
1342    member: RoomMember,
1343    room_id: OwnedRoomId,
1344}
1345
1346impl MemberItem {
1347    fn new(member: RoomMember, room_id: OwnedRoomId) -> Self {
1348        Self { member, room_id }
1349    }
1350}
1351
1352impl ToString for MemberItem {
1353    fn to_string(&self) -> String {
1354        self.member.user_id().to_string()
1355    }
1356}
1357
1358impl ListItem<IambInfo> for MemberItem {
1359    fn show(
1360        &self,
1361        selected: bool,
1362        _: &ViewportContext<ListCursor>,
1363        store: &mut ProgramStore,
1364    ) -> Text {
1365        let info = store.application.rooms.get_or_default(self.room_id.clone());
1366        let user_id = self.member.user_id();
1367
1368        let (color, name) = store.application.settings.get_user_overrides(self.member.user_id());
1369        let color = color.unwrap_or_else(|| super::config::user_color(user_id.as_str()));
1370        let mut style = super::config::user_style_from_color(color);
1371
1372        if selected {
1373            style = style.add_modifier(StyleModifier::REVERSED);
1374        }
1375
1376        let mut spans = vec![];
1377        let mut parens = false;
1378
1379        if let Some(name) = name {
1380            spans.push(Span::styled(name, style));
1381            parens = true;
1382        } else if let Some(display) = info.display_names.get(user_id) {
1383            spans.push(Span::styled(display.clone(), style));
1384            parens = true;
1385        }
1386
1387        spans.extend(parens.then_some(Span::styled(" (", style)));
1388        spans.push(Span::styled(user_id.as_str(), style));
1389        spans.extend(parens.then_some(Span::styled(")", style)));
1390
1391        let state = match self.member.membership() {
1392            MembershipState::Ban => Span::raw(" (banned)").into(),
1393            MembershipState::Invite => Span::raw(" (invited)").into(),
1394            MembershipState::Knock => Span::raw(" (wants to join)").into(),
1395            MembershipState::Leave => Span::raw(" (left)").into(),
1396            MembershipState::Join => None,
1397            _ => None,
1398        };
1399
1400        spans.extend(state);
1401
1402        return Line::from(spans).into();
1403    }
1404
1405    fn get_word(&self) -> Option<String> {
1406        self.member.user_id().to_string().into()
1407    }
1408}
1409
1410impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
1411    fn prompt(
1412        &mut self,
1413        act: &PromptAction,
1414        _: &ProgramContext,
1415        _: &mut ProgramStore,
1416    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1417        match act {
1418            PromptAction::Submit => Ok(vec![]),
1419            PromptAction::Abort(_) => {
1420                let msg = "Cannot abort entry inside a list";
1421                let err = EditError::Failure(msg.into());
1422
1423                Err(err)
1424            },
1425            PromptAction::Recall(..) => {
1426                let msg = "Cannot recall history inside a list";
1427                let err = EditError::Failure(msg.into());
1428
1429                Err(err)
1430            },
1431            _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
1432        }
1433    }
1434}
1435
1436#[cfg(test)]
1437mod tests {
1438    use super::*;
1439    use matrix_sdk::ruma::{room_alias_id, server_name};
1440
1441    #[derive(Debug, Eq, PartialEq)]
1442    struct TestRoomItem {
1443        room_id: OwnedRoomId,
1444        tags: Vec<TagName>,
1445        alias: Option<OwnedRoomAliasId>,
1446        name: &'static str,
1447    }
1448
1449    impl RoomLikeItem for &TestRoomItem {
1450        fn room_id(&self) -> &RoomId {
1451            self.room_id.as_ref()
1452        }
1453
1454        fn has_tag(&self, tag: TagName) -> bool {
1455            self.tags.contains(&tag)
1456        }
1457
1458        fn alias(&self) -> Option<&RoomAliasId> {
1459            self.alias.as_deref()
1460        }
1461
1462        fn name(&self) -> &str {
1463            self.name
1464        }
1465    }
1466
1467    #[test]
1468    fn test_sort_rooms() {
1469        let server = server_name!("example.com");
1470
1471        let room1 = TestRoomItem {
1472            room_id: RoomId::new(server).to_owned(),
1473            tags: vec![TagName::Favorite],
1474            alias: Some(room_alias_id!("#room1:example.com").to_owned()),
1475            name: "Z",
1476        };
1477
1478        let room2 = TestRoomItem {
1479            room_id: RoomId::new(server).to_owned(),
1480            tags: vec![],
1481            alias: Some(room_alias_id!("#a:example.com").to_owned()),
1482            name: "Unnamed Room",
1483        };
1484
1485        let room3 = TestRoomItem {
1486            room_id: RoomId::new(server).to_owned(),
1487            tags: vec![],
1488            alias: None,
1489            name: "Cool Room",
1490        };
1491
1492        // Sort by Name ascending.
1493        let mut rooms = vec![&room1, &room2, &room3];
1494        let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Ascending)];
1495        rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1496        assert_eq!(rooms, vec![&room3, &room2, &room1]);
1497
1498        // Sort by Name descending.
1499        let mut rooms = vec![&room1, &room2, &room3];
1500        let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Descending)];
1501        rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1502        assert_eq!(rooms, vec![&room1, &room2, &room3]);
1503
1504        // Sort by Favorite and Alias before Name to show order matters.
1505        let mut rooms = vec![&room1, &room2, &room3];
1506        let fields = &[
1507            SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
1508            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1509            SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1510        ];
1511        rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1512        assert_eq!(rooms, vec![&room1, &room2, &room3]);
1513
1514        // Now flip order of Favorite with Descending
1515        let mut rooms = vec![&room1, &room2, &room3];
1516        let fields = &[
1517            SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1518            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1519            SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1520        ];
1521        rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1522        assert_eq!(rooms, vec![&room2, &room3, &room1]);
1523    }
1524}