yapper 0.4.0

A modern, ergonomic UART serial TUI terminal for embedded workflows
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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
use std::sync::mpsc::{self, Receiver, Sender};
use std::time::{Duration, Instant};

use crate::buffer::ScrollbackBuffer;
use crate::config::AppConfig;
use crate::filter::LineFilter;
use crate::history::CommandHistory;
use crate::logging::SessionLogger;
use crate::macros::MacroManager;
use crate::mouse::{LayoutRegions, TextSelection};
use crate::search::Search;
use crate::serial::config::SerialConfig;
use crate::serial::connection::{SerialConnection, SerialEvent};
use crate::serial::detector::{self, PortInfo};

/// The application mode determines how keyboard input is handled.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Mode {
    /// Normal mode: scroll, search, toggle settings.
    Normal,
    /// Input mode: typing commands to send.
    Input,
    /// Search mode: typing search query.
    Search,
    /// Port selector popup is open.
    PortSelect,
    /// UART settings popup is open.
    Settings,
    /// Help overlay is shown.
    Help,
    /// Macro selector popup is open.
    MacroSelect,
    /// Filter manager popup is open.
    Filter,
}

/// Connection state for display purposes.
#[derive(Debug, Clone, PartialEq)]
pub enum ConnectionState {
    Disconnected,
    Connected(String),
    Reconnecting(String),
    Error(String),
}

/// Central application state.
pub struct App {
    /// Current input mode.
    pub mode: Mode,
    /// Whether the app should quit.
    pub should_quit: bool,
    /// Scrollback buffer containing all received lines.
    pub buffer: ScrollbackBuffer,
    /// The text currently being typed in the input bar.
    pub input_text: String,
    /// Cursor position within input_text.
    pub input_cursor: usize,
    /// Line ending to append when sending commands.
    pub line_ending: String,
    /// Serial port configuration.
    pub serial_config: SerialConfig,
    /// Current connection state.
    pub connection_state: ConnectionState,
    /// Active serial connection (if connected).
    connection: Option<SerialConnection>,
    /// Receiver for serial events from the reader thread.
    serial_rx: Option<Receiver<SerialEvent>>,
    /// Sender end — kept to pass to new connections.
    serial_tx: Option<Sender<SerialEvent>>,
    /// Scroll offset (0 = bottom/latest, higher = scrolled up).
    pub scroll_offset: usize,
    /// Whether to auto-follow new output.
    pub follow_output: bool,
    /// Total RX bytes (persisted across reconnects).
    pub rx_bytes: u64,
    /// Total TX bytes (persisted across reconnects).
    pub tx_bytes: u64,
    /// Available ports for the port selector.
    pub available_ports: Vec<PortInfo>,
    /// Selected index in the port selector.
    pub port_select_index: usize,
    /// Whether timestamps are enabled.
    pub show_timestamps: bool,
    /// Whether hex view mode is enabled.
    pub hex_mode: bool,
    /// Whether to show line ending indicators.
    pub show_line_endings: bool,
    /// Command history.
    pub history: CommandHistory,
    /// Search state.
    pub search: Search,
    /// Session logger.
    pub logger: SessionLogger,
    /// Auto-reconnect enabled.
    pub auto_reconnect: bool,
    /// Port name for auto-reconnect.
    reconnect_port: Option<String>,
    /// When the last reconnect attempt was made.
    last_reconnect_attempt: Option<Instant>,
    /// Reconnect delay.
    reconnect_delay: Duration,
    /// Status message (shown temporarily in status bar).
    pub status_message: Option<(String, Instant)>,
    /// Line filter (regex-based include/exclude).
    pub filter: LineFilter,
    /// Macro manager.
    pub macros: MacroManager,
    /// Selected macro index (for macro selector popup).
    pub macro_select_index: usize,
    /// Currently selected field in settings popup (0-4).
    pub settings_field: usize,
    /// Layout regions for mouse click detection.
    pub layout: LayoutRegions,
    /// Text selection state for click-drag-copy.
    pub selection: TextSelection,
    /// Ghost auto-complete suggestion from history.
    pub ghost_suggestion: Option<String>,
    /// Application config (for persistence).
    pub app_config: AppConfig,
    /// Timestamp of the last sent command (for response timing).
    pub last_command_sent: Option<Instant>,
    /// Duration of the last command round-trip.
    pub last_response_time: Option<Duration>,
    /// Quick-send commands (most frequently used from history).
    pub quicksend: Vec<String>,
    /// Whether to display sent messages in the terminal view.
    pub show_sent: bool,
    /// Input text for the filter popup.
    pub filter_input: String,
    /// Whether filter input mode is exclude (true) vs include (false).
    pub filter_mode_is_exclude: bool,
    /// Selected filter index for deletion.
    pub filter_select_index: usize,
    /// Whether hex input mode is active.
    pub hex_input_mode: bool,
}

