bevy_gooey 0.35.0

Game interfaces made easy for Bevy: a skin, ready-made game widgets (buttons, panels, menus, HUD meters, tooltips, modal dialogs) and keyboard and gamepad navigation, on Bevy's own headless widgets.
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
//! Test helpers (cargo feature `testing`): drive a gooey interface in a headless [`App`] by what
//! the player reads, not by entity ids.
//!
//! A player finds "Options" by its words, clicks it where it is drawn and sees where focus went.
//! These helpers do the same through the real input path (`PointerInput`, `MouseButtonInput`,
//! `KeyboardInput`), so a test cannot pass while a button is covered, hidden, unfocusable or
//! mislabelled, which a test that triggers an entity directly can.
//!
//! The app needs [`crate::GooeyPlugins`], a camera that draws the interface and one `update` after
//! the interface is spawned, so it has been laid out. A click goes to the render target of the camera
//! that draws the widget, as the picking backend matches pointers to cameras: a primary window
//! (Bevy's `WindowPlugin`, with `WinitPlugin` and a renderer left out is enough) or an `Image`, so
//! a test of an interface drawn into a texture needs no window at all. Bevy's own key handling of
//! a focused widget (Enter on a button, a character in a field) is dispatched only while a primary
//! window exists, so a test that presses keys on such a widget wants one.
//!
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_gooey::testing::{FindError, click, find_by_label, focused_label};
//!
//! // `app` is a headless app with `GooeyPlugins` and the interface under test, updated once.
//! fn clicking_options_focuses_it(app: &mut App) -> Result<(), FindError> {
//!     let options = find_by_label(app, "Options")?;
//!     click(app, options);
//!     assert_eq!(focused_label(app).as_deref(), Some("Options"));
//!     Ok(())
//! }
//! ```

use std::fmt;

use bevy::camera::{NormalizedRenderTarget, RenderTarget};
use bevy::input::ButtonState;
use bevy::input::keyboard::{Key, KeyboardInput, NativeKey};
use bevy::input::mouse::MouseButtonInput;
use bevy::input_focus::tab_navigation::TabIndex;
use bevy::input_focus::{AcquireFocus, InputFocus, InputFocusVisible};
use bevy::picking::events::PointerPress;
use bevy::picking::pointer::{Location, PointerAction, PointerButton, PointerId, PointerInput};
use bevy::prelude::*;
use bevy::ui::{ComputedNode, ComputedUiTargetCamera, UiGlobalTransform};
use bevy::window::PrimaryWindow;

use crate::skin::Role;
use crate::text::TextInputOf;

/// Updates run after each action, so the input is read in `PreUpdate`, its observers run, and the
/// crate's `Style` pass lands. A design default; the crate's own tests settle for four.
const SETTLE_FRAMES: usize = 2;

/// Why [`find_by_label`] did not return one widget.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FindError {
    /// No visible widget reads `label`.
    NotFound {
        /// The words looked for.
        label: String,
    },
    /// More than one visible widget reads `label`: the test must say which, because a silent first
    /// match would pass for the wrong one.
    Ambiguous {
        /// The words looked for.
        label: String,
        /// Each match as `Entity (Role)`.
        matches: Vec<(Entity, String)>,
    },
}

impl fmt::Display for FindError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotFound { label } => write!(
                f,
                "no visible widget reads \"{label}\" (has the app updated since the interface was spawned?)"
            ),
            Self::Ambiguous { label, matches } => {
                write!(f, "{} widgets read \"{label}\":", matches.len())?;
                for (entity, what) in matches {
                    write!(f, " {entity} ({what})")?;
                }
                Ok(())
            }
        }
    }
}

impl std::error::Error for FindError {}

