cellix 0.4.2

The AI companion IDE inside your agent: a Claude Code mod, Codex plugin and Gemini CLI extension
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
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
use std::io::{self, Write};
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use base64::Engine;
use cellix_input::{Event, Key, KeyEvent, Mods, MouseEvent, MouseKind};
use cellix_render::{CellMeasure, FontMeasure, Grid, Measure, SoftwareRasterizer};
use cellix_term::{
    Backend, Bleed, CellBackend, DEFAULT_QUOTA, PixelBackend, Placement, Smooth, Tier, detect,
    select_tier,
};
use crossterm::event::{
    self as ct, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture,
    EnableBracketedPaste, EnableFocusChange, EnableMouseCapture, KeyCode, KeyEventKind,
    KeyModifiers, MouseButton, MouseEventKind,
};
#[cfg(not(windows))]
use crossterm::event::{
    KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};
use crossterm::execute;
use crossterm::style::Print;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode, size,
    window_size,
};

use crate::App;

/// Set when the terminal hangs up or Cellix is asked to stop. Left to their default, those
/// signals end the process on the spot and leave the workspace socket behind.
static STOPPED: AtomicBool = AtomicBool::new(false);

#[cfg(unix)]
extern "C" fn stop(_: libc::c_int) {
    STOPPED.store(true, Ordering::Relaxed);
}

/// Hangs up and stops end the loop, so they leave the way Quit does.
///
/// A stop that lands while crossterm waits for input is retried inside crossterm, and if the
/// terminal then closes, crossterm reads its end over and over and never returns, so the loop
/// never sees the stop. A watch outside the loop ends Cellix after a moment in that case,
/// clearing `left` (the socket and the like) as the loop would have.
#[cfg(unix)]
fn catch_stops(left: Vec<PathBuf>) {
    for signal in [libc::SIGHUP, libc::SIGTERM] {
        // SAFETY: the handler only stores to an atomic, which is safe in a signal handler.
        unsafe {
            libc::signal(signal, stop as *const () as libc::sighandler_t);
        }
    }
    std::thread::spawn(move || {
        while !STOPPED.load(Ordering::Relaxed) {
            std::thread::sleep(Duration::from_millis(100));
        }
        // The loop sees a stop within a frame; leaving normally ends this thread with it.
        std::thread::sleep(Duration::from_secs(2));
        // In case the terminal is still there after all, it gets itself back.
        let _ = disable_raw_mode();
        let _ = write!(io::stdout(), "\x1b[?1049l\x1b[?25h");
        let _ = io::stdout().flush();
        for path in left {
            let _ = std::fs::remove_file(&path);
            let _ = std::fs::remove_dir_all(&path);
        }
        std::process::exit(0);
    });
}

/// Set once Cellix has kept what it must and cleared what it leaves, so a closing console
/// can let Windows end it.
#[cfg(windows)]
static FINISHED: AtomicBool = AtomicBool::new(false);

/// How long a closing console waits for Cellix to finish. Windows ends the process at about
/// five seconds whatever the handler is doing.
#[cfg(windows)]
const CLOSE_GRACE: Duration = Duration::from_millis(4500);

/// Closing the window, logging off or shutting down ends the loop as Quit does, and Windows
/// waits while it finishes, since it ends the process as soon as this returns.
#[cfg(windows)]
unsafe extern "system" fn console_closing(kind: u32) -> windows_sys::core::BOOL {
    use windows_sys::Win32::System::Console::{
        CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT,
    };
    if !matches!(
        kind,
        CTRL_CLOSE_EVENT | CTRL_LOGOFF_EVENT | CTRL_SHUTDOWN_EVENT
    ) {
        return 0;
    }
    STOPPED.store(true, Ordering::Relaxed);
    let started = Instant::now();
    while !FINISHED.load(Ordering::Relaxed) && started.elapsed() < CLOSE_GRACE {
        std::thread::sleep(Duration::from_millis(20));
    }
    1
}

/// Windows has no hang-up signal: a closing console calls a handler instead. The loop finishes
/// as it would on Quit, so unsent comments are kept and the socket and lock files go.
#[cfg(windows)]
fn catch_stops(_left: Vec<PathBuf>) {
    // SAFETY: the handler only touches atomics and sleeps, which any thread may do.
    unsafe {
        windows_sys::Win32::System::Console::SetConsoleCtrlHandler(Some(console_closing), 1);
    }
}

