src/windows/room/mod.rs

1008 lines · 36897 bytes

   1//! # Windows for Matrix rooms and spaces
   2use std::collections::HashSet;
   3
   4use matrix_sdk::{
   5    RoomDisplayName,
   6    RoomState as MatrixRoomState,
   7    notification_settings::RoomNotificationMode,
   8    room::Room as MatrixRoom,
   9    ruma::{
  10        OwnedEventId,
  11        OwnedRoomAliasId,
  12        OwnedUserId,
  13        RoomId,
  14        api::{
  15            client::room::upgrade_room::v3::Request as UpgradeRoomRequest,
  16            error::ErrorKind as ClientApiErrorKind,
  17        },
  18        events::{
  19            room::{
  20                canonical_alias::RoomCanonicalAliasEventContent,
  21                history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
  22                name::RoomNameEventContent,
  23                topic::RoomTopicEventContent,
  24            },
  25            tag::{TagInfo, Tags},
  26        },
  27    },
  28};
  29
  30use ratatui::{
  31    buffer::Buffer,
  32    layout::{Alignment, Rect},
  33    style::{Modifier as StyleModifier, Style},
  34    text::{Line, Span, Text},
  35    widgets::{Paragraph, StatefulWidget, Widget},
  36};
  37
  38use modalkit::actions::{
  39    Action,
  40    Editable,
  41    EditorAction,
  42    Jumpable,
  43    PromptAction,
  44    Promptable,
  45    Scrollable,
  46    WindowAction,
  47};
  48use modalkit::errors::{EditResult, UIError};
  49use modalkit::prelude::*;
  50use modalkit::{editing::completion::CompletionList, keybindings::dialog::PromptYesNo};
  51use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps};
  52
  53use crate::base::{
  54    IambAction,
  55    IambError,
  56    IambId,
  57    IambInfo,
  58    IambResult,
  59    MemberUpdateAction,
  60    MessageAction,
  61    ProgramAction,
  62    ProgramContext,
  63    ProgramStore,
  64    RoomAction,
  65    RoomField,
  66    SendAction,
  67    SpaceAction,
  68};
  69
  70use self::chat::ChatState;
  71use self::space::{Space, SpaceState};
  72use crate::config::EncryptionIndicatorLocation;
  73
  74use std::convert::TryFrom;
  75
  76mod chat;
  77mod scrollback;
  78mod space;
  79
  80macro_rules! delegate {
  81    ($s: expr, $id: ident => $e: expr) => {
  82        match $s {
  83            RoomState::Chat($id) => $e,
  84            RoomState::Space($id) => $e,
  85        }
  86    };
  87}
  88
  89fn notification_mode(name: impl Into<String>) -> IambResult<RoomNotificationMode> {
  90    let name = name.into();
  91
  92    let mode = match name.to_lowercase().as_str() {
  93        "mute" => RoomNotificationMode::Mute,
  94        "mentions" | "keywords" => RoomNotificationMode::MentionsAndKeywordsOnly,
  95        "all" => RoomNotificationMode::AllMessages,
  96        _ => return Err(IambError::InvalidNotificationLevel(name).into()),
  97    };
  98
  99    Ok(mode)
 100}
 101
 102fn hist_visibility_mode(name: impl Into<String>) -> IambResult<HistoryVisibility> {
 103    let name = name.into();
 104
 105    let mode = match name.to_lowercase().as_str() {
 106        "invited" => HistoryVisibility::Invited,
 107        "joined" => HistoryVisibility::Joined,
 108        "shared" => HistoryVisibility::Shared,
 109        "world" | "world_readable" => HistoryVisibility::WorldReadable,
 110        _ => return Err(IambError::InvalidHistoryVisibility(name).into()),
 111    };
 112
 113    Ok(mode)
 114}
 115
 116pub async fn room_command(
 117    id: &RoomId,
 118    act: RoomAction,
 119    ctx: ProgramContext,
 120    store: &mut ProgramStore,
 121) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
 122    let worker = &store.application.worker;
 123
 124    match act {
 125        RoomAction::Follow(cmd, dir) => {
 126            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 127            let room_id = match dir {
 128                MoveDir1D::Next => {
 129                    let successor = room
 130                        .successor_room()
 131                        .ok_or_else(|| UIError::Failure("No successor room found".into()))?;
 132                    successor.room_id
 133                },
 134                MoveDir1D::Previous => {
 135                    let predecessor = room
 136                        .predecessor_room()
 137                        .ok_or_else(|| UIError::Failure("No predecessor room found".into()))?;
 138                    predecessor.room_id
 139                },
 140            };
 141
 142            let id = IambId::Room(room_id.to_owned(), None);
 143            let target = OpenTarget::Application(id);
 144            let act = cmd.switch(target);
 145
 146            Ok(vec![(act, cmd.context.clone())])
 147        },
 148        RoomAction::InviteAccept => {
 149            if let Some(room) = store.application.worker.client.get_room(id) {
 150                room.join().await.map_err(IambError::from)?;
 151                Ok(vec![])
 152            } else {
 153                Err(IambError::NotInvited.into())
 154            }
 155        },
 156        RoomAction::InviteReject => {
 157            if let Some(room) = store.application.worker.client.get_room(id) {
 158                room.leave().await.map_err(IambError::from)?;
 159
 160                Ok(vec![])
 161            } else {
 162                Err(IambError::NotInvited.into())
 163            }
 164        },
 165        RoomAction::InviteSend(user) => {
 166            if let Some(room) = store.application.worker.client.get_room(id) {
 167                room.invite_user_by_id(user.as_ref()).await.map_err(IambError::from)?;
 168
 169                Ok(vec![])
 170            } else {
 171                Err(IambError::NotJoined.into())
 172            }
 173        },
 174        RoomAction::KnockAccept(user) => {
 175            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 176            room.invite_user_by_id(&user).await.map_err(IambError::from)?;
 177            Ok(vec![])
 178        },
 179        RoomAction::KnockReject(user, reason) => {
 180            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 181            room.kick_user(&user, reason.as_deref()).await.map_err(IambError::from)?;
 182            Ok(vec![])
 183        },
 184        RoomAction::KnockBan(user, reason) => {
 185            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 186            room.ban_user(&user, reason.as_deref()).await.map_err(IambError::from)?;
 187            Ok(vec![])
 188        },
 189        RoomAction::Leave(skip_confirm) => {
 190            if let Some(room) = store.application.worker.client.get_room(id) {
 191                if skip_confirm {
 192                    room.leave().await.map_err(IambError::from)?;
 193
 194                    Ok(vec![])
 195                } else {
 196                    let msg = "Do you really want to leave this room?";
 197                    let leave = IambAction::Room(RoomAction::Leave(true));
 198                    let prompt = PromptYesNo::new(msg, vec![Action::from(leave)]);
 199                    let prompt = Box::new(prompt);
 200
 201                    Err(UIError::NeedConfirm(prompt))
 202                }
 203            } else {
 204                Err(IambError::NotJoined.into())
 205            }
 206        },
 207        RoomAction::MemberUpdate(mua, user, reason, skip_confirm) => {
 208            let Some(room) = store.application.worker.client.get_room(id) else {
 209                return Err(IambError::NotJoined.into());
 210            };
 211
 212            let Ok(user_id) = OwnedUserId::try_from(user.as_str()) else {
 213                let err = IambError::InvalidUserId(user);
 214
 215                return Err(err.into());
 216            };
 217
 218            if !skip_confirm {
 219                let msg = format!("Do you really want to {mua} {user} from this room?");
 220                let act = RoomAction::MemberUpdate(mua, user, reason, true);
 221                let act = IambAction::from(act);
 222                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 223                let prompt = Box::new(prompt);
 224
 225                return Err(UIError::NeedConfirm(prompt));
 226            }
 227
 228            match mua {
 229                MemberUpdateAction::Ban => {
 230                    room.ban_user(&user_id, reason.as_deref()).await.map_err(IambError::from)?;
 231                },
 232                MemberUpdateAction::Unban => {
 233                    room.unban_user(&user_id, reason.as_deref())
 234                        .await
 235                        .map_err(IambError::from)?;
 236                },
 237                MemberUpdateAction::Kick => {
 238                    room.kick_user(&user_id, reason.as_deref())
 239                        .await
 240                        .map_err(IambError::from)?;
 241                },
 242            }
 243
 244            Ok(vec![])
 245        },
 246        RoomAction::Members(mut cmd) => {
 247            let id = IambId::MemberList(id.to_owned());
 248            let target = OpenTarget::Application(id);
 249            let cmd = cmd.default_relation(MoveDir1D::Next);
 250
 251            let act = match store.application.settings.tunables.members_split {
 252                Some(dir) => cmd.default_axis(dir.to_axis()).window(target, None),
 253                None => cmd.switch(target),
 254            };
 255
 256            Ok(vec![(act, cmd.context.clone())])
 257        },
 258        RoomAction::SetDirect(is_direct) => {
 259            let room = store
 260                .application
 261                .get_joined_room(id)
 262                .ok_or(UIError::Application(IambError::NotJoined))?;
 263
 264            room.set_is_direct(is_direct).await.map_err(IambError::from)?;
 265
 266            Ok(vec![])
 267        },
 268        RoomAction::SetUnread(is_unread) => {
 269            let room = store
 270                .application
 271                .get_joined_room(id)
 272                .ok_or(UIError::Application(IambError::NotJoined))?;
 273
 274            room.set_unread_flag(is_unread).await.map_err(IambError::from)?;
 275
 276            if !is_unread {
 277                let user_id = store.application.settings.profile.user_id.clone();
 278                let info = store.application.get_room_info(id.to_owned());
 279                let messages = info.get_thread(None).expect("room main timeline doesn't exist");
 280                if let Some((key, _)) = messages.last_key_value() &&
 281                    let Some(event_id) = key.id.as_origin()
 282                {
 283                    info.set_receipt(
 284                        matrix_sdk::ruma::events::receipt::ReceiptThread::Main,
 285                        user_id,
 286                        event_id.to_owned(),
 287                    );
 288                }
 289            }
 290
 291            Ok(vec![])
 292        },
 293        RoomAction::Set(field, value) => {
 294            let room = store
 295                .application
 296                .get_joined_room(id)
 297                .ok_or(UIError::Application(IambError::NotJoined))?;
 298
 299            match field {
 300                RoomField::History => {
 301                    let visibility = hist_visibility_mode(value)?;
 302                    let ev = RoomHistoryVisibilityEventContent::new(visibility);
 303                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 304                },
 305                RoomField::Name => {
 306                    let ev = RoomNameEventContent::new(value);
 307                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 308                },
 309                RoomField::Tag(tag) => {
 310                    let mut info = TagInfo::new();
 311                    info.order = Some(1.0);
 312
 313                    let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
 314                },
 315                RoomField::Topic => {
 316                    let ev = RoomTopicEventContent::new(value);
 317                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 318                },
 319                RoomField::NotificationMode => {
 320                    let mode = notification_mode(value)?;
 321                    let client = &store.application.worker.client;
 322                    let notifications = client.notification_settings().await;
 323
 324                    notifications
 325                        .set_room_notification_mode(id, mode)
 326                        .await
 327                        .map_err(IambError::from)?;
 328                },
 329                RoomField::CanonicalAlias => {
 330                    let client = &mut store.application.worker.client;
 331
 332                    let Ok(orai) = OwnedRoomAliasId::try_from(value.as_str()) else {
 333                        let err = IambError::InvalidRoomAlias(value);
 334
 335                        return Err(err.into());
 336                    };
 337
 338                    let mut alt_aliases = room.alt_aliases().into_iter().collect::<HashSet<_>>();
 339                    let canonical_old = room.canonical_alias();
 340
 341                    // If the room's alias is already that, ignore it
 342                    if canonical_old.as_ref() == Some(&orai) {
 343                        let msg = format!("The canonical room alias is already {orai}");
 344
 345                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 346                    }
 347
 348                    // Try creating the room alias on the server.
 349                    if let Err(e) = client.create_room_alias(&orai, room.room_id()).await {
 350                        if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
 351                            // Ignore when it already exists.
 352                        } else {
 353                            return Err(IambError::from(e).into());
 354                        }
 355                    }
 356
 357                    // Demote the previous one to an alt alias.
 358                    alt_aliases.extend(canonical_old);
 359
 360                    // At this point the room alias definitely exists, and we can update the
 361                    // state event.
 362                    let mut ev = RoomCanonicalAliasEventContent::new();
 363                    ev.alias = Some(orai);
 364                    ev.alt_aliases = alt_aliases.into_iter().collect();
 365                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 366                },
 367                RoomField::Alias(alias) => {
 368                    let client = &mut store.application.worker.client;
 369
 370                    let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
 371                        let err = IambError::InvalidRoomAlias(alias);
 372
 373                        return Err(err.into());
 374                    };
 375
 376                    let mut alt_aliases = room.alt_aliases().into_iter().collect::<HashSet<_>>();
 377                    let canonical = room.canonical_alias();
 378
 379                    if alt_aliases.contains(&orai) || canonical.as_ref() == Some(&orai) {
 380                        let msg = format!("The alias {orai} already maps to this room");
 381
 382                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 383                    } else {
 384                        alt_aliases.insert(orai.clone());
 385                    }
 386
 387                    // If the room alias does not exist on the server, create it
 388                    if let Err(e) = client.create_room_alias(&orai, room.room_id()).await {
 389                        if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
 390                            // Ignore when it already exists.
 391                        } else {
 392                            return Err(IambError::from(e).into());
 393                        }
 394                    }
 395
 396                    // And add it to the aliases in the state event.
 397                    let mut ev = RoomCanonicalAliasEventContent::new();
 398                    ev.alias = canonical;
 399                    ev.alt_aliases = alt_aliases.into_iter().collect();
 400                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 401                },
 402                RoomField::UserName => {
 403                    room.set_own_member_display_name(Some(value))
 404                        .await
 405                        .map_err(IambError::from)?;
 406                },
 407                RoomField::Aliases => {
 408                    // This never happens, aliases is only used for showing
 409                },
 410                RoomField::Id => {
 411                    // This never happens, id is only used for showing
 412                },
 413                RoomField::Version => {
 414                    // This never happens, version is only used for showing or upgrading.
 415                },
 416            }
 417
 418            Ok(vec![])
 419        },
 420        RoomAction::Unset(field) => {
 421            let room = store
 422                .application
 423                .get_joined_room(id)
 424                .ok_or(UIError::Application(IambError::NotJoined))?;
 425
 426            match field {
 427                RoomField::History => {
 428                    let visibility = HistoryVisibility::Joined;
 429                    let ev = RoomHistoryVisibilityEventContent::new(visibility);
 430                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 431                },
 432                RoomField::Name => {
 433                    let ev = RoomNameEventContent::new("".into());
 434                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 435                },
 436                RoomField::Tag(tag) => {
 437                    let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
 438                },
 439                RoomField::Topic => {
 440                    let ev = RoomTopicEventContent::new("".into());
 441                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 442                },
 443                RoomField::NotificationMode => {
 444                    let client = &store.application.worker.client;
 445                    let notifications = client.notification_settings().await;
 446
 447                    notifications
 448                        .delete_user_defined_room_rules(id)
 449                        .await
 450                        .map_err(IambError::from)?;
 451                },
 452                RoomField::CanonicalAlias => {
 453                    let Some(alias_to_destroy) = room.canonical_alias() else {
 454                        let msg = "This room has no canonical alias to unset";
 455
 456                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 457                    };
 458
 459                    // Remove the canonical alias from the state event.
 460                    let mut ev = RoomCanonicalAliasEventContent::new();
 461                    ev.alias = None;
 462                    ev.alt_aliases = room.alt_aliases();
 463                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 464
 465                    // And then unmap it on the server.
 466                    store
 467                        .application
 468                        .worker
 469                        .client
 470                        .remove_room_alias(&alias_to_destroy)
 471                        .await
 472                        .map_err(IambError::from)?;
 473                },
 474                RoomField::Alias(alias) => {
 475                    let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
 476                        let err = IambError::InvalidRoomAlias(alias);
 477
 478                        return Err(err.into());
 479                    };
 480
 481                    let alt_aliases = room.alt_aliases();
 482                    let canonical = room.canonical_alias();
 483
 484                    if !alt_aliases.contains(&orai) && canonical.as_ref() != Some(&orai) {
 485                        let msg = format!("The alias {orai:?} isn't mapped to this room");
 486
 487                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 488                    }
 489
 490                    // Remove the alias from the state event if it's in it.
 491                    let mut ev = RoomCanonicalAliasEventContent::new();
 492                    ev.alias = canonical.filter(|canon| canon != &orai);
 493                    ev.alt_aliases = alt_aliases;
 494                    ev.alt_aliases.retain(|in_orai| in_orai != &orai);
 495                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 496
 497                    // And then unmap it on the server.
 498                    store
 499                        .application
 500                        .worker
 501                        .client
 502                        .remove_room_alias(&orai)
 503                        .await
 504                        .map_err(IambError::from)?;
 505                },
 506                RoomField::UserName => {
 507                    room.set_own_member_display_name(None).await.map_err(IambError::from)?;
 508                },
 509                RoomField::Aliases => {
 510                    // This will not happen, you cannot unset all aliases
 511                },
 512                RoomField::Id => {
 513                    // This never happens, id is only used for showing
 514                },
 515                RoomField::Version => {
 516                    // This never happens, version is only used for showing or upgrading.
 517                },
 518            }
 519
 520            Ok(vec![])
 521        },
 522        RoomAction::Show(field) => {
 523            let room = store
 524                .application
 525                .get_joined_room(id)
 526                .ok_or(UIError::Application(IambError::NotJoined))?;
 527
 528            let msg = match field {
 529                RoomField::History => {
 530                    let visibility = room.history_visibility();
 531                    let visibility = visibility.as_ref().map(|v| v.as_str());
 532                    format!("Room history visibility: {}", visibility.unwrap_or("<unknown>"))
 533                },
 534                RoomField::Id => {
 535                    let id = room.room_id();
 536                    format!("Room identifier: {id}")
 537                },
 538                RoomField::Version => {
 539                    let v = room.version();
 540                    let v = v.as_ref().map(|v| v.as_str()).unwrap_or("<version unknown>");
 541                    format!("Room version: {v}")
 542                },
 543                RoomField::Name => {
 544                    match room.name() {
 545                        None => "Room has no name".into(),
 546                        Some(name) => format!("Room name: {name:?}"),
 547                    }
 548                },
 549                RoomField::Topic => {
 550                    match room.topic() {
 551                        None => "Room has no topic".into(),
 552                        Some(topic) => format!("Room topic: {topic:?}"),
 553                    }
 554                },
 555                RoomField::NotificationMode => {
 556                    let client = &store.application.worker.client;
 557                    let notifications = client.notification_settings().await;
 558                    let mode = notifications.get_user_defined_room_notification_mode(id).await;
 559
 560                    let level = match mode {
 561                        Some(RoomNotificationMode::Mute) => "mute",
 562                        Some(RoomNotificationMode::MentionsAndKeywordsOnly) => "keywords",
 563                        Some(RoomNotificationMode::AllMessages) => "all",
 564                        None => "default",
 565                    };
 566
 567                    format!("Room notification level: {level:?}")
 568                },
 569                RoomField::Aliases => {
 570                    let aliases = room
 571                        .alt_aliases()
 572                        .iter()
 573                        .map(OwnedRoomAliasId::to_string)
 574                        .collect::<Vec<String>>();
 575
 576                    if aliases.is_empty() {
 577                        "No alternative aliases in room".into()
 578                    } else {
 579                        format!("Alternative aliases: {}.", aliases.join(", "))
 580                    }
 581                },
 582                RoomField::CanonicalAlias => {
 583                    match room.canonical_alias() {
 584                        None => "No canonical alias for room".into(),
 585                        Some(can) => format!("Canonical alias: {can}"),
 586                    }
 587                },
 588                RoomField::Tag(_) => "Cannot currently show value for a tag".into(),
 589                RoomField::Alias(_) => {
 590                    "Cannot show a single alias; use `:room aliases show` instead.".into()
 591                },
 592                RoomField::UserName => {
 593                    let user_id = &store.application.settings.profile.user_id;
 594                    let Some(member) = room.get_member(user_id).await.map_err(IambError::from)?
 595                    else {
 596                        let msg = "Cannot find membership data".into();
 597                        return Err(IambError::Custom(msg))?;
 598                    };
 599
 600                    match member.display_name() {
 601                        Some(name) => format!("User name: \"{name}\""),
 602                        None => "No user name set".into(),
 603                    }
 604                },
 605            };
 606
 607            let msg = InfoMessage::Pager(msg);
 608            let act = Action::ShowInfoMessage(msg);
 609
 610            Ok(vec![(act, ctx)])
 611        },
 612        RoomAction::Upgrade(new_version, additional_creators, false) => {
 613            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 614            let alias = room.canonical_alias();
 615            let name = alias.as_ref().map(|c| c.as_str()).unwrap_or_else(|| id.as_str());
 616            let msg = format!(
 617                "Are you sure you want to upgrade {name} to version {new_version} with {} additional creators set?",
 618                additional_creators.len()
 619            );
 620            let upgrade =
 621                IambAction::Room(RoomAction::Upgrade(new_version, additional_creators, true));
 622            let prompt = PromptYesNo::new(msg, vec![Action::from(upgrade)]);
 623            let prompt = Box::new(prompt);
 624
 625            Err(UIError::NeedConfirm(prompt))
 626        },
 627        RoomAction::Upgrade(new_version, additional_creators, true) => {
 628            let mut request = UpgradeRoomRequest::new(id.to_owned(), new_version);
 629            request.additional_creators = additional_creators;
 630
 631            let response = worker.client.send(request).await.map_err(IambError::from)?;
 632            let id = IambId::Room(response.replacement_room, None);
 633            let target = OpenTarget::Application(id);
 634            let act = WindowAction::Switch(target);
 635
 636            Ok(vec![(act.into(), ctx)])
 637        },
 638    }
 639}
 640
 641/// State for a Matrix room or space.
 642///
 643/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
 644/// that operations like sending and accepting invites, opening the members window, etc., all work
 645/// similarly.
 646pub enum RoomState {
 647    Chat(Box<ChatState>),
 648    Space(Box<SpaceState>),
 649}
 650
 651impl From<ChatState> for RoomState {
 652    fn from(chat: ChatState) -> Self {
 653        RoomState::Chat(Box::new(chat))
 654    }
 655}
 656
 657impl From<SpaceState> for RoomState {
 658    fn from(space: SpaceState) -> Self {
 659        RoomState::Space(Box::new(space))
 660    }
 661}
 662
 663impl RoomState {
 664    pub fn new(
 665        room: MatrixRoom,
 666        thread: Option<OwnedEventId>,
 667        name: RoomDisplayName,
 668        tags: Option<Tags>,
 669        store: &mut ProgramStore,
 670    ) -> Self {
 671        let room_id = room.room_id().to_owned();
 672        let info = store.application.get_room_info(room_id);
 673        info.name = name.to_string().into();
 674        info.tags = tags;
 675
 676        if room.is_space() {
 677            SpaceState::new(room).into()
 678        } else {
 679            ChatState::new(room, thread, store).into()
 680        }
 681    }
 682
 683    pub fn thread(&self) -> Option<&OwnedEventId> {
 684        match self {
 685            RoomState::Chat(chat) => chat.thread(),
 686            RoomState::Space(_) => None,
 687        }
 688    }
 689
 690    pub fn refresh_room(&mut self, store: &mut ProgramStore) {
 691        match self {
 692            RoomState::Chat(chat) => chat.refresh_room(store),
 693            RoomState::Space(space) => space.refresh_room(store),
 694        }
 695    }
 696
 697    fn draw_invite(
 698        &self,
 699        invited: &MatrixRoom,
 700        area: Rect,
 701        buf: &mut Buffer,
 702        store: &mut ProgramStore,
 703    ) {
 704        let inviter = store.application.worker.get_inviter(invited.clone());
 705
 706        let name = match invited.canonical_alias() {
 707            Some(alias) => alias.to_string(),
 708            None => format!("{:?}", store.application.get_room_title(self.id())),
 709        };
 710
 711        let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
 712
 713        if let Ok(Some(inviter)) = &inviter {
 714            let info = store.application.rooms.get_or_default(self.id().to_owned());
 715            invited.push(Span::from(" by "));
 716            invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
 717        }
 718
 719        let l1 = Line::from(invited);
 720        let l2 = Line::from(
 721            "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
 722        );
 723        let text = Text::from(vec![l1, l2]);
 724
 725        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
 726
 727        return;
 728    }
 729
 730    fn draw_knock(
 731        &self,
 732        knocked: &MatrixRoom,
 733        area: Rect,
 734        buf: &mut Buffer,
 735        store: &mut ProgramStore,
 736    ) {
 737        let name = match knocked.canonical_alias() {
 738            Some(alias) => alias.to_string(),
 739            None => format!("{:?}", store.application.get_room_title(self.id())),
 740        };
 741
 742        let l1 = Line::from(format!(
 743            "Your request to join {name} is pending review by room moderators."
 744        ));
 745        let l2 = Line::from("You can run `:leave` to withdraw your knock request.");
 746        let text = Text::from(vec![l1, l2]);
 747
 748        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
 749
 750        return;
 751    }
 752
 753    fn draw_left(&self, room: &MatrixRoom, area: Rect, buf: &mut Buffer, store: &mut ProgramStore) {
 754        let name = match room.canonical_alias() {
 755            Some(alias) => alias.to_string(),
 756            None => format!("{:?}", store.application.get_room_title(self.id())),
 757        };
 758
 759        let mut lines = vec![Line::from(format!("You have left {name}!"))];
 760
 761        if room.is_public().is_some_and(|b| b) {
 762            lines.push(Line::from(format!("You can run `:join {name}` to rejoin.")));
 763        }
 764
 765        let text = Text::from(lines);
 766
 767        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
 768
 769        return;
 770    }
 771
 772    pub async fn message_command(
 773        &mut self,
 774        act: MessageAction,
 775        ctx: ProgramContext,
 776        store: &mut ProgramStore,
 777    ) -> IambResult<EditInfo> {
 778        match self {
 779            RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
 780            RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
 781        }
 782    }
 783
 784    pub async fn space_command(
 785        &mut self,
 786        act: SpaceAction,
 787        ctx: ProgramContext,
 788        store: &mut ProgramStore,
 789    ) -> IambResult<EditInfo> {
 790        match self {
 791            RoomState::Space(space) => space.space_command(act, ctx, store).await,
 792            RoomState::Chat(_) => Err(IambError::NoSelectedSpace.into()),
 793        }
 794    }
 795
 796    pub async fn send_command(
 797        &mut self,
 798        act: SendAction,
 799        ctx: ProgramContext,
 800        store: &mut ProgramStore,
 801    ) -> IambResult<EditInfo> {
 802        match self {
 803            RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
 804            RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
 805        }
 806    }
 807
 808    pub fn get_title(&self, store: &mut ProgramStore) -> Line<'_> {
 809        let room = store.application.worker.client.get_room(self.id());
 810
 811        let title = store.application.get_room_title(self.id());
 812        let style = Style::default().add_modifier(StyleModifier::BOLD);
 813        let mut spans = vec![];
 814
 815        if let RoomState::Chat(chat) = self &&
 816            chat.thread().is_some()
 817        {
 818            spans.push("Thread in ".into());
 819        }
 820
 821        spans.push(Span::styled(title, style));
 822
 823        if let Some(room) = room {
 824            let encryption_settings = &store.application.settings.tunables.encryption;
 825            let encryption_indicator = encryption_settings
 826                .get_indicator(EncryptionIndicatorLocation::TITLE, room.encryption_state());
 827            spans.extend(encryption_indicator);
 828        }
 829
 830        match self.room().topic() {
 831            Some(desc) if !desc.is_empty() => {
 832                spans.push(" (".into());
 833                spans.push(desc.into());
 834                spans.push(")".into());
 835            },
 836            _ => {
 837                spans.push(" ".into());
 838            },
 839        }
 840
 841        Line::from(spans)
 842    }
 843
 844    pub fn focus_toggle(&mut self) {
 845        match self {
 846            RoomState::Chat(chat) => chat.focus_toggle(),
 847            RoomState::Space(_) => return,
 848        }
 849    }
 850
 851    pub fn room(&self) -> &MatrixRoom {
 852        match self {
 853            RoomState::Chat(chat) => chat.room(),
 854            RoomState::Space(space) => space.room(),
 855        }
 856    }
 857
 858    pub fn id(&self) -> &RoomId {
 859        match self {
 860            RoomState::Chat(chat) => chat.id(),
 861            RoomState::Space(space) => space.id(),
 862        }
 863    }
 864}
 865
 866impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
 867    fn editor_command(
 868        &mut self,
 869        act: &EditorAction,
 870        ctx: &ProgramContext,
 871        store: &mut ProgramStore,
 872    ) -> EditResult<EditInfo, IambInfo> {
 873        delegate!(self, w => w.editor_command(act, ctx, store))
 874    }
 875}
 876
 877impl Jumpable<ProgramContext, IambInfo> for RoomState {
 878    fn jump(
 879        &mut self,
 880        list: PositionList,
 881        dir: MoveDir1D,
 882        count: usize,
 883        ctx: &ProgramContext,
 884    ) -> IambResult<usize> {
 885        delegate!(self, w => w.jump(list, dir, count, ctx))
 886    }
 887}
 888
 889impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
 890    fn scroll(
 891        &mut self,
 892        style: &ScrollStyle,
 893        ctx: &ProgramContext,
 894        store: &mut ProgramStore,
 895    ) -> EditResult<EditInfo, IambInfo> {
 896        delegate!(self, w => w.scroll(style, ctx, store))
 897    }
 898}
 899
 900impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
 901    fn prompt(
 902        &mut self,
 903        act: &PromptAction,
 904        ctx: &ProgramContext,
 905        store: &mut ProgramStore,
 906    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 907        delegate!(self, w => w.prompt(act, ctx, store))
 908    }
 909}
 910
 911impl TerminalCursor for RoomState {
 912    fn get_term_cursor(&self) -> Option<TermOffset> {
 913        delegate!(self, w => w.get_term_cursor())
 914    }
 915}
 916
 917impl WindowOps<IambInfo> for RoomState {
 918    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
 919        if self.room().state() != MatrixRoomState::Joined {
 920            self.refresh_room(store);
 921        }
 922
 923        match self.room().state() {
 924            MatrixRoomState::Invited => return self.draw_invite(self.room(), area, buf, store),
 925            MatrixRoomState::Knocked => return self.draw_knock(self.room(), area, buf, store),
 926            MatrixRoomState::Left => return self.draw_left(self.room(), area, buf, store),
 927            _ => (),
 928        }
 929
 930        match self {
 931            RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
 932            RoomState::Space(space) => {
 933                Space::new(store).focus(focused).render(area, buf, space);
 934            },
 935        }
 936    }
 937
 938    fn dup(&self, store: &mut ProgramStore) -> Self {
 939        match self {
 940            RoomState::Chat(chat) => RoomState::Chat(Box::new(chat.dup(store))),
 941            RoomState::Space(space) => RoomState::Space(Box::new(space.dup(store))),
 942        }
 943    }
 944
 945    fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
 946        match self {
 947            RoomState::Chat(chat) => chat.close(flags, store),
 948            RoomState::Space(space) => space.close(flags, store),
 949        }
 950    }
 951
 952    fn write(
 953        &mut self,
 954        path: Option<&str>,
 955        flags: WriteFlags,
 956        store: &mut ProgramStore,
 957    ) -> IambResult<EditInfo> {
 958        match self {
 959            RoomState::Chat(chat) => chat.write(path, flags, store),
 960            RoomState::Space(space) => space.write(path, flags, store),
 961        }
 962    }
 963
 964    fn get_completions(&self) -> Option<CompletionList> {
 965        match self {
 966            RoomState::Chat(chat) => chat.get_completions(),
 967            RoomState::Space(space) => space.get_completions(),
 968        }
 969    }
 970
 971    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
 972        match self {
 973            RoomState::Chat(chat) => chat.get_cursor_word(style),
 974            RoomState::Space(space) => space.get_cursor_word(style),
 975        }
 976    }
 977
 978    fn get_selected_word(&self) -> Option<String> {
 979        match self {
 980            RoomState::Chat(chat) => chat.get_selected_word(),
 981            RoomState::Space(space) => space.get_selected_word(),
 982        }
 983    }
 984}
 985
 986#[cfg(test)]
 987mod tests {
 988    use super::*;
 989
 990    #[test]
 991    fn test_parse_room_notification_level() {
 992        let tests = vec![
 993            ("mute", RoomNotificationMode::Mute),
 994            ("mentions", RoomNotificationMode::MentionsAndKeywordsOnly),
 995            ("keywords", RoomNotificationMode::MentionsAndKeywordsOnly),
 996            ("all", RoomNotificationMode::AllMessages),
 997        ];
 998
 999        for (input, expect) in tests {
1000            let res = notification_mode(input).unwrap();
1001            assert_eq!(expect, res);
1002        }
1003
1004        assert!(notification_mode("invalid").is_err());
1005        assert!(notification_mode("not a level").is_err());
1006        assert!(notification_mode("@user:example.com").is_err());
1007    }
1008}