tgt 1.0.0

A simple TUI for Telegram
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
use crate::{
    action::{Action, Modifiers},
    app_context::AppContext,
    component_name::ComponentName,
    components::component_traits::{Component, HandleFocus},
    event::Event,
    tg::td_enums::TdMessageReplyToMessage,
};
use arboard::Clipboard;
use crossterm::event::KeyCode;
use ratatui::{
    layout::Rect,
    symbols::{
        border::{Set, PLAIN},
        line::NORMAL,
    },
    text::{Line, Span},
    widgets::{block::Block, Borders, Paragraph},
    Frame,
};
use std::{io, sync::Arc};
use tokio::sync::mpsc::UnboundedSender;

/// `DirSelection` is an enum that represents the direction of the selection.
/// It is used to keep track of the direction of the selection when the user
/// is selecting text.
#[derive(Debug, Clone, Eq, PartialEq)]
enum DirSelection {
    /// The user is not selecting text.
    Empty,
    /// The user is selecting text to the left.
    Left,
    /// The user is selecting text to the right.
    Right,
    /// The user is selecting text up.
    Up,
    /// The user is selecting text down.
    Down,
}
/// `Mode` is an enum that represents the mode of the prompt.
/// It is used to keep track of the mode of the prompt.
enum Mode {
    /// The normal mode of the prompt.
    Normal,
    /// The edit mode of the prompt.
    /// Usually, when the prompt is editing a message.
    /// The parameter is the message id of the message that is being replied.
    Edit(i64),
    /// The reply mode of the prompt.
    /// Usually, when the prompt is replying to a message.
    /// The parameter is the message id of the message that is being replied.
    Reply(i64),
}
/// `InputCell` is a struct that represents a cell of the input.
/// It is responsible for managing the input cell of the prompt.
#[derive(Debug, Clone, Eq, PartialEq)]
struct InputCell {
    /// The character of the input cell.
    c: char,
    /// A flag indicating whether the input cell is selected or not.
    selected: bool,
}
/// `Input` is a struct that represents the input of a prompt.
/// It is responsible for managing the input of the prompt.
struct Input {
    /// The text of the input.
    text: Vec<Vec<InputCell>>,
    /// The cursor position of the input.
    cursor: (usize, usize),
    /// The area of the component where the input is displayed.
    area_input: Rect,
    /// An unbounded sender that send action for processing.
    /// It is used to send actions to the main event loop for processing.
    /// Basically, it is used to send `IncreasePromptSize` and `DecreasePromptSize`
    /// actions.
    action_tx: Option<UnboundedSender<Action>>,
    /// An enum that represents the direction of the selection.
    /// Implicitly, it is used to keep track whether the user is selecting text
    /// or not.
    dir_selection: DirSelection,
    /// The correct prompt size.
    /// It is used to keep track of the correct prompt size when the prompt
    /// window is focused or unfocused.
    correct_prompt_size: usize,
    /// A flag indicating whether the prompt size is restored or not.
    /// Basically, it is used to keep track of whether the prompt size is
    /// equal to the correct prompt size or not.
    is_restored: bool,
    /// The mode of the input.
    /// It is used to keep track of the mode of the input.
    mode: Mode,
}
/// Implement the `Input` struct.
impl Input {
    /// Set the command sender of the `Input` struct.
    ///
    /// # Arguments
    /// * `command_tx` - An unbounded sender that send action for processing.
    fn set_command_tx(&mut self, command_tx: UnboundedSender<Action>) {
        self.action_tx = Some(command_tx);
    }
    /// Get the cursor x position of the `Input` struct.
    fn cursor_x(&self) -> usize {
        self.cursor.0
    }
    /// Get the cursor y position of the `Input` struct.
    fn cursor_y(&self) -> usize {
        self.cursor.1
    }
    /// Get the text of the `Input` struct.
    fn text(&mut self) -> &Vec<Vec<InputCell>> {
        &self.text
    }
    /// Insert a character into the `Input` struct.
    /// The character is inserted at the current cursor position.
    /// If the cursor is at the end of the line, a new line is inserted.
    ///
    /// # Arguments
    /// * `c` - The character to insert.
    fn insert(&mut self, c: char) {
        // The -2 is to account the cursor at the end of the line.
        if self.cursor.0 + 1 == (self.area_input.width - 2) as usize {
            self.insert_newline();
        }
        self.text[self.cursor.1].insert(self.cursor.0, InputCell { c, selected: false });
        self.cursor.0 += 1;
    }
    /// Insert a newline into the `Input` struct.
    /// A newline is inserted at the current cursor position.
    /// The text after the cursor position is moved to the next line.
    fn insert_newline(&mut self) {
        self.insert('\n');
        let line = &mut self.text[self.cursor.1];
        let right = line[self.cursor.0..].to_vec();
        line.truncate(self.cursor.0);
        self.text.insert(self.cursor.1 + 1, right);
        self.cursor.0 = 0;
        self.cursor.1 += 1;
        if let Some(tx) = self.action_tx.as_ref() {
            self.correct_prompt_size += 1;
            tx.send(Action::IncreasePromptSize).unwrap()
        }
    }
    /// Delete the character before the cursor position.
    fn backspace(&mut self) {
        if self.text[self.cursor.1].is_empty() && self.cursor.1 > 0 {
            if let Some(tx) = self.action_tx.as_ref() {
                self.correct_prompt_size -= 1;
                tx.send(Action::DecreasePromptSize).unwrap();
            }
        }
        if self.cursor.0 == 0 {
            if self.cursor.1 > 0 {
                let line = self.text.remove(self.cursor.1);
                self.cursor.1 -= 1;
                self.cursor.0 = self.text[self.cursor.1].len();
                self.text[self.cursor.1].extend(line);
            }
        } else {
            self.text[self.cursor.1].remove(self.cursor.0 - 1);
            self.cursor.0 -= 1;
        }
    }
    /// Delete the character next to the cursor position.
    fn delete(&mut self) {
        if self.cursor.0 == self.text[self.cursor.1].len() {
            if self.cursor.1 < self.text.len() - 1 {
                let line = self.text.remove(self.cursor.1 + 1);
                self.text[self.cursor.1].extend(line);
            }
        } else {
            self.text[self.cursor.1].remove(self.cursor.0);
        }
    }
    /// Move the cursor to the left.
    fn move_cursor_left(&mut self) {
        if self.cursor.0 > 0 {
            self.cursor.0 -= 1;
        }
    }
    /// Move the cursor to the right.
    fn move_cursor_right(&mut self) {
        if self.cursor.0 < self.text[self.cursor.1].len() {
            self.cursor.0 += 1;
        }
    }
    /// Move the cursor up.
    fn move_cursor_up(&mut self) {
        if self.cursor.1 > 0 {
            // Handle moving cursor to the left if the current line is shorter
            // than the previous line.
            if self.cursor.0 > self.text[self.cursor.1 - 1].len() {
                self.cursor.0 = self.text[self.cursor.1 - 1].len();
            }
            self.cursor.1 -= 1;
        }
    }
    /// Move the cursor down.
    fn move_cursor_down(&mut self) {
        if self.cursor.1 < self.text.len() - 1 {
            // Handle moving cursor to the left if the current line is shorter
            // than the next line.
            if self.cursor.0 > self.text[self.cursor.1 + 1].len() {
                self.cursor.0 = self.text[self.cursor.1 + 1].len();
            }
            self.cursor.1 += 1;
        }
    }
    /// Move the cursor to the previous word.
    fn move_cursor_to_previous_word(&mut self) {
        let line = &self.text[self.cursor.1];
        let mut i = self.cursor.0;
        while i > 0 && line[i - 1].c.is_whitespace() {
            i -= 1;
        }
        while i > 0 && !line[i - 1].c.is_whitespace() {
            i -= 1;
        }
        self.cursor.0 = i;
    }
    /// Move the cursor to the next word.
    fn move_cursor_to_next_word(&mut self) {
        let line = &self.text[self.cursor.1];
        let mut i = self.cursor.0;
        while i < line.len() && line[i].c.is_whitespace() {
            i += 1;
        }
        while i < line.len() && !line[i].c.is_whitespace() {
            i += 1;
        }
        self.cursor.0 = i;
    }
    /// Move the cursor to the start of the line.
    fn move_cursor_to_end(&mut self) {
        self.cursor.0 = self.text[self.cursor.1].len();
    }
    /// Move the cursor to the end of the line.
    fn move_cursor_to_start(&mut self) {
        self.cursor.0 = 0;
    }
    /// Delete the previous word.
    fn delete_previous_word(&mut self) {
        let line = &mut self.text[self.cursor.1];
        let mut i = self.cursor.0;
        while i > 0 && line[i - 1].c.is_whitespace() {
            i -= 1;
        }
        while i > 0 && !line[i - 1].c.is_whitespace() {
            i -= 1;
        }
        line.drain(i..self.cursor.0);
        self.cursor.0 = i;
    }
    /// Restore the prompt size of the `Input` struct.
    /// It is used to restore the prompt size to the correct prompt size when
    /// the prompt window is focused.
    /// It sends `IncreasePromptSize` actions to the main event loop to increase
    /// the prompt size.
    fn restore_prompt_size(&mut self) {
        if !self.is_restored {
            if let Some(tx) = self.action_tx.as_ref() {
                for _ in 0..self.correct_prompt_size {
                    tx.send(Action::IncreasePromptSize).unwrap();
                }
            }
            self.is_restored = true;
        }
    }
    /// Set the prompt size to one.
    /// It is used to set the prompt size to one.
    fn set_prompt_size_to_one(&mut self) {
        if let Some(tx) = self.action_tx.as_ref() {
            for _ in 0..self.correct_prompt_size {
                tx.send(Action::DecreasePromptSize).unwrap();
            }
        }
    }
    /// Set the prompt size to one.
    /// It is used to set the prompt size to one when the prompt window is
    /// focused.
    /// Simply, it set the correct prompt size to zero and the cursor to the
    /// start of the line.
    fn set_prompt_size_to_one_focused(&mut self) {
        self.set_prompt_size_to_one();
        self.correct_prompt_size = 0;
        self.cursor = (0, 0);
    }
    /// Set the prompt size to one.
    /// It is used to set the prompt size to one when the prompt window is
    /// unfocused.
    /// It means that when the prompt window will return to focus, the prompt
    /// size will be restored to the correct prompt size.
    fn set_prompt_size_to_one_unfocused(&mut self) {
        self.set_prompt_size_to_one();
        self.is_restored = false;
    }
    /// Move the cursor to the left and toggle the selection.
    fn move_cursor_left_and_toggle_selection(&mut self) {
        if self.cursor.0 > 0 {
            self.cursor.0 -= 1;
            self.text[self.cursor.1][self.cursor.0].selected =
                !self.text[self.cursor.1][self.cursor.0].selected;
        }
        self.dir_selection = DirSelection::Left;
    }
    /// Move the cursor to the right and toggle the selection.
    fn move_cursor_right_and_toggle_selection(&mut self) {
        if self.cursor.0 < self.text[self.cursor.1].len() {
            self.text[self.cursor.1][self.cursor.0].selected =
                !self.text[self.cursor.1][self.cursor.0].selected;
            self.cursor.0 += 1;
        }
        self.dir_selection = DirSelection::Right;
    }
    // Move the cursor to the previous word and toggle the selection.
    fn move_cursor_to_previous_word_and_toggle_selection(&mut self) {
        let line = &self.text[self.cursor.1];
        let mut i = self.cursor.0;
        while i > 0 && line[i - 1].c.is_whitespace() {
            i -= 1;
        }
        while i > 0 && !line[i - 1].c.is_whitespace() {
            i -= 1;
        }
        for cell in &mut self.text[self.cursor.1][i..self.cursor.0] {
            cell.selected = !cell.selected;
        }
        self.cursor.0 = i;
        self.dir_selection = DirSelection::Left;
    }
    /// Move the cursor to the next word and toggle the selection.
    fn move_cursor_to_next_word_and_toggle_selection(&mut self) {
        let line = &self.text[self.cursor.1];
        let mut i = self.cursor.0;
        while i < line.len() && line[i].c.is_whitespace() {
            i += 1;
        }
        while i < line.len() && !line[i].c.is_whitespace() {
            i += 1;
        }
        for cell in &mut self.text[self.cursor.1][self.cursor.0..i] {
            cell.selected = !cell.selected;
        }
        self.cursor.0 = i;
        self.dir_selection = DirSelection::Right;
    }
    /// Move the cursor up and toggle the selection.
    fn move_cursor_up_and_toggle_selection(&mut self) {
        if self.cursor.1 > 0 {
            self.toggle_selection_from_cursor_to_start_of_line();
            self.move_cursor_up();
            self.toggle_selection_from_end_of_line_to_cursor();
            self.dir_selection = DirSelection::Up;
        }
    }
    /// Move the cursor down and toggle the selection.
    fn move_cursor_down_and_toggle_selection(&mut self) {
        if self.cursor.1 < self.text.len() - 1 {
            self.toggle_selection_from_cursor_to_end_of_line();
            self.move_cursor_down();
            self.toggle_selection_from_start_of_line_to_cursor();
            self.dir_selection = DirSelection::Down;
        }
    }
    /// Toggle the selection from the cursor to the start of the line.
    fn toggle_selection_from_cursor_to_start_of_line(&mut self) {
        for cell in &mut self.text[self.cursor.1][..self.cursor.0] {
            cell.selected = !cell.selected;
        }
    }
    /// Toggle the selection from the cursor to the end of the line.
    fn toggle_selection_from_cursor_to_end_of_line(&mut self) {
        for cell in &mut self.text[self.cursor.1][self.cursor.0..] {
            cell.selected = !cell.selected;
        }
    }
    /// Toggle the selection from the start of the line to the cursor.
    fn toggle_selection_from_start_of_line_to_cursor(&mut self) {
        for cell in &mut self.text[self.cursor.1][..self.cursor.0] {
            cell.selected = !cell.selected;
        }
    }
    /// Toggle the selection from the end of the line to the cursor.
    fn toggle_selection_from_end_of_line_to_cursor(&mut self) {
        for cell in &mut self.text[self.cursor.1][self.cursor.0..] {
            cell.selected = !cell.selected;
        }
    }
    /// Unselect all the text.
    fn unselect_all(&mut self) {
        if self.dir_selection != DirSelection::Empty {
            for line in &mut self.text {
                for cell in line {
                    cell.selected = false;
                }
            }
            self.dir_selection = DirSelection::Empty;
        }
    }
    /// Copy the selected text of the `Input` struct.
    /// The selected text is copied to the clipboard.
    fn copy_selected(&self) {
        if let Ok(mut clipboard) = Clipboard::new() {
            let mut text = String::new();
            for (i, line) in self.text.iter().enumerate() {
                for cell in line {
                    if cell.selected {
                        text.push(cell.c);
                    }
                }
                if i < self.text.len() - 1 {
                    text.push('\n');
                }
            }
            clipboard.set_text(text).unwrap();
        }
    }
    /// Paste text into the `Input` struct.
    /// The text is pasted at the current cursor position.
    fn paste(&mut self, text: String) {
        for c in text.chars() {
            if c == '\n' {
                self.insert_newline();
            } else {
                self.insert(c);
            }
        }
    }
    /// Edit a message.
    ///
    /// # Arguments
    /// * `message_id` - The message id of the message to edit.
    /// * `message` - The message to edit.
    fn edit_message(&mut self, message_id: i64, message: String) {
        self.mode = Mode::Edit(message_id);
        self.text = message
            .split('\n')
            .map(|line| {
                line.chars()
                    .map(|c| InputCell { c, selected: false })
                    .collect()
            })
            .collect();
        for _ in 0..self.text.len() - 1 {
            if let Some(tx) = self.action_tx.as_ref() {
                tx.send(Action::IncreasePromptSize).unwrap();
            }
        }
        self.cursor = (0, 0);
    }

