Skip to main content

bevy_window_as_ui_root/
lib.rs

1//! Easily spawn windows as independent UI roots. Ideal for debug widgets!
2//!
3//! ## Usage
4//!
5//! ```
6//! app.add_plugins(WindowAsUiRootPlugin);
7//!
8//! commands.spawn((
9//!   WindowAsUiRoot,
10//!   BackgroundColor(Color::WHITE),
11//!   children![(
12//!     Text::new("Hello World!"),
13//!     TextColor(Color::BLACK),
14//!   )],
15//! ));
16//! ```
17//!
18//! Insert the [`WindowAsUiRoot`] component on an entity and this plugin will:
19//!
20//! - Insert `Node`, `Window`, and `Camera` components if they don't already exist.
21//! - Connect the camera to the root node and window.
22//! - Automatically resize the window to match the root node's layout size (if it is auto or fixed).
23//!
24//! ## Tips
25//! - Use the [`CloseWith`] relation to automatically close nested windows.
26//! - Set `WindowPlugin.exit_condition` to `ExitCondition::OnPrimaryClosed` to prevent popups from outliving the main window.
27//! - Insert `Node { width: percent(100), height: percent(100), ..default() }` on the UI root to make it resizable by the user.
28
29use bevy_app::{App, Plugin, Update};
30use bevy_camera::{Camera, Camera2d, RenderTarget};
31use bevy_ecs::{
32    component::Component,
33    lifecycle::HookContext,
34    query::{Changed, With, Without},
35    system::{Commands, Query},
36    world::DeferredWorld,
37};
38use bevy_ecs::{entity::Entity, query::Has, schedule::IntoScheduleConfigs};
39use bevy_ui::{ComputedNode, Node, UiTargetCamera, Val};
40use bevy_window::{Window, WindowRef};
41
42/// This plugin handles creating and resizing windows, add it to use this library.
43pub struct WindowAsUiRootPlugin;
44
45impl Plugin for WindowAsUiRootPlugin {
46    fn build(&self, app: &mut App) {
47        app.add_systems(Update, (update_resizable, update_size).chain());
48    }
49}
50
51/// Add this relation from sub-windows to their parents to automatically close them.
52#[derive(Component, Clone, Copy)]
53#[relationship(relationship_target = AlsoClose)]
54pub struct CloseWith(pub Entity);
55
56#[doc(hidden)]
57#[derive(Component, Clone)]
58#[relationship_target(relationship = CloseWith, linked_spawn)]
59pub struct AlsoClose(Vec<Entity>);
60
61/// Use this component to spawn windows as independent UI roots.
62///
63/// Inserting it on an entity will:
64///
65/// - Insert `Node`, `Window`, and `Camera` components if they don't already exist.
66/// - Connect the camera to the root node and window.
67/// - Automatically resize the window to match the root node's layout size (if it is auto or fixed).
68#[derive(Component, Clone, Copy, Default)]
69#[require(Window, Node, Camera2d, Camera)]
70#[component(on_add = add_hook)]
71pub struct WindowAsUiRoot;
72
73fn add_hook(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
74    let mut camera = world.get_mut::<Camera>(entity).unwrap();
75    camera.target = RenderTarget::Window(WindowRef::Entity(entity));
76    world
77        .commands()
78        .get_entity(entity)
79        .unwrap()
80        .insert(UiTargetCamera(entity));
81}
82
83#[derive(Component)]
84struct Resizable;
85
86fn update_size(
87    mut windows: Query<
88        (&ComputedNode, &mut Window),
89        (
90            Changed<ComputedNode>,
91            With<WindowAsUiRoot>,
92            Without<Resizable>,
93        ),
94    >,
95) {
96    for (computed_node, mut window) in &mut windows {
97        let size = computed_node.size();
98        if size.x <= 0.0 || size.y <= 0.0 {
99            continue;
100        }
101        window.resolution.set(size.x, size.y);
102    }
103}
104
105fn update_resizable(
106    mut commands: Commands,
107    mut windows: Query<
108        (Entity, &Node, &mut Window, Has<Resizable>),
109        (Changed<Node>, With<WindowAsUiRoot>),
110    >,
111) {
112    for (entity, node, mut window, has_resizable_component) in &mut windows {
113        let resizable = !matches!(node.width, Val::Px(_) | Val::Auto)
114            && !matches!(node.height, Val::Px(_) | Val::Auto);
115
116        if window.resizable != resizable {
117            window.resizable = resizable;
118        }
119
120        if has_resizable_component != resizable {
121            let mut entity_commands = commands.get_entity(entity).unwrap();
122            if resizable {
123                entity_commands.insert(Resizable);
124            } else {
125                entity_commands.remove::<Resizable>();
126            }
127        }
128    }
129}