impl App {
    pub fn new(serial_config: SerialConfig, line_ending: String, app_config: AppConfig) -> Self {
        let history = CommandHistory::new(500);
        let quicksend = history.top_commands(8);
        Self {
            mode: Mode::Input,
            should_quit: false,
            buffer: ScrollbackBuffer::new(10000),
            input_text: String::new(),
            input_cursor: 0,
            line_ending,
            serial_config,
            connection_state: ConnectionState::Disconnected,
            connection: None,
            serial_rx: None,
            serial_tx: None,
            scroll_offset: 0,
            follow_output: true,
            rx_bytes: 0,
            tx_bytes: 0,
            available_ports: Vec::new(),
            port_select_index: 0,
            show_timestamps: true,
            hex_mode: false,
            show_line_endings: false,
            history,
            search: Search::new(),
            logger: SessionLogger::new(),
            auto_reconnect: true,
            reconnect_port: None,
            last_reconnect_attempt: None,
            reconnect_delay: Duration::from_secs(1),
            status_message: None,
            filter: LineFilter::new(),
            macros: MacroManager::new(),
            macro_select_index: 0,
            settings_field: 0,
            layout: LayoutRegions::default(),
            selection: TextSelection::new(),
            ghost_suggestion: None,
            app_config,
            last_command_sent: None,
            last_response_time: None,
            quicksend,
            show_sent: true,
            filter_input: String::new(),
            filter_mode_is_exclude: false,
            filter_select_index: 0,
            hex_input_mode: false,
        }
    }

    /// Connect to the specified serial port.
    pub fn connect(&mut self, port_name: &str) {
        // Disconnect first if already connected
        self.disconnect_internal(false);

        let (tx, rx) = mpsc::channel();

        match SerialConnection::open(port_name, &self.serial_config, tx.clone()) {
            Ok(conn) => {
                self.connection_state = ConnectionState::Connected(port_name.to_string());
                self.connection = Some(conn);
                self.serial_rx = Some(rx);
                self.serial_tx = Some(tx);
                self.reconnect_port = Some(port_name.to_string());
                self.set_status(format!("Connected to {}", port_name));
                // Save last port for auto-connect on next launch
                self.app_config.connection.last_port = Some(port_name.to_string());
                self.app_config.save();
            }
            Err(e) => {
                self.connection_state = ConnectionState::Error(e.to_string());
            }
        }
    }

    /// Internal disconnect, optionally preserving reconnect state.
    fn disconnect_internal(&mut self, keep_reconnect: bool) {
        if let Some(conn) = self.connection.take() {
            self.rx_bytes += conn.rx_bytes;
            self.tx_bytes += conn.tx_bytes();
            conn.close();
        }
        self.serial_rx = None;
        self.serial_tx = None;
        if !keep_reconnect {
            self.connection_state = ConnectionState::Disconnected;
            self.reconnect_port = None;
        }
    }

    /// Disconnect from the current serial port.
    pub fn disconnect(&mut self) {
        self.disconnect_internal(false);
        self.set_status("Disconnected".to_string());
    }

    /// Toggle connection: disconnect if connected, open port selector if not.
    pub fn toggle_connection(&mut self) {
        match &self.connection_state {
            ConnectionState::Connected(_) => {
                self.disconnect();
            }
            ConnectionState::Reconnecting(_) => {
                // Cancel reconnection
                self.reconnect_port = None;
                self.connection_state = ConnectionState::Disconnected;
                self.set_status("Reconnection cancelled".to_string());
            }
            _ => {
                self.open_port_selector();
            }
        }
    }