    /// Send a message.
    /// The message is sent to the main event loop for processing.
    ///
    /// # Arguments
    /// * `app_context` - An Arc wrapped AppContext struct.
    fn send_message(&mut self, app_context: Arc<AppContext>) {
        if let Some(event_tx) = app_context.tg_context().event_tx().as_ref() {
            match self.mode {
                Mode::Normal => {
                    event_tx
                        .send(Event::SendMessage(self.text_to_string(), None))
                        .unwrap();
                    self.text = vec![vec![]];
                    self.set_prompt_size_to_one_focused();
                }
                Mode::Edit(message_id) => {
                    event_tx
                        .send(Event::SendMessageEdited(message_id, self.text_to_string()))
                        .unwrap();
                    self.text = vec![vec![]];
                    self.set_prompt_size_to_one_focused();
                    self.mode = Mode::Normal;
                }
                Mode::Reply(message_id) => {
                    event_tx
                        .send(Event::SendMessage(
                            self.text_to_string(),
                            Some(TdMessageReplyToMessage {
                                chat_id: 0, // This must be  0 and not `app_context.tg_context().open_chat_id()` because the tdlib (maybe from the version 1.8.29 or before)  is able to know the chat id from the message_id; it will infer the chat id from the message_id.
                                message_id,
                            }),
                        ))
                        .unwrap();
                    self.text = vec![vec![]];
                    self.set_prompt_size_to_one_focused();
                    self.mode = Mode::Normal;
                }
            }
        }
    }
    /// Convert the text of the `Input` struct to a string.
    fn text_to_string(&mut self) -> String {
        // TODO: Parse into markdown
        let mut message = String::new();
        self.text.iter().for_each(|e| {
            if e.is_empty() {
                message.push('\n');
            } else {
                e.iter().for_each(|e| message.push(e.c))
            }
        });
        message
    }
}
/// Implement the `Default` trait for the `Input` struct.
impl Default for Input {
    fn default() -> Self {
        Self {
            text: vec![vec![]],
            cursor: (0, 0),
            area_input: Rect::default(),
            action_tx: None,
            dir_selection: DirSelection::Empty,
            correct_prompt_size: 0,
            is_restored: true,
            mode: Mode::Normal,
        }
    }
}
/// `PromptWindow` is a struct that represents a window for displaying a prompt.
/// It is responsible for managing the layout and rendering of the prompt
/// window.
pub struct PromptWindow {
    /// The application context.
    app_context: Arc<AppContext>,
    /// The name of the `PromptWindow`.
    name: String,
    /// An unbounded sender that send action for processing.
    action_tx: Option<UnboundedSender<Action>>,
    /// Indicates whether the `PromptWindow` is focused or not.
    focused: bool,
    /// The keys that allows the `PromptWindow` to be focused.
    focused_keys: Vec<Event>,
    /// The current input of the `PromptWindow`.
    input: Input,
}
/// Implement the `PromptWindow` struct.
impl PromptWindow {
    /// Create a new instance of the `PromptWindow` struct.
    ///
    /// # Arguments
    /// * `app_context` - An Arc wrapped AppContext struct.
    ///
    /// # Returns
    /// * `Self` - The new instance of the `PromptWindow` struct.
    pub fn new(app_context: Arc<AppContext>) -> Self {
        let name = "".to_string();
        let action_tx = None;
        let focused = false;
        let focused_keys = app_context.keymap_config().get_key_of_single_action(
            ComponentName::CoreWindow,
            Action::FocusComponent(ComponentName::Prompt),
        );

        let input = Input::default();

        PromptWindow {
            app_context,
            name,
            action_tx,
            focused,
            focused_keys,
            input,
        }
    }
    /// Set the name of the `PromptWindow`.
    ///
    /// # Arguments
    /// * `name` - The name of the `PromptWindow`
    ///
    /// # Returns
    /// * `Self` - The modified instance of the `PromptWindow`.
    pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
        self.name = name.as_ref().to_string();
        self
    }
    /// Update the input area of the `PromptWindow`.
    /// It is used to update the input area of the `PromptWindow` when a new
    /// line is inserted or deleted.
    ///
    /// # Arguments
    /// * `area_input` - The new input area of the `PromptWindow`.
    pub fn update_input(&mut self, area_input: Rect) {
        if self.input.area_input != area_input {
            self.input.area_input = area_input;
        }
    }
}