#[cfg(not(any(unix, windows)))]
fn catch_stops(_left: Vec<PathBuf>) {}

/// How often a scroll moves. Over a network each frame costs a round of placements.
const SCROLL_FRAME: Duration = Duration::from_millis(8);
const REMOTE_SCROLL_FRAME: Duration = Duration::from_millis(33);
/// How quickly a scroll closes on where it's going. It only blends one line into the next: any
/// longer and the page trails the hand, which reads as lag and not as smoothness.
const SCROLL_EASE: Duration = Duration::from_millis(14);
/// The longest to spend on queued input before drawing.
const INPUT_SLICE: Duration = Duration::from_millis(4);
/// How often the page under a scroll is brought up to date while it moves.
const SCROLL_PRESENT: Duration = Duration::from_millis(120);
/// How long to wait for input before checking on language servers.
const POLL: Duration = Duration::from_millis(50);
/// How long to wait with a session in the side pane, whose output should feel typed.
const SESSION_POLL: Duration = Duration::from_millis(8);
/// Background file checks run about twice a second.
const TICK: Duration = Duration::from_millis(500);

/// Restores the terminal however the loop ends, including on panic.
struct Session;

impl Session {
    fn start() -> io::Result<Self> {
        enable_raw_mode()?;
        execute!(
            io::stdout(),
            EnterAlternateScreen,
            EnableMouseCapture,
            EnableBracketedPaste,
            EnableFocusChange,
        )?;
        // Terminals without the Kitty keyboard protocol ignore this, and Ctrl+Shift+P
        // and Cmd keys then can't be told apart: F1 and Alt+P still open commands. On Windows
        // keys arrive as console events, which have no such protocol, and crossterm refuses it.
        #[cfg(not(windows))]
        execute!(
            io::stdout(),
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        )?;
        // tmux ignores kitty's flags but passes modified keys on with its extended-keys, once
        // asked this way, so Ctrl+Shift+P stops arriving as Ctrl+P. Only in the csi-u form:
        // the xterm form, tmux's default, is one crossterm can't read, and every Ctrl key
        // would be lost.
        if std::env::var_os("TMUX").is_some() && tmux_keys_readable() {
            execute!(io::stdout(), Print("\x1b[>4;2m"))?;
        }
        Ok(Self)
    }
}

/// Whether tmux sends extended keys in the form crossterm reads.
fn tmux_keys_readable() -> bool {
    let output = std::process::Command::new("tmux")
        .args(["show", "-sv", "extended-keys-format"])
        .output();
    output.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).trim() == "csi-u")
}

impl Drop for Session {
    fn drop(&mut self) {
        #[cfg(not(windows))]
        let _ = execute!(io::stdout(), PopKeyboardEnhancementFlags);
        let _ = execute!(
            io::stdout(),
            Print("\x1b[?1016l"),
            Print(if std::env::var_os("TMUX").is_some() {
                "\x1b[>4;0m"
            } else {
                ""
            }),
            DisableBracketedPaste,
            DisableMouseCapture,
            DisableFocusChange,
            LeaveAlternateScreen,
            crossterm::cursor::Show
        );
        let _ = disable_raw_mode();
    }
}

fn mods(m: KeyModifiers) -> Mods {
    Mods {
        // Cmd on macOS behaves as Ctrl, so VS Code habits work on either key.
        ctrl: m.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER),
        alt: m.contains(KeyModifiers::ALT),
        shift: m.contains(KeyModifiers::SHIFT),
    }
}