    /// Send a command string over the serial port.
    pub fn send_command(&mut self) {
        if self.input_text.is_empty() {
            return;
        }

        let text = self.input_text.clone();

        // Hex input mode: parse space-separated hex bytes, send raw binary
        if self.hex_input_mode {
            match Self::parse_hex_bytes(&text) {
                Ok(bytes) => {
                    if self.show_sent {
                        self.buffer.push_sent_line(format!("HEX: {}", text));
                    }
                    if let Some(conn) = &self.connection {
                        match conn.write(&bytes) {
                            Ok(_) => {
                                self.tx_bytes = conn.tx_bytes();
                                self.last_command_sent = Some(Instant::now());
                            }
                            Err(_) => {
                                self.connection_state =
                                    ConnectionState::Error("Write failed".to_string());
                            }
                        }
                    }
                }
                Err(e) => {
                    self.set_status(format!("Hex parse error: {}", e));
                    return; // Don't clear input on error
                }
            }
        } else {
            let line_ending = self.line_ending.clone();
            let data = format!("{}{}", text, line_ending);

            // Echo command to scrollback buffer
            if self.show_sent {
                self.buffer.push_sent_line(text.clone());
            }

            if let Some(conn) = &self.connection {
                match conn.write(data.as_bytes()) {
                    Ok(_) => {
                        self.tx_bytes = conn.tx_bytes();
                        self.last_command_sent = Some(Instant::now());
                    }
                    Err(_) => {
                        self.connection_state =
                            ConnectionState::Error("Write failed".to_string());
                    }
                }
            }
        }

        // Add to history
        self.history.push(text);
        self.history.reset_navigation();

        self.input_text.clear();
        self.input_cursor = 0;
        self.ghost_suggestion = None;
        self.update_quicksend();
    }

    /// Update the quick-send command list from history frequency.
    pub fn update_quicksend(&mut self) {
        self.quicksend = self.history.top_commands(8);
    }

    /// Send a quick-send command by index (0-based).
    pub fn send_quicksend(&mut self, index: usize) {
        if let Some(cmd) = self.quicksend.get(index).cloned() {
            self.input_text = cmd;
            self.input_cursor = self.input_text.len();
            self.send_command();
        }
    }

    /// Poll for serial events. Returns true if anything happened (needs re-render).
    pub fn poll_serial(&mut self) -> bool {
        let mut changed = false;

        // Clear expired status messages
        if let Some((_, time)) = &self.status_message {
            if time.elapsed() > Duration::from_secs(3) {
                self.status_message = None;
                changed = true;
            }
        }

        let rx = match &self.serial_rx {
            Some(rx) => rx,
            None => {
                // Try auto-reconnect if needed
                self.try_reconnect();
                return changed;
            }
        };

        // Drain all available events
        loop {
            match rx.try_recv() {
                Ok(SerialEvent::Data(data, received_at)) => {
                    self.rx_bytes += data.len() as u64;
                    self.logger.log_bytes(&data);
                    self.buffer.push_bytes(&data);
                    if self.follow_output {
                        self.scroll_offset = 0;
                    }
                    // Measure response time using reader-thread timestamp
                    if let Some(sent_at) = self.last_command_sent.take() {
                        self.last_response_time = Some(received_at.duration_since(sent_at));
                    }
                    changed = true;
                }
                Ok(SerialEvent::Disconnected) => {
                    let port = match &self.connection_state {
                        ConnectionState::Connected(p) => p.clone(),
                        _ => String::new(),
                    };
                    self.disconnect_internal(true);
                    if self.auto_reconnect && !port.is_empty() {
                        self.reconnect_port = Some(port.clone());
                        self.connection_state = ConnectionState::Reconnecting(port);
                        self.set_status("Port disconnected, reconnecting...".to_string());
                    } else {
                        self.connection_state =
                            ConnectionState::Error("Port disconnected".to_string());
                    }
                    break;
                }
                Ok(SerialEvent::Error(e)) => {
                    let port = match &self.connection_state {
                        ConnectionState::Connected(p) => p.clone(),
                        _ => String::new(),
                    };
                    self.disconnect_internal(true);
                    if self.auto_reconnect && !port.is_empty() {
                        self.reconnect_port = Some(port.clone());
                        self.connection_state = ConnectionState::Reconnecting(port);
                    } else {
                        self.connection_state = ConnectionState::Error(e);
                    }
                    break;
                }
                Err(mpsc::TryRecvError::Empty) => break,
                Err(mpsc::TryRecvError::Disconnected) => {
                    let port = match &self.connection_state {
                        ConnectionState::Connected(p) => p.clone(),
                        _ => String::new(),
                    };
                    self.disconnect_internal(true);
                    if self.auto_reconnect && !port.is_empty() {
                        self.reconnect_port = Some(port.clone());
                        self.connection_state = ConnectionState::Reconnecting(port);
                    } else {
                        self.connection_state =
                            ConnectionState::Error("Reader thread died".to_string());
                    }
                    break;
                }
            }
        }

        changed
    }

