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