/// Implement the `HandleFocus` trait for the `PromptWindow` struct.
/// This trait allows the `PromptWindow` to be focused or unfocused.
impl HandleFocus for PromptWindow {
    /// Set the `focused` flag for the `PromptWindow`.
    fn focus(&mut self) {
        self.focused = true;
    }
    /// Set the `focused` flag for the `PromptWindow`.
    fn unfocus(&mut self) {
        self.focused = false;
        self.input.mode = Mode::Normal;
        self.input.text = vec![vec![]];
    }
}

/// Implement the `Component` trait for the `ChatListWindow` struct.
impl Component for PromptWindow {
    fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> std::io::Result<()> {
        self.action_tx = Some(tx.clone());
        self.input.set_command_tx(tx);
        Ok(())
    }

    fn update(&mut self, action: Action) {
        match action {
            Action::Key(key_code, modifiers) => match (key_code, modifiers) {
                (KeyCode::Home, ..)
                | (
                    KeyCode::Left | KeyCode::Char('b'),
                    Modifiers {
                        shift: true,
                        super_: true,
                        ..
                    },
                )
                | (
                    KeyCode::Left | KeyCode::Char('b'),
                    Modifiers {
                        control: true,
                        alt: true,
                        ..
                    },
                )
                | (KeyCode::Char('a'), Modifiers { control: true, .. }) => {
                    self.input.unselect_all();
                    self.input.move_cursor_to_start();
                }

                (KeyCode::End, ..)
                | (
                    KeyCode::Right | KeyCode::Char('f'),
                    Modifiers {
                        shift: true,
                        super_: true,
                        ..
                    },
                )
                | (
                    KeyCode::Right | KeyCode::Char('f'),
                    Modifiers {
                        control: true,
                        alt: true,
                        ..
                    },
                )
                | (KeyCode::Char('e'), Modifiers { control: true, .. }) => {
                    self.input.unselect_all();
                    self.input.move_cursor_to_end();
                }

                (
                    KeyCode::Left,
                    Modifiers {
                        shift: true,
                        control: true,
                        ..
                    },
                ) => {
                    self.input
                        .move_cursor_to_previous_word_and_toggle_selection();
                }

                (
                    KeyCode::Right,
                    Modifiers {
                        shift: true,
                        control: true,
                        ..
                    },
                ) => {
                    self.input.move_cursor_to_next_word_and_toggle_selection();
                }

                (KeyCode::Left, Modifiers { shift: true, .. }) => {
                    self.input.move_cursor_left_and_toggle_selection();
                }

                (KeyCode::Right, Modifiers { shift: true, .. }) => {
                    self.input.move_cursor_right_and_toggle_selection();
                }

                (KeyCode::Up, Modifiers { shift: true, .. }) => {
                    self.input.move_cursor_up_and_toggle_selection();
                }

                (KeyCode::Down, Modifiers { shift: true, .. }) => {
                    self.input.move_cursor_down_and_toggle_selection();
                }

                (KeyCode::Char('c'), Modifiers { control: true, .. }) => {
                    self.input.copy_selected();
                    self.input.unselect_all();
                }

                (KeyCode::Char('v'), Modifiers { control: true, .. }) => {
                    if let Ok(mut clipboard) = Clipboard::new() {
                        if let Ok(text) = clipboard.get_text() {
                            self.input.paste(text);
                        }
                    }
                }

                (KeyCode::Left | KeyCode::Char('b'), Modifiers { alt: true, .. }) => {
                    self.input.unselect_all();
                    self.input.move_cursor_to_previous_word();
                }

                (KeyCode::Right | KeyCode::Char('f'), Modifiers { alt: true, .. }) => {
                    self.input.unselect_all();
                    self.input.move_cursor_to_next_word();
                }

                (KeyCode::Enter, Modifiers { alt: true, .. }) => {
                    self.input.unselect_all();
                    self.input.send_message(Arc::clone(&self.app_context));
                }

                (KeyCode::Backspace, Modifiers { alt: true, .. })
                | (KeyCode::Char('w'), Modifiers { control: true, .. }) => {
                    self.input.unselect_all();
                    self.input.delete_previous_word();
                }

                (
                    KeyCode::Char(c),
                    Modifiers {
                        alt: false,
                        control: false,
                        meta: false,
                        super_: false,
                        hyper: false,
                        ..
                    },
                ) => {
                    self.input.unselect_all();
                    self.input.insert(c);
                }

                (KeyCode::Backspace, ..) => {
                    self.input.unselect_all();
                    self.input.backspace();
                }

                (KeyCode::Delete, ..) => {
                    self.input.unselect_all();
                    self.input.delete();
                }

                (KeyCode::Enter, ..) => {
                    self.input.unselect_all();
                    self.input.insert_newline();
                }

                (KeyCode::Left, ..) => {
                    self.input.unselect_all();
                    self.input.move_cursor_left();
                }

                (KeyCode::Right, ..) => {
                    self.input.unselect_all();
                    self.input.move_cursor_right();
                }

                (KeyCode::Up, ..) => {
                    self.input.unselect_all();
                    self.input.move_cursor_up();
                }

                (KeyCode::Down, ..) => {
                    self.input.unselect_all();
                    self.input.move_cursor_down();
                }
                _ => {}
            },
            Action::Paste(text) => {
                self.input.unselect_all();
                self.input.paste(text);
            }
            Action::EditMessage(message_id, message) => {
                self.input.edit_message(message_id, message);
            }
            Action::ReplyMessage(message_id, _) => {
                self.input.mode = Mode::Reply(message_id);
            }
            _ => {}
        }
    }

