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