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
use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};

use crate::app::{App, Mode};

/// Regions of the UI for click detection.
/// These are set during rendering and read during mouse handling.
pub struct LayoutRegions {
    pub status_bar: (u16, u16, u16, u16),     // x, y, w, h
    pub terminal_view: (u16, u16, u16, u16),
    pub input_bar: (u16, u16, u16, u16),
}

impl Default for LayoutRegions {
    fn default() -> Self {
        Self {
            status_bar: (0, 0, 0, 0),
            terminal_view: (0, 0, 0, 0),
            input_bar: (0, 0, 0, 0),
        }
    }
}

/// Text selection state for click-drag-copy.
pub struct TextSelection {
    /// Whether a drag selection is in progress.
    pub is_selecting: bool,
    /// Start position (column, row in terminal coords).
    pub start: (u16, u16),
    /// End position (column, row in terminal coords).
    pub end: (u16, u16),
}

impl TextSelection {
    pub fn new() -> Self {
        Self {
            is_selecting: false,
            start: (0, 0),
            end: (0, 0),
        }
    }

    pub fn clear(&mut self) {
        self.is_selecting = false;
    }

    /// Get the selection range as (start_row, start_col, end_row, end_col), normalized.
    pub fn range(&self) -> (u16, u16, u16, u16) {
        let (sr, sc, er, ec) = if self.start.1 < self.end.1
            || (self.start.1 == self.end.1 && self.start.0 <= self.end.0)
        {
            (self.start.1, self.start.0, self.end.1, self.end.0)
        } else {
            (self.end.1, self.end.0, self.start.1, self.start.0)
        };
        (sr, sc, er, ec)
    }

    /// Check if a cell (col, row) is within the selection.
    pub fn contains(&self, col: u16, row: u16) -> bool {
        if !self.is_selecting {
            return false;
        }
        let (sr, sc, er, ec) = self.range();

        if row < sr || row > er {
            return false;
        }
        if sr == er {
            // Single line selection
            col >= sc && col <= ec
        } else if row == sr {
            col >= sc
        } else if row == er {
            col <= ec
        } else {
            true // Middle lines fully selected
        }
    }
}

/// Handle a mouse event.
pub fn handle_mouse_event(app: &mut App, event: MouseEvent) {
    match event.kind {
        // ── Scroll wheel ────────────────────────────────
        MouseEventKind::ScrollUp => {
            match app.mode {
                Mode::PortSelect => {
                    if app.port_select_index > 0 {
                        app.port_select_index -= 1;
                    }
                }
                Mode::Settings => {
                    if app.settings_field > 0 {
                        app.settings_field -= 1;
                    }
                }
                _ => {
                    app.scroll_up(3);
                }
            }
        }
        MouseEventKind::ScrollDown => {
            match app.mode {
                Mode::PortSelect => {
                    if app.port_select_index + 1 < app.available_ports.len() {
                        app.port_select_index += 1;
                    }
                }
                Mode::Settings => {
                    if app.settings_field < 4 {
                        app.settings_field += 1;
                    }
                }
                _ => {
                    app.scroll_down(3);
                }
            }
        }

        // ── Click ───────────────────────────────────────
        MouseEventKind::Down(MouseButton::Left) => {
            let col = event.column;
            let row = event.row;

            match app.mode {
                Mode::Normal | Mode::Input | Mode::Search => {
                    handle_click(app, col, row);
                }
                Mode::PortSelect => {
                    handle_port_click(app, col, row);
                }
                Mode::Settings => {
                    handle_settings_click(app, row);
                }
                _ => {}
            }
        }

        // ── Drag (text selection) ───────────────────────
        MouseEventKind::Drag(MouseButton::Left) => {
            app.selection.end = (event.column, event.row);
            if !app.selection.is_selecting {
                app.selection.is_selecting = true;
                app.selection.start = (event.column, event.row);
            }
        }

        // ── Release (copy selection) ────────────────────
        MouseEventKind::Up(MouseButton::Left) => {
            if app.selection.is_selecting {
                copy_selection(app);
                // Keep selection visible briefly
            }
        }

        _ => {}
    }
}

