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