src/windows/mod.rs
696 lines · 20221 bytes
1use std::cmp::{Ord, Ordering, PartialOrd};
2use std::collections::hash_map::Entry;
3
4use matrix_sdk::{
5 encryption::verification::{format_emojis, SasVerification},
6 room::Room as MatrixRoom,
7 ruma::RoomId,
8 DisplayName,
9};
10
11use modalkit::tui::{
12 buffer::Buffer,
13 layout::Rect,
14 style::{Modifier as StyleModifier, Style},
15 text::{Span, Spans, Text},
16 widgets::{Block, Borders, Widget},
17};
18
19use modalkit::{
20 editing::{
21 action::{
22 EditError,
23 EditInfo,
24 EditResult,
25 Editable,
26 EditorAction,
27 Jumpable,
28 PromptAction,
29 Promptable,
30 Scrollable,
31 UIError,
32 WindowAction,
33 },
34 base::{
35 CloseFlags,
36 MoveDir1D,
37 OpenTarget,
38 PositionList,
39 ScrollStyle,
40 ViewportContext,
41 WordStyle,
42 },
43 },
44 widgets::{
45 list::{ListCursor, ListItem, ListState},
46 TermOffset,
47 TerminalCursor,
48 Window,
49 WindowOps,
50 },
51};
52
53use super::base::{
54 ChatStore,
55 IambBufferId,
56 IambId,
57 IambInfo,
58 IambResult,
59 ProgramAction,
60 ProgramContext,
61 ProgramStore,
62};
63
64use self::{room::RoomState, welcome::WelcomeState};
65
66pub mod room;
67pub mod welcome;
68
69#[inline]
70fn selected_style(selected: bool) -> Style {
71 if selected {
72 Style::default().add_modifier(StyleModifier::REVERSED)
73 } else {
74 Style::default()
75 }
76}
77
78#[inline]
79fn selected_span(s: &str, selected: bool) -> Span {
80 Span::styled(s, selected_style(selected))
81}
82
83#[inline]
84fn selected_text(s: &str, selected: bool) -> Text {
85 Text::from(selected_span(s, selected))
86}
87
88#[inline]
89fn room_prompt(
90 room_id: &RoomId,
91 act: &PromptAction,
92 ctx: &ProgramContext,
93) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
94 match act {
95 PromptAction::Submit => {
96 let room = IambId::Room(room_id.to_owned());
97 let open = WindowAction::Switch(OpenTarget::Application(room));
98 let acts = vec![(open.into(), ctx.clone())];
99
100 Ok(acts)
101 },
102 PromptAction::Abort(_) => {
103 let msg = "Cannot abort entry inside a list";
104 let err = EditError::Failure(msg.into());
105
106 Err(err)
107 },
108 PromptAction::Recall(_, _) => {
109 let msg = "Cannot recall history inside a list";
110 let err = EditError::Failure(msg.into());
111
112 Err(err)
113 },
114 _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
115 }
116}
117
118macro_rules! delegate {
119 ($s: expr, $id: ident => $e: expr) => {
120 match $s {
121 IambWindow::Room($id) => $e,
122 IambWindow::DirectList($id) => $e,
123 IambWindow::RoomList($id) => $e,
124 IambWindow::SpaceList($id) => $e,
125 IambWindow::VerifyList($id) => $e,
126 IambWindow::Welcome($id) => $e,
127 }
128 };
129}
130
131pub enum IambWindow {
132 DirectList(DirectListState),
133 Room(RoomState),
134 VerifyList(VerifyListState),
135 RoomList(RoomListState),
136 SpaceList(SpaceListState),
137 Welcome(WelcomeState),
138}
139
140impl IambWindow {
141 pub fn focus_toggle(&mut self) {
142 if let IambWindow::Room(w) = self {
143 w.focus_toggle()
144 } else {
145 return;
146 }
147 }
148
149 pub fn get_title(&self, store: &mut ProgramStore) -> String {
150 match self {
151 IambWindow::Room(w) => w.get_title(store),
152 IambWindow::DirectList(_) => "Direct Messages".to_string(),
153 IambWindow::RoomList(_) => "Rooms".to_string(),
154 IambWindow::SpaceList(_) => "Spaces".to_string(),
155 IambWindow::VerifyList(_) => "Verifications".to_string(),
156 IambWindow::Welcome(_) => "Welcome to iamb".to_string(),
157 }
158 }
159}
160
161pub type DirectListState = ListState<DirectItem, IambInfo>;
162pub type RoomListState = ListState<RoomItem, IambInfo>;
163pub type SpaceListState = ListState<SpaceItem, IambInfo>;
164pub type VerifyListState = ListState<VerifyItem, IambInfo>;
165
166impl From<RoomState> for IambWindow {
167 fn from(room: RoomState) -> Self {
168 IambWindow::Room(room)
169 }
170}
171
172impl From<VerifyListState> for IambWindow {
173 fn from(list: VerifyListState) -> Self {
174 IambWindow::VerifyList(list)
175 }
176}
177
178impl From<DirectListState> for IambWindow {
179 fn from(list: DirectListState) -> Self {
180 IambWindow::DirectList(list)
181 }
182}
183
184impl From<RoomListState> for IambWindow {
185 fn from(list: RoomListState) -> Self {
186 IambWindow::RoomList(list)
187 }
188}
189
190impl From<SpaceListState> for IambWindow {
191 fn from(list: SpaceListState) -> Self {
192 IambWindow::SpaceList(list)
193 }
194}
195
196impl From<WelcomeState> for IambWindow {
197 fn from(win: WelcomeState) -> Self {
198 IambWindow::Welcome(win)
199 }
200}
201
202impl Editable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
203 fn editor_command(
204 &mut self,
205 act: &EditorAction,
206 ctx: &ProgramContext,
207 store: &mut ProgramStore,
208 ) -> EditResult<EditInfo, IambInfo> {
209 delegate!(self, w => w.editor_command(act, ctx, store))
210 }
211}
212
213impl Jumpable<ProgramContext, IambInfo> for IambWindow {
214 fn jump(
215 &mut self,
216 list: PositionList,
217 dir: MoveDir1D,
218 count: usize,
219 ctx: &ProgramContext,
220 ) -> IambResult<usize> {
221 delegate!(self, w => w.jump(list, dir, count, ctx))
222 }
223}
224
225impl Scrollable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
226 fn scroll(
227 &mut self,
228 style: &ScrollStyle,
229 ctx: &ProgramContext,
230 store: &mut ProgramStore,
231 ) -> EditResult<EditInfo, IambInfo> {
232 delegate!(self, w => w.scroll(style, ctx, store))
233 }
234}
235
236impl Promptable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
237 fn prompt(
238 &mut self,
239 act: &PromptAction,
240 ctx: &ProgramContext,
241 store: &mut ProgramStore,
242 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
243 delegate!(self, w => w.prompt(act, ctx, store))
244 }
245}
246
247impl TerminalCursor for IambWindow {
248 fn get_term_cursor(&self) -> Option<TermOffset> {
249 delegate!(self, w => w.get_term_cursor())
250 }
251}
252
253impl WindowOps<IambInfo> for IambWindow {
254 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
255 let title = self.get_title(store);
256 let block = Block::default().title(title.as_str()).borders(Borders::ALL);
257 let inner = block.inner(area);
258 block.render(area, buf);
259
260 match self {
261 IambWindow::Room(state) => state.draw(inner, buf, focused, store),
262 IambWindow::DirectList(state) => {
263 let dms = store.application.worker.direct_messages();
264 let items = dms.into_iter().map(|(id, name)| DirectItem::new(id, name, store));
265 state.set(items.collect());
266 state.draw(inner, buf, focused, store);
267 },
268 IambWindow::RoomList(state) => {
269 let joined = store.application.worker.joined_rooms();
270 let items = joined.into_iter().map(|(id, name)| RoomItem::new(id, name, store));
271 state.set(items.collect());
272 state.draw(inner, buf, focused, store);
273 },
274 IambWindow::SpaceList(state) => {
275 let spaces = store.application.worker.spaces();
276 let items =
277 spaces.into_iter().map(|(room, name)| SpaceItem::new(room, name, store));
278 state.set(items.collect());
279 state.draw(inner, buf, focused, store);
280 },
281 IambWindow::VerifyList(state) => {
282 let verifications = &store.application.verifications;
283 let mut items = verifications.iter().map(VerifyItem::from).collect::<Vec<_>>();
284
285 // Sort the active verifications towards the top.
286 items.sort();
287
288 state.set(items);
289 state.draw(inner, buf, focused, store);
290 },
291 IambWindow::Welcome(state) => state.draw(inner, buf, focused, store),
292 }
293 }
294
295 fn dup(&self, store: &mut ProgramStore) -> Self {
296 delegate!(self, w => w.dup(store).into())
297 }
298
299 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
300 delegate!(self, w => w.close(flags, store))
301 }
302
303 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
304 delegate!(self, w => w.get_cursor_word(style))
305 }
306
307 fn get_selected_word(&self) -> Option<String> {
308 delegate!(self, w => w.get_selected_word())
309 }
310}
311
312impl Window<IambInfo> for IambWindow {
313 fn id(&self) -> IambId {
314 match self {
315 IambWindow::Room(room) => IambId::Room(room.id().to_owned()),
316 IambWindow::DirectList(_) => IambId::DirectList,
317 IambWindow::RoomList(_) => IambId::RoomList,
318 IambWindow::SpaceList(_) => IambId::SpaceList,
319 IambWindow::VerifyList(_) => IambId::VerifyList,
320 IambWindow::Welcome(_) => IambId::Welcome,
321 }
322 }
323
324 fn open(id: IambId, store: &mut ProgramStore) -> IambResult<Self> {
325 match id {
326 IambId::Room(room_id) => {
327 let (room, name) = store.application.worker.get_room(room_id)?;
328 let room = RoomState::new(room, name, store);
329
330 return Ok(room.into());
331 },
332 IambId::DirectList => {
333 let list = DirectListState::new(IambBufferId::DirectList, vec![]);
334
335 return Ok(list.into());
336 },
337 IambId::RoomList => {
338 let list = RoomListState::new(IambBufferId::RoomList, vec![]);
339
340 return Ok(list.into());
341 },
342 IambId::SpaceList => {
343 let list = SpaceListState::new(IambBufferId::SpaceList, vec![]);
344
345 return Ok(list.into());
346 },
347 IambId::VerifyList => {
348 let list = VerifyListState::new(IambBufferId::VerifyList, vec![]);
349
350 return Ok(list.into());
351 },
352 IambId::Welcome => {
353 let win = WelcomeState::new(store);
354
355 return Ok(win.into());
356 },
357 }
358 }
359
360 fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
361 let ChatStore { names, worker, .. } = &mut store.application;
362
363 match names.entry(name) {
364 Entry::Vacant(v) => {
365 let room_id = worker.join_room(v.key().to_string())?;
366 v.insert(room_id.clone());
367
368 let (room, name) = store.application.worker.get_room(room_id)?;
369 let room = RoomState::new(room, name, store);
370
371 Ok(room.into())
372 },
373 Entry::Occupied(o) => {
374 let id = IambId::Room(o.get().clone());
375
376 IambWindow::open(id, store)
377 },
378 }
379 }
380
381 fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
382 let msg = format!("Cannot find indexed buffer (index = {})", index);
383 let err = UIError::Unimplemented(msg);
384
385 Err(err)
386 }
387}
388
389#[derive(Clone)]
390pub struct RoomItem {
391 room: MatrixRoom,
392 name: String,
393}
394
395impl RoomItem {
396 fn new(room: MatrixRoom, name: DisplayName, store: &mut ProgramStore) -> Self {
397 let name = name.to_string();
398
399 store.application.set_room_name(room.room_id(), name.as_str());
400
401 RoomItem { room, name }
402 }
403}
404
405impl ToString for RoomItem {
406 fn to_string(&self) -> String {
407 return self.name.clone();
408 }
409}
410
411impl ListItem<IambInfo> for RoomItem {
412 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
413 selected_text(self.name.as_str(), selected)
414 }
415}
416
417impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomItem {
418 fn prompt(
419 &mut self,
420 act: &PromptAction,
421 ctx: &ProgramContext,
422 _: &mut ProgramStore,
423 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
424 room_prompt(self.room.room_id(), act, ctx)
425 }
426}
427
428#[derive(Clone)]
429pub struct DirectItem {
430 room: MatrixRoom,
431 name: String,
432}
433
434impl DirectItem {
435 fn new(room: MatrixRoom, name: DisplayName, store: &mut ProgramStore) -> Self {
436 let name = name.to_string();
437
438 store.application.set_room_name(room.room_id(), name.as_str());
439
440 DirectItem { room, name }
441 }
442}
443
444impl ToString for DirectItem {
445 fn to_string(&self) -> String {
446 return self.name.clone();
447 }
448}
449
450impl ListItem<IambInfo> for DirectItem {
451 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
452 selected_text(self.name.as_str(), selected)
453 }
454}
455
456impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
457 fn prompt(
458 &mut self,
459 act: &PromptAction,
460 ctx: &ProgramContext,
461 _: &mut ProgramStore,
462 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
463 room_prompt(self.room.room_id(), act, ctx)
464 }
465}
466
467#[derive(Clone)]
468pub struct SpaceItem {
469 room: MatrixRoom,
470 name: String,
471}
472
473impl SpaceItem {
474 fn new(room: MatrixRoom, name: DisplayName, store: &mut ProgramStore) -> Self {
475 let name = name.to_string();
476
477 store.application.set_room_name(room.room_id(), name.as_str());
478
479 SpaceItem { room, name }
480 }
481}
482
483impl ToString for SpaceItem {
484 fn to_string(&self) -> String {
485 return self.room.room_id().to_string();
486 }
487}
488
489impl ListItem<IambInfo> for SpaceItem {
490 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
491 selected_text(self.name.as_str(), selected)
492 }
493}
494
495impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
496 fn prompt(
497 &mut self,
498 act: &PromptAction,
499 ctx: &ProgramContext,
500 _: &mut ProgramStore,
501 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
502 room_prompt(self.room.room_id(), act, ctx)
503 }
504}
505
506#[derive(Clone)]
507pub struct VerifyItem {
508 user_dev: String,
509 sasv1: SasVerification,
510}
511
512impl VerifyItem {
513 fn new(user_dev: String, sasv1: SasVerification) -> Self {
514 VerifyItem { user_dev, sasv1 }
515 }
516
517 fn show_item(&self) -> String {
518 let state = if self.sasv1.is_done() {
519 "done"
520 } else if self.sasv1.is_cancelled() {
521 "cancelled"
522 } else if self.sasv1.emoji().is_some() {
523 "accepted"
524 } else {
525 "not accepted"
526 };
527
528 if self.sasv1.is_self_verification() {
529 let device = self.sasv1.other_device();
530
531 if let Some(display_name) = device.display_name() {
532 format!("Device verification with {} ({})", display_name, state)
533 } else {
534 format!("Device verification with device {} ({})", device.device_id(), state)
535 }
536 } else {
537 format!("User Verification with {} ({})", self.sasv1.other_user_id(), state)
538 }
539 }
540}
541
542impl PartialEq for VerifyItem {
543 fn eq(&self, other: &Self) -> bool {
544 self.user_dev == other.user_dev
545 }
546}
547
548impl Eq for VerifyItem {}
549
550impl Ord for VerifyItem {
551 fn cmp(&self, other: &Self) -> Ordering {
552 fn state_val(sas: &SasVerification) -> usize {
553 if sas.is_done() {
554 return 3;
555 } else if sas.is_cancelled() {
556 return 2;
557 } else {
558 return 1;
559 }
560 }
561
562 fn device_val(sas: &SasVerification) -> usize {
563 if sas.is_self_verification() {
564 return 1;
565 } else {
566 return 2;
567 }
568 }
569
570 let state1 = state_val(&self.sasv1);
571 let state2 = state_val(&other.sasv1);
572
573 let dev1 = device_val(&self.sasv1);
574 let dev2 = device_val(&other.sasv1);
575
576 let scmp = state1.cmp(&state2);
577 let dcmp = dev1.cmp(&dev2);
578
579 scmp.then(dcmp).then_with(|| {
580 let did1 = self.sasv1.other_device().device_id();
581 let did2 = other.sasv1.other_device().device_id();
582
583 did1.cmp(did2)
584 })
585 }
586}
587
588impl PartialOrd for VerifyItem {
589 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
590 self.cmp(other).into()
591 }
592}
593
594impl From<(&String, &SasVerification)> for VerifyItem {
595 fn from((user_dev, sasv1): (&String, &SasVerification)) -> Self {
596 VerifyItem::new(user_dev.clone(), sasv1.clone())
597 }
598}
599
600impl ToString for VerifyItem {
601 fn to_string(&self) -> String {
602 if self.sasv1.is_done() {
603 String::new()
604 } else if self.sasv1.is_cancelled() {
605 format!(":verify request {}", self.sasv1.other_user_id())
606 } else if self.sasv1.emoji().is_some() {
607 format!(":verify confirm {}", self.user_dev)
608 } else {
609 format!(":verify accept {}", self.user_dev)
610 }
611 }
612}
613
614impl ListItem<IambInfo> for VerifyItem {
615 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
616 let mut lines = vec![];
617
618 let bold = Style::default().add_modifier(StyleModifier::BOLD);
619 let item = Span::styled(self.show_item(), selected_style(selected));
620 lines.push(Spans::from(item));
621
622 if self.sasv1.is_done() {
623 // Print nothing.
624 } else if self.sasv1.is_cancelled() {
625 if let Some(info) = self.sasv1.cancel_info() {
626 lines.push(Spans::from(format!(" Cancelled: {}", info.reason())));
627 lines.push(Spans::from(""));
628 }
629
630 lines.push(Spans::from(" You can start a new verification request with:"));
631 } else if let Some(emoji) = self.sasv1.emoji() {
632 lines.push(Spans::from(
633 " Both devices should see the following Emoji sequence:".to_string(),
634 ));
635 lines.push(Spans::from(""));
636
637 for line in format_emojis(emoji).lines() {
638 lines.push(Spans::from(format!(" {}", line)));
639 }
640
641 lines.push(Spans::from(""));
642 lines.push(Spans::from(" If they don't match, run:"));
643 lines.push(Spans::from(""));
644 lines.push(Spans::from(Span::styled(
645 format!(":verify mismatch {}", self.user_dev),
646 bold,
647 )));
648 lines.push(Spans::from(""));
649 lines.push(Spans::from(" If everything looks right, you can confirm with:"));
650 } else {
651 lines.push(Spans::from(" To accept this request, run:"));
652 }
653
654 let cmd = self.to_string();
655
656 if !cmd.is_empty() {
657 lines.push(Spans::from(""));
658 lines.push(Spans(vec![Span::from(" "), Span::styled(cmd, bold)]));
659 lines.push(Spans::from(""));
660 lines.push(Spans(vec![
661 Span::from("You can copy the above command with "),
662 Span::styled("yy", bold),
663 Span::from(" and then execute it with "),
664 Span::styled("@\"", bold),
665 ]));
666 }
667
668 Text { lines }
669 }
670}
671
672impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
673 fn prompt(
674 &mut self,
675 act: &PromptAction,
676 _: &ProgramContext,
677 _: &mut ProgramStore,
678 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
679 match act {
680 PromptAction::Submit => Ok(vec![]),
681 PromptAction::Abort(_) => {
682 let msg = "Cannot abort entry inside a list";
683 let err = EditError::Failure(msg.into());
684
685 Err(err)
686 },
687 PromptAction::Recall(_, _) => {
688 let msg = "Cannot recall history inside a list";
689 let err = EditError::Failure(msg.into());
690
691 Err(err)
692 },
693 _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
694 }
695 }
696}