    /// Attempt auto-reconnect if conditions are met.
    fn try_reconnect(&mut self) {
        let port = match &self.reconnect_port {
            Some(p) => p.clone(),
            None => return,
        };

        if !matches!(self.connection_state, ConnectionState::Reconnecting(_)) {
            return;
        }

        // Check if enough time has passed since last attempt
        if let Some(last) = &self.last_reconnect_attempt {
            if last.elapsed() < self.reconnect_delay {
                return;
            }
        }

        self.last_reconnect_attempt = Some(Instant::now());

        let (tx, rx) = mpsc::channel();
        match SerialConnection::open(&port, &self.serial_config, tx.clone()) {
            Ok(conn) => {
                self.connection_state = ConnectionState::Connected(port.clone());
                self.connection = Some(conn);
                self.serial_rx = Some(rx);
                self.serial_tx = Some(tx);
                self.set_status(format!("Reconnected to {}", port));
            }
            Err(_) => {
                // Will retry on next tick
            }
        }
    }

    /// Auto-detect the baud rate for a given port.
    pub fn auto_detect_baud(&mut self, port_name: &str) {
        self.set_status("Auto-detecting baud rate...".to_string());
        match crate::serial::auto_detect::auto_detect_baud(port_name) {
            Some(rate) => {
                self.serial_config.baud_rate = rate;
                self.app_config.defaults.baud_rate = rate;
                self.app_config.save();
                self.set_status(format!("Detected baud rate: {}", rate));
            }
            None => {
                self.set_status("Could not detect baud rate — no readable data".to_string());
            }
        }
    }

    /// Open the port selector popup.
    pub fn open_port_selector(&mut self) {
        self.available_ports = detector::available_ports();
        self.port_select_index = 0;
        self.mode = Mode::PortSelect;
    }

    /// Connect to the currently selected port in the selector.
    pub fn connect_selected_port(&mut self) {
        if let Some(port) = self.available_ports.get(self.port_select_index) {
            let port_name = port.name.clone();
            self.mode = Mode::Normal;
            self.connect(&port_name);
        }
    }

    // ── Scrolling ───────────────────────────────────────

    pub fn scroll_up(&mut self, lines: usize) {
        let view_height = self.layout.terminal_view.3 as usize; // height from layout
        let max_scroll = self.buffer.display_len().saturating_sub(view_height);
        self.scroll_offset = (self.scroll_offset + lines).min(max_scroll);
        if max_scroll > 0 {
            self.follow_output = false;
        }
    }

    pub fn scroll_down(&mut self, lines: usize) {
        self.scroll_offset = self.scroll_offset.saturating_sub(lines);
        if self.scroll_offset == 0 {
            self.follow_output = true;
        }
    }

    pub fn scroll_to_bottom(&mut self) {
        self.scroll_offset = 0;
        self.follow_output = true;
    }

    pub fn scroll_to_top(&mut self) {
        let max_scroll = self.buffer.display_len().saturating_sub(1);
        self.scroll_offset = max_scroll;
        self.follow_output = false;
    }

    /// Scroll to show a specific line index.
    pub fn scroll_to_line(&mut self, line_index: usize) {
        let total = self.buffer.display_len();
        if total == 0 {
            return;
        }
        // scroll_offset is distance from bottom
        self.scroll_offset = total.saturating_sub(line_index + 1);
        self.follow_output = false;
    }