/// The one visible widget whose words are `label` (compared after trimming).
///
/// The words are a `Text` node's string. The widget is that node's nearest ancestor that takes
/// focus (a button, a toggle, a slider: anything with a `TabIndex`), or the node itself when
/// nothing above it does (a heading). A hidden page, a `Display::None` subtree and an option a
/// choice is not showing are not visible, so a "Back" on another tab is no match. Two widgets with
/// the same label are an [`FindError::Ambiguous`] naming both; one widget whose label appears twice
/// inside it (a name and its tooltip) is one match.
pub fn find_by_label(app: &mut App, label: &str) -> Result<Entity, FindError> {
    let world = app.world_mut();
    let mut texts = world.query::<(Entity, &Text, &InheritedVisibility, &ComputedNode)>();
    let mut found = Vec::new();
    for (entity, text, shown, node) in texts.iter(world) {
        if text.0.trim() != label.trim() || !shown.get() {
            continue;
        }
        let size = node.size();
        if size.x <= 0.0 || size.y <= 0.0 {
            continue;
        }
        let widget = std::iter::once(entity)
            .chain(ancestors(world, entity))
            .find(|e| world.entity(*e).contains::<TabIndex>())
            .unwrap_or(entity);
        if !found.contains(&widget) {
            found.push(widget);
        }
    }
    found.sort();
    match found.as_slice() {
        [] => Err(FindError::NotFound {
            label: label.to_owned(),
        }),
        [one] => Ok(*one),
        many => Err(FindError::Ambiguous {
            label: label.to_owned(),
            matches: many
                .iter()
                .map(|e| {
                    let entity = world.entity(*e);
                    let what = entity
                        .get::<Name>()
                        .map(|n| n.to_string())
                        .or_else(|| entity.get::<Role>().map(|r| format!("{r:?}")))
                        .unwrap_or_else(|| "no role".to_owned());
                    (*e, what)
                })
                .collect(),
        }),
    }
}

/// The window the keyboard's and the mouse's messages name: the primary window, or none when a
/// test draws only into images (the messages' `window` is then a placeholder, which nothing reads).
fn primary_window(app: &mut App) -> Option<Entity> {
    app.world_mut()
        .query_filtered::<Entity, With<PrimaryWindow>>()
        .single(app.world())
        .ok()
}

/// What a pointer needs to land on a widget: the render target of the camera that draws it, that
/// target's scale factor (a window's, an image's) and the window the input messages name.
struct Surface {
    target: NormalizedRenderTarget,
    scale: f32,
    window: Entity,
}

/// Marks an app whose clicks are given focus by [`windowless_click_to_focus`].
#[derive(Resource)]
struct WindowlessFocus;

/// Bevy gives a clicked widget focus only while a primary window exists (`click_to_focus` looks the
/// window up to name it in the request), so in an app that draws only into images a click would
/// reach the widget and leave focus where it was. This is that observer without the window: the
/// same hidden focus ring, the same bubbling `AcquireFocus` that the widgets' own resolvers answer.
fn windowless_click_to_focus(
    press: On<PointerPress>,
    mut shown: ResMut<InputFocusVisible>,
    windows: Query<(), With<PrimaryWindow>>,
    mut commands: Commands,
) {
    if press.entity == press.original_event_target() && windows.is_empty() {
        if shown.0 {
            shown.0 = false;
        }
        commands.trigger(AcquireFocus {
            focused_entity: press.entity,
            window: Entity::PLACEHOLDER,
        });
    }
}

