lune-tty 0.1.0

A GPU-accelerated Wayland terminal emulator for Linux
Documentation
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
//! IME preedit state, display-width cell layout, and cursor-area caching.

use std::num::NonZeroU32;

use lune_terminal::{CellPosition, PixelPosition, PixelSize};
use lune_text::WidthPolicy;
use unicode_segmentation::UnicodeSegmentation;
use winit::keyboard::{Key, NamedKey, PhysicalKey};

use crate::PixelRect;

const MAX_PREEDIT_BYTES: usize = 1024;

/// Active IME preedit text and optional byte-offset selection/caret range.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct Preedit {
    pub(super) text: String,
    pub(super) cursor: Option<(usize, usize)>,
}

/// One positioned grapheme cell inside an inline terminal preedit overlay.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct PreeditCell<'a> {
    pub(super) position: CellPosition,
    pub(super) width: usize,
    pub(super) text: &'a str,
    pub(super) selected: bool,
}

impl Preedit {
    pub(super) fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    pub(super) fn text(&self) -> &str {
        &self.text
    }

    pub(super) fn clear(&mut self) -> bool {
        if self.text.is_empty() && self.cursor.is_none() {
            return false;
        }
        self.text.clear();
        self.cursor = None;
        true
    }

    pub(super) fn set(&mut self, mut text: String, cursor: Option<(usize, usize)>) -> bool {
        text.truncate(text.floor_char_boundary(MAX_PREEDIT_BYTES));
        let cursor = cursor.map(|(start, end)| {
            let start = clamp_char_boundary(&text, start);
            let end = clamp_char_boundary(&text, end);
            (start, end)
        });
        if self.text == text && self.cursor == cursor {
            return false;
        }
        self.text = text;
        self.cursor = cursor;
        true
    }

    /// Computes the viewport cell of the preedit caret, wrapping across rows
    /// from `origin`. When `cursor` is `None`, anchors at the end of `text`.
    pub(super) fn cursor_cell(
        &self,
        origin: CellPosition,
        columns: usize,
        rows: usize,
    ) -> Option<CellPosition> {
        if self.text.is_empty() || columns == 0 || rows == 0 {
            return None;
        }
        let target_byte = self.cursor.map_or(self.text.len(), |(_, end)| end);
        let mut col = origin.column.min(columns - 1);
        let mut row = origin.row.min(rows - 1);

        for (byte_start, _, width) in graphemes_with_widths(&self.text) {
            if byte_start >= target_byte {
                break;
            }
            if width == 0 {
                continue;
            }
            let width = width.min(columns);
            if col.saturating_add(width) > columns {
                col = 0;
                row = row.saturating_add(1);
            }
            if row >= rows {
                return Some(CellPosition {
                    row: rows - 1,
                    column: columns - 1,
                });
            }
            col = col.saturating_add(width);
            if col >= columns {
                col = 0;
                row = row.saturating_add(1);
            }
        }

        Some(CellPosition {
            row: row.min(rows - 1),
            column: col.min(columns - 1),
        })
    }

    /// Lays out preedit graphemes into wrapped viewport cells starting at `origin`.
    pub(super) fn layout_cells(
        &self,
        origin: CellPosition,
        columns: usize,
        rows: usize,
    ) -> Vec<PreeditCell<'_>> {
        if self.text.is_empty() || columns == 0 || rows == 0 {
            return Vec::new();
        }
        let selection = self
            .cursor
            .map(|(start, end)| (start.min(end), start.max(end)))
            .filter(|(start, end)| start != end);

        let mut cells = Vec::new();
        let mut col = origin.column.min(columns - 1);
        let mut row = origin.row.min(rows - 1);

