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