/// The surface `entity` is drawn on, found the way the picking backend matches pointers to
/// cameras: its `ComputedUiTargetCamera` (a `UiTargetCamera`, or the default UI camera), then that
/// camera's `RenderTarget`.
fn surface_of(app: &mut App, entity: Entity) -> Surface {
    let primary = primary_window(app);
    let world = app.world();
    let camera = world
        .get::<ComputedUiTargetCamera>(entity)
        .and_then(ComputedUiTargetCamera::get)
        .unwrap_or_else(|| {
            panic!(
                "{entity} is drawn by no camera: spawn a camera for the interface (a `Camera2d`, or \
                 a `UiTargetCamera` on its root) and update the app"
            )
        });
    let target = world
        .get::<RenderTarget>(camera)
        .unwrap_or_else(|| panic!("the camera {camera} that draws {entity} has no `RenderTarget`"))
        .normalize(primary)
        .unwrap_or_else(|| {
            panic!(
                "the camera {camera} that draws {entity} renders to a window, and the app has none"
            )
        });
    let (scale, window) = match &target {
        NormalizedRenderTarget::Window(window) => (
            world
                .get::<Window>(window.entity())
                .map_or(1.0, |w| w.scale_factor()),
            window.entity(),
        ),
        NormalizedRenderTarget::Image(image) => {
            (image.scale_factor, primary.unwrap_or(Entity::PLACEHOLDER))
        }
        _ => (1.0, primary.unwrap_or(Entity::PLACEHOLDER)),
    };
    Surface {
        target,
        scale,
        window,
    }
}

fn settle(app: &mut App) {
    for _ in 0..SETTLE_FRAMES {
        app.update();
    }
}

fn pointer(app: &mut App, surface: &Surface, at: Vec2, action: PointerAction) {
    let location = Location {
        target: surface.target.clone(),
        position: at,
    };
    app.world_mut()
        .write_message(PointerInput::new(PointerId::Mouse, location, action));
    app.update();
}

/// Click `entity` with the primary button, where it is drawn: the pointer moves to the centre of
/// its laid-out box, then presses and releases, as a mouse does.
///
/// # Panics
///
/// When `entity` has not been laid out (no `ComputedNode`): update the app first. When no camera
/// draws it, or the camera renders to a window the app does not have, with a message that names
/// which.
pub fn click(app: &mut App, entity: Entity) {
    let centre = {
        let world = app.world();
        world
            .get::<ComputedNode>(entity)
            .expect("click needs a laid-out node: update the app after spawning it");
        world
            .get::<UiGlobalTransform>(entity)
            .expect("click needs a placed node: update the app after spawning it")
            .translation
    };
    // Layout is in physical pixels, the pointer in the target's logical ones (the target's scale
    // factor alone: `UiScale` is already in the layout).
    let surface = surface_of(app, entity);
    if primary_window(app).is_none() && !app.world().contains_resource::<WindowlessFocus>() {
        app.world_mut().insert_resource(WindowlessFocus);
        app.add_observer(windowless_click_to_focus);
    }
    let at = centre / surface.scale;
    pointer(app, &surface, at, PointerAction::Move { delta: Vec2::ONE });
    settle(app);
    for state in [ButtonState::Pressed, ButtonState::Released] {
        app.world_mut().write_message(MouseButtonInput {
            button: MouseButton::Left,
            state,
            window: surface.window,
        });
        let action = match state {
            ButtonState::Pressed => PointerAction::Press(PointerButton::Primary),
            ButtonState::Released => PointerAction::Release(PointerButton::Primary),
        };
        pointer(app, &surface, at, action);
    }
    settle(app);
}

/// The logical key a physical one produces on a QWERTY keyboard, for the keys a UI reads by name
/// (Enter, Escape, the arrows, Tab ...) and the letters and digits.
fn logical_key(key: KeyCode) -> Key {
    match key {
        KeyCode::Enter | KeyCode::NumpadEnter => Key::Enter,
        KeyCode::Escape => Key::Escape,
        KeyCode::Tab => Key::Tab,
        KeyCode::Space => Key::Space,
        KeyCode::Backspace => Key::Backspace,
        KeyCode::Delete => Key::Delete,
        KeyCode::ArrowUp => Key::ArrowUp,
        KeyCode::ArrowDown => Key::ArrowDown,
        KeyCode::ArrowLeft => Key::ArrowLeft,
        KeyCode::ArrowRight => Key::ArrowRight,
        KeyCode::Home => Key::Home,
        KeyCode::End => Key::End,
        KeyCode::PageUp => Key::PageUp,
        KeyCode::PageDown => Key::PageDown,
        KeyCode::ShiftLeft | KeyCode::ShiftRight => Key::Shift,
        KeyCode::ControlLeft | KeyCode::ControlRight => Key::Control,
        KeyCode::AltLeft | KeyCode::AltRight => Key::Alt,
        KeyCode::SuperLeft | KeyCode::SuperRight => Key::Super,
        KeyCode::F6 => Key::F6,
        KeyCode::F10 => Key::F10,
        other => {
            let name = format!("{other:?}");
            if let Some(letter) = name.strip_prefix("Key") {
                Key::Character(letter.to_lowercase().as_str().into())
            } else if let Some(digit) = name.strip_prefix("Digit") {
                Key::Character(digit.into())
            } else {
                Key::Unidentified(NativeKey::Unidentified)
            }
        }
    }
}