    // ── Input editing ───────────────────────────────────

    pub fn input_char(&mut self, c: char) {
        self.input_text.insert(self.input_cursor, c);
        self.input_cursor += 1;
        self.update_ghost();
    }

    pub fn input_backspace(&mut self) {
        if self.input_cursor > 0 {
            self.input_cursor -= 1;
            self.input_text.remove(self.input_cursor);
            self.update_ghost();
        }
    }

    pub fn input_delete(&mut self) {
        if self.input_cursor < self.input_text.len() {
            self.input_text.remove(self.input_cursor);
            self.update_ghost();
        }
    }

    pub fn input_cursor_left(&mut self) {
        self.input_cursor = self.input_cursor.saturating_sub(1);
    }

    pub fn input_cursor_right(&mut self) {
        self.input_cursor = (self.input_cursor + 1).min(self.input_text.len());
    }

    pub fn input_cursor_home(&mut self) {
        self.input_cursor = 0;
    }

    pub fn input_cursor_end(&mut self) {
        self.input_cursor = self.input_text.len();
    }

    /// Update the ghost auto-complete suggestion from history.
    pub fn update_ghost(&mut self) {
        // Only suggest when cursor is at the end of input
        if self.input_cursor != self.input_text.len() || self.input_text.is_empty() {
            self.ghost_suggestion = None;
            return;
        }
        self.ghost_suggestion = self.history.suggest(&self.input_text).map(|s| s.to_string());
    }

    /// Accept the current ghost suggestion, filling in the input text.
    pub fn accept_suggestion(&mut self) {
        if let Some(suggestion) = self.ghost_suggestion.take() {
            self.input_text = suggestion;
            self.input_cursor = self.input_text.len();
        }
    }

    // ── History navigation ──────────────────────────────

    pub fn history_previous(&mut self) {
        if let Some(text) = self.history.previous(&self.input_text) {
            self.input_text = text.to_string();
            self.input_cursor = self.input_text.len();
        }
    }

    pub fn history_next(&mut self) {
        if let Some(text) = self.history.next() {
            self.input_text = text.to_string();
            self.input_cursor = self.input_text.len();
        }
    }

    // ── Search ──────────────────────────────────────────

    pub fn start_search(&mut self) {
        self.search.activate();
        self.mode = Mode::Search;
    }

    pub fn search_char(&mut self, c: char) {
        self.search.push_char(c);
        self.search.execute(&self.buffer);
        // Jump to current match
        if let Some(line) = self.search.current_line() {
            self.scroll_to_line(line);
        }
    }

    pub fn search_backspace(&mut self) {
        self.search.pop_char();
        self.search.execute(&self.buffer);
    }

    pub fn search_next(&mut self) {
        if let Some(line) = self.search.next_match() {
            self.scroll_to_line(line);
        }
    }

    pub fn search_prev(&mut self) {
        if let Some(line) = self.search.prev_match() {
            self.scroll_to_line(line);
        }
    }

    pub fn end_search(&mut self) {
        self.search.deactivate();
        self.mode = Mode::Normal;
    }

    // ── Toggles ─────────────────────────────────────────

    pub fn toggle_hex_mode(&mut self) {
        self.hex_mode = !self.hex_mode;
    }

    pub fn toggle_line_endings(&mut self) {
        self.show_line_endings = !self.show_line_endings;
    }

    pub fn toggle_logging(&mut self) {
        match self.logger.toggle() {
            Ok(Some(path)) => {
                self.set_status(format!("Logging to {}", path.display()));
            }
            Ok(None) => {
                self.set_status("Logging stopped".to_string());
            }
            Err(e) => {
                self.set_status(format!("Log error: {}", e));
            }
        }
    }

    /// Clear the scrollback buffer.
    pub fn clear_buffer(&mut self) {
        self.buffer.clear();
        self.scroll_offset = 0;
        self.follow_output = true;
        self.search.deactivate();
        self.set_status("Buffer cleared".to_string());
    }

    // ── Status ──────────────────────────────────────────

    fn set_status(&mut self, msg: String) {
        self.status_message = Some((msg, Instant::now()));
    }

