src/windows/room/mod.rs
464 lines · 14462 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 { lines: 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::Set(field, value) => {
253 let room = store
254 .application
255 .get_joined_room(self.id())
256 .ok_or(UIError::Application(IambError::NotJoined))?;
257
258 match field {
259 RoomField::Name => {
260 let ev = RoomNameEventContent::new(value);
261 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
262 },
263 RoomField::Tag(tag) => {
264 let mut info = TagInfo::new();
265 info.order = Some(1.0);
266
267 let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
268 },
269 RoomField::Topic => {
270 let ev = RoomTopicEventContent::new(value);
271 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
272 },
273 }
274
275 Ok(vec![])
276 },
277 RoomAction::Unset(field) => {
278 let room = store
279 .application
280 .get_joined_room(self.id())
281 .ok_or(UIError::Application(IambError::NotJoined))?;
282
283 match field {
284 RoomField::Name => {
285 let ev = RoomNameEventContent::new("".into());
286 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
287 },
288 RoomField::Tag(tag) => {
289 let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
290 },
291 RoomField::Topic => {
292 let ev = RoomTopicEventContent::new("".into());
293 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
294 },
295 }
296
297 Ok(vec![])
298 },
299 }
300 }
301
302 pub fn get_title(&self, store: &mut ProgramStore) -> Line {
303 let title = store.application.get_room_title(self.id());
304 let style = Style::default().add_modifier(StyleModifier::BOLD);
305 let mut spans = vec![];
306
307 if let RoomState::Chat(chat) = self {
308 if chat.thread().is_some() {
309 spans.push("Thread in ".into());
310 }
311 }
312
313 spans.push(Span::styled(title, style));
314
315 match self.room().topic() {
316 Some(desc) if !desc.is_empty() => {
317 spans.push(" (".into());
318 spans.push(desc.into());
319 spans.push(")".into());
320 },
321 _ => {},
322 }
323
324 Line::from(spans)
325 }
326
327 pub fn focus_toggle(&mut self) {
328 match self {
329 RoomState::Chat(chat) => chat.focus_toggle(),
330 RoomState::Space(_) => return,
331 }
332 }
333
334 pub fn room(&self) -> &MatrixRoom {
335 match self {
336 RoomState::Chat(chat) => chat.room(),
337 RoomState::Space(space) => space.room(),
338 }
339 }
340
341 pub fn id(&self) -> &RoomId {
342 match self {
343 RoomState::Chat(chat) => chat.id(),
344 RoomState::Space(space) => space.id(),
345 }
346 }
347}
348
349impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
350 fn editor_command(
351 &mut self,
352 act: &EditorAction,
353 ctx: &ProgramContext,
354 store: &mut ProgramStore,
355 ) -> EditResult<EditInfo, IambInfo> {
356 delegate!(self, w => w.editor_command(act, ctx, store))
357 }
358}
359
360impl Jumpable<ProgramContext, IambInfo> for RoomState {
361 fn jump(
362 &mut self,
363 list: PositionList,
364 dir: MoveDir1D,
365 count: usize,
366 ctx: &ProgramContext,
367 ) -> IambResult<usize> {
368 delegate!(self, w => w.jump(list, dir, count, ctx))
369 }
370}
371
372impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
373 fn scroll(
374 &mut self,
375 style: &ScrollStyle,
376 ctx: &ProgramContext,
377 store: &mut ProgramStore,
378 ) -> EditResult<EditInfo, IambInfo> {
379 delegate!(self, w => w.scroll(style, ctx, store))
380 }
381}
382
383impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
384 fn prompt(
385 &mut self,
386 act: &PromptAction,
387 ctx: &ProgramContext,
388 store: &mut ProgramStore,
389 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
390 delegate!(self, w => w.prompt(act, ctx, store))
391 }
392}
393
394impl TerminalCursor for RoomState {
395 fn get_term_cursor(&self) -> Option<TermOffset> {
396 delegate!(self, w => w.get_term_cursor())
397 }
398}
399
400impl WindowOps<IambInfo> for RoomState {
401 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
402 if self.room().state() == MatrixRoomState::Invited {
403 self.refresh_room(store);
404 }
405
406 if self.room().state() == MatrixRoomState::Invited {
407 self.draw_invite(self.room().clone(), area, buf, store);
408 }
409
410 match self {
411 RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
412 RoomState::Space(space) => {
413 Space::new(store).focus(focused).render(area, buf, space);
414 },
415 }
416 }
417
418 fn dup(&self, store: &mut ProgramStore) -> Self {
419 match self {
420 RoomState::Chat(chat) => RoomState::Chat(chat.dup(store)),
421 RoomState::Space(space) => RoomState::Space(space.dup(store)),
422 }
423 }
424
425 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
426 match self {
427 RoomState::Chat(chat) => chat.close(flags, store),
428 RoomState::Space(space) => space.close(flags, store),
429 }
430 }
431
432 fn write(
433 &mut self,
434 path: Option<&str>,
435 flags: WriteFlags,
436 store: &mut ProgramStore,
437 ) -> IambResult<EditInfo> {
438 match self {
439 RoomState::Chat(chat) => chat.write(path, flags, store),
440 RoomState::Space(space) => space.write(path, flags, store),
441 }
442 }
443
444 fn get_completions(&self) -> Option<CompletionList> {
445 match self {
446 RoomState::Chat(chat) => chat.get_completions(),
447 RoomState::Space(space) => space.get_completions(),
448 }
449 }
450
451 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
452 match self {
453 RoomState::Chat(chat) => chat.get_cursor_word(style),
454 RoomState::Space(space) => space.get_cursor_word(style),
455 }
456 }
457
458 fn get_selected_word(&self) -> Option<String> {
459 match self {
460 RoomState::Chat(chat) => chat.get_selected_word(),
461 RoomState::Space(space) => space.get_selected_word(),
462 }
463 }
464}