src/windows/room/chat.rs
342 lines · 9475 bytes
1use matrix_sdk::{
2 room::Room as MatrixRoom,
3 ruma::{OwnedRoomId, RoomId},
4};
5
6use modalkit::tui::{buffer::Buffer, layout::Rect, widgets::StatefulWidget};
7
8use modalkit::{
9 widgets::textbox::{TextBox, TextBoxState},
10 widgets::TerminalCursor,
11 widgets::{PromptActions, WindowOps},
12};
13
14use modalkit::editing::{
15 action::{
16 EditError,
17 EditInfo,
18 EditResult,
19 Editable,
20 EditorAction,
21 Jumpable,
22 PromptAction,
23 Promptable,
24 Scrollable,
25 },
26 base::{CloseFlags, Count, MoveDir1D, PositionList, ScrollStyle, WordStyle},
27 context::Resolve,
28 history::{self, HistoryList},
29 rope::EditRope,
30};
31
32use crate::base::{
33 IambAction,
34 IambBufferId,
35 IambInfo,
36 IambResult,
37 ProgramAction,
38 ProgramContext,
39 ProgramStore,
40 RoomFocus,
41};
42
43use super::scrollback::{Scrollback, ScrollbackState};
44
45pub struct ChatState {
46 room_id: OwnedRoomId,
47
48 tbox: TextBoxState<IambInfo>,
49 sent: HistoryList<EditRope>,
50 sent_scrollback: history::ScrollbackState,
51
52 scrollback: ScrollbackState,
53 focus: RoomFocus,
54}
55
56impl ChatState {
57 pub fn new(room: MatrixRoom, store: &mut ProgramStore) -> Self {
58 let room_id = room.room_id().to_owned();
59 let scrollback = ScrollbackState::new(room_id.clone());
60 let id = IambBufferId::Room(room_id.clone(), RoomFocus::MessageBar);
61 let ebuf = store.load_buffer(id);
62 let tbox = TextBoxState::new(ebuf);
63
64 ChatState {
65 room_id,
66
67 tbox,
68 sent: HistoryList::new(EditRope::from(""), 100),
69 sent_scrollback: history::ScrollbackState::Pending,
70
71 scrollback,
72 focus: RoomFocus::MessageBar,
73 }
74 }
75
76 pub fn focus_toggle(&mut self) {
77 self.focus = match self.focus {
78 RoomFocus::Scrollback => RoomFocus::MessageBar,
79 RoomFocus::MessageBar => RoomFocus::Scrollback,
80 };
81 }
82
83 pub fn id(&self) -> &RoomId {
84 &self.room_id
85 }
86
87 pub fn typing_notice(
88 &self,
89 act: &EditorAction,
90 ctx: &ProgramContext,
91 store: &mut ProgramStore,
92 ) {
93 if !self.focus.is_msgbar() || act.is_readonly(ctx) {
94 return;
95 }
96
97 if matches!(act, EditorAction::History(_)) {
98 return;
99 }
100
101 if !store.application.settings.tunables.typing_notice {
102 return;
103 }
104
105 store.application.worker.typing_notice(self.room_id.clone());
106 }
107}
108
109macro_rules! delegate {
110 ($s: expr, $id: ident => $e: expr) => {
111 match $s.focus {
112 RoomFocus::Scrollback => {
113 match $s {
114 ChatState { scrollback: $id, .. } => $e,
115 }
116 },
117 RoomFocus::MessageBar => {
118 match $s {
119 ChatState { tbox: $id, .. } => $e,
120 }
121 },
122 }
123 };
124}
125
126impl WindowOps<IambInfo> for ChatState {
127 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
128 Chat::new(store).focus(focused).render(area, buf, self)
129 }
130
131 fn dup(&self, store: &mut ProgramStore) -> Self {
132 // XXX: I want each WindowSlot to have its own shared buffer, instead of each Room; need to
133 // find a good way to pass that info here so that it can be part of the content id.
134 let id = IambBufferId::Room(self.room_id.clone(), RoomFocus::MessageBar);
135 let ebuf = store.load_buffer(id);
136 let tbox = TextBoxState::new(ebuf);
137
138 ChatState {
139 room_id: self.room_id.clone(),
140
141 tbox,
142 sent: self.sent.clone(),
143 sent_scrollback: history::ScrollbackState::Pending,
144
145 scrollback: self.scrollback.dup(store),
146 focus: self.focus,
147 }
148 }
149
150 fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
151 // XXX: what's the right closing behaviour for a room?
152 // Should write send a message?
153 true
154 }
155
156 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
157 delegate!(self, w => w.get_cursor_word(style))
158 }
159
160 fn get_selected_word(&self) -> Option<String> {
161 delegate!(self, w => w.get_selected_word())
162 }
163}
164
165impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
166 fn editor_command(
167 &mut self,
168 act: &EditorAction,
169 ctx: &ProgramContext,
170 store: &mut ProgramStore,
171 ) -> EditResult<EditInfo, IambInfo> {
172 self.typing_notice(act, ctx, store);
173
174 match delegate!(self, w => w.editor_command(act, ctx, store)) {
175 res @ Ok(_) => res,
176 Err(EditError::WrongBuffer(IambBufferId::Room(room_id, focus)))
177 if room_id == self.room_id && act.is_switchable(ctx) =>
178 {
179 // Switch focus.
180 self.focus = focus;
181
182 // Run command again.
183 delegate!(self, w => w.editor_command(act, ctx, store))
184 },
185 res @ Err(_) => res,
186 }
187 }
188}
189
190impl TerminalCursor for ChatState {
191 fn get_term_cursor(&self) -> Option<(u16, u16)> {
192 delegate!(self, w => w.get_term_cursor())
193 }
194}
195
196impl Jumpable<ProgramContext, IambInfo> for ChatState {
197 fn jump(
198 &mut self,
199 list: PositionList,
200 dir: MoveDir1D,
201 count: usize,
202 ctx: &ProgramContext,
203 ) -> IambResult<usize> {
204 delegate!(self, w => w.jump(list, dir, count, ctx))
205 }
206}
207
208impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ChatState {
209 fn scroll(
210 &mut self,
211 style: &ScrollStyle,
212 ctx: &ProgramContext,
213 store: &mut ProgramStore,
214 ) -> EditResult<EditInfo, IambInfo> {
215 // Send all scroll commands to the scrollback.
216 //
217 // If there's enough message text for scrolling to be necessary,
218 // navigating with movement keys should be enough to do the job.
219 self.scrollback.scroll(style, ctx, store)
220 }
221}
222
223impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
224 fn submit(
225 &mut self,
226 ctx: &ProgramContext,
227 _: &mut ProgramStore,
228 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
229 let txt = self.tbox.reset_text();
230
231 let act = if txt.is_empty() {
232 vec![]
233 } else {
234 let act = IambAction::SendMessage(self.room_id.clone(), txt).into();
235
236 vec![(act, ctx.clone())]
237 };
238
239 Ok(act)
240 }
241
242 fn abort(
243 &mut self,
244 empty: bool,
245 _: &ProgramContext,
246 _: &mut ProgramStore,
247 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
248 let text = self.tbox.get();
249
250 if empty && text.is_blank() {
251 return Ok(vec![]);
252 }
253
254 let text = self.tbox.reset().trim();
255
256 if text.is_empty() {
257 let _ = self.sent.end();
258 } else {
259 self.sent.select(text);
260 }
261
262 return Ok(vec![]);
263 }
264
265 fn recall(
266 &mut self,
267 dir: &MoveDir1D,
268 count: &Count,
269 ctx: &ProgramContext,
270 _: &mut ProgramStore,
271 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
272 let count = ctx.resolve(count);
273 let rope = self.tbox.get();
274
275 let text = self.sent.recall(&rope, &mut self.sent_scrollback, *dir, count);
276
277 if let Some(text) = text {
278 self.tbox.set_text(text);
279 }
280
281 Ok(vec![])
282 }
283}
284
285impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
286 fn prompt(
287 &mut self,
288 act: &PromptAction,
289 ctx: &ProgramContext,
290 store: &mut ProgramStore,
291 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
292 if let RoomFocus::Scrollback = self.focus {
293 return Ok(vec![]);
294 }
295
296 match act {
297 PromptAction::Submit => self.submit(ctx, store),
298 PromptAction::Abort(empty) => self.abort(*empty, ctx, store),
299 PromptAction::Recall(dir, count) => self.recall(dir, count, ctx, store),
300 _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
301 }
302 }
303}
304
305pub struct Chat<'a> {
306 store: &'a mut ProgramStore,
307 focused: bool,
308}
309
310impl<'a> Chat<'a> {
311 pub fn new(store: &'a mut ProgramStore) -> Chat<'a> {
312 Chat { store, focused: false }
313 }
314
315 pub fn focus(mut self, focused: bool) -> Self {
316 self.focused = focused;
317 self
318 }
319}
320
321impl<'a> StatefulWidget for Chat<'a> {
322 type State = ChatState;
323
324 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
325 let lines = state.tbox.has_lines(5).max(1) as u16;
326 let drawh = area.height;
327 let texth = lines.min(drawh).clamp(1, 5);
328 let scrollh = drawh.saturating_sub(texth);
329
330 let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
331 let textarea = Rect::new(scrollarea.x, scrollarea.y + scrollh, scrollarea.width, texth);
332
333 let scrollback_focused = state.focus.is_scrollback() && self.focused;
334 let scrollback = Scrollback::new(self.store).focus(scrollback_focused);
335 scrollback.render(scrollarea, buf, &mut state.scrollback);
336
337 let prompt = if self.focused { "> " } else { " " };
338
339 let tbox = TextBox::new().prompt(prompt);
340 tbox.render(textarea, buf, &mut state.tbox);
341 }
342}