/// `pixels` is the cell size when the mouse reports pixels instead of cells.
fn translate(event: ct::Event, pixels: Option<(usize, usize)>) -> Option<Event> {
    Some(match event {
        ct::Event::Key(k) if k.kind != KeyEventKind::Release => {
            let key = match k.code {
                KeyCode::Char(c) => Key::Char(c),
                KeyCode::Enter => Key::Enter,
                KeyCode::Tab => Key::Tab,
                KeyCode::BackTab => Key::BackTab,
                KeyCode::Backspace => Key::Backspace,
                KeyCode::Delete => Key::Delete,
                KeyCode::Esc => Key::Esc,
                KeyCode::Left => Key::Left,
                KeyCode::Right => Key::Right,
                KeyCode::Up => Key::Up,
                KeyCode::Down => Key::Down,
                KeyCode::Home => Key::Home,
                KeyCode::End => Key::End,
                KeyCode::PageUp => Key::PageUp,
                KeyCode::PageDown => Key::PageDown,
                KeyCode::F(n) => Key::F(n),
                _ => return None,
            };
            Event::Key(KeyEvent {
                key,
                mods: mods(k.modifiers),
            })
        }
        ct::Event::Mouse(m) => {
            let kind = match m.kind {
                MouseEventKind::Down(MouseButton::Left) => MouseKind::Left,
                MouseEventKind::Down(MouseButton::Middle) => MouseKind::Middle,
                MouseEventKind::Down(MouseButton::Right) => MouseKind::Right,
                MouseEventKind::Up(_) => MouseKind::Up,
                MouseEventKind::Drag(_) => MouseKind::Drag,
                MouseEventKind::Moved => MouseKind::Move,
                MouseEventKind::ScrollUp => MouseKind::ScrollUp,
                MouseEventKind::ScrollDown => MouseKind::ScrollDown,
                MouseEventKind::ScrollLeft => MouseKind::ScrollLeft,
                MouseEventKind::ScrollRight => MouseKind::ScrollRight,
            };
            let (x, y, fine_x) = match pixels {
                Some((cw, ch)) => {
                    let fine = m.column as f32 / cw.max(1) as f32;
                    (fine as u16, m.row / ch.max(1) as u16, fine)
                }
                None => (m.column, m.row, m.column as f32),
            };
            Event::Mouse(MouseEvent {
                kind,
                x,
                y,
                fine_x,
                mods: mods(m.modifiers),
            })
        }
        ct::Event::Paste(text) => Event::Paste(text),
        ct::Event::Resize(w, h) => Event::Resize(w, h),
        _ => return None,
    })
}

/// The character a key types into text, if it's a key that types and isn't a shortcut.
fn typed(event: &ct::Event) -> Option<char> {
    let ct::Event::Key(key) = event else {
        return None;
    };
    if key.kind == KeyEventKind::Release {
        return None;
    }
    let plain = key.modifiers.difference(KeyModifiers::SHIFT).is_empty();
    match key.code {
        KeyCode::Char(c) if plain => Some(c),
        KeyCode::Enter if key.modifiers.is_empty() => Some('\n'),
        KeyCode::Tab if key.modifiers.is_empty() => Some('\t'),
        _ => None,
    }
}

/// Whether `events` starts with a bracketed paste's marker, `Esc [ 2 0 <last> ~`, sent as keys.
fn marker(events: &[ct::Event], last: char) -> bool {
    let is_esc = matches!(
        events.first(),
        Some(ct::Event::Key(k)) if k.code == KeyCode::Esc && k.kind != KeyEventKind::Release
    );
    is_esc
        && events.len() >= 6
        && events[1..6]
            .iter()
            .map(typed)
            .eq(['[', '2', '0', last, '~'].map(Some))
}

/// Windows' console gives Cellix no pastes, only the keys that would type them, and typed,
/// a paste's brackets close themselves and its lines indent. So in one batch of input, keys
/// between a bracketed paste's markers become a paste, as do keys that type more after a line
/// break or a tab, which no one types faster than Cellix reads. Anything else stays keys.
fn pasted_keys(events: Vec<ct::Event>) -> Vec<ct::Event> {
    // Releases say nothing here, and would split a run of keys.
    let events: Vec<ct::Event> = events
        .into_iter()
        .filter(|e| !matches!(e, ct::Event::Key(k) if k.kind == KeyEventKind::Release))
        .collect();
    let text = |run: &[ct::Event]| run.iter().filter_map(typed).collect::<String>();
    let mut out = Vec::new();
    let mut i = 0;
    while i < events.len() {
        if marker(&events[i..], '0') {
            let start = i + 6;
            let end = (start..events.len())
                .find(|&j| marker(&events[j..], '1'))
                .unwrap_or(events.len());
            out.push(ct::Event::Paste(text(&events[start..end])));
            i = (end + 6).min(events.len());
            continue;
        }
        let run = events[i..]
            .iter()
            .take_while(|e| typed(e).is_some())
            .count();
        let typed_run = &events[i..i + run];
        let breaks_then_types = typed_run
            .iter()
            .take(run.saturating_sub(1))
            .any(|e| matches!(typed(e), Some('\n' | '\t')));
        if run >= 3 && breaks_then_types {
            out.push(ct::Event::Paste(text(typed_run)));
        } else {
            out.extend_from_slice(&events[i..i + run.max(1)]);
        }
        i += run.max(1);
    }
    out
}

