use std::ops::{Deref, DerefMut};
use anyhow::Result;
use crate::{
app::{self, Input, Runtime},
config::WindowConfig,
gfx,
};
pub use app::{WindowError, WindowedTask};
pub fn create_windowed_task<T, F>(
rt: &Runtime,
config: WindowConfig,
window_fn: F,
) -> WindowedTask<Result<T, gfx::Error>>
where
T: 'static,
F: AsyncFnOnce(Window<'_>) -> T + 'static,
{
app::create_windowed_task(rt, config.app, async move |app_window| {
let window = Window::new(app_window, config.gfx).await?;
Ok(window_fn(window).await)
})
}
pub async fn within_window<T, F>(config: WindowConfig, window_fn: F) -> Result<T>
where
T: 'static,
F: AsyncFnOnce(Window<'_>) -> Result<T> + 'static,
{
create_windowed_task(&Runtime::current(), config, window_fn).await??
}
pub struct Window<'a> {
gfx: gfx::Surface<'a>,
app: app::Window<'a>,
pending_resize: Option<(u32, u32)>,
host_input: crate::host_input::PlainInput,
update_events: Input,
last_scale: f64,
}
impl<'a> Window<'a> {
async fn new(app: app::Window<'a>, gfx_cfg: gfx::Config) -> Result<Self> {
let display = Runtime::current()
.run_within_event_loop(
|event_loop| event_loop.owned_display_handle(),
Default::default(),
)
.await;
let mut gfx = gfx::Surface::with_display_handle(gfx_cfg, app.raw(), display).await?;
gfx.resize(app.size());
let pending_resize = Some(app.size());
let host_input = crate::host_input::PlainInput::new(app.input(), app.raw().has_focus());
let last_scale = app.scale_factor();
let mut update_events = app.input();
update_events.set_include_redraws(true);
Ok(Self {
host_input,
update_events,
last_scale,
app,
gfx,
pending_resize,
})
}
pub fn raw(&self) -> &'a app::RawWindow {
self.app.raw()
}
pub fn scale_factor(&self) -> f64 {
self.app.scale_factor()
}
pub fn input(&self) -> Input {
self.app.input()
}
pub async fn wait_for_update(&mut self, timeout: Option<std::time::Duration>) {
use futures::{StreamExt, future};
if timeout == Some(std::time::Duration::ZERO) {
return;
}
let deadline = timeout.and_then(|delay| app::time::Instant::now().checked_add(delay));
let timer = async {
if let Some(deadline) = deadline {
app::runtime::sleep_until(deadline).await;
} else {
future::pending::<()>().await;
}
};
future::select(Box::pin(self.update_events.next()), Box::pin(timer)).await;
}
pub async fn next_frame(&mut self) -> Result<Option<Frame<'a, '_>>> {
loop {
let Some(redraw) = self.app.request_redraw().await else {
return Ok(None);
};
if let Some(size) = redraw.resized() {
self.gfx.resize(size);
self.pending_resize = Some(size);
}
if !self.gfx.prepare_frame()? {
continue;
}
let changed = self.pending_resize.is_some() || self.last_scale != redraw.scale_factor();
let mut input = self.host_input.collect(redraw.scale_factor(), changed);
if input.focused
&& !input
.events
.iter()
.any(|event| matches!(event, crate::canvas::Event::Cancelled))
{
let (x, y) = redraw.mouse_motion();
input.relative_motion = glam::Vec2::new(x as f32, y as f32);
}
self.last_scale = redraw.scale_factor();
while self.update_events.try_next().is_some() {}
return Ok(Some(Frame {
input,
app: redraw,
gfx: Some(self.gfx.frame()?),
resized: self.pending_resize.take(),
}));
}
}
pub fn graphics(&self) -> &gfx::Graphics {
self.gfx.state()
}
}
pub struct Frame<'a, 'b> {
gfx: Option<gfx::Frame<'a, 'b>>,
app: app::window::Redraw<'b>,
resized: Option<(u32, u32)>,
input: crate::canvas::CanvasInput,
}
impl<'a, 'b> Deref for Frame<'a, 'b> {
type Target = gfx::Frame<'a, 'b>;
fn deref(&self) -> &Self::Target {
self.gfx.as_ref().unwrap()
}
}
impl DerefMut for Frame<'_, '_> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.gfx.as_mut().unwrap()
}
}
impl Drop for Frame<'_, '_> {
fn drop(&mut self) {
if !std::thread::panicking() {
self.present_inner();
}
}
}
impl Frame<'_, '_> {
pub fn input(&self) -> &crate::canvas::CanvasInput {
&self.input
}
fn present_inner(&mut self) {
if let Some(frame) = self.gfx.take() {
self.app.pre_present();
frame.present();
}
}
pub fn present(mut self) {
self.present_inner();
}
pub fn discard(mut self) {
self.gfx.take();
}
pub fn scale_factor(&self) -> f64 {
self.app.scale_factor()
}
pub fn logical_size(&self) -> (f64, f64) {
self.app.logical_size()
}
pub fn logical_camera(&mut self) -> gfx::Camera {
let scale_factor = self.scale_factor();
logical_camera(&mut **self, scale_factor)
}
pub fn size(&self) -> (u32, u32) {
self.app.size()
}
pub fn resized(&self) -> Option<(u32, u32)> {
self.resized
}
}
fn logical_camera(target: &mut impl gfx::Target, scale_factor: f64) -> gfx::Camera {
use gfx::prelude::Transformable;
target
.physical_camera()
.transform(glam::Affine2::from_scale(glam::Vec2::splat(
scale_factor as f32,
)))
}
#[cfg(test)]
#[path = "window/tests.rs"]
mod tests;
impl gfx::Target for Frame<'_, '_> {
fn state(&self) -> &gfx::Graphics {
gfx::Target::state(&**self)
}
fn view(&self) -> &wgpu::TextureView {
gfx::Target::view(&**self)
}
fn depth_view(&self) -> &wgpu::TextureView {
gfx::Target::depth_view(&**self)
}
fn encoder(&mut self) -> &mut wgpu::CommandEncoder {
gfx::Target::encoder(&mut **self)
}
}
impl crate::ContentFrame for Frame<'_, '_> {
fn input(&self) -> &crate::canvas::CanvasInput {
self.input()
}
fn scale_factor(&self) -> f64 {
self.scale_factor()
}
fn resized(&self) -> Option<(u32, u32)> {
self.resized()
}
fn present(self) {
self.present();
}
fn discard(self) {
self.discard();
}
}
impl<'w> crate::WindowHost for Window<'w> {
type Frame<'a>
= Frame<'w, 'a>
where
Self: 'a;
fn graphics(&self) -> &gfx::Graphics {
self.graphics()
}
async fn wait_for_update(&mut self, timeout: Option<std::time::Duration>) {
self.wait_for_update(timeout).await;
}
async fn next_frame(&mut self) -> Result<Option<Self::Frame<'_>>> {
self.next_frame().await
}
}