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