src/windows/room/chat.rs
338 lines · 9391 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 !store.application.settings.tunables.typing_notice {
98 return;
99 }
100
101 store.application.worker.typing_notice(self.room_id.clone());
102 }
103}
104
105macro_rules! delegate {
106 ($s: expr, $id: ident => $e: expr) => {
107 match $s.focus {
108 RoomFocus::Scrollback => {
109 match $s {
110 ChatState { scrollback: $id, .. } => $e,
111 }
112 },
113 RoomFocus::MessageBar => {
114 match $s {
115 ChatState { tbox: $id, .. } => $e,
116 }
117 },
118 }
119 };
120}
121
122impl WindowOps<IambInfo> for ChatState {
123 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
124 Chat::new(store).focus(focused).render(area, buf, self)
125 }
126
127 fn dup(&self, store: &mut ProgramStore) -> Self {
128 // XXX: I want each WindowSlot to have its own shared buffer, instead of each Room; need to
129 // find a good way to pass that info here so that it can be part of the content id.
130 let id = IambBufferId::Room(self.room_id.clone(), RoomFocus::MessageBar);
131 let ebuf = store.load_buffer(id);
132 let tbox = TextBoxState::new(ebuf);
133
134 ChatState {
135 room_id: self.room_id.clone(),
136
137 tbox,
138 sent: self.sent.clone(),
139 sent_scrollback: history::ScrollbackState::Pending,
140
141 scrollback: self.scrollback.dup(store),
142 focus: self.focus,
143 }
144 }
145
146 fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
147 // XXX: what's the right closing behaviour for a room?
148 // Should write send a message?
149 true
150 }
151
152 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
153 delegate!(self, w => w.get_cursor_word(style))
154 }
155
156 fn get_selected_word(&self) -> Option<String> {
157 delegate!(self, w => w.get_selected_word())
158 }
159}
160
161impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
162 fn editor_command(
163 &mut self,
164 act: &EditorAction,
165 ctx: &ProgramContext,
166 store: &mut ProgramStore,
167 ) -> EditResult<EditInfo, IambInfo> {
168 self.typing_notice(act, ctx, store);
169
170 match delegate!(self, w => w.editor_command(act, ctx, store)) {
171 res @ Ok(_) => res,
172 Err(EditError::WrongBuffer(IambBufferId::Room(room_id, focus)))
173 if room_id == self.room_id && act.is_switchable(ctx) =>
174 {
175 // Switch focus.
176 self.focus = focus;
177
178 // Run command again.
179 delegate!(self, w => w.editor_command(act, ctx, store))
180 },
181 res @ Err(_) => res,
182 }
183 }
184}
185
186impl TerminalCursor for ChatState {
187 fn get_term_cursor(&self) -> Option<(u16, u16)> {
188 delegate!(self, w => w.get_term_cursor())
189 }
190}
191
192impl Jumpable<ProgramContext, IambInfo> for ChatState {
193 fn jump(
194 &mut self,
195 list: PositionList,
196 dir: MoveDir1D,
197 count: usize,
198 ctx: &ProgramContext,
199 ) -> IambResult<usize> {
200 delegate!(self, w => w.jump(list, dir, count, ctx))
201 }
202}
203
204impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ChatState {
205 fn scroll(
206 &mut self,
207 style: &ScrollStyle,
208 ctx: &ProgramContext,
209 store: &mut ProgramStore,
210 ) -> EditResult<EditInfo, IambInfo> {
211 // Send all scroll commands to the scrollback.
212 //
213 // If there's enough message text for scrolling to be necessary,
214 // navigating with movement keys should be enough to do the job.
215 self.scrollback.scroll(style, ctx, store)
216 }
217}
218
219impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
220 fn submit(
221 &mut self,
222 ctx: &ProgramContext,
223 _: &mut ProgramStore,
224 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
225 let txt = self.tbox.reset_text();
226
227 let act = if txt.is_empty() {
228 vec![]
229 } else {
230 let act = IambAction::SendMessage(self.room_id.clone(), txt).into();
231
232 vec![(act, ctx.clone())]
233 };
234
235 Ok(act)
236 }
237
238 fn abort(
239 &mut self,
240 empty: bool,
241 _: &ProgramContext,
242 _: &mut ProgramStore,
243 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
244 let text = self.tbox.get();
245
246 if empty && text.is_blank() {
247 return Ok(vec![]);
248 }
249
250 let text = self.tbox.reset().trim();
251
252 if text.is_empty() {
253 let _ = self.sent.end();
254 } else {
255 self.sent.select(text);
256 }
257
258 return Ok(vec![]);
259 }
260
261 fn recall(
262 &mut self,
263 dir: &MoveDir1D,
264 count: &Count,
265 ctx: &ProgramContext,
266 _: &mut ProgramStore,
267 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
268 let count = ctx.resolve(count);
269 let rope = self.tbox.get();
270
271 let text = self.sent.recall(&rope, &mut self.sent_scrollback, *dir, count);
272
273 if let Some(text) = text {
274 self.tbox.set_text(text);
275 }
276
277 Ok(vec![])
278 }
279}
280
281impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
282 fn prompt(
283 &mut self,
284 act: &PromptAction,
285 ctx: &ProgramContext,
286 store: &mut ProgramStore,
287 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
288 if let RoomFocus::Scrollback = self.focus {
289 return Ok(vec![]);
290 }
291
292 match act {
293 PromptAction::Submit => self.submit(ctx, store),
294 PromptAction::Abort(empty) => self.abort(*empty, ctx, store),
295 PromptAction::Recall(dir, count) => self.recall(dir, count, ctx, store),
296 _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
297 }
298 }
299}
300
301pub struct Chat<'a> {
302 store: &'a mut ProgramStore,
303 focused: bool,
304}
305
306impl<'a> Chat<'a> {
307 pub fn new(store: &'a mut ProgramStore) -> Chat<'a> {
308 Chat { store, focused: false }
309 }
310
311 pub fn focus(mut self, focused: bool) -> Self {
312 self.focused = focused;
313 self
314 }
315}
316
317impl<'a> StatefulWidget for Chat<'a> {
318 type State = ChatState;
319
320 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
321 let lines = state.tbox.has_lines(5).max(1) as u16;
322 let drawh = area.height;
323 let texth = lines.min(drawh).clamp(1, 5);
324 let scrollh = drawh.saturating_sub(texth);
325
326 let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
327 let textarea = Rect::new(scrollarea.x, scrollarea.y + scrollh, scrollarea.width, texth);
328
329 let scrollback_focused = state.focus.is_scrollback() && self.focused;
330 let scrollback = Scrollback::new(self.store).focus(scrollback_focused);
331 scrollback.render(scrollarea, buf, &mut state.scrollback);
332
333 let prompt = if self.focused { "> " } else { " " };
334
335 let tbox = TextBox::new().prompt(prompt);
336 tbox.render(textarea, buf, &mut state.tbox);
337 }
338}