/// Press and release `key`, as a keyboard does: focus's widget hears it as a real key press.
pub fn press(app: &mut App, key: KeyCode) {
    let window = primary_window(app).unwrap_or(Entity::PLACEHOLDER);
    for state in [ButtonState::Pressed, ButtonState::Released] {
        app.world_mut().write_message(KeyboardInput {
            key_code: key,
            logical_key: logical_key(key),
            state,
            text: None,
            repeat: false,
            window,
        });
        app.update();
    }
    settle(app);
}

/// Type `text` into whatever has focus, one key press and release per character, each carrying the
/// text it produces (as a platform reports it), so a text field takes it.
pub fn type_text(app: &mut App, text: &str) {
    let window = primary_window(app).unwrap_or(Entity::PLACEHOLDER);
    for c in text.chars() {
        let s = c.to_string();
        for state in [ButtonState::Pressed, ButtonState::Released] {
            app.world_mut().write_message(KeyboardInput {
                key_code: KeyCode::KeyA,
                logical_key: Key::Character(s.as_str().into()),
                state,
                text: (state == ButtonState::Pressed).then(|| s.as_str().into()),
                repeat: false,
                window,
            });
            app.update();
        }
    }
    settle(app);
}

/// The entity that has input focus, if any. With nothing focused Bevy may report the window:
/// [`focused_label`] is `None` for that.
pub fn focused(app: &App) -> Option<Entity> {
    app.world().resource::<InputFocus>().get()
}

/// The words of `entity`: its own `Text`, else the first `Text` below it in tree order. A text
/// field reads as its row (the label before the field), not as the field it is.
pub fn label_of(app: &App, entity: Entity) -> Option<String> {
    let world = app.world();
    let entity = world.get::<TextInputOf>(entity).map_or(entity, |row| row.0);
    std::iter::once(entity)
        .chain(descendants(world, entity))
        .find_map(|e| {
            world
                .get::<Text>(e)
                .map(|t| t.0.trim().to_owned())
                .filter(|t| !t.is_empty())
        })
}

/// The words of the focused widget ([`label_of`]), or `None` when nothing but the window has focus.
pub fn focused_label(app: &App) -> Option<String> {
    label_of(app, focused(app)?)
}

/// `entity`'s parents, nearest first.
fn ancestors(world: &World, entity: Entity) -> Vec<Entity> {
    let mut up = Vec::new();
    let mut at = entity;
    while let Some(parent) = world.entity(at).get::<ChildOf>() {
        at = parent.parent();
        up.push(at);
    }
    up
}

/// Everything below `entity`, depth first in child order: the order the player reads a widget.
fn descendants(world: &World, entity: Entity) -> Vec<Entity> {
    let mut out = Vec::new();
    let mut stack: Vec<Entity> = world
        .entity(entity)
        .get::<Children>()
        .map(|c| c.iter().rev().collect())
        .unwrap_or_default();
    while let Some(at) = stack.pop() {
        out.push(at);
        if let Some(children) = world.entity(at).get::<Children>() {
            stack.extend(children.iter().rev());
        }
    }
    out
}