fn handle_click(app: &mut App, col: u16, row: u16) {
    let regions = &app.layout;

    // Clear any existing selection
    app.selection.clear();

    // Click on status bar
    let (sx, sy, sw, _sh) = regions.status_bar;
    if row == sy && col >= sx && col < sx + sw {
        // Left half: toggle connection, right half: open settings
        if col < sx + sw / 2 {
            app.toggle_connection();
        } else {
            app.open_settings();
        }
        return;
    }

    // Click on input bar
    let (ix, iy, _iw, _ih) = regions.input_bar;
    if row == iy && col >= ix {
        if app.mode != Mode::Input {
            app.mode = Mode::Input;
        }
        // Position cursor roughly
        let prompt_len = 4; // "> > " prefix
        let click_pos = (col as usize).saturating_sub(ix as usize + prompt_len);
        app.input_cursor = click_pos.min(app.input_text.len());
        return;
    }

    // Click on terminal view — start selection or just switch to normal mode
    let (_tx, ty, _tw, th) = regions.terminal_view;
    if row >= ty && row < ty + th {
        if app.mode == Mode::Input {
            app.mode = Mode::Normal;
        }
        // Set selection start for potential drag
        app.selection.start = (col, row);
        app.selection.end = (col, row);
    }
}

fn handle_port_click(app: &mut App, _col: u16, row: u16) {
    // The port selector is a centered popup. We need to figure out which
    // port was clicked based on the row. The popup has a 1-row title + 1-row padding,
    // so items start at roughly row offset 3 from the popup top.
    // For simplicity, we'll calculate based on terminal height.
    let total_height = app.layout.terminal_view.3 + 4; // rough terminal height
    let popup_height = (app.available_ports.len() as u16 + 6).min(total_height - 4);
    let popup_y = (total_height.saturating_sub(popup_height)) / 2;
    let item_start = popup_y + 3; // title + border + padding

    if row >= item_start {
        let clicked_index = (row - item_start) as usize;
        if clicked_index < app.available_ports.len() {
            app.port_select_index = clicked_index;
        }
    }
}

fn handle_settings_click(app: &mut App, row: u16) {
    // Settings popup has 5 fields with spacing. Fields are at rows 3, 5, 7, 9, 11
    // relative to the popup top.
    let total_height = app.layout.terminal_view.3 + 4;
    let popup_height = 16.min(total_height - 4);
    let popup_y = (total_height.saturating_sub(popup_height)) / 2;
    let field_start = popup_y + 2; // border + padding

    if row >= field_start {
        let relative = (row - field_start) as usize;
        // Fields are at relative positions 0, 2, 4, 6, 8 (with blank lines between)
        if relative % 2 == 0 {
            let field_index = relative / 2;
            if field_index < 5 {
                app.settings_field = field_index;
            }
        }
    }
}

