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