src/windows/room/mod.rs
1151 lines · 44218 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.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(
785 store
786 .application
787 .settings
788 .get_user_span(inviter.user_id(), info.display_names.get(inviter.user_id())),
789 );
790 }
791
792 let l1 = Line::from(invited);
793 let l2 = Line::from(
794 "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
795 );
796 let text = Text::from(vec![l1, l2]);
797
798 Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
799
800 return;
801 }
802
803 fn draw_knock(
804 &self,
805 knocked: &MatrixRoom,
806 area: Rect,
807 buf: &mut Buffer,
808 store: &mut ProgramStore,
809 ) {
810 let name = match knocked.canonical_alias() {
811 Some(alias) => alias.to_string(),
812 None => format!("{:?}", store.application.get_room_title(knocked.room_id())),
813 };
814
815 let l1 = Line::from(format!(
816 "Your request to join {name} is pending review by room moderators."
817 ));
818 let l2 = Line::from("You can run `:leave` to withdraw your knock request.");
819 let text = Text::from(vec![l1, l2]);
820
821 Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
822
823 return;
824 }
825
826 pub async fn timeline_command(
827 &mut self,
828 act: TimelineAction,
829 ctx: ProgramContext,
830 store: &mut ProgramStore,
831 ) -> IambResult<EditInfo> {
832 if let RoomState::Chat(chat) = self {
833 chat.timeline_command(act, ctx, store).await
834 } else {
835 Err(IambError::NoSelectedRoom.into())
836 }
837 }
838
839 pub async fn message_command(
840 &mut self,
841 act: MessageAction,
842 ctx: ProgramContext,
843 store: &mut ProgramStore,
844 ) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
845 match self {
846 RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
847 RoomState::Message(msg) => msg.message_command(act, ctx, store).await,
848 _ => Err(IambError::NoSelectedMessage.into()),
849 }
850 }
851
852 pub async fn space_command(
853 &mut self,
854 act: SpaceAction,
855 ctx: ProgramContext,
856 store: &mut ProgramStore,
857 ) -> IambResult<EditInfo> {
858 if let RoomState::Space(space) = self {
859 space.space_command(act, ctx, store).await
860 } else {
861 Err(IambError::NoSelectedSpace.into())
862 }
863 }
864
865 pub fn join_command(
866 &mut self,
867 act: JoinAction,
868 ctx: ProgramContext,
869 store: &mut ProgramStore,
870 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
871 if let RoomState::NotJoined(nj) = self {
872 nj.join_command(act, ctx, store)
873 } else {
874 Err(IambError::NoSelectedSpace.into())
875 }
876 }
877
878 pub async fn send_command(
879 &mut self,
880 act: SendAction,
881 ctx: ProgramContext,
882 store: &mut ProgramStore,
883 ) -> IambResult<EditInfo> {
884 if let RoomState::Chat(chat) = self {
885 chat.send_command(act, ctx, store).await
886 } else {
887 Err(IambError::NoSelectedRoom.into())
888 }
889 }
890
891 pub fn get_title(&self, store: &mut ProgramStore) -> Line<'_> {
892 let theme = &store.application.settings.theme;
893 let default_style = theme.windows.default;
894 let title_style = theme.windows.title;
895
896 let Some(room) = self.room() else {
897 if let RoomState::NotJoined(nj) = self {
898 return nj.get_title(store);
899 } else {
900 return Line::styled("Unknown Room", title_style);
901 }
902 };
903
904 let room_id = room.room_id();
905 let title = store.application.get_room_title(room_id);
906 let mut spans = vec![];
907
908 let encryption_settings = &store.application.settings.tunables.encryption;
909 let encryption_indicator = encryption_settings.get_indicator(
910 EncryptionIndicatorLocation::TITLE,
911 room.encryption_state(),
912 theme,
913 );
914 spans.extend(encryption_indicator);
915 spans.push(Span::styled(" ", default_style));
916
917 if let RoomState::Chat(chat) = self &&
918 chat.thread().is_some()
919 {
920 spans.push(Span::styled("Thread in ", default_style));
921 }
922 if let RoomState::Message(_) = self {
923 spans.push("Message in ".into());
924 }
925
926 spans.push(Span::styled(title, title_style));
927
928 match room.topic() {
929 Some(desc) if !desc.is_empty() => {
930 spans.push(Span::styled(" (", default_style));
931 spans.push(Span::styled(desc, default_style));
932 spans.push(Span::styled(")", default_style));
933 },
934 _ => {
935 spans.push(Span::styled(" ", default_style));
936 },
937 }
938
939 Line::from(spans)
940 }
941
942 pub fn get_tab_title(&self, store: &mut ProgramStore) -> Line<'_> {
943 match self {
944 RoomState::Space(w) => store.application.get_room_title(w.id()).into(),
945 RoomState::Chat(w) => store.application.get_room_title(w.id()).into(),
946 RoomState::NotJoined(w) => w.get_tab_title(store),
947 RoomState::Message(w) => {
948 let name = store.application.get_room_title(w.room_id());
949
950 Line::from(vec![Span::raw("Message in "), Span::raw(name)])
951 },
952 }
953 }
954
955 pub fn focus_toggle(&mut self) {
956 if let RoomState::Chat(chat) = self {
957 chat.focus_toggle();
958 }
959 }
960
961 pub fn room(&self) -> Option<&MatrixRoom> {
962 match self {
963 RoomState::Chat(chat) => Some(chat.room()),
964 RoomState::Space(space) => Some(space.room()),
965 RoomState::Message(msg) => Some(msg.room()),
966 RoomState::NotJoined(_) => None,
967 }
968 }
969
970 pub fn id(&mut self, store: &ProgramStore) -> Option<&RoomId> {
971 match self {
972 RoomState::Chat(chat) => Some(chat.id()),
973 RoomState::Space(space) => Some(space.id()),
974 RoomState::NotJoined(nj) => nj.room_id(store),
975 RoomState::Message(msg) => Some(msg.room_id()),
976 }
977 }
978}
979
980impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
981 fn editor_command(
982 &mut self,
983 act: &EditorAction,
984 ctx: &ProgramContext,
985 store: &mut ProgramStore,
986 ) -> EditResult<EditInfo, IambInfo> {
987 delegate!(self, w => w.editor_command(act, ctx, store))
988 }
989}
990
991impl Jumpable<ProgramContext, IambInfo> for RoomState {
992 fn jump(
993 &mut self,
994 list: PositionList,
995 dir: MoveDir1D,
996 count: usize,
997 ctx: &ProgramContext,
998 ) -> IambResult<usize> {
999 delegate!(self, w => w.jump(list, dir, count, ctx))
1000 }
1001}
1002
1003impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
1004 fn scroll(
1005 &mut self,
1006 style: &ScrollStyle,
1007 ctx: &ProgramContext,
1008 store: &mut ProgramStore,
1009 ) -> EditResult<EditInfo, IambInfo> {
1010 delegate!(self, w => w.scroll(style, ctx, store))
1011 }
1012}
1013
1014impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
1015 fn prompt(
1016 &mut self,
1017 act: &PromptAction,
1018 ctx: &ProgramContext,
1019 store: &mut ProgramStore,
1020 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1021 delegate!(self, w => w.prompt(act, ctx, store))
1022 }
1023}
1024
1025impl TerminalCursor for RoomState {
1026 fn get_term_cursor(&self) -> Option<TermOffset> {
1027 delegate!(self, w => w.get_term_cursor())
1028 }
1029
1030 fn hide_term_cursor(&self) -> bool {
1031 delegate!(self, w => w.hide_term_cursor())
1032 }
1033}
1034
1035impl WindowOps<IambInfo> for RoomState {
1036 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
1037 let theme = &store.application.settings.theme;
1038 let default_style = theme.timeline.default;
1039 buf.set_style(area, default_style);
1040
1041 if self.room_state() != Some(MatrixRoomState::Joined) {
1042 self.refresh_room(store);
1043 }
1044
1045 if let Some(room) = self.room() {
1046 match room.state() {
1047 MatrixRoomState::Invited => return self.draw_invite(room, area, buf, store),
1048 MatrixRoomState::Knocked => return self.draw_knock(room, area, buf, store),
1049 _ => (),
1050 }
1051 }
1052
1053 match self {
1054 RoomState::Chat(chat) => {
1055 chat.draw(area, buf, focused, store);
1056 },
1057 RoomState::NotJoined(state) => {
1058 NotJoined::new(store).render(area, buf, state);
1059 },
1060 RoomState::Message(msg) => {
1061 MessageWidget::new(store).focus(focused).render(area, buf, msg)
1062 },
1063 RoomState::Space(space) => {
1064 Space::new(store).focus(focused).render(area, buf, space);
1065 },
1066 }
1067 }
1068
1069 fn dup(&self, store: &mut ProgramStore) -> Self {
1070 match self {
1071 RoomState::NotJoined(w) => RoomState::NotJoined(Box::new(w.dup())),
1072 RoomState::Chat(chat) => RoomState::Chat(Box::new(chat.dup(store))),
1073 RoomState::Space(space) => RoomState::Space(Box::new(space.dup(store))),
1074 RoomState::Message(msg) => RoomState::Message(Box::new(msg.dup(store))),
1075 }
1076 }
1077
1078 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
1079 match self {
1080 RoomState::NotJoined(_) => true,
1081 RoomState::Chat(chat) => chat.close(flags, store),
1082 RoomState::Space(space) => space.close(flags, store),
1083 RoomState::Message(msg) => msg.close(flags, store),
1084 }
1085 }
1086
1087 fn write(
1088 &mut self,
1089 path: Option<&str>,
1090 flags: WriteFlags,
1091 store: &mut ProgramStore,
1092 ) -> IambResult<EditInfo> {
1093 match self {
1094 RoomState::NotJoined(_) => Err(EditError::ReadOnly.into()),
1095 RoomState::Chat(chat) => chat.write(path, flags, store),
1096 RoomState::Space(space) => space.write(path, flags, store),
1097 RoomState::Message(msg) => msg.write(path, flags, store),
1098 }
1099 }
1100
1101 fn get_completions(&self) -> Option<CompletionList> {
1102 match self {
1103 RoomState::NotJoined(_) => None,
1104 RoomState::Chat(chat) => chat.get_completions(),
1105 RoomState::Space(space) => space.get_completions(),
1106 RoomState::Message(msg) => msg.get_completions(),
1107 }
1108 }
1109
1110 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
1111 match self {
1112 RoomState::NotJoined(_) => None,
1113 RoomState::Chat(chat) => chat.get_cursor_word(style),
1114 RoomState::Space(space) => space.get_cursor_word(style),
1115 RoomState::Message(msg) => msg.get_cursor_word(style),
1116 }
1117 }
1118
1119 fn get_selected_word(&self) -> Option<String> {
1120 match self {
1121 RoomState::NotJoined(_) => None,
1122 RoomState::Chat(chat) => chat.get_selected_word(),
1123 RoomState::Space(space) => space.get_selected_word(),
1124 RoomState::Message(msg) => msg.get_selected_word(),
1125 }
1126 }
1127}
1128
1129#[cfg(test)]
1130mod tests {
1131 use super::*;
1132
1133 #[test]
1134 fn test_parse_room_notification_level() {
1135 let tests = vec![
1136 ("mute", RoomNotificationMode::Mute),
1137 ("mentions", RoomNotificationMode::MentionsAndKeywordsOnly),
1138 ("keywords", RoomNotificationMode::MentionsAndKeywordsOnly),
1139 ("all", RoomNotificationMode::AllMessages),
1140 ];
1141
1142 for (input, expect) in tests {
1143 let res = notification_mode(input).unwrap();
1144 assert_eq!(expect, res);
1145 }
1146
1147 assert!(notification_mode("invalid").is_err());
1148 assert!(notification_mode("not a level").is_err());
1149 assert!(notification_mode("@user:example.com").is_err());
1150 }
1151}