pub use crate::platform::gles::BackgroundOptions;
use crate::{
DrawCommand, Frame, Input, Key as UiKey, KeyInput, MotionPreference, PointerKind, Rect, Ui,
platform::{
gles::{BackgroundMode, Renderer},
profile::{EnvOverrides, FrameSample, InputScript, Profiler, ScriptAction},
},
};
use glutin::{
config::{Api, ConfigTemplateBuilder},
context::{ContextApi, ContextAttributesBuilder, PossiblyCurrentContext, Version},
display::GetGlDisplay,
prelude::*,
surface::{Surface, SurfaceAttributesBuilder, SwapInterval, WindowSurface},
};
use glutin_winit::DisplayBuilder;
use raw_window_handle::HasWindowHandle;
use std::{
collections::VecDeque,
error::Error,
ffi::CString,
num::NonZeroU32,
path::PathBuf,
time::{Duration, Instant},
};
use winit::{
application::ApplicationHandler,
dpi::LogicalSize,
event::{ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
keyboard::{Key, NamedKey},
platform::wayland::{EventLoopBuilderExtWayland, WindowAttributesExtWayland},
window::{Window, WindowId},
};
type Result<T> = std::result::Result<T, Box<dyn Error>>;
pub struct WindowOptions {
pub title: String,
pub app_id: Option<String>,
pub size: [u32; 2],
pub decorations: bool,
pub font: Option<PathBuf>,
pub capture: Option<PathBuf>,
pub motion: MotionPreference,
pub ripple_style: crate::RippleStyle,
pub background: BackgroundOptions,
}
impl Default for WindowOptions {
fn default() -> Self {
Self {
title: "Bhoo".into(),
app_id: None,
size: [420, 360],
decorations: true,
font: None,
capture: None,
motion: MotionPreference::Full,
ripple_style: crate::RippleStyle::default(),
background: BackgroundOptions::default(),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FrameAction {
#[default]
Wait,
Redraw,
BlockClose,
Exit,
}
pub fn run(options: WindowOptions, build: impl FnMut(&mut Frame<'_>) -> FrameAction) -> Result<()> {
run_with_background(options, None, build)
}
pub fn run_with_background(
mut options: WindowOptions,
fragment: Option<&'static str>,
build: impl FnMut(&mut Frame<'_>) -> FrameAction,
) -> Result<()> {
let overrides = EnvOverrides::from_env();
if let Some(size) = overrides.size {
options.size = size;
}
if let Some(scale) = overrides.bg_scale {
options.background.scale = scale;
}
if let Some(interval) = overrides.bg_interval {
options.background.update_interval = interval;
}
if options.size.contains(&0) {
return Err("Window dimensions must be nonzero".into());
}
let event_loop = EventLoop::builder().with_wayland().build()?;
event_loop.set_control_flow(ControlFlow::Wait);
let motion = overrides.apply_motion(options.motion);
let ripple_style = options.ripple_style;
let profiler = Profiler::from_env(&overrides);
let script = InputScript::from_env();
let mut app = App {
options,
overrides,
profiler,
script,
fragment,
build,
ui: Ui {
motion_preference: motion,
ripple_style,
..Ui::default()
},
commands: Vec::new(),
graphics: None,
input: PendingInput::default(),
error: None,
exit_requested: false,
block_close: false,
started: Instant::now(),
next_font_check: Instant::now(),
shift: false,
shortcut_modifier: false,
occluded: false,
pending_resize_ns: None,
pending_wake_deadline_ns: None,
pending_wake_fired_ns: None,
pending_font_check_us: None,
};
event_loop.run_app(&mut app)?;
if let Some(profiler) = app.profiler.as_mut() {
if let Some(graphics) = app.graphics.as_mut() {
let drain_start = Instant::now();
loop {
let timings = graphics.renderer.drain_gpu_timings();
if !timings.is_empty() {
profiler.merge_gpu_timings(&timings);
}
if !graphics.renderer.has_pending_gpu_timings()
|| drain_start.elapsed() >= Duration::from_millis(50)
{
break;
}
std::thread::sleep(Duration::from_millis(2));
}
}
profiler.dump(app.started.elapsed().as_nanos() as u64);
}
app.graphics.take();
match app.error {
Some(error) => Err(error.into()),
None => Ok(()),
}
}
struct Graphics {
renderer: Renderer,
surface: Surface<WindowSurface>,
surface_size: [u32; 2],
context: PossiblyCurrentContext,
window: Window,
}
impl Graphics {
fn new(
event_loop: &ActiveEventLoop,
options: &WindowOptions,
fragment: Option<&str>,
bg_mode: BackgroundMode,
enable_gpu_timers: bool,
) -> Result<Self> {
let font = resolve_font(options.font.as_ref())?;
let app_id = options.app_id.as_deref().unwrap_or("org.spectreos.bhoo");
let attributes = Window::default_attributes()
.with_title(&options.title)
.with_name(app_id, &options.title)
.with_decorations(options.decorations)
.with_inner_size(LogicalSize::new(options.size[0], options.size[1]));
let template = ConfigTemplateBuilder::new()
.with_api(Api::GLES3)
.with_alpha_size(8)
.with_depth_size(0)
.with_stencil_size(0);
let (window, config) = DisplayBuilder::new()
.with_window_attributes(Some(attributes))
.build(event_loop, template, |configs| {
configs
.min_by_key(|config| config.num_samples())
.expect("EGL returned no GLES configs")
})?;
let window = window.ok_or("Wayland window creation returned no window")?;
let handle = window.window_handle()?.as_raw();
let display = config.display();
let attributes = ContextAttributesBuilder::new()
.with_context_api(ContextApi::Gles(Some(Version::new(3, 0))))
.build(Some(handle));
let size = window.inner_size();
let surface_attributes = SurfaceAttributesBuilder::<WindowSurface>::new().build(
handle,
nonzero(size.width),
nonzero(size.height),
);
let (surface, context) = unsafe {
let context = display.create_context(&config, &attributes)?;
let surface = display.create_window_surface(&config, &surface_attributes)?;
let context = context.make_current(&surface)?;
(surface, context)
};
let _ = surface.set_swap_interval(&context, SwapInterval::DontWait);
let gl = unsafe {
glow::Context::from_loader_function(|name| {
display.get_proc_address(&CString::new(name).expect("GL symbol contains NUL"))
})
};
let mut renderer = Renderer::new(gl, &font)?;
renderer.set_background_mode(bg_mode);
if enable_gpu_timers {
renderer.set_gpu_timers(true);
}
if let Some(fragment) = fragment {
renderer.set_background(fragment, options.background)?;
}
Ok(Self {
renderer,
surface,
surface_size: [size.width.max(1), size.height.max(1)],
context,
window,
})
}
}
fn nonzero(value: u32) -> NonZeroU32 {
NonZeroU32::new(value.max(1)).unwrap()
}
fn resolve_font(explicit: Option<&PathBuf>) -> Result<PathBuf> {
if let Some(path) = explicit {
return Ok(path.clone());
}
if let Some(path) = std::env::var_os("BHOO_FONT") {
return Ok(path.into());
}
super::gles::fonts::find_default_primary_font()
.ok_or_else(|| "No default font found. Set BHOO_FONT to a TTF/OTF file.".into())
}
#[derive(Default)]
struct PendingInput {
kind: PointerKind,
touch: Option<u64>,
pointer: Option<[f32; 2]>,
events: VecDeque<Input>,
event_times_ns: VecDeque<Option<u64>>,
}
impl PendingInput {
fn push(&mut self, pressed: bool, released: bool, cancelled: bool) {
self.push_at(pressed, released, cancelled, None);
}
fn push_at(&mut self, pressed: bool, released: bool, cancelled: bool, time_ns: Option<u64>) {
let event = Input {
pointer: self.pointer,
pointer_kind: self.kind,
pressed,
released,
cancelled,
..Input::default()
};
if !pressed
&& !released
&& !cancelled
&& self.events.back().is_some_and(|e| {
!e.pressed
&& !e.released
&& !e.cancelled
&& e.key.is_none()
&& e.scroll == [0.0; 2]
&& !e.blurred
})
{
*self.events.back_mut().unwrap() = event;
if let Some(slot) = self.event_times_ns.back_mut()
&& slot.is_none()
{
*slot = time_ns;
}
} else {
self.events.push_back(event);
self.event_times_ns.push_back(time_ns);
}
}
fn push_event_at(&mut self, event: Input, time_ns: Option<u64>) {
self.events.push_back(event);
self.event_times_ns.push_back(time_ns);
}
fn next_with_time(&mut self) -> (Input, Option<u64>) {
let ns = self.event_times_ns.pop_front().flatten();
let input = self.events.pop_front().unwrap_or(Input {
pointer: self.pointer,
pointer_kind: self.kind,
..Input::default()
});
(input, ns)
}
#[cfg(test)]
fn next(&mut self) -> Input {
self.next_with_time().0
}
fn cancel(&mut self) {
self.touch = None;
self.events.clear();
self.event_times_ns.clear();
self.pointer = None;
self.push(false, false, true);
}
}
struct App<F> {
options: WindowOptions,
overrides: EnvOverrides,
profiler: Option<Profiler>,
script: Option<InputScript>,
fragment: Option<&'static str>,
build: F,
ui: Ui,
commands: Vec<DrawCommand>,
graphics: Option<Graphics>,
input: PendingInput,
error: Option<String>,
exit_requested: bool,
block_close: bool,
started: Instant,
next_font_check: Instant,
shift: bool,
shortcut_modifier: bool,
occluded: bool,
pending_resize_ns: Option<u64>,
pending_wake_deadline_ns: Option<u64>,
pending_wake_fired_ns: Option<u64>,
pending_font_check_us: Option<u32>,
}
impl<F: FnMut(&mut Frame<'_>) -> FrameAction> App<F> {
fn fail(&mut self, event_loop: &ActiveEventLoop, error: impl std::fmt::Display) {
self.error = Some(error.to_string());
event_loop.exit();
}
fn now_ns(&self) -> Option<u64> {
self.profiler
.is_some()
.then(|| self.started.elapsed().as_nanos() as u64)
}
fn draw(&mut self) -> Result<()> {
if self.occluded {
return Ok(());
}
let Some(graphics) = self.graphics.as_mut() else {
return Ok(());
};
let size = graphics.window.inner_size();
if size.width == 0 || size.height == 0 {
return Ok(());
}
if graphics.surface_size != [size.width, size.height] {
graphics.surface.resize(
&graphics.context,
nonzero(size.width),
nonzero(size.height),
);
graphics.surface_size = [size.width, size.height];
}
let profiling = self.profiler.is_some();
let draw_start_ns = if profiling {
self.started.elapsed().as_nanos() as u64
} else {
0
};
let pending_resize_ns = self.pending_resize_ns.take();
let wake_deadline_ns = self.pending_wake_deadline_ns.take();
let wake_fired_ns = self.pending_wake_fired_ns.take();
let font_check_us = self.pending_font_check_us.take();
let scale = graphics.window.scale_factor() as f32;
let logical = size.to_logical::<f32>(scale as f64);
let mut action = FrameAction::Wait;
let (mut input, input_event_ns) = self.input.next_with_time();
input.time = self.started.elapsed().as_secs_f64();
self.ui.viewport = Some(Rect {
x: 0.0,
y: 0.0,
width: logical.width,
height: logical.height,
});
self.ui.frame_into(
input,
Rect {
x: 24.0,
y: 24.0,
width: (logical.width - 48.0).max(0.0),
height: (logical.height - 48.0).max(0.0),
},
12.0,
&mut self.commands,
|frame| action = (self.build)(frame),
);
let ui_build_end_ns = if profiling {
self.started.elapsed().as_nanos() as u64
} else {
0
};
let static_background = self.ui.motion_preference == MotionPreference::Reduced;
graphics.renderer.render_at(
&self.commands,
[size.width, size.height],
scale,
if static_background { 0.0 } else { input.time },
static_background,
)?;
let render_end_ns = if profiling {
self.started.elapsed().as_nanos() as u64
} else {
0
};
self.block_close = action == FrameAction::BlockClose;
if action == FrameAction::Exit
&& let Some(path) = self.options.capture.take()
{
graphics
.renderer
.capture(&path, [size.width, size.height])?;
}
graphics.window.pre_present_notify();
graphics.surface.swap_buffers(&graphics.context)?;
if let Some(profiler) = self.profiler.as_mut() {
let swap_end_ns = self.started.elapsed().as_nanos() as u64;
let gpu_timings = graphics.renderer.drain_gpu_timings();
if !gpu_timings.is_empty() {
profiler.merge_gpu_timings(&gpu_timings);
}
let input_enqueued_ns = match (input_event_ns, pending_resize_ns) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
let action_code = match action {
FrameAction::Wait => 0,
FrameAction::Redraw => 1,
FrameAction::BlockClose => 2,
FrameAction::Exit => 3,
};
let tag = self
.script
.as_ref()
.map_or_else(|| "run".to_string(), |s| s.tag().to_string());
profiler.record_frame(FrameSample {
frame: graphics.renderer.frame_counter(),
tag,
logical_w: logical.width,
logical_h: logical.height,
phys_w: size.width,
phys_h: size.height,
scale,
input_enqueued_ns,
wake_deadline_ns,
wake_fired_ns,
draw_start_ns,
ui_build_end_ns,
render_end_ns,
swap_end_ns,
cmd_count: self.commands.len() as u32,
stats: graphics.renderer.last_stats(),
action: action_code,
needs_redraw: self.ui.needs_redraw(),
font_check_us,
gpu_bg_ns: None,
gpu_fg_ns: None,
gpu_disjoint: false,
});
if profiler.should_exit(swap_end_ns) {
self.exit_requested = true;
}
}
if action == FrameAction::Exit {
self.exit_requested = true;
}
if action == FrameAction::Redraw || self.ui.needs_redraw() || !self.input.events.is_empty()
{
graphics.window.request_redraw();
}
Ok(())
}
}
impl<F: FnMut(&mut Frame<'_>) -> FrameAction> ApplicationHandler for App<F> {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.graphics.is_some() {
return;
}
match Graphics::new(
event_loop,
&self.options,
self.fragment,
self.overrides.bg_mode,
self.profiler.is_some(),
) {
Ok(graphics) => {
if let Some(profiler) = self.profiler.as_mut() {
profiler.set_gl_info(
graphics.renderer.gl_version().to_string(),
graphics.renderer.gl_renderer().to_string(),
graphics.renderer.supports_gpu_timers(),
self.started.elapsed().as_nanos() as u64,
);
}
self.ui.text_metrics = graphics.renderer.text_metrics();
self.ui.text_metrics.system_font = crate::SystemFont::load_session();
graphics.window.request_redraw();
self.graphics = Some(graphics);
}
Err(error) => self.fail(event_loop, error),
}
}
fn suspended(&mut self, _: &ActiveEventLoop) {
self.graphics.take();
self.input.cancel();
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
let now = Instant::now();
let now_ns = now.saturating_duration_since(self.started).as_nanos() as u64;
if self
.profiler
.as_ref()
.is_some_and(|p| p.should_exit(now_ns))
{
event_loop.exit();
return;
}
if let Some(script) = self.script.as_mut() {
let mut needs_script_redraw = false;
let time_ns = self.profiler.is_some().then_some(now_ns);
while let Some(action) = script.pop_due(now_ns) {
match action {
ScriptAction::Tag(_) => {}
ScriptAction::Resize(w, h) => {
if let Some(graphics) = &self.graphics {
if let Some(ns) = time_ns {
self.pending_resize_ns.get_or_insert(ns);
}
let _ = graphics.window.request_inner_size(LogicalSize::new(w, h));
needs_script_redraw = true;
}
}
ScriptAction::Move(x, y) => {
self.input.kind = PointerKind::Mouse;
self.input.pointer = Some([x, y]);
self.input.push_at(false, false, false, time_ns);
needs_script_redraw = true;
}
ScriptAction::Press(x, y) => {
self.input.kind = PointerKind::Mouse;
self.input.pointer = Some([x, y]);
self.input.push_at(true, false, false, time_ns);
needs_script_redraw = true;
}
ScriptAction::Release(x, y) => {
self.input.kind = PointerKind::Mouse;
self.input.pointer = Some([x, y]);
self.input.push_at(false, true, false, time_ns);
needs_script_redraw = true;
}
ScriptAction::Scroll(dx, dy) => {
self.input.push_event_at(
Input {
pointer: self.input.pointer,
scroll: [dx, dy],
..Input::default()
},
time_ns,
);
needs_script_redraw = true;
}
ScriptAction::Key(key, pressed) => {
self.input.push_event_at(
Input {
pointer: self.input.pointer,
key: Some(KeyInput {
key,
pressed,
repeat: false,
shift: false,
}),
..Input::default()
},
time_ns,
);
needs_script_redraw = true;
}
ScriptAction::Exit => {
event_loop.exit();
return;
}
}
}
if needs_script_redraw
&& let Some(graphics) = &self.graphics
{
graphics.window.request_redraw();
}
}
if now >= self.next_font_check {
self.next_font_check = now + Duration::from_secs(1);
let fc_start = self.profiler.is_some().then(Instant::now);
let font = crate::SystemFont::load_session();
if let Some(t0) = fc_start {
self.pending_font_check_us = Some(t0.elapsed().as_micros().min(u32::MAX as u128) as u32);
}
if self.ui.text_metrics.system_font != font {
self.ui.text_metrics.system_font = font;
if let Some(graphics) = &self.graphics {
graphics.window.request_redraw();
}
}
}
let mut next = self.next_font_check;
if let Some(deadline) = self.ui.next_wakeup() {
let dur = Duration::from_secs_f64(deadline.max(0.0));
let when = self.started + dur;
if self.profiler.is_some() {
self.pending_wake_deadline_ns = Some(dur.as_nanos() as u64);
}
if now >= when {
if self.profiler.is_some() && self.pending_wake_fired_ns.is_none() {
self.pending_wake_fired_ns = Some(now_ns);
}
if let Some(graphics) = &self.graphics {
graphics.window.request_redraw();
}
} else {
next = next.min(when);
}
}
if let Some(script_ns) = self.script.as_ref().and_then(InputScript::next_deadline_ns) {
next = next.min(self.started + Duration::from_nanos(script_ns));
}
if let Some(dur) = self.profiler.as_ref().and_then(Profiler::duration_deadline) {
next = next.min(self.started + dur);
}
event_loop.set_control_flow(ControlFlow::WaitUntil(next));
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
let event_now_ns = self.now_ns();
let Some(graphics) = self.graphics.as_ref() else {
return;
};
if graphics.window.id() != id {
return;
}
match event {
WindowEvent::CloseRequested if !self.block_close => event_loop.exit(),
WindowEvent::KeyboardInput { event, .. } => {
let key = match event.logical_key {
Key::Named(NamedKey::Tab) => Some(UiKey::Tab),
Key::Named(NamedKey::Enter) => Some(UiKey::Enter),
Key::Named(NamedKey::Backspace) => Some(UiKey::Character('\u{8}')),
Key::Named(NamedKey::Space) => Some(UiKey::Space),
Key::Named(NamedKey::ArrowLeft) => Some(UiKey::Left),
Key::Named(NamedKey::ArrowRight) => Some(UiKey::Right),
Key::Named(NamedKey::ArrowUp) => Some(UiKey::Up),
Key::Named(NamedKey::ArrowDown) => Some(UiKey::Down),
Key::Named(NamedKey::Home) => Some(UiKey::Home),
Key::Named(NamedKey::End) => Some(UiKey::End),
Key::Named(NamedKey::PageUp) => Some(UiKey::PageUp),
Key::Named(NamedKey::PageDown) => Some(UiKey::PageDown),
Key::Named(NamedKey::Escape) => Some(UiKey::Escape),
Key::Named(NamedKey::ContextMenu) => Some(UiKey::Menu),
Key::Named(NamedKey::F10) if self.shift => Some(UiKey::Menu),
Key::Character(ref value) if !self.shortcut_modifier => {
let mut chars = value.chars();
chars
.next()
.filter(|c| !c.is_control())
.filter(|_| chars.next().is_none())
.map(UiKey::Character)
}
_ => None,
};
if let Some(key) = key {
if key == UiKey::Escape
&& event.state == ElementState::Pressed
&& !self.ui.has_escape_target()
&& !self.block_close
{
event_loop.exit();
} else {
self.input.push_event_at(
Input {
pointer: self.input.pointer,
key: Some(KeyInput {
key,
pressed: event.state == ElementState::Pressed,
repeat: event.repeat,
shift: self.shift,
}),
..Input::default()
},
event_now_ns,
);
graphics.window.request_redraw();
}
}
}
WindowEvent::ModifiersChanged(modifiers) => {
let state = modifiers.state();
self.shift = state.shift_key();
self.shortcut_modifier =
state.control_key() || state.alt_key() || state.super_key();
}
WindowEvent::MouseWheel { delta, .. } => {
let scroll = match delta {
MouseScrollDelta::LineDelta(x, y) => [-x * 40.0, -y * 40.0],
MouseScrollDelta::PixelDelta(p) => {
let p = p.to_logical::<f32>(graphics.window.scale_factor());
[-p.x, -p.y]
}
};
self.input.push_event_at(
Input {
pointer: self.input.pointer,
scroll,
..Input::default()
},
event_now_ns,
);
graphics.window.request_redraw();
}
WindowEvent::Resized(size) => {
if size.width > 0 && size.height > 0 {
if let Some(ns) = event_now_ns {
self.pending_resize_ns.get_or_insert(ns);
}
if let Some(graphics) = self.graphics.as_mut() {
graphics.surface.resize(
&graphics.context,
nonzero(size.width),
nonzero(size.height),
);
graphics.surface_size = [size.width, size.height];
graphics.window.request_redraw();
}
}
}
WindowEvent::ScaleFactorChanged { .. } => {
if let Some(ns) = event_now_ns {
self.pending_resize_ns.get_or_insert(ns);
}
self.input.cancel();
graphics.window.request_redraw();
}
WindowEvent::Occluded(occluded) => {
self.occluded = occluded;
if occluded {
self.ui.pause_animations();
self.input.cancel();
event_loop.set_control_flow(ControlFlow::Wait);
} else {
graphics.window.request_redraw();
}
}
WindowEvent::Touch(touch) => {
let owned = self.input.touch == Some(touch.id);
if touch.phase == TouchPhase::Started && self.input.touch.is_none() {
self.input.touch = Some(touch.id);
}
if owned || self.input.touch == Some(touch.id) {
let p = touch
.location
.to_logical::<f32>(graphics.window.scale_factor());
self.input.pointer = Some([p.x, p.y]);
self.input.kind = PointerKind::Touch;
match touch.phase {
TouchPhase::Started => self.input.push_at(true, false, false, event_now_ns),
TouchPhase::Moved => self.input.push_at(false, false, false, event_now_ns),
TouchPhase::Ended => {
self.input.push_at(false, true, false, event_now_ns);
self.input.touch = None;
self.input.pointer = None;
}
TouchPhase::Cancelled => {
self.input.cancel();
self.input.touch = None;
}
}
graphics.window.request_redraw();
}
}
WindowEvent::CursorMoved { position, .. } if self.input.touch.is_none() => {
self.input.kind = PointerKind::Mouse;
let p = position.to_logical::<f32>(graphics.window.scale_factor());
self.input.pointer = Some([p.x, p.y]);
self.input.push_at(false, false, false, event_now_ns);
graphics.window.request_redraw();
}
WindowEvent::Focused(false) => {
self.input.cancel();
if let Some(input) = self.input.events.back_mut() {
input.blurred = true;
}
self.shift = false;
graphics.window.request_redraw();
}
WindowEvent::CursorLeft { .. } if self.input.touch.is_none() => {
self.input.cancel();
graphics.window.request_redraw();
}
WindowEvent::MouseInput {
state: ElementState::Pressed,
button: MouseButton::Right,
..
} if self.input.touch.is_none() => {
self.input.push_event_at(
Input {
pointer: self.input.pointer,
key: Some(KeyInput {
key: UiKey::Menu,
pressed: true,
repeat: false,
shift: self.shift,
}),
..Input::default()
},
event_now_ns,
);
graphics.window.request_redraw();
}
WindowEvent::MouseInput {
state,
button: MouseButton::Left,
..
} if self.input.touch.is_none() => {
self.input.kind = PointerKind::Mouse;
self.input.push_at(
state == ElementState::Pressed,
state == ElementState::Released,
false,
event_now_ns,
);
graphics.window.request_redraw();
}
WindowEvent::RedrawRequested => {
if let Err(error) = self.draw() {
self.fail(event_loop, error);
}
if self.exit_requested {
event_loop.exit();
}
}
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn input_keeps_fast_click_edges_in_order() {
let mut input = PendingInput {
pointer: Some([10.0, 10.0]),
..Default::default()
};
input.push(true, false, false);
input.push(false, true, false);
assert!(input.next().pressed);
assert!(input.next().released);
assert!(!input.next().released);
}
#[test]
fn focus_loss_discards_pending_clicks() {
let mut input = PendingInput::default();
input.push(true, false, false);
input.cancel();
assert!(input.next().cancelled);
assert!(input.events.is_empty());
}
#[test]
fn pointer_motion_coalesces() {
let mut input = PendingInput::default();
for i in 0..100 {
input.pointer = Some([i as f32, 0.0]);
input.push(false, false, false);
}
assert_eq!(input.events.len(), 1);
assert_eq!(input.next().pointer, Some([99.0, 0.0]));
}
}