Skip to main content

pushrod/backend/
headless.rs

1// Headless Backend
2// Pushrod
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! # Headless backend
17//!
18//! A [`Painter`] that draws nothing and records every call, and a [`HeadlessBackend`] that has no
19//! window and records what the engine asks of it, so a `Widget`'s `paint` and a whole `Engine` can
20//! be unit tested without a display.
21//!
22//! ```rust
23//! use pushrod::backend::headless::{PaintCall, RecordingPainter};
24//! use pushrod::color::Color;
25//! use pushrod::paint;
26//!
27//! let mut p = RecordingPainter::default();
28//! paint::fill(&mut p, Color::WHITE);
29//! assert_eq!(p.calls, vec![PaintCall::Fill(Color::WHITE)]);
30//! ```
31
32use super::{Backend, Waker};
33use crate::color::Color;
34use crate::error::Error;
35use crate::event::{EngineEvent, EventMask};
36use crate::geometry::{Point, Rect, Size};
37use crate::input::InputEvent;
38use crate::paint::{CachePolicy, Painter, TextStyle};
39use crate::widget::WidgetId;
40use std::collections::VecDeque;
41use std::time::Duration;
42
43/// One call made on a [`RecordingPainter`].
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum PaintCall {
46    /// `fill(color)`
47    Fill(Color),
48    /// `fill_rect(bounds, color)`
49    FillRect(Rect, Color),
50    /// `rect(bounds, color)`
51    Rect(Rect, Color),
52    /// `line(from, to, color)`
53    Line(Point, Point, Color),
54    /// `text(bounds, msg, color)`
55    Text(Rect, String, Color),
56    /// `image(path, bounds)`
57    Image(String, Rect),
58    /// `dither(bounds, first, second)`
59    Dither(Rect, Color, Color),
60    /// `dither_overlay(bounds, color)`
61    DitherOverlay(Rect, Color),
62    /// `clip(bounds)`
63    Clip(Option<Rect>),
64}
65
66/// A [`Painter`] that records its calls in [`calls`](RecordingPainter::calls).
67#[derive(Debug, Default)]
68pub struct RecordingPainter {
69    /// Every call made, in order.
70    pub calls: Vec<PaintCall>,
71}
72
73impl Painter for RecordingPainter {
74    /// Returns the policy of a recording painter.
75    ///
76    /// # Returns
77    ///
78    /// [`CachePolicy::DirectDraw`], since nothing is cached.
79    fn cache_policy(&self) -> CachePolicy {
80        CachePolicy::DirectDraw
81    }
82
83    /// Records a fill.
84    ///
85    /// # Arguments
86    ///
87    /// * `color` - The fill color.
88    fn fill(&mut self, color: Color) {
89        self.calls.push(PaintCall::Fill(color));
90    }
91
92    /// Records a rectangle fill.
93    ///
94    /// # Arguments
95    ///
96    /// * `bounds` - The rectangle.
97    /// * `color` - The fill color.
98    fn fill_rect(&mut self, bounds: Rect, color: Color) {
99        self.calls.push(PaintCall::FillRect(bounds, color));
100    }
101
102    /// Records a rectangle outline.
103    ///
104    /// # Arguments
105    ///
106    /// * `bounds` - The rectangle.
107    /// * `color` - The line color.
108    fn rect(&mut self, bounds: Rect, color: Color) {
109        self.calls.push(PaintCall::Rect(bounds, color));
110    }
111
112    /// Records a line.
113    ///
114    /// # Arguments
115    ///
116    /// * `from` - The start point.
117    /// * `to` - The end point.
118    /// * `color` - The line color.
119    fn line(&mut self, from: Point, to: Point, color: Color) {
120        self.calls.push(PaintCall::Line(from, to, color));
121    }
122
123    /// Records text.
124    ///
125    /// # Arguments
126    ///
127    /// * `bounds` - The rectangle to draw within.
128    /// * `style` - The font (its size sets the recorded text height).
129    /// * `color` - The text color.
130    /// * `msg` - The text.
131    ///
132    /// # Returns
133    ///
134    /// A deterministic size: half the font size per character wide (at most the width of `bounds`),
135    /// one font size tall.
136    fn text(&mut self, bounds: Rect, style: &TextStyle, color: Color, msg: &str) -> Size {
137        self.calls
138            .push(PaintCall::Text(bounds, msg.to_string(), color));
139
140        let width = (msg.chars().count() as u32 * (style.font_size as u32 / 2)).min(bounds.w);
141
142        Size::new(width, style.font_size as u32)
143    }
144
145    /// Returns the line height: the font size.
146    ///
147    /// # Arguments
148    ///
149    /// * `style` - The font.
150    ///
151    /// # Returns
152    ///
153    /// The font size in pixels.
154    fn line_height(&mut self, style: &TextStyle) -> u32 {
155        style.font_size as u32
156    }
157
158    /// Measures text the way [`text`](Painter::text) sizes it, without recording a call.
159    ///
160    /// # Arguments
161    ///
162    /// * `style` - The font (its size sets the width of each character).
163    /// * `msg` - The text.
164    ///
165    /// # Returns
166    ///
167    /// Half the font size per character.
168    fn text_width(&mut self, style: &TextStyle, msg: &str) -> u32 {
169        msg.chars().count() as u32 * (style.font_size as u32 / 2)
170    }
171
172    /// Records an image.
173    ///
174    /// # Arguments
175    ///
176    /// * `path` - The image path.
177    /// * `bounds` - The rectangle.
178    ///
179    /// # Returns
180    ///
181    /// `Ok(())`, always.
182    ///
183    /// # Errors
184    ///
185    /// Never fails.
186    fn image(&mut self, path: &str, bounds: Rect) -> Result<(), Error> {
187        self.calls.push(PaintCall::Image(path.to_string(), bounds));
188        Ok(())
189    }
190
191    /// Records a dither.
192    ///
193    /// # Arguments
194    ///
195    /// * `bounds` - The rectangle.
196    /// * `first` - The corner pixel color.
197    /// * `second` - The other color.
198    fn dither(&mut self, bounds: Rect, first: Color, second: Color) {
199        self.calls.push(PaintCall::Dither(bounds, first, second));
200    }
201
202    /// Records a dither overlay.
203    ///
204    /// # Arguments
205    ///
206    /// * `bounds` - The rectangle.
207    /// * `color` - The color to blend.
208    fn dither_overlay(&mut self, bounds: Rect, color: Color) {
209        self.calls.push(PaintCall::DitherOverlay(bounds, color));
210    }
211
212    /// Records a clip change.
213    ///
214    /// # Arguments
215    ///
216    /// * `bounds` - The clip rectangle, or `None`.
217    fn clip(&mut self, bounds: Option<Rect>) {
218        self.calls.push(PaintCall::Clip(bounds));
219    }
220}
221
222/// A [`Backend`] with no window: input is scripted, drawing is recorded, and nothing needs a
223/// display.
224///
225/// Queue input with [`HeadlessBackend::push_event`]; after the engine runs, read
226/// [`painted`](HeadlessBackend::painted), [`draws`](HeadlessBackend::draws) and
227/// [`frames`](HeadlessBackend::frames).  Each `Widget` is painted with a [`RecordingPainter`].
228///
229/// # Examples
230///
231/// ```rust
232/// use pushrod::backend::Backend;
233/// use pushrod::backend::headless::HeadlessBackend;
234/// use pushrod::geometry::size;
235/// use pushrod::input::InputEvent;
236///
237/// let mut backend = HeadlessBackend::new(size(320, 200));
238///
239/// backend.push_event(InputEvent::Quit);
240/// assert_eq!(backend.poll_events(None), vec![InputEvent::Quit]);
241/// ```
242#[derive(Debug, Default)]
243pub struct HeadlessBackend {
244    size: Size,
245    script: VecDeque<InputEvent>,
246    /// Every `Widget` paint, in order: the widget, and the calls it made.
247    pub painted: Vec<(WidgetId, Vec<PaintCall>)>,
248    /// Every `Widget` texture drawn into a frame, in order, with its bounds.
249    pub draws: Vec<(WidgetId, Rect)>,
250    /// The number of frames presented.
251    pub frames: usize,
252    /// The last mask the engine set.
253    pub mask: Option<EventMask>,
254    /// Whether text input is currently on.
255    pub text_input: bool,
256    /// The clipboard contents.
257    pub clipboard: Option<String>,
258    /// The URLs the engine asked to open.
259    pub opened_urls: Vec<String>,
260}
261
262impl HeadlessBackend {
263    /// Creates a headless backend.
264    ///
265    /// # Arguments
266    ///
267    /// * `size` - The size of the pretend window.
268    ///
269    /// # Returns
270    ///
271    /// A new `HeadlessBackend` with no scripted input.
272    pub fn new(size: Size) -> Self {
273        Self {
274            size,
275            ..Self::default()
276        }
277    }
278
279    /// Queues an input event for the next [`Backend::poll_events`].
280    ///
281    /// # Arguments
282    ///
283    /// * `event` - The event to deliver.
284    pub fn push_event(&mut self, event: InputEvent) {
285        self.script.push_back(event);
286    }
287}
288
289impl Backend for HeadlessBackend {
290    /// Returns the cache policy.
291    ///
292    /// # Returns
293    ///
294    /// [`CachePolicy::TextureCache`].
295    fn cache_policy(&self) -> CachePolicy {
296        CachePolicy::TextureCache
297    }
298
299    /// Returns the size of the pretend window.
300    ///
301    /// # Returns
302    ///
303    /// The size.
304    fn window_size(&self) -> Size {
305        self.size
306    }
307
308    /// Records a new window size.
309    ///
310    /// # Arguments
311    ///
312    /// * `size` - The new size.
313    fn resize_window(&mut self, size: Size) {
314        self.size = size;
315    }
316
317    /// Records the event mask in [`HeadlessBackend::mask`].
318    ///
319    /// # Arguments
320    ///
321    /// * `mask` - The run loop's event mask.
322    fn set_event_mask(&mut self, mask: EventMask) {
323        self.mask = Some(mask);
324    }
325
326    /// Records the text input state in [`HeadlessBackend::text_input`].
327    ///
328    /// # Arguments
329    ///
330    /// * `active` - Whether text input is on.
331    fn set_text_input(&mut self, active: bool) {
332        self.text_input = active;
333    }
334
335    /// Returns the scripted events, all at once; it never waits.  With an empty script the
336    /// window is treated as closed, so a loop run against this backend always ends.
337    ///
338    /// # Arguments
339    ///
340    /// * `_wait` - Ignored.
341    ///
342    /// # Returns
343    ///
344    /// The scripted events, or [`InputEvent::Quit`] if there are none.
345    fn poll_events(&mut self, _wait: Option<Duration>) -> Vec<InputEvent> {
346        if self.script.is_empty() {
347            return vec![InputEvent::Quit];
348        }
349
350        self.script.drain(..).collect()
351    }
352
353    /// A headless backend cannot be woken.
354    ///
355    /// # Returns
356    ///
357    /// `None`.
358    fn waker(&self) -> Option<Waker> {
359        None
360    }
361
362    /// Paints the `Widget` with a [`RecordingPainter`] and stores the calls in
363    /// [`HeadlessBackend::painted`].
364    ///
365    /// # Arguments
366    ///
367    /// * `id` - The `Widget`.
368    /// * `_size` - The `Widget`'s size; not needed to record.
369    /// * `paint` - Draws the `Widget`.
370    fn paint_widget(&mut self, id: WidgetId, _size: Size, paint: &mut dyn FnMut(&mut dyn Painter)) {
371        let mut painter = RecordingPainter::default();
372
373        paint(&mut painter);
374        self.painted.push((id, painter.calls));
375    }
376
377    /// Starts a frame; nothing to clear.
378    ///
379    /// # Arguments
380    ///
381    /// * `_clear` - The clear color; ignored.
382    fn begin_frame(&mut self, _clear: Color) {}
383
384    /// Records the draw in [`HeadlessBackend::draws`].
385    ///
386    /// # Arguments
387    ///
388    /// * `id` - The `Widget` drawn.
389    /// * `bounds` - Where it was drawn.
390    fn draw_widget(&mut self, id: WidgetId, bounds: Rect) {
391        self.draws.push((id, bounds));
392    }
393
394    /// Counts a presented frame in [`HeadlessBackend::frames`].
395    fn present(&mut self) {
396        self.frames += 1;
397    }
398
399    /// A headless backend loads no fonts, so it has no notices.
400    ///
401    /// # Returns
402    ///
403    /// An empty list.
404    fn take_notices(&mut self) -> Vec<EngineEvent> {
405        Vec::new()
406    }
407
408    /// Reads the stored clipboard text.
409    ///
410    /// # Returns
411    ///
412    /// The text, or `None` if nothing was stored.
413    fn clipboard_text(&mut self) -> Option<String> {
414        self.clipboard.clone()
415    }
416
417    /// Stores clipboard text.
418    ///
419    /// # Arguments
420    ///
421    /// * `text` - The text to store.
422    fn set_clipboard_text(&mut self, text: &str) {
423        self.clipboard = Some(text.to_string());
424    }
425
426    /// Records the URL in [`HeadlessBackend::opened_urls`] without opening anything.
427    ///
428    /// # Arguments
429    ///
430    /// * `url` - The URL.
431    ///
432    /// # Returns
433    ///
434    /// Always `Ok`.
435    ///
436    /// # Errors
437    ///
438    /// Never fails.
439    fn open_url(&mut self, url: &str) -> Result<(), String> {
440        self.opened_urls.push(url.to_string());
441        Ok(())
442    }
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448    use crate::color::FontStyle;
449    use crate::paint::TextJustify;
450
451    #[test]
452    fn records_every_call_in_order() {
453        let mut p = RecordingPainter::default();
454        let r = Rect::new(1, 2, 3, 4);
455
456        p.fill(Color::BLACK);
457        p.fill_rect(r, Color::RED);
458        p.line(Point::new(0, 0), Point::new(5, 5), Color::BLUE);
459        p.dither(r, Color::BLACK, Color::WHITE);
460        p.clip(Some(r));
461        p.clip(None);
462        assert!(p.image("a.png", r).is_ok());
463
464        assert_eq!(p.calls.len(), 7);
465        assert_eq!(p.calls[0], PaintCall::Fill(Color::BLACK));
466        assert_eq!(p.calls[5], PaintCall::Clip(None));
467        assert_eq!(p.calls[6], PaintCall::Image(String::from("a.png"), r));
468    }
469
470    #[test]
471    fn text_size_is_deterministic_and_clamped() {
472        let mut p = RecordingPainter::default();
473        let style = TextStyle::new(
474            String::from("f.ttf"),
475            FontStyle::NORMAL,
476            10,
477            Color::BLACK,
478            TextJustify::Left,
479        );
480
481        assert_eq!(
482            p.text(Rect::new(0, 0, 100, 20), &style, Color::BLACK, "abcd"),
483            Size::new(20, 10)
484        );
485        assert_eq!(
486            p.text(Rect::new(0, 0, 8, 20), &style, Color::BLACK, "abcd"),
487            Size::new(8, 10)
488        );
489    }
490
491    #[test]
492    fn policy_is_direct_draw() {
493        assert_eq!(
494            RecordingPainter::default().cache_policy(),
495            CachePolicy::DirectDraw
496        );
497    }
498
499    #[test]
500    fn headless_backend_scripts_input_and_records_drawing() {
501        let mut b = HeadlessBackend::new(Size::new(10, 10));
502
503        b.push_event(InputEvent::Exposed);
504        assert_eq!(b.poll_events(None), vec![InputEvent::Exposed]);
505        assert_eq!(b.poll_events(None), vec![InputEvent::Quit]);
506
507        b.paint_widget(3, Size::new(4, 4), &mut |p| p.fill(Color::RED));
508        b.draw_widget(3, Rect::new(0, 0, 4, 4));
509        b.present();
510        b.set_clipboard_text("hi");
511
512        assert_eq!(b.painted, vec![(3, vec![PaintCall::Fill(Color::RED)])]);
513        assert_eq!(b.draws.len(), 1);
514        assert_eq!(b.frames, 1);
515        assert_eq!(b.clipboard_text().as_deref(), Some("hi"));
516        assert!(b.open_url("https://example.com").is_ok());
517        assert_eq!(b.opened_urls, vec!["https://example.com"]);
518    }
519}