        for (byte_start, byte_end, width) in graphemes_with_widths(&self.text) {
            if width == 0 {
                continue;
            }
            let width = width.min(columns);
            if col.saturating_add(width) > columns {
                col = 0;
                row = row.saturating_add(1);
            }
            if row >= rows {
                break;
            }
            let selected =
                selection.is_some_and(|(start, end)| byte_start < end && byte_end > start);
            cells.push(PreeditCell {
                position: CellPosition { row, column: col },
                width,
                text: &self.text[byte_start..byte_end],
                selected,
            });
            col = col.saturating_add(width);
            if col >= columns {
                col = 0;
                row = row.saturating_add(1);
            }
        }
        cells
    }
}

/// Computes the total terminal display-cell width of `text`.
pub(super) fn display_width(text: &str) -> usize {
    graphemes_with_widths(text)
        .into_iter()
        .map(|(_, _, width)| width)
        .sum()
}

/// Deduplicates `set_ime_cursor_area` updates across frames while respecting
/// display scale changes.
#[derive(Debug, Default)]
pub(super) struct ImeAreaCache {
    last: Option<(PixelPosition, PixelSize, u64)>,
}

impl ImeAreaCache {
    pub(super) fn record_if_changed(
        &mut self,
        origin: PixelPosition,
        size: PixelSize,
        scale_factor: f64,
    ) -> bool {
        let next = (origin, size, scale_factor.to_bits());
        if self.last == Some(next) {
            return false;
        }
        self.last = Some(next);
        true
    }

    pub(super) fn invalidate(&mut self) {
        self.last = None;
    }
}

/// Returns whether `key` is a modifier or lock key that does not generate character repeats.
pub(super) fn is_modifier_key(key: &Key) -> bool {
    matches!(
        key,
        Key::Named(
            NamedKey::Shift
                | NamedKey::Control
                | NamedKey::Alt
                | NamedKey::AltGraph
                | NamedKey::Super
                | NamedKey::Meta
                | NamedKey::CapsLock
                | NamedKey::NumLock
                | NamedKey::ScrollLock
        )
    )
}

/// Coordinates `Window::set_ime_allowed` across keyboard-driven mode transitions.
///
/// Enabling Wayland `zwp_text_input_v3` synchronously inside a key-press handler can let the
/// input method grab the matching key-release event before `wl_keyboard` sees it, leaving
/// winit's client-side repeat timer running until the next keyboard event. Deferring
/// `false -> true` transitions until the pressed non-modifier key releases avoids the grab
/// race, while swallowing repeats and orphan releases for the modal-exit trigger key.
#[derive(Debug)]
pub(super) struct ImeAllowGate {
    applied: bool,
    desired: bool,
    active_repeat_key: Option<PhysicalKey>,
    swallowed_keys: Vec<PhysicalKey>,
}

impl ImeAllowGate {
    pub(super) fn new(initial: bool) -> Self {
        Self {
            applied: initial,
            desired: initial,
            active_repeat_key: None,
            swallowed_keys: Vec::new(),
        }
    }

    pub(super) fn on_key_press(
        &mut self,
        key: PhysicalKey,
        is_modifier: bool,
        repeat: bool,
    ) -> bool {
        if repeat {
            return self.swallowed_keys.contains(&key);
        }
        self.swallowed_keys.retain(|held| *held != key);
        if !self.applied && !is_modifier {
            self.active_repeat_key = Some(key);
        }
        false
    }

    pub(super) fn swallow_until_release(&mut self, key: PhysicalKey) {
        if !self.swallowed_keys.contains(&key) {
            self.swallowed_keys.push(key);
        }
    }

    pub(super) fn on_key_release(&mut self, key: PhysicalKey) -> (bool, Option<bool>) {
        let mut swallowed = false;
        self.swallowed_keys.retain(|held| {
            if *held == key {
                swallowed = true;
                false
            } else {
                true
            }
        });
        if self.active_repeat_key == Some(key) {
            self.active_repeat_key = None;
        }
        let ime_update = if !self.applied && self.desired && self.active_repeat_key.is_none() {
            self.applied = true;
            Some(true)
        } else {
            None
        };
        (swallowed, ime_update)
    }

