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