    pub fn set_status_pub(&mut self, msg: String) {
        self.set_status(msg);
    }

    pub fn total_rx_bytes(&self) -> u64 {
        self.rx_bytes
    }

    pub fn total_tx_bytes(&self) -> u64 {
        self.tx_bytes
    }

    pub fn is_connected(&self) -> bool {
        matches!(self.connection_state, ConnectionState::Connected(_))
    }

    pub fn is_reconnecting(&self) -> bool {
        matches!(self.connection_state, ConnectionState::Reconnecting(_))
    }

    // ── Filter ──────────────────────────────────────────

    pub fn add_filter_include(&mut self, pattern: &str) {
        match self.filter.add_include(pattern) {
            Ok(_) => self.set_status(format!("Filter +{}", pattern)),
            Err(e) => self.set_status(e),
        }
    }

    pub fn add_filter_exclude(&mut self, pattern: &str) {
        match self.filter.add_exclude(pattern) {
            Ok(_) => self.set_status(format!("Filter -{}", pattern)),
            Err(e) => self.set_status(e),
        }
    }

    pub fn clear_filters(&mut self) {
        self.filter.clear();
        self.set_status("Filters cleared".to_string());
    }

    /// Open the filter popup.
    pub fn open_filter_popup(&mut self) {
        self.filter_input.clear();
        self.filter_select_index = 0;
        self.mode = Mode::Filter;
    }

    /// Submit the current filter input.
    pub fn submit_filter(&mut self) {
        if self.filter_input.is_empty() {
            return;
        }
        let pattern = self.filter_input.clone();
        if self.filter_mode_is_exclude {
            self.add_filter_exclude(&pattern);
        } else {
            self.add_filter_include(&pattern);
        }
        self.filter_input.clear();
    }

    /// Remove a filter by index.
    pub fn remove_filter(&mut self, index: usize) {
        self.filter.remove(index);
        if self.filter.count() == 0 {
            self.set_status("All filters removed".to_string());
        }
        // Keep select index in bounds
        if self.filter_select_index >= self.filter.count() && self.filter_select_index > 0 {
            self.filter_select_index -= 1;
        }
    }

    // ── Macros ──────────────────────────────────────────

    /// Open the macro selector popup.
    pub fn open_macro_selector(&mut self) {
        self.macro_select_index = 0;
        self.mode = Mode::MacroSelect;
    }


    /// Send raw text over serial (used by macros).
    pub fn send_text(&mut self, text: &str) {
        let line_ending = self.line_ending.clone();
        let data = format!("{}{}", text, line_ending);

        if let Some(conn) = &self.connection {
            match conn.write(data.as_bytes()) {
                Ok(_) => {
                    self.tx_bytes = conn.tx_bytes();
                }
                Err(_) => {
                    self.connection_state =
                        ConnectionState::Error("Write failed".to_string());
                }
            }
        }
    }

    /// Execute a macro by name.
    pub fn execute_macro(&mut self, name: &str) {
        if let Some(m) = self.macros.get(name) {
            let commands: Vec<String> = m.commands.iter().map(|c| c.text.clone()).collect();
            self.set_status(format!("Running macro: {}", name));
            for cmd in commands {
                self.send_text(&cmd);
            }
        } else {
            self.set_status(format!("Macro not found: {}", name));
        }
    }

    /// Execute the currently selected macro.
    pub fn execute_selected_macro(&mut self) {
        let macros = self.macros.list();
        if let Some(m) = macros.get(self.macro_select_index) {
            let name = m.name.clone();
            self.execute_macro(&name);
        }
    }

    // ── Settings ────────────────────────────────────────

    pub fn open_settings(&mut self) {
        self.settings_field = 0;
        self.mode = Mode::Settings;
    }