    pub(super) fn sync(&mut self, desired: bool) -> Option<bool> {
        self.desired = desired;
        if !desired {
            if self.applied {
                self.applied = false;
                return Some(false);
            }
            return None;
        }
        if !self.applied && self.active_repeat_key.is_none() {
            self.applied = true;
            return Some(true);
        }
        None
    }

    pub(super) fn force_disable(&mut self, active_key: Option<PhysicalKey>) -> bool {
        if let Some(key) = active_key {
            self.active_repeat_key = Some(key);
        }
        if self.applied {
            self.applied = false;
            return true;
        }
        false
    }

    pub(super) fn clear_keys(&mut self) {
        self.active_repeat_key = None;
        self.swallowed_keys.clear();
    }
}

/// Clamps an IME cursor rectangle in physical pixels to stay strictly inside
/// the window surface dimensions.
pub(super) fn clamp_to_surface(
    origin: PixelPosition,
    size: PixelSize,
    surface_width: u32,
    surface_height: u32,
) -> Option<PixelRect> {
    if surface_width == 0 || surface_height == 0 {
        return None;
    }
    let width = size.width.get().min(surface_width);
    let height = size.height.get().min(surface_height);
    let x = origin.x.min(surface_width - width);
    let y = origin.y.min(surface_height - height);
    Some(PixelRect {
        origin: PixelPosition { x, y },
        size: PixelSize {
            width: NonZeroU32::new(width)?,
            height: NonZeroU32::new(height)?,
        },
    })
}

fn clamp_char_boundary(text: &str, byte: usize) -> usize {
    text.floor_char_boundary(byte.min(text.len()))
}