/// Ghostty sends Ctrl+A for Cmd+Left, and keeps Cmd+A for itself, so there Ctrl+A means
/// the start of the line. Select All stays in the palette.
fn cmd_left(event: Event, ghostty: bool) -> Event {
    match event {
        Event::Key(key) if ghostty && key == KeyEvent::ctrl('a') => {
            Event::Key(KeyEvent::plain(Key::Home))
        }
        other => other,
    }
}

/// How the terminal was found to work, kept so the backend can be rebuilt on a font zoom.
struct Display {
    placement: Option<Placement>,
    cell: Option<(usize, usize)>,
    /// The terminal said its cell size itself. Under tmux the window's own size can be one
    /// tmux made up, so a resize doesn't overrule it.
    told_cell: bool,
    pixel_mouse: bool,
    light: Option<bool>,
    background: Option<(u8, u8, u8)>,
    smooth: Option<Smooth>,
    bleed: Bleed,
}

impl Display {
    fn detect(setting: Option<&str>, smooth: bool) -> io::Result<Self> {
        let forced = std::env::var("CELLIX_TIER")
            .ok()
            .as_deref()
            .or(setting)
            .and_then(|v| v.parse().ok());
        let env = detect(|k| std::env::var(k).ok())?;
        let placement = match select_tier(env, forced) {
            Tier::PixelsDirect => Some(Placement::Direct),
            Tier::PixelsPlaceholder => Some(Placement::Placeholder),
            Tier::Cells => None,
        };
        let cell = env.cell.or_else(window_cell);
        let bleed = cell.map_or_else(Bleed::default, |cell| {
            crate::integrations::window_bleed(|k| std::env::var(k).ok(), cell.1)
        });
        Ok(Self {
            bleed,
            placement,
            cell,
            told_cell: env.cell.is_some() && env.multiplexer == cellix_term::Multiplexer::Tmux,
            pixel_mouse: env.pixel_mouse,
            light: env.light,
            background: env.background,
            smooth: smooth.then(|| Smooth {
                frame: if std::env::var_os("SSH_CONNECTION").is_some() {
                    REMOTE_SCROLL_FRAME
                } else {
                    SCROLL_FRAME
                },
                ease: SCROLL_EASE,
            }),
        })
    }

    /// Turns the wheel's animation on or off.
    fn set_smooth(&mut self, on: bool) {
        self.smooth = on.then_some(Smooth {
            frame: SCROLL_FRAME,
            ease: SCROLL_EASE,
        });
    }

    /// How to measure text for this display.
    fn measure(&self) -> Rc<dyn Measure> {
        match self.placement.zip(self.cell) {
            Some((_, cell)) => Rc::new(FontMeasure::new(cell.0, cell.1)),
            None => Rc::new(CellMeasure),
        }
    }

    /// Any failure on the way to pixels lands on cells, which always work.
    fn backend(&self) -> Box<dyn Backend> {
        let pixels = self.placement.zip(self.cell).and_then(|(placement, cell)| {
            let rasterizer = SoftwareRasterizer::new(cell.0, cell.1)?;
            let backend =
                PixelBackend::new(rasterizer, placement, DEFAULT_QUOTA).with_bleed(self.bleed);
            Some(match self.smooth {
                Some(smooth) => backend.with_smooth(smooth),
                None => backend,
            })
        });
        match pixels {
            Some(backend) => Box::new(backend),
            None => Box::new(CellBackend::default()),
        }
    }
}