/// Copy the selected text to clipboard, formatted to match the rendered view.
fn copy_selection(app: &mut App) {
    if !app.selection.is_selecting {
        return;
    }

    let (start_row, _start_col, end_row, _end_col) = app.selection.range();
    let regions = &app.layout;
    let (_, ty, _, th) = regions.terminal_view;

    if app.hex_mode {
        copy_hex_selection(app, start_row, end_row, ty, th);
        return;
    }

    let mut selected_text = String::new();

    // Build the same filtered visible indices as the renderer
    let filter_active = app.filter.is_active;
    let mut visible_indices: Vec<usize> = Vec::new();
    for i in 0..app.buffer.len() {
        if filter_active {
            if let Some(entry) = app.buffer.get(i) {
                if !app.filter.should_display(&entry.text) {
                    continue;
                }
            }
        }
        visible_indices.push(i);
    }
    if app.buffer.partial_line().is_some() {
        visible_indices.push(app.buffer.len()); // sentinel for partial line
    }

    let total_visible = visible_indices.len();
    let end = total_visible.saturating_sub(app.scroll_offset);
    let start = end.saturating_sub(th as usize);

    for screen_row in start_row..=end_row {
        if screen_row < ty || screen_row >= ty + th {
            continue;
        }
        let line_offset = (screen_row - ty) as usize;
        let vi = start + line_offset;

        if vi >= end {
            continue;
        }

        let i = visible_indices[vi];

        let formatted = if i < app.buffer.len() {
            if let Some(entry) = app.buffer.get(i) {
                format_entry_for_copy(
                    &entry.text,
                    entry.timestamp,
                    &entry.line_ending,
                    entry.is_sent,
                    app.show_timestamps,
                    app.show_line_endings,
                )
            } else {
                continue;
            }
        } else {
            // Partial line
            if let Some(partial) = app.buffer.partial_line() {
                let mut line = String::new();
                if app.show_timestamps {
                    line.push_str(&format!(
                        "[{}] ",
                        chrono::Local::now().format("%H:%M:%S%.3f")
                    ));
                }
                line.push_str(partial);
                line
            } else {
                continue;
            }
        };

        if !selected_text.is_empty() {
            selected_text.push('\n');
        }
        selected_text.push_str(&formatted);
    }

    if !selected_text.is_empty() {
        match cli_clipboard::set_contents(selected_text) {
            Ok(_) => {
                let lines = end_row - start_row + 1;
                app.set_status_pub(format!("Copied {} line(s)", lines));
            }
            Err(_) => {
                app.set_status_pub("Clipboard unavailable".to_string());
            }
        }
    }
}

/// Format a single buffer entry for clipboard copy, matching the rendered view.
fn format_entry_for_copy(
    text: &str,
    timestamp: chrono::DateTime<chrono::Local>,
    line_ending: &crate::buffer::LineEnding,
    is_sent: bool,
    show_timestamps: bool,
    show_line_endings: bool,
) -> String {
    let mut line = String::new();

    if show_timestamps {
        line.push_str(&format!(
            "[{}] ",
            timestamp.format("%H:%M:%S%.3f")
        ));
    }

    if is_sent {
        line.push_str("");
    }

    line.push_str(text);

    if show_line_endings && *line_ending != crate::buffer::LineEnding::None {
        line.push(' ');
        line.push_str(line_ending.display());
    }

    line
}

/// Copy hex view selection to clipboard.
fn copy_hex_selection(app: &mut App, start_row: u16, end_row: u16, ty: u16, th: u16) {
    let mut all_bytes = Vec::new();
    for i in 0..app.buffer.len() {
        if let Some(entry) = app.buffer.get(i) {
            all_bytes.extend_from_slice(&entry.raw_bytes);
        }
    }

    if all_bytes.is_empty() {
        return;
    }

    let hex_lines = crate::hex::format_hex_lines(&all_bytes, 0);
    let total = hex_lines.len();
    let end = total.saturating_sub(app.scroll_offset);
    let start = end.saturating_sub(th as usize);

    let mut selected_text = String::new();

    for screen_row in start_row..=end_row {
        if screen_row < ty || screen_row >= ty + th {
            continue;
        }
        let line_offset = (screen_row - ty) as usize;
        let hex_idx = start + line_offset;

        if hex_idx >= end {
            continue;
        }

        if let Some(hex_line) = hex_lines.get(hex_idx) {
            if !selected_text.is_empty() {
                selected_text.push('\n');
            }
            selected_text.push_str(&format!(
                "{:08x}  {:<23} {:<23} |{}|",
                hex_line.offset, hex_line.hex_left, hex_line.hex_right, hex_line.ascii
            ));
        }
    }

    if !selected_text.is_empty() {
        match cli_clipboard::set_contents(selected_text) {
            Ok(_) => {
                let lines = end_row - start_row + 1;
                app.set_status_pub(format!("Copied {} hex line(s)", lines));
            }
            Err(_) => {
                app.set_status_pub("Clipboard unavailable".to_string());
            }
        }
    }
}