fn graphemes_with_widths(text: &str) -> Vec<(usize, usize, usize)> {
    text.grapheme_indices(true)
        .filter(|(_, grapheme)| !grapheme.chars().all(char::is_control))
        .map(|(start, grapheme)| {
            let width = WidthPolicy::Narrow.columns(grapheme).min(2);
            (start, start + grapheme.len(), width)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use winit::keyboard::KeyCode;

    use super::*;

    #[test]
    fn cursor_cell_advances_across_ascii_and_wide_preedit_with_wrapping() {
        let mut preedit = Preedit::default();
        assert!(preedit.set("你好ab".into(), Some((8, 8))));
        // Origin at col 4 in a 6-column grid:
        // 'ä½ ' -> (0, 4..6), wraps to (1, 0)
        // '好' -> (1, 0..2)
        // 'a'  -> (1, 2..3)
        // 'b'  -> (1, 3..4)
        // Caret ends at (1, 4).
        let caret = preedit
            .cursor_cell(CellPosition { row: 0, column: 4 }, 6, 4)
            .unwrap();
        assert_eq!(caret, CellPosition { row: 1, column: 4 });

        // Mid-preedit cursor after "ä½ " (byte 3) lands at (1, 0).
        assert!(preedit.set("你好ab".into(), Some((3, 3))));
        let mid = preedit
            .cursor_cell(CellPosition { row: 0, column: 4 }, 6, 4)
            .unwrap();
        assert_eq!(mid, CellPosition { row: 1, column: 0 });
    }

    #[test]
    fn layout_cells_marks_selected_subrange_and_respects_bounds() {
        let mut preedit = Preedit::default();
        assert!(preedit.set("ni hao".into(), Some((3, 6))));
        let cells = preedit.layout_cells(CellPosition { row: 2, column: 1 }, 10, 4);
        assert_eq!(cells.len(), 6);
        assert!(!cells[0].selected);
        assert!(!cells[2].selected);
        assert!(cells[3].selected);
        assert!(cells[5].selected);
        assert_eq!(cells[5].position, CellPosition { row: 2, column: 6 });
    }

    #[test]
    fn cache_invalidates_on_scale_change_and_clamps_to_surface() {
        let mut cache = ImeAreaCache::default();
        let origin = PixelPosition { x: 100, y: 200 };
        let size = PixelSize {
            width: NonZeroU32::new(10).unwrap(),
            height: NonZeroU32::new(20).unwrap(),
        };
        assert!(cache.record_if_changed(origin, size, 1.0));
        assert!(!cache.record_if_changed(origin, size, 1.0));
        assert!(cache.record_if_changed(origin, size, 1.5));
        cache.invalidate();
        assert!(cache.record_if_changed(origin, size, 1.5));

        let clamped = clamp_to_surface(
            PixelPosition { x: 995, y: 590 },
            PixelSize {
                width: NonZeroU32::new(10).unwrap(),
                height: NonZeroU32::new(20).unwrap(),
            },
            1000,
            600,
        )
        .unwrap();
        assert_eq!(clamped.origin, PixelPosition { x: 990, y: 580 });
    }

    #[test]
    fn vi_exit_defers_ime_enable_until_key_release_and_swallows_repeats() {
        let mut gate = ImeAllowGate::new(true);
        assert_eq!(gate.sync(false), Some(false));
        assert!(!gate.applied);

        let key_j = PhysicalKey::Code(KeyCode::KeyJ);
        let key_q = PhysicalKey::Code(KeyCode::KeyQ);

        assert!(!gate.on_key_press(key_j, false, false));
        assert!(!gate.on_key_press(key_j, false, true));
        assert_eq!(gate.on_key_release(key_j), (false, None));

        assert!(!gate.on_key_press(key_q, false, false));
        gate.swallow_until_release(key_q);
        assert_eq!(gate.sync(true), None);
        assert!(!gate.applied);

        assert!(gate.on_key_press(key_q, false, true));
        assert_eq!(gate.on_key_release(key_q), (true, Some(true)));
        assert!(gate.applied);

        assert!(!gate.on_key_press(key_q, false, false));
    }

    #[test]
    fn rollover_key_defers_ime_enable_until_latest_repeat_key_releases() {
        let mut gate = ImeAllowGate::new(true);
        assert_eq!(gate.sync(false), Some(false));

        let key_q = PhysicalKey::Code(KeyCode::KeyQ);
        let key_l = PhysicalKey::Code(KeyCode::KeyL);

        assert!(!gate.on_key_press(key_q, false, false));
        gate.swallow_until_release(key_q);
        assert_eq!(gate.sync(true), None);

        assert!(!gate.on_key_press(key_l, false, false));
        assert_eq!(gate.on_key_release(key_q), (true, None));
        assert!(!gate.applied);

        assert_eq!(gate.on_key_release(key_l), (false, Some(true)));
        assert!(gate.applied);
    }

    #[test]
    fn ctrl_shift_space_exit_ignores_modifiers_and_enables_on_space_release() {
        let mut gate = ImeAllowGate::new(true);
        assert_eq!(gate.sync(false), Some(false));

        let ctrl = PhysicalKey::Code(KeyCode::ControlLeft);
        let shift = PhysicalKey::Code(KeyCode::ShiftLeft);
        let space = PhysicalKey::Code(KeyCode::Space);

        assert!(!gate.on_key_press(ctrl, true, false));
        assert!(!gate.on_key_press(shift, true, false));
        assert!(!gate.on_key_press(space, false, false));
        gate.swallow_until_release(space);
        assert_eq!(gate.sync(true), None);
        assert!(!gate.applied);

        assert_eq!(gate.on_key_release(space), (true, Some(true)));
        assert!(gate.applied);
    }

    #[test]
    fn focus_loss_clears_deferred_key_and_swallowed_state() {
        let mut gate = ImeAllowGate::new(true);
        assert_eq!(gate.sync(false), Some(false));

        let key_q = PhysicalKey::Code(KeyCode::KeyQ);
        assert!(!gate.on_key_press(key_q, false, false));
        gate.swallow_until_release(key_q);
        assert_eq!(gate.sync(true), None);

        gate.clear_keys();
        assert_eq!(gate.sync(false), None);
        assert_eq!(gate.sync(true), Some(true));
        assert!(gate.applied);
    }
}