    /// Cycle the selected settings field value forward.
    pub fn settings_next_value(&mut self) {
        use serialport::*;
        match self.settings_field {
            0 => {
                // Baud rate: cycle through common rates
                let rates = crate::ui::settings::BAUD_RATES;
                let current_idx = rates.iter().position(|&r| r == self.serial_config.baud_rate);
                let next_idx = match current_idx {
                    Some(i) => (i + 1) % rates.len(),
                    None => 0,
                };
                self.serial_config.baud_rate = rates[next_idx];
            }
            1 => {
                self.serial_config.data_bits = match self.serial_config.data_bits {
                    DataBits::Five => DataBits::Six,
                    DataBits::Six => DataBits::Seven,
                    DataBits::Seven => DataBits::Eight,
                    DataBits::Eight => DataBits::Five,
                };
            }
            2 => {
                self.serial_config.parity = match self.serial_config.parity {
                    Parity::None => Parity::Odd,
                    Parity::Odd => Parity::Even,
                    Parity::Even => Parity::None,
                };
            }
            3 => {
                self.serial_config.stop_bits = match self.serial_config.stop_bits {
                    StopBits::One => StopBits::Two,
                    StopBits::Two => StopBits::One,
                };
            }
            4 => {
                self.serial_config.flow_control = match self.serial_config.flow_control {
                    FlowControl::None => FlowControl::Software,
                    FlowControl::Software => FlowControl::Hardware,
                    FlowControl::Hardware => FlowControl::None,
                };
            }
            5 => {
                // Line ending cycle: CRLF -> LF -> CR
                self.line_ending = match self.line_ending.as_str() {
                    "\r\n" => "\n".to_string(),
                    "\n" => "\r".to_string(),
                    "\r" => "\r\n".to_string(),
                    _ => "\r\n".to_string(),
                };
            }
            _ => {}
        }
    }

    /// Cycle the selected settings field value backward.
    pub fn settings_prev_value(&mut self) {
        use serialport::*;
        match self.settings_field {
            0 => {
                let rates = crate::ui::settings::BAUD_RATES;
                let current_idx = rates.iter().position(|&r| r == self.serial_config.baud_rate);
                let next_idx = match current_idx {
                    Some(0) | None => rates.len() - 1,
                    Some(i) => i - 1,
                };
                self.serial_config.baud_rate = rates[next_idx];
            }
            1 => {
                self.serial_config.data_bits = match self.serial_config.data_bits {
                    DataBits::Five => DataBits::Eight,
                    DataBits::Six => DataBits::Five,
                    DataBits::Seven => DataBits::Six,
                    DataBits::Eight => DataBits::Seven,
                };
            }
            2 => {
                self.serial_config.parity = match self.serial_config.parity {
                    Parity::None => Parity::Even,
                    Parity::Odd => Parity::None,
                    Parity::Even => Parity::Odd,
                };
            }
            3 => {
                self.serial_config.stop_bits = match self.serial_config.stop_bits {
                    StopBits::One => StopBits::Two,
                    StopBits::Two => StopBits::One,
                };
            }
            4 => {
                self.serial_config.flow_control = match self.serial_config.flow_control {
                    FlowControl::None => FlowControl::Hardware,
                    FlowControl::Software => FlowControl::None,
                    FlowControl::Hardware => FlowControl::Software,
                };
            }
            5 => {
                // Line ending cycle backward: CRLF -> CR -> LF
                self.line_ending = match self.line_ending.as_str() {
                    "\r\n" => "\r".to_string(),
                    "\n" => "\r\n".to_string(),
                    "\r" => "\n".to_string(),
                    _ => "\r\n".to_string(),
                };
            }
            _ => {}
        }
    }

    /// Apply settings changes: reconnect if currently connected.
    pub fn apply_settings(&mut self) {
        self.mode = Mode::Normal;
        let summary = self.serial_config.summary();
        self.set_status(format!("Settings: {}", summary));

        // Persist all serial settings to config file
        self.sync_config_to_disk();

        // If connected, reconnect with new settings
        if let ConnectionState::Connected(port) = &self.connection_state {
            let port = port.clone();
            self.disconnect();
            self.connect(&port);
        }
    }

