Skip to main content

qframe/runtime/
harness.rs

1//! Driving an application in tests: no terminal, a fake clock and inline background work.
2
3use std::time::Duration;
4
5use ratatui_core::buffer::Buffer;
6use ratatui_core::layout::Rect as BufferRect;
7use ratatui_core::style::{Color, Modifier};
8
9use super::app::App;
10use super::detached::DetachedOutcome;
11use super::engine::{Engine, TaskMode};
12use super::follow::{Member, Start};
13use super::handoff::{HandoffOutcome, HandoffRequest};
14use super::open::{OpenOutcome, OpenRequest};
15use super::termination::Termination;
16use crate::color::{ColorDepth, Rgb};
17use crate::env::Env;
18use crate::event::{Event, KeyEvent, MouseButton, MouseEvent, MouseKind};
19use crate::icons::GlyphMode;
20use crate::keymap::Modifiers;
21use crate::widget::PointerShape;
22
23/// Time the fake clock moves before every simulated key press, so presses are never mistaken
24/// for a held key.
25const KEY_INTERVAL: Duration = Duration::from_millis(150);
26
27/// Runs an [`App`] against an in-memory screen.
28///
29/// Every input method renders afterwards, like the real runtime does. Work of
30/// [`Command::perform`](super::Command::perform) runs inline, one round per step like one pass of
31/// the terminal loop: work that performs again runs at the next step, so a chain of performs
32/// takes one [`Harness::render`] per link and an endless one never blocks a test.
33pub struct Harness<A: App> {
34    engine: Engine<A>,
35    buffer: Buffer,
36    now: Duration,
37}
38
39impl<A: App> Harness<A> {
40    /// A harness with the built-in environment and a `width` × `height` screen, already rendered.
41    ///
42    /// The first frame starts the application as the terminal runtime does: the size reaches
43    /// [`App::resized`], then [`App::init`] runs, so the focus it asks for is in place before the
44    /// first simulated key.
45    pub fn new(app: A, width: u16, height: u16) -> Self {
46        Self::with_env(app, Env::builtin(), width, height)
47    }
48
49    /// A harness with a custom environment.
50    pub fn with_env(app: A, env: Env, width: u16, height: u16) -> Self {
51        let mut harness = Self {
52            engine: Engine::new(app, env, TaskMode::Inline),
53            buffer: Buffer::empty(BufferRect::new(0, 0, width, height)),
54            now: Duration::ZERO,
55        };
56        harness.render();
57        harness
58    }
59
60    /// A harness for `app` started as member `name` of `ecosystem`, the way
61    /// [`Runtime::member_in`](super::Runtime::member_in) starts it, with `config_dir` as the
62    /// ecosystem's folder: the application's own settings and the shared preferences are read
63    /// from there and applied before the first frame, and
64    /// [`App::preferences`](super::App::preferences) hears them before [`App::init`]. A missing
65    /// shared file is written with the detected values, as it is on a first start.
66    ///
67    /// The folder is not watched: after writing a file, as another application would,
68    /// [`poll_preferences`](Self::poll_preferences) reads the files again the way the runtime
69    /// does when its watch hears them change.
70    pub fn member_in(
71        app: A,
72        ecosystem: crate::storage::Ecosystem,
73        config_dir: &std::path::Path,
74        name: &str,
75        width: u16,
76        height: u16,
77    ) -> Self {
78        let mut env = Env::builtin();
79        let start = Start { theme: None, settings: None, preferences: None };
80        let follow = start.apply(&mut env, Some(Member::new(ecosystem, name, Some(config_dir.to_path_buf()))), false);
81        let mut engine = Engine::new(app, env, TaskMode::Inline);
82        if let Some(follow) = follow {
83            engine.follow(follow);
84        }
85        let mut harness =
86            Self { engine, buffer: Buffer::empty(BufferRect::new(0, 0, width, height)), now: Duration::ZERO };
87        harness.render();
88        harness
89    }
90
91    /// Reads the member's files again and applies what changed, exactly as the runtime does when
92    /// its watch hears the ecosystem's shared file or the application's own file change; see
93    /// [`Runtime::member`](super::Runtime::member). A frame is drawn only when something changed:
94    /// a file written again with what it already said changes nothing and reaches no hook. A
95    /// harness not made with [`member_in`](Self::member_in) has nothing to read.
96    pub fn poll_preferences(&mut self) -> &mut Self {
97        self.engine.check_preferences();
98        if self.engine.dirty {
99            self.render();
100        }
101        self
102    }
103
104    /// Paints the current view.
105    pub fn render(&mut self) -> &mut Self {
106        self.settle_tasks();
107        self.engine.render(&mut self.buffer, self.now);
108        self.write_out();
109        // Settling hover or scrolling to a focused widget can ask for one more frame at once.
110        for _ in 0..3 {
111            let due = self.engine.deadline().is_some_and(|deadline| deadline <= self.now);
112            if !self.engine.dirty && !due {
113                break;
114            }
115            self.engine.render(&mut self.buffer, self.now);
116            self.write_out();
117        }
118        self
119    }
120
121    /// Paints the current view onto `screen` as the terminal runtime paints a frame, for the tests
122    /// that read what a screen writes. Answers whether anything was written.
123    #[cfg(all(test, feature = "image"))]
124    pub(crate) fn present_to<W: std::io::Write>(&mut self, screen: &mut super::present::Screen<W>) -> bool {
125        let now = self.now;
126        let engine = &mut self.engine;
127        screen
128            .present(|buffer| {
129                engine.render(buffer, now);
130                engine.painted()
131            })
132            .expect("a frame")
133    }
134
135    /// Works out what the terminal would be sent for this frame over a cleared screen, as the
136    /// terminal runtime does before writing, so a cell no terminal can take fails the test that
137    /// drew it instead of the application that ships it.
138    fn write_out(&self) {
139        let blank = Buffer::empty(self.buffer.area);
140        let _ = blank.diff(&self.buffer);
141    }
142
143    /// Runs the perform work queued so far, then lets background tasks run up to the fake clock:
144    /// every task works until it sleeps past `now` or ends, and everything they sent is applied.
145    /// Tasks started by those messages settle too. Perform work queued meanwhile runs at the next
146    /// step, so work that performs again never keeps a step from ending.
147    fn settle_tasks(&mut self) {
148        self.engine.run_queued_work();
149        loop {
150            self.engine.task_clock.settle(self.now);
151            if self.engine.poll_tasks() == 0 {
152                break;
153            }
154        }
155    }
156
157    /// Delivers `message` to the application as if a widget had sent it, then renders.
158    pub fn send(&mut self, message: A::Msg) -> &mut Self {
159        self.engine.update(message);
160        self.render()
161    }
162
163    /// Presses a key chord such as `"ctrl+s"`, `"tab"` or `"?"`.
164    pub fn press(&mut self, chord: &str) -> &mut Self {
165        self.now += KEY_INTERVAL;
166        self.engine.handle(Event::Key(KeyEvent::press(chord)), self.now);
167        self.render()
168    }
169
170    /// Types `text` one character at a time.
171    pub fn type_text(&mut self, text: &str) -> &mut Self {
172        for c in text.chars() {
173            let chord = match c {
174                ' ' => "space".to_owned(),
175                '+' => "+".to_owned(),
176                c if c.is_uppercase() => format!("shift+{}", c.to_lowercase()),
177                c => c.to_string(),
178            };
179            self.press(&chord);
180        }
181        self
182    }
183
184    /// Delivers `events` in order at the current clock time and renders once afterwards, the
185    /// way the terminal loop handles every event waiting between two frames: several keys a fast
186    /// typist, a terminal multiplexer or a paste without bracketed paste sent in one read. Each
187    /// event meets what the ones before it did, as the view is rebuilt off screen between them,
188    /// so four keys typed into a controlled [`TextInput`](crate::widgets::TextInput) at once all
189    /// arrive.
190    pub fn events(&mut self, events: &[Event]) -> &mut Self {
191        for event in events {
192            self.engine.handle(event.clone(), self.now);
193        }
194        self.render()
195    }
196
197    /// Delivers `event` at an exact clock time, without moving the clock.
198    #[cfg(test)]
199    pub(crate) fn inject(&mut self, event: Event, at: Duration) -> &mut Self {
200        self.engine.handle(event, at);
201        self.render()
202    }
203
204    /// Pastes `text`.
205    pub fn paste(&mut self, text: &str) -> &mut Self {
206        self.engine.handle(Event::Paste(text.to_owned()), self.now);
207        self.render()
208    }
209
210    /// Clicks the left button on a cell.
211    pub fn click(&mut self, x: i32, y: i32) -> &mut Self {
212        self.mouse(MouseKind::Down(MouseButton::Left), x, y);
213        self.mouse(MouseKind::Up(MouseButton::Left), x, y)
214    }
215
216    /// Clicks the first cell of the first occurrence of `text` on screen.
217    ///
218    /// # Panics
219    ///
220    /// Panics when `text` is not on screen.
221    pub fn click_text(&mut self, text: &str) -> &mut Self {
222        let (x, y) = self.find(text).unwrap_or_else(|| panic!("`{text}` is not on screen:\n{}", self.screen()));
223        self.click(x, y)
224    }
225
226    /// Presses the left button on `from`, drags to `to` and releases there.
227    pub fn drag(&mut self, from: (i32, i32), to: (i32, i32)) -> &mut Self {
228        self.mouse(MouseKind::Down(MouseButton::Left), from.0, from.1);
229        self.mouse(MouseKind::Drag(MouseButton::Left), to.0, to.1);
230        self.mouse(MouseKind::Up(MouseButton::Left), to.0, to.1)
231    }
232
233    /// Moves the pointer to a cell.
234    pub fn hover(&mut self, x: i32, y: i32) -> &mut Self {
235        self.mouse(MouseKind::Moved, x, y)
236    }
237
238    /// Sends a mouse event.
239    pub fn mouse(&mut self, kind: MouseKind, x: i32, y: i32) -> &mut Self {
240        self.engine.handle(Event::Mouse(MouseEvent { kind, x, y, mods: Modifiers::default() }), self.now);
241        self.render()
242    }
243
244    /// Moves the fake clock forward and renders. Idleness moves with it: what
245    /// [`View::idle_for`](crate::widget::View::idle_for) reads grows by `duration`, and a
246    /// [`View::on_idle`](crate::widget::View::on_idle) watch whose silence is reached is told.
247    /// Every simulated input (a key, the mouse, a paste) starts the silence again; `send`,
248    /// `resize` and theme or language changes do not.
249    ///
250    /// A termination whose [`Termination::grace`] is over by then quits, as it does in the
251    /// runtime.
252    pub fn advance(&mut self, duration: Duration) -> &mut Self {
253        self.now += duration;
254        self.engine.tick(self.now);
255        self.engine.end_when_due(self.now);
256        self.render()
257    }
258
259    /// Simulates the signal behind `cause`, the way the terminal runtime hears a `SIGTERM` or a
260    /// `SIGHUP`, then renders. The application hears it through
261    /// [`App::terminating`](super::App::terminating) exactly as it would in a terminal, so a test
262    /// can check its answer:
263    ///
264    /// - An answer of `None` quits at once: [`Harness::quit_requested`] is true.
265    /// - A message is applied; the application stays until it quits or until
266    ///   [`Harness::advance`] moves the clock past [`Termination::grace`].
267    /// - Calling this again with [`Termination::Terminate`] quits, as a second signal does. A
268    ///   repeated [`Termination::Hangup`] changes nothing, and one during a pending terminate is
269    ///   told to the application again.
270    ///
271    /// The harness keeps drawing after a hangup, so a test can still read the screen; the
272    /// runtime stops drawing, since the terminal is gone.
273    ///
274    /// ```
275    /// use qframe::prelude::*;
276    /// use qframe::runtime::Termination;
277    ///
278    /// struct Editor;
279    ///
280    /// impl App for Editor {
281    ///     type Msg = ();
282    ///     fn update(&mut self, (): ()) -> Command<()> {
283    ///         Command::none()
284    ///     }
285    ///     fn view(&self, ui: &mut View<'_, ()>) {
286    ///         ui.add(Text::new("notes.md"));
287    ///     }
288    /// }
289    ///
290    /// // An application that implements nothing quits cleanly on either signal.
291    /// let mut app = Harness::new(Editor, 20, 3);
292    /// app.terminate(Termination::Terminate);
293    /// assert!(app.quit_requested());
294    /// ```
295    pub fn terminate(&mut self, cause: Termination) -> &mut Self {
296        self.engine.terminate(cause, self.now);
297        self.render()
298    }
299
300    /// Delivers a key event exactly as given, without moving the clock: a
301    /// [`KeyKind::Repeat`](crate::event::KeyKind::Repeat) or
302    /// [`KeyKind::Release`](crate::event::KeyKind::Release) from a terminal with the kitty
303    /// keyboard protocol, or a press repeated by a held key.
304    pub fn key(&mut self, event: KeyEvent) -> &mut Self {
305        self.engine.handle(Event::Key(event), self.now);
306        self.render()
307    }
308
309    /// Switches theme, as `Command::set_theme` would.
310    pub fn set_theme(&mut self, id: &str) -> &mut Self {
311        self.engine.env.set_theme(id);
312        self.render()
313    }
314
315    /// Switches language, as `Command::set_locale` would.
316    pub fn set_locale(&mut self, code: &str) -> &mut Self {
317        self.engine.env.set_locale(code);
318        self.render()
319    }
320
321    /// Sets the region, as `Command::set_region` would.
322    pub fn set_region(&mut self, region: Option<&str>) -> &mut Self {
323        self.engine.env.set_region(region);
324        self.render()
325    }
326
327    /// Turns reduced motion on or off.
328    pub fn set_reduced_motion(&mut self, reduced: bool) -> &mut Self {
329        self.engine.env.set_reduced_motion(reduced);
330        self.render()
331    }
332
333    /// Draws as a terminal with `depth` colours would. Cells then carry palette indices instead of
334    /// colours, which [`Harness::fg`] and [`Harness::bg`] cannot read; compare
335    /// [`Harness::buffer`] cells for those.
336    pub fn set_depth(&mut self, depth: ColorDepth) -> &mut Self {
337        self.engine.env.set_depth(depth);
338        self.render()
339    }
340
341    /// Answers the graphics probe as a terminal that shows pictures with `graphics` would. A
342    /// harness asks no terminal, so until this is called it answers
343    /// [`Graphics::HalfBlock`](crate::graphics::Graphics::HalfBlock). The rules of
344    /// [`Env::graphics`](crate::env::Env::graphics) still apply: with [`Harness::set_depth`] at
345    /// 16 colours or [`Harness::set_glyph_mode`] at ASCII no picture is drawn, whatever is set here.
346    pub fn set_graphics(&mut self, graphics: crate::graphics::Graphics) -> &mut Self {
347        self.engine.env.set_terminal_graphics(graphics);
348        self.render()
349    }
350
351    /// Draws as a terminal at the other end of a remote connection would:
352    /// [`Env::remote`](crate::env::Env::remote) answers `remote` in every view that follows. A
353    /// harness is local until this is called, so a test draws the same wherever it runs, over
354    /// SSH included.
355    pub fn set_remote(&mut self, remote: bool) -> &mut Self {
356        self.engine.env.set_remote(remote);
357        self.render()
358    }
359
360    /// Switches the glyph column drawn.
361    pub fn set_glyph_mode(&mut self, mode: GlyphMode) -> &mut Self {
362        self.engine.env.set_glyph_mode(mode);
363        self.render()
364    }
365
366    /// Resizes the screen to `width` × `height` and renders, as a terminal resize does in the
367    /// runtime: the backend hands the engine a fresh, empty buffer of the new size and the next
368    /// frame is drawn in full. A new size reaches [`App::resized`] before that frame is built.
369    pub fn resize(&mut self, width: u16, height: u16) -> &mut Self {
370        self.buffer = Buffer::empty(BufferRect::new(0, 0, width, height));
371        self.engine.dirty = true;
372        self.render()
373    }
374
375    /// The screen as text, one line per row, trailing spaces removed. A double-width character
376    /// reads as itself, without the cell it covers, so `防火墙` is found as it is written.
377    #[must_use]
378    pub fn screen(&self) -> String {
379        let mut out = String::new();
380        for y in 0..self.buffer.area.height {
381            out.push_str(self.row(y).0.trim_end());
382            out.push('\n');
383        }
384        out
385    }
386
387    /// The screen as a self-contained HTML fragment with colours and weights, for looking at
388    /// renders in a browser. Wrap fragments with [`html_page`] to get a document.
389    #[must_use]
390    pub fn html(&self, caption: &str) -> String {
391        let area = self.buffer.area;
392        let escape = |text: &str| text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
393        let css = |color: Color| rgb(color).map_or_else(|| "inherit".to_owned(), |c| c.to_string());
394        let mut out = format!("<figure><figcaption>{}</figcaption><div class=\"screen\">", escape(caption));
395        for y in 0..area.height {
396            out.push_str("<div class=\"row\">");
397            for x in visible_columns(&self.buffer, y) {
398                let cell = &self.buffer[(x, y)];
399                let modifier = cell.modifier;
400                let weight = if modifier.contains(Modifier::BOLD) { "font-weight:700;" } else { "" };
401                let style = if modifier.contains(Modifier::ITALIC) { "font-style:italic;" } else { "" };
402                let line = if modifier.contains(Modifier::UNDERLINED) { "text-decoration:underline;" } else { "" };
403                out.push_str(&format!(
404                    "<span style=\"color:{};background:{};width:{}ch;{weight}{style}{line}\">{}</span>",
405                    css(cell.fg),
406                    css(cell.bg),
407                    crate::text::width(cell.symbol()).max(1),
408                    escape(cell.symbol())
409                ));
410            }
411            out.push_str("</div>");
412        }
413        out.push_str("</div></figure>");
414        out
415    }
416
417    /// Screen position of the first occurrence of `text`, in cells; text after a double-width
418    /// character is found at the column it is drawn in.
419    #[must_use]
420    pub fn find(&self, text: &str) -> Option<(i32, i32)> {
421        (0..self.buffer.area.height).find_map(|y| {
422            let (line, columns) = self.row(y);
423            line.find(text).map(|byte| (i32::from(columns[byte]), i32::from(y)))
424        })
425    }
426
427    /// Row `y` of the screen as text, with the column each byte of that text was drawn in.
428    fn row(&self, y: u16) -> (String, Vec<u16>) {
429        let mut line = String::new();
430        let mut columns = Vec::new();
431        for x in visible_columns(&self.buffer, y) {
432            let symbol = self.buffer[(x, y)].symbol();
433            columns.extend(std::iter::repeat_n(x, symbol.len()));
434            line.push_str(symbol);
435        }
436        (line, columns)
437    }
438
439    /// Text colour of a cell.
440    ///
441    /// # Panics
442    ///
443    /// Panics when the cell is outside the screen.
444    #[must_use]
445    pub fn fg(&self, x: u16, y: u16) -> Option<Rgb> {
446        rgb(self.buffer[(x, y)].fg)
447    }
448
449    /// Background colour of a cell.
450    ///
451    /// # Panics
452    ///
453    /// Panics when the cell is outside the screen.
454    #[must_use]
455    pub fn bg(&self, x: u16, y: u16) -> Option<Rgb> {
456        rgb(self.buffer[(x, y)].bg)
457    }
458
459    /// Whether a cell is bold.
460    ///
461    /// # Panics
462    ///
463    /// Panics when the cell is outside the screen.
464    #[must_use]
465    pub fn is_bold(&self, x: u16, y: u16) -> bool {
466        self.buffer[(x, y)].modifier.contains(Modifier::BOLD)
467    }
468
469    /// The rendered buffer.
470    #[must_use]
471    pub fn buffer(&self) -> &Buffer {
472        &self.buffer
473    }
474
475    /// The application.
476    #[must_use]
477    pub fn app(&self) -> &A {
478        &self.engine.app
479    }
480
481    /// The environment.
482    #[must_use]
483    pub fn env(&self) -> &Env {
484        &self.engine.env
485    }
486
487    /// The pointer shape the last frame asks for where the pointer is, as the terminal runtime
488    /// would send it to a terminal that understands pointer shapes. The harness records the
489    /// request whatever terminal a real run would meet; nothing is written anywhere.
490    #[must_use]
491    pub fn pointer_shape(&self) -> PointerShape {
492        self.engine.pointer_shape()
493    }
494
495    /// Texts copied to the clipboard so far.
496    #[must_use]
497    pub fn copied(&self) -> &[String] {
498        &self.engine.clipboard
499    }
500
501    /// The in-process clipboard: the text copied last, if any.
502    #[must_use]
503    pub fn clipboard(&self) -> Option<&str> {
504        self.engine.clipboard_text.as_deref()
505    }
506
507    /// Stands in for the system clipboard that pasting reads first: `Some` text as if the user
508    /// had copied it in another program, `None` for an empty clipboard (the start). A harness
509    /// never reads the real clipboard or asks a terminal, so without this pasting uses the text
510    /// the application copied last.
511    pub fn set_system_clipboard(&mut self, text: Option<&str>) -> &mut Self {
512        let system = super::clipboard::SystemClipboard::Fixed(text.map(str::to_owned));
513        self.engine.clipboard_reader.set_system(system);
514        self
515    }
516
517    /// The handoffs of [`Command::handoff`](super::Command::handoff) the application asked for,
518    /// oldest first. A harness has no terminal to hand over, so it records the request and
519    /// answers it with the outcome of [`Harness::set_handoff_outcome`] instead of running the
520    /// program.
521    #[must_use]
522    pub fn handoffs(&self) -> &[HandoffRequest] {
523        self.engine.handoff_requests()
524    }
525
526    /// The outcome every handoff from now on ends with; `Finished { code: Some(0) }` without
527    /// this.
528    pub fn set_handoff_outcome(&mut self, outcome: HandoffOutcome) -> &mut Self {
529        self.engine.set_handoff_outcome(outcome);
530        self
531    }
532
533    /// The handoffs of [`Command::handoff_detached`](super::Command::handoff_detached) the
534    /// application asked for, oldest first. Like [`Harness::handoffs`] they are recorded, not
535    /// run, and answered with the outcome of [`Harness::set_detached_outcome`].
536    #[must_use]
537    pub fn detached_handoffs(&self) -> &[HandoffRequest] {
538        self.engine.detached_requests()
539    }
540
541    /// The outcome every detached handoff from now on ends with; `Finished { code: Some(0) }`
542    /// without this. A [`DetachedOutcome::Detached`] with the child of
543    /// [`LiveChild::for_tests`](super::LiveChild::for_tests) lets the test play the program: what
544    /// the application writes is recorded on its [`TestChild`](super::TestChild), and the lines
545    /// the test says there reach [`DetachedHandoff::on_line`](super::DetachedHandoff::on_line)
546    /// at the next step.
547    ///
548    /// The harness keeps the outcome, and with it a clone of the child, until it is given
549    /// another or dropped; the child's input closes then at the latest, as it does when a real
550    /// run ends.
551    pub fn set_detached_outcome(&mut self, outcome: DetachedOutcome) -> &mut Self {
552        self.engine.set_detached_outcome(outcome);
553        self
554    }
555
556    /// The openings of [`Command::open`](super::Command::open) and
557    /// [`Command::open_with`](super::Command::open_with) the application asked for, oldest first.
558    ///
559    /// A harness reaches no desktop: the opening is recorded and answered with the outcome of
560    /// [`Harness::set_open_outcome`] instead of starting anything. [`OpenRequest::target`] is
561    /// what was asked to be opened, so a test reads the address without knowing which opener
562    /// this system has.
563    #[must_use]
564    pub fn opens(&self) -> &[OpenRequest] {
565        self.engine.open_requests()
566    }
567
568    /// The outcome every opening from now on ends with; [`OpenOutcome::Opened`] without this.
569    pub fn set_open_outcome(&mut self, outcome: OpenOutcome) -> &mut Self {
570        self.engine.set_open_outcome(outcome);
571        self
572    }
573
574    /// The questions for a newer version of
575    /// [`Command::check_for_update`](super::Command::check_for_update) the application asked,
576    /// oldest first. A harness reaches no network and reads or writes none of the check's
577    /// folders: the question is recorded and answered with the version of
578    /// [`set_latest_version`](Self::set_latest_version), if any.
579    #[cfg(feature = "updates")]
580    #[must_use]
581    pub fn update_checks(&self) -> &[super::UpdateCheckRequest] {
582        self.engine.update_checks()
583    }
584
585    /// Answers the questions for a newer version as if the registry had named `latest` the newest,
586    /// the ones asked already and every one from now on, then renders. With `None`, the default,
587    /// a question gets no answer, as when the network is down. The application's message arrives
588    /// only when the version is newer than the one it runs.
589    #[cfg(feature = "updates")]
590    pub fn set_latest_version(&mut self, latest: Option<&str>) -> &mut Self {
591        self.engine.set_latest_version(latest.map(str::to_owned));
592        self.render()
593    }
594
595    /// Whether the application asked to quit.
596    #[must_use]
597    pub fn quit_requested(&self) -> bool {
598        self.engine.quit
599    }
600
601    /// Whether the widget named `name` has keyboard focus.
602    #[must_use]
603    pub fn is_focused(&self, name: &str) -> bool {
604        self.engine.interaction.focused.is_some_and(|id| self.engine.frame.names.get(&id).is_some_and(|n| n == name))
605    }
606}
607
608/// Wraps [`Harness::html`] fragments in an HTML document that lays screens out on a dark page.
609#[must_use]
610pub fn html_page(fragments: &[String]) -> String {
611    format!(
612        "<!doctype html><meta charset=\"utf-8\"><title>Quvyta review</title><style>\
613         body{{background:#050507;margin:24px;font-family:'JetBrainsMono Nerd Font Mono','JetBrains Mono',monospace}}\
614         figure{{margin:0 0 28px}}figcaption{{color:#8a8f99;font:12px sans-serif;margin-bottom:6px}}\
615         .screen{{display:inline-block;font-size:14px;line-height:19px;white-space:pre}}\
616         .row{{display:flex;height:19px}}.row span{{display:inline-block;overflow:hidden}}</style>{}",
617        fragments.concat()
618    )
619}
620
621/// The columns of row `y` a terminal shows a symbol of: every one except those a wide
622/// character before them covers. Such a cell holds nothing or, when ratatui or a painter unaware
623/// of the character drew it, a space; reading it would split `防火墙` into `防 火 墙`.
624fn visible_columns(buffer: &Buffer, y: u16) -> impl Iterator<Item = u16> + '_ {
625    let mut covered = 0u16;
626    (0..buffer.area.width).filter(move |&x| {
627        if covered > 0 {
628            covered -= 1;
629            return false;
630        }
631        let symbol = buffer[(x, y)].symbol();
632        covered = crate::text::width(symbol).saturating_sub(1);
633        !symbol.is_empty()
634    })
635}
636
637fn rgb(color: Color) -> Option<Rgb> {
638    match color {
639        Color::Rgb(r, g, b) => Some(Rgb::new(r, g, b)),
640        _ => None,
641    }
642}
643
644#[cfg(test)]
645mod resize_tests {
646    use super::Harness;
647    use crate::runtime::{App, Command};
648    use crate::widget::View;
649    use crate::widgets::Text;
650
651    struct Greeting;
652
653    impl App for Greeting {
654        type Msg = ();
655        fn update(&mut self, (): ()) -> Command<()> {
656            Command::none()
657        }
658        fn view(&self, ui: &mut View<'_, ()>) {
659            ui.add(Text::new("container engines"));
660        }
661    }
662
663    #[test]
664    fn resize_redraws_the_whole_screen_at_the_new_size() {
665        let mut harness = Harness::new(Greeting, 30, 2);
666        assert_eq!(harness.screen(), "container engines\n\n");
667        harness.resize(9, 1);
668        assert_eq!(harness.screen(), "container\n");
669        harness.resize(0, 0);
670        assert_eq!(harness.screen(), "");
671        harness.resize(40, 3);
672        assert_eq!((harness.buffer().area.width, harness.buffer().area.height), (40, 3));
673        assert_eq!(harness.screen(), "container engines\n\n\n");
674    }
675
676    struct Raw;
677
678    impl App for Raw {
679        type Msg = ();
680        fn update(&mut self, (): ()) -> Command<()> {
681            Command::none()
682        }
683        fn view(&self, ui: &mut View<'_, ()>) {
684            ui.add(Text::new("bell\u{7} tab\t\u{1b}[1mé\r"));
685        }
686    }
687
688    #[test]
689    fn a_control_character_handed_to_any_widget_never_reaches_a_cell() {
690        let harness = Harness::new(Raw, 30, 1);
691        assert_eq!(harness.screen(), "bell  tab  [1mé\n", "each control character is a blank cell");
692    }
693}
694
695#[cfg(test)]
696mod handoff_tests {
697    use std::ffi::OsString;
698
699    use super::Harness;
700    use crate::runtime::{App, Command, Handoff, HandoffOutcome};
701    use crate::widget::View;
702    use crate::widgets::{Button, Text};
703
704    /// Asks for the authorization ticket and shows how the handoff ended.
705    #[derive(Default)]
706    struct Installer {
707        outcomes: Vec<HandoffOutcome>,
708    }
709
710    #[derive(Clone)]
711    enum Msg {
712        Authorize,
713        Done(HandoffOutcome),
714    }
715
716    impl App for Installer {
717        type Msg = Msg;
718        fn update(&mut self, msg: Msg) -> Command<Msg> {
719            match msg {
720                Msg::Authorize => Command::handoff(
721                    Handoff::new("sudo", Msg::Done).arg("-v").notice("Authorizing the installation").pause(false),
722                ),
723                Msg::Done(outcome) => {
724                    self.outcomes.push(outcome);
725                    Command::none()
726                }
727            }
728        }
729        fn view(&self, ui: &mut View<'_, Msg>) {
730            ui.add(Button::new("Authorize").on_press(Msg::Authorize)).id("authorize");
731            let text = match self.outcomes.last() {
732                None => "not asked yet".to_owned(),
733                Some(HandoffOutcome::Finished { code }) => format!("finished {code:?}"),
734                Some(HandoffOutcome::Failed(reason)) => format!("failed {reason}"),
735            };
736            ui.add(Text::new(text));
737        }
738    }
739
740    #[test]
741    fn a_handoff_is_recorded_and_answered_with_the_outcome_the_test_set() {
742        let mut harness = Harness::new(Installer::default(), 40, 3);
743        assert!(harness.handoffs().is_empty(), "nothing was asked for yet");
744        harness.send(Msg::Authorize);
745        let asked = harness.handoffs();
746        assert_eq!(asked.len(), 1);
747        assert_eq!(asked[0].program, OsString::from("sudo"));
748        assert_eq!(asked[0].args, vec![OsString::from("-v")]);
749        assert_eq!(asked[0].notice.as_deref(), Some("Authorizing the installation"));
750        assert!(!asked[0].pause);
751        // No program ran: the outcome the harness holds answered the request.
752        assert_eq!(harness.app().outcomes, [HandoffOutcome::Finished { code: Some(0) }]);
753        assert!(harness.screen().contains("finished Some(0)"), "{}", harness.screen());
754    }
755
756    #[test]
757    fn the_outcome_a_test_sets_reaches_the_application() {
758        let mut harness = Harness::new(Installer::default(), 40, 3);
759        harness.set_handoff_outcome(HandoffOutcome::Finished { code: Some(1) });
760        harness.send(Msg::Authorize);
761        assert_eq!(harness.app().outcomes, [HandoffOutcome::Finished { code: Some(1) }]);
762        harness.set_handoff_outcome(HandoffOutcome::Failed("sudo is not installed".to_owned()));
763        harness.send(Msg::Authorize);
764        assert_eq!(harness.app().outcomes.len(), 2);
765        assert!(harness.screen().contains("failed sudo is not installed"), "{}", harness.screen());
766        assert_eq!(harness.handoffs().len(), 2, "both requests are kept, oldest first");
767    }
768
769    #[test]
770    fn several_handoffs_are_answered_one_after_another() {
771        let mut harness = Harness::new(Installer::default(), 40, 3);
772        harness.send(Msg::Authorize).send(Msg::Authorize).send(Msg::Authorize);
773        assert_eq!(harness.handoffs().len(), 3);
774        assert_eq!(harness.app().outcomes.len(), 3);
775    }
776}
777
778#[cfg(test)]
779mod wide_text_tests {
780    use super::Harness;
781    use crate::runtime::{App, Command};
782    use crate::widget::View;
783    use crate::widgets::{Button, Text};
784
785    /// A Chinese status line and a button with a Chinese label that counts its presses.
786    #[derive(Default)]
787    struct Firewall {
788        presses: u32,
789    }
790
791    impl App for Firewall {
792        type Msg = ();
793        fn update(&mut self, (): ()) -> Command<()> {
794            self.presses += 1;
795            Command::none()
796        }
797        fn view(&self, ui: &mut View<'_, ()>) {
798            ui.add(Text::new("状态 防火墙 on"));
799            ui.add(Button::new("启用").on_press(()));
800        }
801    }
802
803    /// The screen as ratatui leaves it when it draws wide text itself: the cell each wide
804    /// character covers holds a space, as does a cell drawn by any painter that knows nothing of
805    /// the character before it.
806    fn with_covered_cells_as_spaces(harness: &mut Harness<Firewall>) {
807        let area = harness.buffer.area;
808        for y in 0..area.height {
809            let mut covered = 0;
810            for x in 0..area.width {
811                let cell = &mut harness.buffer[(x, y)];
812                if covered > 0 {
813                    covered -= 1;
814                    cell.reset();
815                    continue;
816                }
817                covered = crate::text::width(cell.symbol()).saturating_sub(1);
818            }
819        }
820    }
821
822    fn firewall() -> Harness<Firewall> {
823        let mut harness = Harness::new(Firewall::default(), 30, 3);
824        with_covered_cells_as_spaces(&mut harness);
825        harness
826    }
827
828    #[test]
829    fn the_screen_reads_wide_text_without_gaps() {
830        let harness = firewall();
831        let screen = harness.screen();
832        assert!(screen.starts_with("状态 防火墙 on\n"), "{screen}");
833        assert!(screen.contains("防火墙"), "{screen}");
834    }
835
836    #[test]
837    fn find_gives_the_column_a_wide_text_is_drawn_in() {
838        let harness = firewall();
839        assert_eq!(harness.find("防火墙"), Some((5, 0)));
840        assert_eq!(harness.find("on"), Some((12, 0)), "text after wide characters keeps its column");
841        let (x, y) = harness.find("启用").expect("the button label is on screen");
842        assert_eq!(harness.buffer()[(u16::try_from(x).unwrap(), u16::try_from(y).unwrap())].symbol(), "启");
843    }
844
845    #[test]
846    fn click_text_presses_a_wide_label() {
847        let mut harness = firewall();
848        harness.click_text("启用");
849        assert_eq!(harness.app().presses, 1);
850    }
851
852    #[test]
853    fn html_draws_a_wide_character_once() {
854        let harness = firewall();
855        let html = harness.html("wide");
856        let first_row = html.split("<div class=\"row\">").nth(1).expect("a first row");
857        assert_eq!(first_row.matches("<span").count(), 30 - 5, "five characters take two cells each: {first_row}");
858        assert!(first_row.contains(">防</span><span"), "{first_row}");
859    }
860}
861
862#[cfg(test)]
863mod graphics_tests {
864    use super::Harness;
865    use crate::color::ColorDepth;
866    use crate::graphics::Graphics;
867    use crate::icons::GlyphMode;
868    use crate::runtime::{App, Command};
869    use crate::widget::View;
870    use crate::widgets::Text;
871
872    /// Shows the graphics its view reads from the environment.
873    struct Pictures;
874
875    impl App for Pictures {
876        type Msg = ();
877        fn update(&mut self, (): ()) -> Command<()> {
878            Command::none()
879        }
880        fn view(&self, ui: &mut View<'_, ()>) {
881            let graphics = ui.env().graphics();
882            ui.add(Text::new(graphics.name()));
883        }
884    }
885
886    #[test]
887    fn a_harness_answers_half_blocks_until_told_otherwise() {
888        let mut harness = Harness::new(Pictures, 20, 1);
889        assert_eq!(harness.screen(), "halfblock\n", "no terminal is asked in a test");
890        harness.set_graphics(Graphics::Kitty);
891        assert_eq!(harness.screen(), "kitty\n");
892        harness.set_graphics(Graphics::Sixel);
893        assert_eq!(harness.screen(), "sixel\n");
894    }
895
896    #[test]
897    fn the_rules_still_apply_to_what_a_harness_is_told() {
898        let mut harness = Harness::new(Pictures, 20, 1);
899        harness.set_graphics(Graphics::Kitty).set_depth(ColorDepth::Ansi16);
900        assert_eq!(harness.screen(), "none\n", "16 colours show no picture");
901        harness.set_depth(ColorDepth::TrueColor).set_glyph_mode(GlyphMode::Ascii);
902        assert_eq!(harness.screen(), "none\n", "ASCII glyphs show no picture");
903        harness.set_glyph_mode(GlyphMode::Unicode);
904        assert_eq!(harness.screen(), "kitty\n");
905    }
906
907    /// Says whether its view is drawn for a remote connection.
908    struct Link;
909
910    impl App for Link {
911        type Msg = ();
912        fn update(&mut self, (): ()) -> Command<()> {
913            Command::none()
914        }
915        fn view(&self, ui: &mut View<'_, ()>) {
916            ui.add(Text::new(if ui.env().remote() { "remote" } else { "local" }));
917        }
918    }
919
920    #[test]
921    fn a_harness_draws_a_remote_screen_when_told_so() {
922        let mut harness = Harness::new(Link, 20, 1);
923        assert_eq!(harness.screen(), "local\n", "a test draws the same wherever it runs");
924        harness.set_remote(true);
925        assert_eq!(harness.screen(), "remote\n");
926        harness.set_remote(false);
927        assert_eq!(harness.screen(), "local\n");
928    }
929}