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