src/windows/room/mod.rs
474 lines · 14818 bytes
1//! # Windows for Matrix rooms and spaces
2use matrix_sdk::{
3 room::Room as MatrixRoom,
4 ruma::{
5 events::{
6 room::{name::RoomNameEventContent, topic::RoomTopicEventContent},
7 tag::{TagInfo, Tags},
8 },
9 OwnedEventId,
10 RoomId,
11 },
12 DisplayName,
13 RoomState as MatrixRoomState,
14};
15
16use ratatui::{
17 buffer::Buffer,
18 layout::{Alignment, Rect},
19 style::{Modifier as StyleModifier, Style},
20 text::{Line, Span, Text},
21 widgets::{Paragraph, StatefulWidget, Widget},
22};
23
24use modalkit::actions::{
25 Action,
26 Editable,
27 EditorAction,
28 Jumpable,
29 PromptAction,
30 Promptable,
31 Scrollable,
32};
33use modalkit::errors::{EditResult, UIError};
34use modalkit::prelude::*;
35use modalkit::{editing::completion::CompletionList, keybindings::dialog::PromptYesNo};
36use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps};
37
38use crate::base::{
39 IambAction,
40 IambError,
41 IambId,
42 IambInfo,
43 IambResult,
44 MessageAction,
45 ProgramAction,
46 ProgramContext,
47 ProgramStore,
48 RoomAction,
49 RoomField,
50 SendAction,
51};
52
53use self::chat::ChatState;
54use self::space::{Space, SpaceState};
55
56mod chat;
57mod scrollback;
58mod space;
59
60macro_rules! delegate {
61 ($s: expr, $id: ident => $e: expr) => {
62 match $s {
63 RoomState::Chat($id) => $e,
64 RoomState::Space($id) => $e,
65 }
66 };
67}
68
69/// State for a Matrix room or space.
70///
71/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
72/// that operations like sending and accepting invites, opening the members window, etc., all work
73/// similarly.
74pub enum RoomState {
75 Chat(ChatState),
76 Space(SpaceState),
77}
78
79impl From<ChatState> for RoomState {
80 fn from(chat: ChatState) -> Self {
81 RoomState::Chat(chat)
82 }
83}
84
85impl From<SpaceState> for RoomState {
86 fn from(space: SpaceState) -> Self {
87 RoomState::Space(space)
88 }
89}
90
91impl RoomState {
92 pub fn new(
93 room: MatrixRoom,
94 thread: Option<OwnedEventId>,
95 name: DisplayName,
96 tags: Option<Tags>,
97 store: &mut ProgramStore,
98 ) -> Self {
99 let room_id = room.room_id().to_owned();
100 let info = store.application.get_room_info(room_id);
101 info.name = name.to_string().into();
102 info.tags = tags;
103
104 if room.is_space() {
105 SpaceState::new(room).into()
106 } else {
107 ChatState::new(room, thread, store).into()
108 }
109 }
110
111 pub fn thread(&self) -> Option<&OwnedEventId> {
112 match self {
113 RoomState::Chat(chat) => chat.thread(),
114 RoomState::Space(_) => None,
115 }
116 }
117
118 pub fn refresh_room(&mut self, store: &mut ProgramStore) {
119 match self {
120 RoomState::Chat(chat) => chat.refresh_room(store),
121 RoomState::Space(space) => space.refresh_room(store),
122 }
123 }
124
125 fn draw_invite(
126 &self,
127 invited: MatrixRoom,
128 area: Rect,
129 buf: &mut Buffer,
130 store: &mut ProgramStore,
131 ) {
132 let inviter = store.application.worker.get_inviter(invited.clone());
133
134 let name = match invited.canonical_alias() {
135 Some(alias) => alias.to_string(),
136 None => format!("{:?}", store.application.get_room_title(self.id())),
137 };
138
139 let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
140
141 if let Ok(Some(inviter)) = &inviter {
142 let info = store.application.rooms.get_or_default(self.id().to_owned());
143 invited.push(Span::from(" by "));
144 invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
145 }
146
147 let l1 = Line::from(invited);
148 let l2 = Line::from(
149 "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
150 );
151 let text = Text::from(vec![l1, l2]);
152
153 Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
154
155 return;
156 }
157
158 pub async fn message_command(
159 &mut self,
160 act: MessageAction,
161 ctx: ProgramContext,
162 store: &mut ProgramStore,
163 ) -> IambResult<EditInfo> {
164 match self {
165 RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
166 RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
167 }
168 }
169
170 pub async fn send_command(
171 &mut self,
172 act: SendAction,
173 ctx: ProgramContext,
174 store: &mut ProgramStore,
175 ) -> IambResult<EditInfo> {
176 match self {
177 RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
178 RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
179 }
180 }
181
182 pub async fn room_command(
183 &mut self,
184 act: RoomAction,
185 _: ProgramContext,
186 store: &mut ProgramStore,
187 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
188 match act {
189 RoomAction::InviteAccept => {
190 if let Some(room) = store.application.worker.client.get_room(self.id()) {
191 let details = room.invite_details().await.map_err(IambError::from)?;
192 let details = details.invitee.event().original_content();
193 let is_direct = details.and_then(|ev| ev.is_direct).unwrap_or_default();
194
195 room.join().await.map_err(IambError::from)?;
196
197 if is_direct {
198 room.set_is_direct(true).await.map_err(IambError::from)?;
199 }
200
201 Ok(vec![])
202 } else {
203 Err(IambError::NotInvited.into())
204 }
205 },
206 RoomAction::InviteReject => {
207 if let Some(room) = store.application.worker.client.get_room(self.id()) {
208 room.leave().await.map_err(IambError::from)?;
209
210 Ok(vec![])
211 } else {
212 Err(IambError::NotInvited.into())
213 }
214 },
215 RoomAction::InviteSend(user) => {
216 if let Some(room) = store.application.worker.client.get_room(self.id()) {
217 room.invite_user_by_id(user.as_ref()).await.map_err(IambError::from)?;
218
219 Ok(vec![])
220 } else {
221 Err(IambError::NotJoined.into())
222 }
223 },
224 RoomAction::Leave(skip_confirm) => {
225 if let Some(room) = store.application.worker.client.get_room(self.id()) {
226 if skip_confirm {
227 room.leave().await.map_err(IambError::from)?;
228
229 Ok(vec![])
230 } else {
231 let msg = "Do you really want to leave this room?";
232 let leave = IambAction::Room(RoomAction::Leave(true));
233 let prompt = PromptYesNo::new(msg, vec![Action::from(leave)]);
234 let prompt = Box::new(prompt);
235
236 Err(UIError::NeedConfirm(prompt))
237 }
238 } else {
239 Err(IambError::NotJoined.into())
240 }
241 },
242 RoomAction::Members(mut cmd) => {
243 let width = Count::Exact(30);
244 let act =
245 cmd.default_axis(Axis::Vertical).default_relation(MoveDir1D::Next).window(
246 OpenTarget::Application(IambId::MemberList(self.id().to_owned())),
247 width.into(),
248 );
249
250 Ok(vec![(act, cmd.context.clone())])
251 },
252 RoomAction::SetDirect(is_direct) => {
253 let room = store
254 .application
255 .get_joined_room(self.id())
256 .ok_or(UIError::Application(IambError::NotJoined))?;
257
258 room.set_is_direct(is_direct).await.map_err(IambError::from)?;
259
260 Ok(vec![])
261 },
262 RoomAction::Set(field, value) => {
263 let room = store
264 .application
265 .get_joined_room(self.id())
266 .ok_or(UIError::Application(IambError::NotJoined))?;
267
268 match field {
269 RoomField::Name => {
270 let ev = RoomNameEventContent::new(value);
271 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
272 },
273 RoomField::Tag(tag) => {
274 let mut info = TagInfo::new();
275 info.order = Some(1.0);
276
277 let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
278 },
279 RoomField::Topic => {
280 let ev = RoomTopicEventContent::new(value);
281 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
282 },
283 }
284
285 Ok(vec![])
286 },
287 RoomAction::Unset(field) => {
288 let room = store
289 .application
290 .get_joined_room(self.id())
291 .ok_or(UIError::Application(IambError::NotJoined))?;
292
293 match field {
294 RoomField::Name => {
295 let ev = RoomNameEventContent::new("".into());
296 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
297 },
298 RoomField::Tag(tag) => {
299 let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
300 },
301 RoomField::Topic => {
302 let ev = RoomTopicEventContent::new("".into());
303 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
304 },
305 }
306
307 Ok(vec![])
308 },
309 }
310 }
311
312 pub fn get_title(&self, store: &mut ProgramStore) -> Line {
313 let title = store.application.get_room_title(self.id());
314 let style = Style::default().add_modifier(StyleModifier::BOLD);
315 let mut spans = vec![];
316
317 if let RoomState::Chat(chat) = self {
318 if chat.thread().is_some() {
319 spans.push("Thread in ".into());
320 }
321 }
322
323 spans.push(Span::styled(title, style));
324
325 match self.room().topic() {
326 Some(desc) if !desc.is_empty() => {
327 spans.push(" (".into());
328 spans.push(desc.into());
329 spans.push(")".into());
330 },
331 _ => {},
332 }
333
334 Line::from(spans)
335 }
336
337 pub fn focus_toggle(&mut self) {
338 match self {
339 RoomState::Chat(chat) => chat.focus_toggle(),
340 RoomState::Space(_) => return,
341 }
342 }
343
344 pub fn room(&self) -> &MatrixRoom {
345 match self {
346 RoomState::Chat(chat) => chat.room(),
347 RoomState::Space(space) => space.room(),
348 }
349 }
350
351 pub fn id(&self) -> &RoomId {
352 match self {
353 RoomState::Chat(chat) => chat.id(),
354 RoomState::Space(space) => space.id(),
355 }
356 }
357}
358
359impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
360 fn editor_command(
361 &mut self,
362 act: &EditorAction,
363 ctx: &ProgramContext,
364 store: &mut ProgramStore,
365 ) -> EditResult<EditInfo, IambInfo> {
366 delegate!(self, w => w.editor_command(act, ctx, store))
367 }
368}
369
370impl Jumpable<ProgramContext, IambInfo> for RoomState {
371 fn jump(
372 &mut self,
373 list: PositionList,
374 dir: MoveDir1D,
375 count: usize,
376 ctx: &ProgramContext,
377 ) -> IambResult<usize> {
378 delegate!(self, w => w.jump(list, dir, count, ctx))
379 }
380}
381
382impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
383 fn scroll(
384 &mut self,
385 style: &ScrollStyle,
386 ctx: &ProgramContext,
387 store: &mut ProgramStore,
388 ) -> EditResult<EditInfo, IambInfo> {
389 delegate!(self, w => w.scroll(style, ctx, store))
390 }
391}
392
393impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
394 fn prompt(
395 &mut self,
396 act: &PromptAction,
397 ctx: &ProgramContext,
398 store: &mut ProgramStore,
399 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
400 delegate!(self, w => w.prompt(act, ctx, store))
401 }
402}
403
404impl TerminalCursor for RoomState {
405 fn get_term_cursor(&self) -> Option<TermOffset> {
406 delegate!(self, w => w.get_term_cursor())
407 }
408}
409
410impl WindowOps<IambInfo> for RoomState {
411 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
412 if self.room().state() == MatrixRoomState::Invited {
413 self.refresh_room(store);
414 }
415
416 if self.room().state() == MatrixRoomState::Invited {
417 self.draw_invite(self.room().clone(), area, buf, store);
418 }
419
420 match self {
421 RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
422 RoomState::Space(space) => {
423 Space::new(store).focus(focused).render(area, buf, space);
424 },
425 }
426 }
427
428 fn dup(&self, store: &mut ProgramStore) -> Self {
429 match self {
430 RoomState::Chat(chat) => RoomState::Chat(chat.dup(store)),
431 RoomState::Space(space) => RoomState::Space(space.dup(store)),
432 }
433 }
434
435 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
436 match self {
437 RoomState::Chat(chat) => chat.close(flags, store),
438 RoomState::Space(space) => space.close(flags, store),
439 }
440 }
441
442 fn write(
443 &mut self,
444 path: Option<&str>,
445 flags: WriteFlags,
446 store: &mut ProgramStore,
447 ) -> IambResult<EditInfo> {
448 match self {
449 RoomState::Chat(chat) => chat.write(path, flags, store),
450 RoomState::Space(space) => space.write(path, flags, store),
451 }
452 }
453
454 fn get_completions(&self) -> Option<CompletionList> {
455 match self {
456 RoomState::Chat(chat) => chat.get_completions(),
457 RoomState::Space(space) => space.get_completions(),
458 }
459 }
460
461 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
462 match self {
463 RoomState::Chat(chat) => chat.get_cursor_word(style),
464 RoomState::Space(space) => space.get_cursor_word(style),
465 }
466 }
467
468 fn get_selected_word(&self) -> Option<String> {
469 match self {
470 RoomState::Chat(chat) => chat.get_selected_word(),
471 RoomState::Space(space) => space.get_selected_word(),
472 }
473 }
474}