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
#![doc(html_favicon_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo-icon.png")]
#![doc(html_logo_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo.png")]
//!
//! App window and monitors manager.
//!
//! # Crate
//!
#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
#![warn(unused_extern_crates)]
#![warn(missing_docs)]
// suppress nag about very simple boxed closure signatures.
#![expect(clippy::type_complexity)]
#[macro_use]
extern crate bitflags;
mod control;
pub use control::{NestedWindowNode, NestedWindowWidgetInfoExt, OpenNestedHandlerArgs};
mod ime;
pub use ime::*;
mod types;
pub use types::*;
mod monitor;
pub use monitor::*;
mod vars;
pub use vars::*;
mod service;
pub use service::*;
use std::future::{Future, IntoFuture};
use zng_app::{
update::{EventUpdate, InfoUpdates, LayoutUpdates, RenderUpdates, WidgetUpdates},
view_process::raw_events::{RawWindowFocusArgs, RAW_WINDOW_FOCUS_EVENT},
window::WindowId,
AppControlFlow, AppExtended, AppExtension, HeadlessApp,
};
use zng_ext_image::{ImageVar, IMAGES_WINDOW};
use zng_view_api::image::ImageMaskMode;
pub mod cmd;
/// Application extension that manages windows.
///
/// # Events
///
/// Events this extension provides:
///
/// * [`WINDOW_OPEN_EVENT`]
/// * [`WINDOW_CHANGED_EVENT`]
/// * [`WINDOW_FOCUS_CHANGED_EVENT`]
/// * [`WINDOW_CLOSE_REQUESTED_EVENT`]
/// * [`WINDOW_CLOSE_EVENT`]
/// * [`MONITORS_CHANGED_EVENT`]
///
/// # Services
///
/// Services this extension provides:
///
/// * [`WINDOWS`]
/// * [`MONITORS`]
///
/// The [`WINDOWS`] service is also setup as the implementer for [`IMAGES`] rendering.
///
/// [`IMAGES`]: zng_ext_image::IMAGES
#[derive(Default)]
pub struct WindowManager {}
impl AppExtension for WindowManager {
fn init(&mut self) {
IMAGES_WINDOW.hook_render_windows_service(Box::new(WINDOWS));
}
fn event_preview(&mut self, update: &mut EventUpdate) {
MonitorsService::on_pre_event(update);
WINDOWS::on_pre_event(update);
}
fn event_ui(&mut self, update: &mut EventUpdate) {
WINDOWS::on_ui_event(update);
}
fn event(&mut self, update: &mut EventUpdate) {
WINDOWS::on_event(update);
}
fn update_ui(&mut self, update_widgets: &mut WidgetUpdates) {
WINDOWS::on_ui_update(update_widgets);
}
fn update(&mut self) {
WINDOWS::on_update();
}
fn info(&mut self, info_widgets: &mut InfoUpdates) {
WINDOWS::on_info(info_widgets);
}
fn layout(&mut self, layout_widgets: &mut LayoutUpdates) {
WINDOWS::on_layout(layout_widgets);
}
fn render(&mut self, render_widgets: &mut RenderUpdates, render_update_widgets: &mut RenderUpdates) {
WINDOWS::on_render(render_widgets, render_update_widgets);
}
}
/// Extension trait, adds [`run_window`] to [`AppExtended`].
///
/// [`run_window`]: AppRunWindowExt::run_window
/// [`AppExtended`]: zng_app::AppExtended
pub trait AppRunWindowExt {
/// Runs the application event loop and requests a new window.
///
/// The window opens after the future returns it. The [`WINDOW`] context for the new window is already available in the `new_window` future.
///
/// This method only returns when the app has exited.
///
/// # Examples
///
/// ```no_run
/// # use zng_app::window::WINDOW;
/// # use zng_app::APP;
/// # use zng_ext_window::AppRunWindowExt as _;
/// # trait AppDefaults { fn defaults(&self) -> zng_app::AppExtended<impl zng_app::AppExtension> { APP.minimal() } }
/// # impl AppDefaults for APP { }
/// # macro_rules! Window { ($($tt:tt)*) => { unimplemented!() } }
/// APP.defaults().run_window(async {
/// println!("starting app with window {:?}", WINDOW.id());
/// Window! {
/// title = "Window 1";
/// child = Text!("Window 1");
/// }
/// })
/// ```
///
/// Which is a shortcut for:
///
/// ```no_run
/// # use zng_app::window::WINDOW;
/// # use zng_ext_window::WINDOWS;
/// # use zng_app::APP;
/// # use zng_ext_window::AppRunWindowExt as _;
/// # trait AppDefaults { fn defaults(&self) -> zng_app::AppExtended<impl zng_app::AppExtension> { APP.minimal() } }
/// # impl AppDefaults for APP { }
/// # macro_rules! Window { ($($tt:tt)*) => { unimplemented!() } }
/// APP.defaults().run(async {
/// WINDOWS.open(async {
/// println!("starting app with window {:?}", WINDOW.id());
/// Window! {
/// title = "Window 1";
/// child = Text!("Window 1");
/// }
/// });
/// })
/// ```
///
/// [`WINDOW`]: zng_app::window::WINDOW
fn run_window<F>(self, new_window: impl IntoFuture<IntoFuture = F>)
where
F: Future<Output = WindowRoot> + Send + 'static;
}
impl<E: AppExtension> AppRunWindowExt for AppExtended<E> {
fn run_window<F>(self, new_window: impl IntoFuture<IntoFuture = F>)
where
F: Future<Output = WindowRoot> + Send + 'static,
{
let new_window = new_window.into_future();
self.run(async move {
WINDOWS.open(new_window);
})
}
}
/// Window extension methods for [`HeadlessApp`].
///
/// [`open_window`]: HeadlessAppWindowExt::open_window
/// [`HeadlessApp`]: zng_app::HeadlessApp
pub trait HeadlessAppWindowExt {
/// Open a new headless window and returns the new window ID.
///
/// The `new_window` runs inside the [`WINDOW`] context of the new window.
///
/// Returns the [`WindowId`] of the new window after the window is open and loaded and has generated one frame
/// or if the window already closed before the first frame.
///
/// [`WINDOW`]: zng_app::window::WINDOW
/// [`WindowId`]: zng_app::window::WindowId
fn open_window<F>(&mut self, new_window: impl IntoFuture<IntoFuture = F>) -> WindowId
where
F: Future<Output = WindowRoot> + Send + 'static;
/// Cause the headless window to think it is focused in the screen.
fn focus_window(&mut self, window_id: WindowId);
/// Cause the headless window to think focus moved away from it.
fn blur_window(&mut self, window_id: WindowId);
/// Copy the current frame pixels of the window.
///
/// The var will update until the image is loaded or error.
fn window_frame_image(&mut self, window_id: WindowId, mask: Option<ImageMaskMode>) -> ImageVar;
/// Sends a close request.
///
/// Returns if the window was found and closed.
fn close_window(&mut self, window_id: WindowId) -> bool;
/// Open a new headless window and update the app until the window closes.
fn run_window<F>(&mut self, new_window: impl IntoFuture<IntoFuture = F>)
where
F: Send + Future<Output = WindowRoot> + 'static;
/// Open a new headless window and update the app until the window closes or 60 seconds elapse.
#[cfg(any(test, doc, feature = "test_util"))]
fn doc_test_window<F>(&mut self, new_window: impl IntoFuture<IntoFuture = F>)
where
F: Future<Output = WindowRoot> + 'static + Send;
}
impl HeadlessAppWindowExt for HeadlessApp {
fn open_window<F>(&mut self, new_window: impl IntoFuture<IntoFuture = F>) -> WindowId
where
F: Future<Output = WindowRoot> + Send + 'static,
{
zng_app::APP.extensions().require::<WindowManager>();
let response = WINDOWS.open(new_window);
self.run_task(async move {
let window_id = response.wait_rsp().await;
if !WINDOWS.is_loaded(window_id) {
let close_rcv = WINDOW_CLOSE_EVENT.receiver();
let frame_rcv = FRAME_IMAGE_READY_EVENT.receiver();
zng_task::any!(
async {
while let Ok(args) = close_rcv.recv_async().await {
if args.windows.contains(&window_id) {
break;
}
}
},
async {
while let Ok(args) = frame_rcv.recv_async().await {
if args.window_id == window_id {
break;
}
}
}
)
.await;
}
window_id
})
.unwrap()
}
fn focus_window(&mut self, window_id: WindowId) {
let args = RawWindowFocusArgs::now(None, Some(window_id));
RAW_WINDOW_FOCUS_EVENT.notify(args);
let _ = self.update(false);
}
fn blur_window(&mut self, window_id: WindowId) {
let args = RawWindowFocusArgs::now(Some(window_id), None);
RAW_WINDOW_FOCUS_EVENT.notify(args);
let _ = self.update(false);
}
fn window_frame_image(&mut self, window_id: WindowId, mask: Option<ImageMaskMode>) -> ImageVar {
WINDOWS.frame_image(window_id, mask)
}
fn close_window(&mut self, window_id: WindowId) -> bool {
use zng_app::view_process::raw_events::*;
let args = RawWindowCloseRequestedArgs::now(window_id);
RAW_WINDOW_CLOSE_REQUESTED_EVENT.notify(args);
let mut requested = false;
let mut closed = false;
let _ = self.update_observe_event(
|update| {
if let Some(args) = WINDOW_CLOSE_REQUESTED_EVENT.on(update) {
requested |= args.windows.contains(&window_id);
} else if let Some(args) = WINDOW_CLOSE_EVENT.on(update) {
closed |= args.windows.contains(&window_id);
}
},
false,
);
assert_eq!(requested, closed);
closed
}
fn run_window<F>(&mut self, new_window: impl IntoFuture<IntoFuture = F>)
where
F: Future<Output = WindowRoot> + Send + 'static,
{
let window_id = self.open_window(new_window);
while WINDOWS.is_open(window_id) {
if let AppControlFlow::Exit = self.update(true) {
return;
}
}
}
#[cfg(any(test, doc, feature = "test_util"))]
fn doc_test_window<F>(&mut self, new_window: impl IntoFuture<IntoFuture = F>)
where
F: Future<Output = WindowRoot> + Send + 'static,
{
use zng_layout::unit::TimeUnits;
use zng_var::Var;
let timer = zng_app::timer::TIMERS.deadline(60.secs());
zng_task::spawn(async {
zng_task::deadline(65.secs()).await;
eprintln!("doc_test_window reached 65s fallback deadline");
zng_env::exit(-1);
});
let window_id = self.open_window(new_window);
while WINDOWS.is_open(window_id) {
if let AppControlFlow::Exit = self.update(true) {
return;
}
if timer.get().has_elapsed() {
panic!("doc_test_window reached 60s deadline");
}
}
}
}