/// Cell size from the window's pixel size, or None when the terminal reports no pixels.
fn window_cell() -> Option<(usize, usize)> {
    let window = window_size().ok()?;
    let cell = (
        window.width as usize / window.columns.max(1) as usize,
        window.height as usize / window.rows.max(1) as usize,
    );
    (cell.0 > 0 && cell.1 > 0).then_some(cell)
}

/// What the command line asked for.
#[derive(Debug, Default)]
pub struct Options {
    pub paths: Vec<PathBuf>,
    /// Behave as `$VISUAL`: write review comments into the file before exiting.
    pub wait: bool,
}

/// Opens the requested files and runs until the user quits.
pub fn run(options: Options) -> io::Result<()> {
    let paths = options.paths;
    let root = paths
        .iter()
        .find(|p| p.is_dir())
        .cloned()
        .map_or_else(std::env::current_dir, Ok)?;
    let root = dunce::canonicalize(root)?;
    let mut app = App::new(root, size()?);
    for path in paths.iter().filter(|p| p.is_file()) {
        let path = dunce::canonicalize(path)?;
        app.open(&path)?;
        if options.wait {
            app.wait_file = Some(path);
        }
    }
    // Agents are optional: a second window on this workspace still edits normally. Anything
    // else that stops agents reaching this one is said, not swallowed.
    let server = match cellix_agent::start(app.workspace.root(), app.comments.clone()) {
        Ok(server) => Some(server),
        Err(e) if e.kind() == io::ErrorKind::AddrInUse => {
            app.say("Another Cellix has this folder open, so agents reach that one");
            None
        }
        Err(e) => {
            app.say(format!("Agents can't reach this Cellix: {e}"));
            None
        }
    };
    if server.is_some() {
        app.restore_unsent();
    }
    app.ide = server.as_ref().and_then(|_| {
        let root = app.workspace.root();
        let kept = crate::hold::folder_of(root).join("ide.json");
        cellix_agent::ide::IdeServer::start_kept(root, &kept).ok()
    });

    let mut left = Vec::new();
    if server.is_some() {
        let socket = cellix_agent::socket_path(app.workspace.root());
        left.push(socket.with_extension(""));
        left.push(socket);
    }
    left.extend(app.ide.as_ref().map(|ide| ide.lock().to_path_buf()));
    catch_stops(left);
    let _session = Session::start()?;
    let smooth = app.settings.smooth_scroll != Some(false);
    let mut display = Display::detect(app.settings.tier.as_deref(), smooth)?;
    let mut backend = display.backend();
    let mut out = io::stdout();
    let mut slow = crate::slow::Log::start();
    let mut phases = crate::slow::Phases::default();
    let mut last_present = Instant::now();
    app.set_measure(display.measure());
    // Only the direct tier moves by less than a line, so elsewhere a notch stays short.
    app.wheel_lines = if display.placement == Some(Placement::Direct) {
        3
    } else {
        1
    };
    app.follow_terminal_theme(display.light);
    app.rejoin_sessions();
    app.match_terminal_background(display.background);
    // Whole cells can't place a caret in proportional text, so ask for pixels where that's
    // on offer. It's only used with a known cell size to divide by.
    let pixel_mouse = display.pixel_mouse && display.placement.is_some() && display.cell.is_some();
    if pixel_mouse {
        write!(out, "\x1b[?1016h")?;
    }
    let mouse_cell = |display: &Display| display.cell.filter(|_| pixel_mouse);
    let mut redraw = true;
    let mut shape = None;
    let mut last_tick = std::time::Instant::now();
    let mut shown: Option<Grid> = None;
    let ghostty = std::env::var("TERM").is_ok_and(|t| t.contains("ghostty"));
    // The loop's errors still come back, but only after what Quit does: a console closing
    // under Cellix can fail its last frame.
    #[allow(clippy::redundant_closure_call)]
    let ended = (|| -> io::Result<()> {
        loop {
            // Polled as well as signalled: a resize during slow startup is otherwise lost.
            let now = size()?;
            if now != app.size() {
                app.handle(Event::Resize(now.0, now.1));
                let cell = window_cell();
                if display.placement.is_some()
                    && !display.told_cell
                    && cell.is_some()
                    && cell != display.cell
                {
                    display.cell = cell;
                    backend = display.backend();
                    app.set_measure(display.measure());
                }
                backend.invalidate();
                redraw = true;
            }
            if let Some(on) = app.take_smooth_change() {
                display.set_smooth(on);
                backend = display.backend();
                redraw = true;
            }
            if redraw {
                let (width, height) = app.size();
                let mut grid = Grid::new(width, height, app.background());
                let started = Instant::now();
                app.draw(&mut grid);
                phases.draw = started.elapsed();
                let started = Instant::now();
                if let (Some((area, rows)), Some(from)) = (app.take_scroll(), &shown) {
                    backend.scroll(from, &grid, area, rows, &mut out)?;
                }
                // Under a scroll the page can wait, so the time goes on moving it.
                if backend.gliding().is_none() || last_present.elapsed() >= SCROLL_PRESENT {
                    backend.present(&grid, &mut out)?;
                    last_present = Instant::now();
                }
                phases.present = started.elapsed();
                slow.note(&phases);
                phases = crate::slow::Phases::default();
                shown = Some(grid);
                if let Some(text) = app.outgoing_clipboard.take() {
                    let encoded = base64::engine::general_purpose::STANDARD.encode(text);
                    write!(out, "\x1b]52;c;{encoded}\x07")?;
                }
                // The terminal's own idea of the pointer drifts, so it's told each time.
                let pointer = app.pointer();
                if shape != Some(pointer) {
                    write!(out, "\x1b]22;{pointer}\x1b\\")?;
                    shape = Some(pointer);
                }
                out.flush()?;
                redraw = false;
            }
            if app.quit || STOPPED.load(Ordering::Relaxed) {
                break;
            }
            let wait = backend.gliding().unwrap_or(if app.has_session() {
                SESSION_POLL
            } else {
                POLL
            });
            // A signal interrupts the wait; the loop goes round and sees it.
            let ready = match ct::poll(wait) {
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                ready => ready?,
            };
            if ready {
                let started = Instant::now();
                // Drain everything queued, so a fast wheel doesn't redraw per event.
                let mut batch = Vec::new();
                loop {
                    let event = ct::read()?;
                    // Anything but the wheel or a passing pointer may change what's under a scroll.
                    // A trackpad wanders sideways as it goes, so those count as the wheel too.
                    let passing = matches!(
                        &event,
                        ct::Event::Mouse(mouse) if matches!(
                            mouse.kind,
                            ct::MouseEventKind::Moved
                                | ct::MouseEventKind::ScrollUp
                                | ct::MouseEventKind::ScrollDown
                                | ct::MouseEventKind::ScrollLeft
                                | ct::MouseEventKind::ScrollRight
                        )
                    );
                    if !passing {
                        backend.settle();
                    }
                    // A multiplexer forgets images when a client leaves, so a new one starts
                    // with an empty window until everything is sent again.
                    if matches!(event, ct::Event::FocusGained)
                        && display.placement == Some(Placement::Placeholder)
                    {
                        backend.invalidate();
                    }
                    // Coming back, or typing, can leave the terminal showing a pointer of its own.
                    if matches!(event, ct::Event::FocusGained | ct::Event::Key(_)) {
                        shape = None;
                    }
                    // Keys that type are taken whole on Windows, where a paste comes as them.
                    let typing = cfg!(windows) && typed(&event).is_some();
                    batch.push(event);
                    // A stream of input mustn't hold up the frames it's asking for.
                    if (started.elapsed() >= INPUT_SLICE && !typing) || !ct::poll(Duration::ZERO)? {
                        break;
                    }
                }
                if cfg!(windows) {
                    batch = pasted_keys(batch);
                }
                for event in batch {
                    match translate(event, mouse_cell(&display)).map(|e| cmd_left(e, ghostty)) {
                        // The size check above handles it, and compares against the old size.
                        Some(Event::Resize(..)) | None => {}
                        Some(event) => app.handle(event),
                    }
                }
                phases.events += started.elapsed();
                redraw = true;
            } else if last_tick.elapsed() >= TICK {
                let started = Instant::now();
                last_tick = started;
                app.handle(Event::Tick);
                phases.events += started.elapsed();
                redraw = true;
            }
            let started = Instant::now();
            redraw |= app.poll();
            phases.poll += started.elapsed();
            if backend.gliding().is_some() {
                backend.glide(Instant::now(), &mut out)?;
                // Arrived, so the page underneath takes over.
                redraw |= backend.gliding().is_none();
            }
            if let Some(server) = &server {
                while let Ok(request) = server.requests.try_recv() {
                    app.serve(request);
                    redraw = true;
                }
            }
        }
        Ok(())
    })();
    // After a hang-up there's no terminal to tell, and the rest must still happen.
    let _ = write!(out, "\x1b]22;default\x1b\\");
    let _ = out.flush();
    drop(_session);
    let finished = app.finish();
    // Before Windows ends the process, which it does as soon as a closing console is let go.
    drop(app.ide.take());
    drop(server);
    #[cfg(windows)]
    FINISHED.store(true, Ordering::Relaxed);
    ended.and(finished)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyEvent as CtKey, KeyEventState};

    fn key(code: KeyCode, kind: KeyEventKind) -> ct::Event {
        ct::Event::Key(CtKey {
            code,
            modifiers: if matches!(code, KeyCode::Char('~' | '(' | 'A')) {
                KeyModifiers::SHIFT
            } else {
                KeyModifiers::NONE
            },
            kind,
            state: KeyEventState::NONE,
        })
    }

    /// Text as a Windows console delivers it: each key pressed, then released.
    fn keys(text: &str) -> Vec<ct::Event> {
        text.chars()
            .flat_map(|c| {
                let code = match c {
                    '\n' => KeyCode::Enter,
                    '\t' => KeyCode::Tab,
                    '\x1b' => KeyCode::Esc,
                    c => KeyCode::Char(c),
                };
                [
                    key(code, KeyEventKind::Press),
                    key(code, KeyEventKind::Release),
                ]
            })
            .collect()
    }

    fn pastes(events: &[ct::Event]) -> Vec<String> {
        events
            .iter()
            .filter_map(|e| match e {
                ct::Event::Paste(text) => Some(text.clone()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn keys_that_paste_on_windows_become_a_paste() {
        // Between a bracketed paste's markers, whatever the text.
        let marked = pasted_keys(keys("\x1b[200~f(x)\x1b[201~"));
        assert_eq!(marked, vec![ct::Event::Paste("f(x)".into())]);
        let marked = pasted_keys(keys("\x1b[200~a(\n\tb\n\x1b[201~"));
        assert_eq!(pastes(&marked), ["a(\n\tb\n"]);
        // Without markers, lines typed faster than anyone types.
        let unmarked = pasted_keys(keys("pasted(\n\ttext\nmore\n"));
        assert_eq!(
            unmarked,
            vec![ct::Event::Paste("pasted(\n\ttext\nmore\n".into())]
        );
        // Typing stays typing: a word, a word and Enter, a shortcut, an Escape.
        for typed in ["new ", "from a human\n", "n\n", "\x1b", "A"] {
            let events = keys(typed);
            let presses: Vec<_> = events
                .iter()
                .filter(|e| !matches!(e, ct::Event::Key(k) if k.kind == KeyEventKind::Release))
                .cloned()
                .collect();
            assert_eq!(pasted_keys(events), presses, "{typed:?}");
        }
        let ctrl_s = ct::Event::Key(CtKey::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
        let mut events = keys("a\nb");
        events.insert(2, ctrl_s.clone());
        assert!(pastes(&pasted_keys(events)).is_empty());
    }

    #[test]
    fn the_wheel_tipped_sideways_arrives_as_itself() {
        let sideways = |kind| {
            let event = ct::Event::Mouse(ct::MouseEvent {
                kind,
                column: 5,
                row: 3,
                modifiers: KeyModifiers::SHIFT,
            });
            translate(event, None)
        };
        let Some(Event::Mouse(left)) = sideways(MouseEventKind::ScrollLeft) else {
            panic!("dropped");
        };
        assert_eq!((left.kind, left.x, left.y), (MouseKind::ScrollLeft, 5, 3));
        let Some(Event::Mouse(right)) = sideways(MouseEventKind::ScrollRight) else {
            panic!("dropped");
        };
        assert_eq!(right.kind, MouseKind::ScrollRight);
        assert!(right.mods.shift);
    }
}