    /// Sync the current serial config and line ending to app_config and save to disk.
    fn sync_config_to_disk(&mut self) {
        self.app_config.defaults.baud_rate = self.serial_config.baud_rate;
        self.app_config.defaults.data_bits = match self.serial_config.data_bits {
            serialport::DataBits::Five => 5,
            serialport::DataBits::Six => 6,
            serialport::DataBits::Seven => 7,
            serialport::DataBits::Eight => 8,
        };
        self.app_config.defaults.parity = match self.serial_config.parity {
            serialport::Parity::None => "none".to_string(),
            serialport::Parity::Odd => "odd".to_string(),
            serialport::Parity::Even => "even".to_string(),
        };
        self.app_config.defaults.stop_bits = match self.serial_config.stop_bits {
            serialport::StopBits::One => 1,
            serialport::StopBits::Two => 2,
        };
        self.app_config.defaults.flow_control = match self.serial_config.flow_control {
            serialport::FlowControl::None => "none".to_string(),
            serialport::FlowControl::Software => "software".to_string(),
            serialport::FlowControl::Hardware => "hardware".to_string(),
        };
        self.app_config.defaults.line_ending = match self.line_ending.as_str() {
            "\n" => "lf".to_string(),
            "\r" => "cr".to_string(),
            _ => "crlf".to_string(),
        };
        self.app_config.save();
    }

    // ── Word-level cursor ───────────────────────────────

    /// Move cursor one word to the left.
    pub fn input_cursor_word_left(&mut self) {
        let chars: Vec<char> = self.input_text.chars().collect();
        if self.input_cursor == 0 {
            return;
        }
        let mut pos = self.input_cursor;
        // Skip non-alphanumeric
        while pos > 0 && !chars[pos - 1].is_alphanumeric() {
            pos -= 1;
        }
        // Skip alphanumeric
        while pos > 0 && chars[pos - 1].is_alphanumeric() {
            pos -= 1;
        }
        self.input_cursor = pos;
    }

    /// Move cursor one word to the right.
    pub fn input_cursor_word_right(&mut self) {
        let chars: Vec<char> = self.input_text.chars().collect();
        let len = chars.len();
        if self.input_cursor >= len {
            return;
        }
        let mut pos = self.input_cursor;
        // Skip alphanumeric
        while pos < len && chars[pos].is_alphanumeric() {
            pos += 1;
        }
        // Skip non-alphanumeric
        while pos < len && !chars[pos].is_alphanumeric() {
            pos += 1;
        }
        self.input_cursor = pos;
    }

    /// Delete one word backward (Ctrl+W).
    pub fn input_delete_word_back(&mut self) {
        if self.input_cursor == 0 {
            return;
        }
        let old_cursor = self.input_cursor;
        self.input_cursor_word_left();
        let new_cursor = self.input_cursor;
        // Remove characters between new_cursor and old_cursor
        let chars: Vec<char> = self.input_text.chars().collect();
        self.input_text = chars[..new_cursor]
            .iter()
            .chain(chars[old_cursor..].iter())
            .collect();
        self.update_ghost();
    }

    /// Kill the entire input line (Ctrl+U).
    pub fn input_kill_line(&mut self) {
        self.input_text.clear();
        self.input_cursor = 0;
        self.ghost_suggestion = None;
    }

    // ── Hex input ───────────────────────────────────────

    /// Toggle hex input mode.
    pub fn toggle_hex_input(&mut self) {
        self.hex_input_mode = !self.hex_input_mode;
        if self.hex_input_mode {
            self.set_status("Hex input mode ON — type space-separated hex bytes".to_string());
        } else {
            self.set_status("Hex input mode OFF".to_string());
        }
    }

    /// Parse a hex string into raw bytes.
    /// Accepts space-separated hex pairs: "01 FF A0" or "01FFA0"
    fn parse_hex_bytes(input: &str) -> Result<Vec<u8>, String> {
        let cleaned: String = input.chars().filter(|c| !c.is_whitespace()).collect();
        if cleaned.is_empty() {
            return Err("Empty hex input".to_string());
        }
        if cleaned.len() % 2 != 0 {
            return Err("Odd number of hex digits".to_string());
        }
        let mut bytes = Vec::with_capacity(cleaned.len() / 2);
        for i in (0..cleaned.len()).step_by(2) {
            let byte_str = &cleaned[i..i + 2];
            match u8::from_str_radix(byte_str, 16) {
                Ok(b) => bytes.push(b),
                Err(_) => return Err(format!("Invalid hex byte: {}", byte_str)),
            }
        }
        Ok(bytes)
    }
}