    fn draw(&mut self, frame: &mut Frame<'_>, area: Rect) -> io::Result<()> {
        self.update_input(area);

        let collapsed_top_and_left_border_set = Set {
            top_left: NORMAL.vertical_right,
            top_right: NORMAL.vertical_left,
            bottom_left: NORMAL.horizontal_up,
            ..PLAIN
        };
        let text = self
            .input
            .text()
            .iter()
            .map(|line| {
                Line::from(
                    line.iter()
                        .map(|cell| {
                            if cell.selected {
                                Span::styled(
                                    cell.c.to_string(),
                                    self.app_context.style_prompt_message_text_selected(),
                                )
                            } else {
                                Span::styled(
                                    cell.c.to_string(),
                                    self.app_context.style_prompt_message_text(),
                                )
                            }
                        })
                        .collect::<Vec<Span>>(),
                )
            })
            .collect::<Vec<Line>>();

        let (text, style_text, style_border_focused) = if self.focused {
            self.input.restore_prompt_size();
            (
                text,
                self.app_context.style_prompt(),
                self.app_context.style_border_component_focused(),
            )
        } else {
            self.input.set_prompt_size_to_one_unfocused();
            (
                vec![Line::from(format!(
                    "Press {} to send a message",
                    self.focused_keys
                        .iter()
                        .map(|e| e.to_string())
                        .collect::<Vec<String>>()
                        .join(" or ")
                ))],
                self.app_context.style_prompt_message_preview_text(),
                self.app_context.style_prompt(),
            )
        };

        let block = Block::new()
            .border_set(collapsed_top_and_left_border_set)
            .border_style(style_border_focused)
            .borders(Borders::ALL)
            .title(self.name.as_str());

        let input = Paragraph::new(text).style(style_text).block(block);

        frame.render_widget(input, area);

        if self.focused {
            frame.set_cursor(
                area.x + self.input.cursor_x() as u16 + 1,
                area.y + self.input.cursor_y() as u16 + 1,
            );
        }
        Ok(())
    }
}