chore(rustfmt): use nightly (#2325)

Stable rustfmt lacks a lot of features resulting in worse formatted
code, thus use nightly formatter.
This commit is contained in:
Kirill Chibisov 2024-04-26 19:11:44 +04:00 committed by GitHub
parent 7006c7ceca
commit 7b0c7b6cb2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
154 changed files with 3439 additions and 5891 deletions

View file

@ -19,10 +19,7 @@ pub struct Abortable<F: Future> {
impl<F: Future> Abortable<F> {
pub fn new(handle: AbortHandle, future: F) -> Self {
Self {
future,
shared: handle.0,
}
Self { future, shared: handle.0 }
}
}
@ -59,10 +56,7 @@ pub struct AbortHandle(Arc<Shared>);
impl AbortHandle {
pub fn new() -> Self {
Self(Arc::new(Shared {
waker: AtomicWaker::new(),
aborted: AtomicBool::new(false),
}))
Self(Arc::new(Shared { waker: AtomicWaker::new(), aborted: AtomicBool::new(false) }))
}
pub fn abort(&self) {

View file

@ -9,19 +9,11 @@ use super::AtomicWaker;
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let (sender, receiver) = mpsc::channel();
let shared = Arc::new(Shared {
closed: AtomicBool::new(false),
waker: AtomicWaker::new(),
});
let shared = Arc::new(Shared { closed: AtomicBool::new(false), waker: AtomicWaker::new() });
let sender = Sender(Arc::new(SenderInner {
sender: Mutex::new(sender),
shared: Arc::clone(&shared),
}));
let receiver = Receiver {
receiver: Rc::new(receiver),
shared,
};
let sender =
Sender(Arc::new(SenderInner { sender: Mutex::new(sender), shared: Arc::clone(&shared) }));
let receiver = Receiver { receiver: Rc::new(receiver), shared };
(sender, receiver)
}
@ -85,10 +77,10 @@ impl<T> Receiver<T> {
} else {
Poll::Pending
}
}
},
Err(TryRecvError::Disconnected) => Poll::Ready(Err(RecvError)),
}
}
},
Err(TryRecvError::Disconnected) => Poll::Ready(Err(RecvError)),
})
.await
@ -105,10 +97,7 @@ impl<T> Receiver<T> {
impl<T> Clone for Receiver<T> {
fn clone(&self) -> Self {
Self {
receiver: Rc::clone(&self.receiver),
shared: Arc::clone(&self.shared),
}
Self { receiver: Rc::clone(&self.receiver), shared: Arc::clone(&self.shared) }
}
}

View file

@ -19,10 +19,7 @@ pub enum PopError {
impl<T> ConcurrentQueue<T> {
pub fn unbounded() -> Self {
Self {
queue: RefCell::new(Vec::new()),
closed: Cell::new(false),
}
Self { queue: RefCell::new(Vec::new()), closed: Cell::new(false) }
}
pub fn push(&self, value: T) -> Result<(), PushError<T>> {

View file

@ -1,9 +1,7 @@
use super::super::main_thread::MainThreadMarker;
use super::{channel, Receiver, Sender, Wrapper};
use std::{
cell::Ref,
sync::{Arc, Condvar, Mutex},
};
use std::cell::Ref;
use std::sync::{Arc, Condvar, Mutex};
pub struct Dispatcher<T: 'static>(Wrapper<T, Sender<Closure<T>>, Closure<T>>);
@ -18,24 +16,25 @@ impl<T> Dispatcher<T> {
main_thread,
value,
|value, Closure(closure)| {
// SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do anything
// funny with it here. See `Self::queue()`.
// SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do
// anything funny with it here. See `Self::queue()`.
closure(value.borrow().as_ref().unwrap())
},
{
let receiver = receiver.clone();
move |value| async move {
while let Ok(Closure(closure)) = receiver.next().await {
// SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do anything
// funny with it here. See `Self::queue()`.
// SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't
// do anything funny with it here. See
// `Self::queue()`.
closure(value.borrow().as_ref().unwrap())
}
}
},
sender,
|sender, closure| {
// SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do anything
// funny with it here. See `Self::queue()`.
// SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do
// anything funny with it here. See `Self::queue()`.
sender.send(closure).unwrap()
},
)
@ -91,19 +90,12 @@ pub struct DispatchRunner<T: 'static> {
impl<T> DispatchRunner<T> {
pub fn run(&self) {
while let Some(Closure(closure)) = self
.receiver
.try_recv()
.expect("should only be closed when `Dispatcher` is dropped")
while let Some(Closure(closure)) =
self.receiver.try_recv().expect("should only be closed when `Dispatcher` is dropped")
{
// SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do anything
// funny with it here. See `Self::queue()`.
closure(
&self
.wrapper
.value()
.expect("don't call this outside the main thread"),
)
closure(&self.wrapper.value().expect("don't call this outside the main thread"))
}
}
}

View file

@ -1,10 +1,7 @@
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::OnceLock;
use std::task::Context;
use std::task::Poll;
use std::task::Waker;
use std::sync::{Arc, OnceLock};
use std::task::{Context, Poll, Waker};
use super::{ConcurrentQueue, PushError};
@ -13,10 +10,7 @@ pub struct Notifier<T: Clone>(Arc<Inner<T>>);
impl<T: Clone> Notifier<T> {
pub fn new() -> Self {
Self(Arc::new(Inner {
queue: ConcurrentQueue::unbounded(),
value: OnceLock::new(),
}))
Self(Arc::new(Inner { queue: ConcurrentQueue::unbounded(), value: OnceLock::new() }))
}
pub fn notify(self, value: T) {
@ -52,11 +46,11 @@ impl<T: Clone> Future for Notified<T> {
self.0 = Some(this);
return Poll::Pending;
}
}
},
Err(PushError::Closed(_)) => (),
Err(PushError::Full(_)) => {
unreachable!("found full queue despite using unbounded queue")
}
},
}
}

View file

@ -92,8 +92,7 @@ impl<T> WakerSpawner<T> {
"this should only be called from the main thread"
);
self.0
.with_sender_data(|inner| inner.0.counter.swap(0, Ordering::Relaxed))
self.0.with_sender_data(|inner| inner.0.counter.swap(0, Ordering::Relaxed))
}
}

View file

@ -17,10 +17,9 @@ struct Value<V> {
// SAFETY:
// This value must not be accessed if not on the main thread.
//
// - We wrap this in an `Arc` to allow it to be safely cloned without
// accessing the value.
// - The `RefCell` lets us mutably access in the main thread but is safe to
// drop in any thread because it has no `Drop` behavior.
// - We wrap this in an `Arc` to allow it to be safely cloned without accessing the value.
// - The `RefCell` lets us mutably access in the main thread but is safe to drop in any thread
// because it has no `Drop` behavior.
// - The `Option` lets us safely drop `T` only in the main thread.
value: Arc<RefCell<Option<V>>>,
// Prevent's `Send` or `Sync` to be automatically implemented.
@ -53,10 +52,7 @@ impl<V, S: Clone + Send, E> Wrapper<V, S, E> {
});
Some(Self {
value: Value {
value,
local: PhantomData,
},
value: Value { value, local: PhantomData },
handler,
sender_data,
sender_handler,
@ -84,10 +80,7 @@ impl<V, S: Clone + Send, E> Wrapper<V, S, E> {
impl<V, S: Clone + Send, E> Clone for Wrapper<V, S, E> {
fn clone(&self) -> Self {
Self {
value: Value {
value: self.value.value.clone(),
local: PhantomData,
},
value: Value { value: self.value.value.clone(), local: PhantomData },
handler: self.handler,
sender_data: self.sender_data.clone(),
sender_handler: self.sender_handler,

View file

@ -11,8 +11,9 @@ use std::time::Duration;
use cursor_icon::CursorIcon;
use js_sys::{Array, Object};
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{closure::Closure, JsCast};
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::{
Blob, Document, DomException, HtmlCanvasElement, HtmlImageElement, ImageBitmap,
@ -29,15 +30,8 @@ use crate::platform::web::CustomCursorError;
#[derive(Debug)]
pub(crate) enum CustomCursorSource {
Image(CursorImage),
Url {
url: String,
hotspot_x: u16,
hotspot_y: u16,
},
Animation {
duration: Duration,
cursors: Vec<RootCustomCursor>,
},
Url { url: String, hotspot_x: u16, hotspot_y: u16 },
Animation { duration: Duration, cursors: Vec<RootCustomCursor> },
}
impl CustomCursorSource {
@ -79,18 +73,10 @@ impl CustomCursor {
match source {
CustomCursorSource::Image(image) => Self::build_spawn(
event_loop,
from_rgba(
event_loop.runner.window(),
event_loop.runner.document().clone(),
&image,
),
from_rgba(event_loop.runner.window(), event_loop.runner.document().clone(), &image),
false,
),
CustomCursorSource::Url {
url,
hotspot_x,
hotspot_y,
} => Self::build_spawn(
CustomCursorSource::Url { url, hotspot_x, hotspot_y } => Self::build_spawn(
event_loop,
from_url(UrlType::Plain(url), hotspot_x, hotspot_y),
false,
@ -130,9 +116,7 @@ impl CustomCursor {
async move {
let result = task.await;
let this = weak
.upgrade()
.expect("`CursorHandler` invalidated without aborting");
let this = weak.upgrade().expect("`CursorHandler` invalidated without aborting");
let mut this = this.get(main_thread).borrow_mut();
match result {
@ -143,7 +127,7 @@ impl CustomCursor {
unreachable!("found invalid state");
};
notifier.notify(Ok(()));
}
},
Err(error) => {
let ImageState::Loading { notifier, .. } =
mem::replace(this.deref_mut(), ImageState::Failed(error.clone()))
@ -151,7 +135,7 @@ impl CustomCursor {
unreachable!("found invalid state");
};
notifier.notify(Err(error));
}
},
}
}
});
@ -175,11 +159,7 @@ impl CustomCursor {
let notified = notifier.notified();
drop(binding);
CustomCursorFuture {
notified,
animation,
state: Some(state),
}
CustomCursorFuture { notified, animation, state: Some(state) }
}
}
@ -199,15 +179,9 @@ impl Future for CustomCursorFuture {
}
let result = ready!(Pin::new(&mut self.notified).poll(cx));
let state = self
.state
.take()
.expect("`CustomCursorFuture` polled after completion");
let state = self.state.take().expect("`CustomCursorFuture` polled after completion");
Poll::Ready(result.map(|_| CustomCursor {
animation: self.animation,
state,
}))
Poll::Ready(result.map(|_| CustomCursor { animation: self.animation, state }))
}
}
@ -244,10 +218,8 @@ impl CursorHandler {
match cursor {
Cursor::Icon(icon) => {
if let SelectedCursor::Icon(old_icon)
| SelectedCursor::Loading {
previous: Previous::Icon(old_icon),
..
} = &this.cursor
| SelectedCursor::Loading { previous: Previous::Icon(old_icon), .. } =
&this.cursor
{
if *old_icon == icon {
return;
@ -256,17 +228,13 @@ impl CursorHandler {
this.cursor = SelectedCursor::Icon(icon);
this.set_style();
}
},
Cursor::Custom(cursor) => {
let cursor = cursor.inner;
if let SelectedCursor::Loading {
cursor: old_cursor, ..
}
if let SelectedCursor::Loading { cursor: old_cursor, .. }
| SelectedCursor::Image(old_cursor)
| SelectedCursor::Animation {
cursor: old_cursor, ..
} = &this.cursor
| SelectedCursor::Animation { cursor: old_cursor, .. } = &this.cursor
{
if *old_cursor == cursor {
return;
@ -299,17 +267,17 @@ impl CursorHandler {
previous: mem::take(&mut this.cursor).into(),
_handle: handle,
};
}
},
ImageState::Failed(error) => {
tracing::error!(
"trying to load custom cursor that has failed to load: {error}"
)
}
},
ImageState::Image(_) => {
drop(state);
this.cursor = SelectedCursor::Image(cursor);
this.set_style();
}
},
ImageState::Animation(animation) => {
let canvas: &CanvasAnimateExt = this.canvas.unchecked_ref();
let animation = canvas.animate_with_keyframe_animation_options(
@ -327,9 +295,9 @@ impl CursorHandler {
cursor,
};
this.set_style();
}
},
};
}
},
}
}
@ -355,37 +323,29 @@ impl Inner {
if self.visible {
match &self.cursor {
SelectedCursor::Icon(icon)
| SelectedCursor::Loading {
previous: Previous::Icon(icon),
..
} => self.style.set("cursor", icon.name()),
SelectedCursor::Loading {
previous: Previous::Image(cursor),
..
}
| SelectedCursor::Loading { previous: Previous::Icon(icon), .. } => {
self.style.set("cursor", icon.name())
},
SelectedCursor::Loading { previous: Previous::Image(cursor), .. }
| SelectedCursor::Image(cursor) => {
match cursor.state.get(self.main_thread).borrow().deref() {
ImageState::Image(Image { style, .. }) => self.style.set("cursor", style),
_ => unreachable!("found invalid saved state"),
}
}
},
SelectedCursor::Loading {
previous: Previous::Animation { animation, .. },
..
previous: Previous::Animation { animation, .. }, ..
}
| SelectedCursor::Animation { animation, .. } => {
self.style.remove("cursor");
animation.0.play()
}
},
}
}
}
fn notify(&mut self) {
let SelectedCursor::Loading {
cursor, previous, ..
} = mem::take(&mut self.cursor)
else {
let SelectedCursor::Loading { cursor, previous, .. } = mem::take(&mut self.cursor) else {
unreachable!("found wrong state")
};
@ -395,7 +355,7 @@ impl Inner {
drop(state);
self.cursor = SelectedCursor::Image(cursor);
self.set_style();
}
},
ImageState::Animation(animation) => {
let canvas: &CanvasAnimateExt = self.canvas.unchecked_ref();
let animation = canvas.animate_with_keyframe_animation_options(
@ -408,16 +368,14 @@ impl Inner {
animation.cancel();
}
self.cursor = SelectedCursor::Animation {
animation: AnimationDropper(animation),
cursor,
};
self.cursor =
SelectedCursor::Animation { animation: AnimationDropper(animation), cursor };
self.set_style();
}
},
ImageState::Failed(error) => {
tracing::error!("custom cursor failed to load: {error}");
self.cursor = previous.into()
}
},
ImageState::Loading { .. } => unreachable!("notified without being ready"),
}
}
@ -426,16 +384,9 @@ impl Inner {
#[derive(Debug)]
enum SelectedCursor {
Icon(CursorIcon),
Loading {
cursor: CustomCursor,
previous: Previous,
_handle: DropAbortHandle,
},
Loading { cursor: CustomCursor, previous: Previous, _handle: DropAbortHandle },
Image(CustomCursor),
Animation {
cursor: CustomCursor,
animation: AnimationDropper,
},
Animation { cursor: CustomCursor, animation: AnimationDropper },
}
impl Default for SelectedCursor {
@ -458,10 +409,7 @@ impl From<Previous> for SelectedCursor {
enum Previous {
Icon(CursorIcon),
Image(CustomCursor),
Animation {
cursor: CustomCursor,
animation: AnimationDropper,
},
Animation { cursor: CustomCursor, animation: AnimationDropper },
}
impl From<SelectedCursor> for Previous {
@ -472,17 +420,14 @@ impl From<SelectedCursor> for Previous {
SelectedCursor::Image(image) => Self::Image(image),
SelectedCursor::Animation { cursor, animation } => {
Self::Animation { cursor, animation }
}
},
}
}
}
#[derive(Debug)]
enum ImageState {
Loading {
notifier: Notifier<Result<(), CustomCursorError>>,
_handle: DropAbortHandle,
},
Loading { notifier: Notifier<Result<(), CustomCursorError>>, _handle: DropAbortHandle },
Failed(CustomCursorError),
Image(Image),
Animation(Animation),
@ -601,23 +546,13 @@ fn from_rgba(
.expect("unexpected exception in `createImageBitmap()`"),
);
let CursorImage {
width,
height,
hotspot_x,
hotspot_y,
..
} = *image;
let CursorImage { width, height, hotspot_x, hotspot_y, .. } = *image;
async move {
let bitmap: ImageBitmap = bitmap
.await
.expect("found invalid state in `ImageData`")
.unchecked_into();
let bitmap: ImageBitmap =
bitmap.await.expect("found invalid state in `ImageData`").unchecked_into();
let canvas: HtmlCanvasElement = document
.create_element("canvas")
.expect("invalid tag name")
.unchecked_into();
let canvas: HtmlCanvasElement =
document.create_element("canvas").expect("invalid tag name").unchecked_into();
#[allow(clippy::disallowed_methods)]
canvas.set_width(width as u32);
#[allow(clippy::disallowed_methods)]
@ -724,7 +659,7 @@ async fn from_animation(
let notified = notifier.notified();
drop(state);
notified.await?;
}
},
ImageState::Failed(error) => return Err(error.clone()),
ImageState::Image(_) => drop(state),
ImageState::Animation(_) => unreachable!("check in `CustomCursorSource` failed"),
@ -750,11 +685,7 @@ async fn from_animation(
options.set_duration(duration.as_millis() as f64);
options.set_iterations(f64::INFINITY);
Ok(Animation {
keyframes,
options,
_images: images,
})
Ok(Animation { keyframes, options, _images: images })
}
#[wasm_bindgen]

View file

@ -27,25 +27,15 @@ pub(crate) struct PlatformSpecificEventLoopAttributes {}
impl<T> EventLoop<T> {
pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> Result<Self, EventLoopError> {
let (user_event_sender, user_event_receiver) = mpsc::channel();
let elw = RootActiveEventLoop {
p: ActiveEventLoop::new(),
_marker: PhantomData,
};
Ok(EventLoop {
elw,
user_event_sender,
user_event_receiver,
})
let elw = RootActiveEventLoop { p: ActiveEventLoop::new(), _marker: PhantomData };
Ok(EventLoop { elw, user_event_sender, user_event_receiver })
}
pub fn run<F>(self, mut event_handler: F) -> !
where
F: FnMut(Event<T>, &RootActiveEventLoop),
{
let target = RootActiveEventLoop {
p: self.elw.p.clone(),
_marker: PhantomData,
};
let target = RootActiveEventLoop { p: self.elw.p.clone(), _marker: PhantomData };
// SAFETY: Don't use `move` to make sure we leak the `event_handler` and `target`.
let handler: Box<dyn FnMut(Event<()>)> = Box::new(|event| {
@ -79,10 +69,7 @@ impl<T> EventLoop<T> {
where
F: 'static + FnMut(Event<T>, &RootActiveEventLoop),
{
let target = RootActiveEventLoop {
p: self.elw.p.clone(),
_marker: PhantomData,
};
let target = RootActiveEventLoop { p: self.elw.p.clone(), _marker: PhantomData };
self.elw.p.run(
Box::new(move |event| {

View file

@ -16,9 +16,7 @@ impl<T: 'static> EventLoopProxy<T> {
}
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
self.sender
.send(event)
.map_err(|SendError(event)| EventLoopClosed(event))?;
self.sender.send(event).map_err(|SendError(event)| EventLoopClosed(event))?;
self.runner.wake();
Ok(())
}
@ -26,9 +24,6 @@ impl<T: 'static> EventLoopProxy<T> {
impl<T: 'static> Clone for EventLoopProxy<T> {
fn clone(&self) -> Self {
Self {
runner: self.runner.clone(),
sender: self.sender.clone(),
}
Self { runner: self.runner.clone(), sender: self.sender.clone() }
}
}

View file

@ -1,6 +1,7 @@
use super::super::main_thread::MainThreadMarker;
use super::super::DeviceId;
use super::{backend, state::State};
use super::backend;
use super::state::State;
use crate::dpi::PhysicalSize;
use crate::event::{
DeviceEvent, DeviceId as RootDeviceId, ElementState, Event, RawKeyEvent, StartCause,
@ -13,13 +14,11 @@ use crate::platform_impl::platform::r#async::{DispatchRunner, Waker, WakerSpawne
use crate::platform_impl::platform::window::Inner;
use crate::window::WindowId;
use std::{
cell::{Cell, RefCell},
collections::{HashSet, VecDeque},
iter,
ops::Deref,
rc::{Rc, Weak},
};
use std::cell::{Cell, RefCell};
use std::collections::{HashSet, VecDeque};
use std::iter;
use std::ops::Deref;
use std::rc::{Rc, Weak};
use wasm_bindgen::prelude::Closure;
use web_sys::{Document, KeyboardEvent, PageTransitionEvent, PointerEvent, WheelEvent};
use web_time::{Duration, Instant};
@ -50,13 +49,7 @@ pub struct Execution {
window: web_sys::Window,
document: Document,
#[allow(clippy::type_complexity)]
all_canvases: RefCell<
Vec<(
WindowId,
Weak<RefCell<backend::Canvas>>,
DispatchRunner<Inner>,
)>,
>,
all_canvases: RefCell<Vec<(WindowId, Weak<RefCell<backend::Canvas>>, DispatchRunner<Inner>)>>,
redraw_pending: RefCell<HashSet<WindowId>>,
destroy_pending: RefCell<VecDeque<WindowId>>,
page_transition_event_handle: RefCell<Option<backend::PageTransitionEventHandle>>,
@ -97,10 +90,7 @@ struct Runner {
impl Runner {
pub fn new(event_handler: Box<EventHandler>) -> Self {
Runner {
state: State::Init,
event_handler,
}
Runner { state: State::Init, event_handler }
}
/// Returns the corresponding `StartCause` for the current `state`, or `None`
@ -109,13 +99,9 @@ impl Runner {
Some(match self.state {
State::Init => StartCause::Init,
State::Poll { .. } => StartCause::Poll,
State::Wait { start } => StartCause::WaitCancelled {
start,
requested_resume: None,
},
State::WaitUntil { start, end, .. } => StartCause::WaitCancelled {
start,
requested_resume: Some(end),
State::Wait { start } => StartCause::WaitCancelled { start, requested_resume: None },
State::WaitUntil { start, end, .. } => {
StartCause::WaitCancelled { start, requested_resume: Some(end) }
},
State::Exit => return None,
})
@ -124,11 +110,7 @@ impl Runner {
fn handle_single_event(&mut self, runner: &Shared, event: impl Into<EventWrapper>) {
match event.into() {
EventWrapper::Event(event) => (self.event_handler)(event),
EventWrapper::ScaleChange {
canvas,
size,
scale,
} => {
EventWrapper::ScaleChange { canvas, size, scale } => {
if let Some(canvas) = canvas.upgrade() {
canvas.borrow().handle_scale_change(
runner,
@ -137,7 +119,7 @@ impl Runner {
scale,
)
}
}
},
}
}
}
@ -280,10 +262,7 @@ impl Shared {
runner.send_event(Event::DeviceEvent {
device_id,
event: DeviceEvent::Button {
button: button.to_id(),
state,
},
event: DeviceEvent::Button { button: button.to_id(), state },
});
return;
@ -292,35 +271,22 @@ impl Shared {
// pointer move event
let mut delta = backend::event::MouseDelta::init(&window, &event);
runner.send_events(backend::event::pointer_move_event(event).flat_map(|event| {
let delta = delta
.delta(&event)
.to_physical(backend::scale_factor(&window));
let delta = delta.delta(&event).to_physical(backend::scale_factor(&window));
let x_motion = (delta.x != 0.0).then_some(Event::DeviceEvent {
device_id,
event: DeviceEvent::Motion {
axis: 0,
value: delta.x,
},
event: DeviceEvent::Motion { axis: 0, value: delta.x },
});
let y_motion = (delta.y != 0.0).then_some(Event::DeviceEvent {
device_id,
event: DeviceEvent::Motion {
axis: 1,
value: delta.y,
},
event: DeviceEvent::Motion { axis: 1, value: delta.y },
});
x_motion
.into_iter()
.chain(y_motion)
.chain(iter::once(Event::DeviceEvent {
device_id,
event: DeviceEvent::MouseMotion {
delta: (delta.x, delta.y),
},
}))
x_motion.into_iter().chain(y_motion).chain(iter::once(Event::DeviceEvent {
device_id,
event: DeviceEvent::MouseMotion { delta: (delta.x, delta.y) },
}))
}));
}),
));
@ -482,10 +448,8 @@ impl Shared {
// Run the logic for waking from a WaitUntil, which involves clearing the queue
// Generally there shouldn't be events built up when this is called
pub fn resume_time_reached(&self, start: Instant, requested_resume: Instant) {
let start_cause = Event::NewEvents(StartCause::ResumeTimeReached {
start,
requested_resume,
});
let start_cause =
Event::NewEvents(StartCause::ResumeTimeReached { start, requested_resume });
self.run_until_cleared(iter::once(start_cause));
}
@ -508,30 +472,28 @@ impl Shared {
let mut process_immediately = true;
match self.0.runner.try_borrow().as_ref().map(Deref::deref) {
Ok(RunnerEnum::Running(ref runner)) => {
// If we're currently polling, queue this and wait for the poll() method to be called
// If we're currently polling, queue this and wait for the poll() method to be
// called
if let State::Poll { .. } = runner.state {
process_immediately = false;
}
}
},
Ok(RunnerEnum::Pending) => {
// The runner still hasn't been attached: queue this event and wait for it to be
process_immediately = false;
}
},
// Some other code is mutating the runner, which most likely means
// the event loop is running and busy. So we queue this event for
// it to be processed later.
Err(_) => {
process_immediately = false;
}
},
// This is unreachable since `self.is_closed() == true`.
Ok(RunnerEnum::Destroyed) => unreachable!(),
}
if !process_immediately {
// Queue these events to look at later
self.0
.events
.borrow_mut()
.extend(events.into_iter().map(Into::into));
self.0.events.borrow_mut().extend(events.into_iter().map(Into::into));
return;
}
// At this point, we know this is a fresh set of events
@ -558,10 +520,7 @@ impl Shared {
// `run_until_cleared`, somewhere between emitting `NewEvents` and `AboutToWait`.
fn process_destroy_pending_windows(&self) {
while let Some(id) = self.0.destroy_pending.borrow_mut().pop_front() {
self.0
.all_canvases
.borrow_mut()
.retain(|&(item_id, _, _)| item_id != id);
self.0.all_canvases.borrow_mut().retain(|&(item_id, ..)| item_id != id);
self.handle_event(Event::WindowEvent {
window_id: id,
event: crate::event::WindowEvent::Destroyed,
@ -617,7 +576,7 @@ impl Shared {
match *self.0.runner.borrow_mut() {
RunnerEnum::Running(ref mut runner) => {
runner.handle_single_event(self, event);
}
},
// If an event is being handled without a runner somehow, add it to the event queue so
// it will eventually be processed
RunnerEnum::Pending => self.0.events.borrow_mut().push_back(event.into()),
@ -675,18 +634,12 @@ impl Shared {
move || cloned.poll(),
),
}
}
ControlFlow::Wait => State::Wait {
start: Instant::now(),
},
ControlFlow::Wait => State::Wait { start: Instant::now() },
ControlFlow::WaitUntil(end) => {
let start = Instant::now();
let delay = if end <= start {
Duration::from_millis(0)
} else {
end - start
};
let delay = if end <= start { Duration::from_millis(0) } else { end - start };
let cloned = self.clone();
@ -699,7 +652,7 @@ impl Shared {
delay,
),
}
}
},
}
};
@ -732,11 +685,10 @@ impl Shared {
}
// At this point, the `self.0` `Rc` should only be strongly referenced
// by the following:
// * `self`, i.e. the item which triggered this event loop wakeup, which
// is usually a `wasm-bindgen` `Closure`, which will be dropped after
// returning to the JS glue code.
// * The `ActiveEventLoop` leaked inside `EventLoop::run_app` due to the
// JS exception thrown at the end.
// * `self`, i.e. the item which triggered this event loop wakeup, which is usually a
// `wasm-bindgen` `Closure`, which will be dropped after returning to the JS glue code.
// * The `ActiveEventLoop` leaked inside `EventLoop::run_app` due to the JS exception thrown
// at the end.
// * For each undropped `Window`:
// * The `register_redraw_request` closure.
// * The `destroy_fn` closure.
@ -774,7 +726,7 @@ impl Shared {
false
}
})
}
},
DeviceEvents::Never => false,
}
}
@ -814,11 +766,7 @@ impl Shared {
pub(crate) enum EventWrapper {
Event(Event<()>),
ScaleChange {
canvas: Weak<RefCell<backend::Canvas>>,
size: PhysicalSize<u32>,
scale: f64,
},
ScaleChange { canvas: Weak<RefCell<backend::Canvas>>, size: PhysicalSize<u32>, scale: f64 },
}
impl From<Event<()>> for EventWrapper {

View file

@ -5,17 +5,9 @@ use web_time::Instant;
#[derive(Debug)]
pub enum State {
Init,
WaitUntil {
_timeout: backend::Schedule,
start: Instant,
end: Instant,
},
Wait {
start: Instant,
},
Poll {
_request: backend::Schedule,
},
WaitUntil { _timeout: backend::Schedule, start: Instant, end: Instant },
Wait { start: Instant },
Poll { _request: backend::Schedule },
Exit,
}

View file

@ -1,26 +1,24 @@
use std::cell::{Cell, RefCell};
use std::clone::Clone;
use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque};
use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::collections::VecDeque;
use std::iter;
use std::rc::{Rc, Weak};
use web_sys::Element;
use super::super::monitor::MonitorHandle;
use super::super::KeyEventExtra;
use super::device::DeviceId;
use super::runner::{EventWrapper, Execution};
use super::{
super::{monitor::MonitorHandle, KeyEventExtra},
backend,
device::DeviceId,
runner,
window::WindowId,
};
use super::window::WindowId;
use super::{backend, runner};
use crate::event::{
DeviceId as RootDeviceId, ElementState, Event, KeyEvent, Touch, TouchPhase, WindowEvent,
};
use crate::event_loop::{ControlFlow, DeviceEvents};
use crate::keyboard::ModifiersState;
use crate::platform::web::CustomCursorFuture;
use crate::platform::web::PollStrategy;
use crate::platform::web::{CustomCursorFuture, PollStrategy};
use crate::platform_impl::platform::cursor::CustomCursor;
use crate::platform_impl::platform::r#async::Waker;
use crate::window::{
@ -54,10 +52,7 @@ pub struct ActiveEventLoop {
impl ActiveEventLoop {
pub fn new() -> Self {
Self {
runner: runner::Shared::new(),
modifiers: ModifiersShared::default(),
}
Self { runner: runner::Shared::new(), modifiers: ModifiersShared::default() }
}
pub fn run(&self, event_handler: Box<runner::EventHandler>, event_loop_recreation: bool) {
@ -70,9 +65,7 @@ impl ActiveEventLoop {
}
pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor {
RootCustomCursor {
inner: CustomCursor::new(self, source.inner),
}
RootCustomCursor { inner: CustomCursor::new(self, source.inner) }
}
pub fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture {
@ -101,14 +94,10 @@ impl ActiveEventLoop {
}
});
runner.send_events(
clear_modifiers
.into_iter()
.chain(iter::once(Event::WindowEvent {
window_id: RootWindowId(id),
event: WindowEvent::Focused(false),
})),
);
runner.send_events(clear_modifiers.into_iter().chain(iter::once(Event::WindowEvent {
window_id: RootWindowId(id),
event: WindowEvent::Focused(false),
})));
});
let runner = self.runner.clone();
@ -304,10 +293,7 @@ impl ActiveEventLoop {
iter::once(Event::WindowEvent {
window_id: RootWindowId(id),
event: WindowEvent::CursorMoved {
device_id,
position,
},
event: WindowEvent::CursorMoved { device_id, position },
})
})));
}
@ -374,18 +360,11 @@ impl ActiveEventLoop {
runner.send_events(modifiers.into_iter().chain([
Event::WindowEvent {
window_id: RootWindowId(id),
event: WindowEvent::CursorMoved {
device_id,
position,
},
event: WindowEvent::CursorMoved { device_id, position },
},
Event::WindowEvent {
window_id: RootWindowId(id),
event: WindowEvent::MouseInput {
device_id,
state,
button,
},
event: WindowEvent::MouseInput { device_id, state, button },
},
]));
}
@ -428,10 +407,7 @@ impl ActiveEventLoop {
runner.send_events(modifiers.into_iter().chain([
Event::WindowEvent {
window_id: RootWindowId(id),
event: WindowEvent::CursorMoved {
device_id,
position,
},
event: WindowEvent::CursorMoved { device_id, position },
},
Event::WindowEvent {
window_id: RootWindowId(id),
@ -512,10 +488,7 @@ impl ActiveEventLoop {
runner.send_events(modifiers.into_iter().chain([
Event::WindowEvent {
window_id: RootWindowId(id),
event: WindowEvent::CursorMoved {
device_id,
position,
},
event: WindowEvent::CursorMoved { device_id, position },
},
Event::WindowEvent {
window_id: RootWindowId(id),
@ -599,11 +572,7 @@ impl ActiveEventLoop {
let runner = self.runner.clone();
canvas.on_dark_mode(move |is_dark_mode| {
let theme = if is_dark_mode {
Theme::Dark
} else {
Theme::Light
};
let theme = if is_dark_mode { Theme::Dark } else { Theme::Light };
runner.send_event(Event::WindowEvent {
window_id: RootWindowId(id),
event: WindowEvent::ThemeChanged(theme),
@ -682,9 +651,7 @@ impl ActiveEventLoop {
pub fn raw_display_handle_rwh_06(
&self,
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
Ok(rwh_06::RawDisplayHandle::Web(
rwh_06::WebDisplayHandle::new(),
))
Ok(rwh_06::RawDisplayHandle::Web(rwh_06::WebDisplayHandle::new()))
}
pub fn listen_device_events(&self, allowed: DeviceEvents) {

View file

@ -45,6 +45,7 @@ pub use self::window::{PlatformSpecificWindowAttributes, Window, WindowId};
pub(crate) use self::keyboard::KeyEventExtra;
pub(crate) use crate::icon::NoIcon as PlatformIcon;
pub(crate) use crate::platform_impl::Fullscreen;
pub(crate) use cursor::CustomCursor as PlatformCustomCursor;
pub(crate) use cursor::CustomCursorFuture;
pub(crate) use cursor::CustomCursorSource as PlatformCustomCursorSource;
pub(crate) use cursor::{
CustomCursor as PlatformCustomCursor, CustomCursorFuture,
CustomCursorSource as PlatformCustomCursorSource,
};

View file

@ -17,11 +17,7 @@ impl AnimationFrameHandler {
move || handle.set(None)
});
Self {
window,
closure,
handle,
}
Self { window, closure, handle }
}
pub fn on_animation_frame<F>(&mut self, mut f: F)
@ -37,9 +33,7 @@ impl AnimationFrameHandler {
pub fn request(&self) {
if let Some(handle) = self.handle.take() {
self.window
.cancel_animation_frame(handle)
.expect("Failed to cancel animation frame");
self.window.cancel_animation_frame(handle).expect("Failed to cancel animation frame");
}
let handle = self
@ -52,9 +46,7 @@ impl AnimationFrameHandler {
pub fn cancel(&mut self) {
if let Some(handle) = self.handle.take() {
self.window
.cancel_animation_frame(handle)
.expect("Failed to cancel animation frame");
self.window.cancel_animation_frame(handle).expect("Failed to cancel animation frame");
}
}
}
@ -62,9 +54,7 @@ impl AnimationFrameHandler {
impl Drop for AnimationFrameHandler {
fn drop(&mut self) {
if let Some(handle) = self.handle.take() {
self.window
.cancel_animation_frame(handle)
.expect("Failed to cancel animation frame");
self.window.cancel_animation_frame(handle).expect("Failed to cancel animation frame");
}
}
}

View file

@ -4,7 +4,8 @@ use std::rc::Rc;
use std::sync::{Arc, Mutex};
use smol_str::SmolStr;
use wasm_bindgen::{closure::Closure, JsCast};
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
use web_sys::{
CssStyleDeclaration, Document, Event, FocusEvent, HtmlCanvasElement, KeyboardEvent,
PointerEvent, WheelEvent,
@ -53,8 +54,9 @@ pub struct Canvas {
pub struct Common {
pub window: web_sys::Window,
pub document: Document,
/// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure the DPI factor is maintained.
/// Note: this is read-only because we use a pointer to this for [`WindowHandle`][rwh_06::WindowHandle].
/// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure
/// the DPI factor is maintained. Note: this is read-only because we use a pointer to this
/// for [`WindowHandle`][rwh_06::WindowHandle].
raw: Rc<HtmlCanvasElement>,
style: Style,
old_size: Rc<Cell<PhysicalSize<u32>>>,
@ -188,10 +190,7 @@ impl Canvas {
pub fn position(&self) -> LogicalPosition<f64> {
let bounds = self.common.raw.get_bounding_client_rect();
let mut position = LogicalPosition {
x: bounds.x(),
y: bounds.y(),
};
let mut position = LogicalPosition { x: bounds.x(), y: bounds.y() };
if self.document().contains(Some(self.raw())) && self.style().get("display") != "none" {
position.x += super::style_size_property(self.style(), "border-left-width")
@ -298,9 +297,8 @@ impl Canvas {
F: 'static + FnMut(PhysicalKey, Key, Option<SmolStr>, KeyLocation, bool, ModifiersState),
{
let prevent_default = Rc::clone(&self.prevent_default);
self.on_keyboard_press = Some(self.common.add_event(
"keydown",
move |event: KeyboardEvent| {
self.on_keyboard_press =
Some(self.common.add_event("keydown", move |event: KeyboardEvent| {
if prevent_default.get() {
event.prevent_default();
}
@ -314,8 +312,7 @@ impl Canvas {
event.repeat(),
modifiers,
);
},
));
}));
}
pub fn on_cursor_leave<F>(&mut self, handler: F)
@ -459,14 +456,12 @@ impl Canvas {
pub(crate) fn on_context_menu(&mut self) {
let prevent_default = Rc::clone(&self.prevent_default);
self.on_context_menu = Some(self.common.add_event(
"contextmenu",
move |event: PointerEvent| {
self.on_context_menu =
Some(self.common.add_event("contextmenu", move |event: PointerEvent| {
if prevent_default.get() {
event.prevent_default();
}
},
));
}));
}
pub fn request_fullscreen(&self) {
@ -580,20 +575,14 @@ impl Style {
}
pub(crate) fn get(&self, property: &str) -> String {
self.read
.get_property_value(property)
.expect("Invalid property")
self.read.get_property_value(property).expect("Invalid property")
}
pub(crate) fn remove(&self, property: &str) {
self.write
.remove_property(property)
.expect("Property is read only");
self.write.remove_property(property).expect("Property is read only");
}
pub(crate) fn set(&self, property: &str, value: &str) {
self.write
.set_property(property, value)
.expect("Property is read only");
self.write.set_property(property, value).expect("Property is read only");
}
}

View file

@ -59,10 +59,9 @@ pub fn mouse_button(event: &MouseEvent) -> Option<MouseButton> {
2 => Some(MouseButton::Right),
3 => Some(MouseButton::Back),
4 => Some(MouseButton::Forward),
i => Some(MouseButton::Other(
i.try_into()
.expect("unexpected negative mouse button value"),
)),
i => {
Some(MouseButton::Other(i.try_into().expect("unexpected negative mouse button value")))
},
}
}
@ -93,10 +92,7 @@ pub fn mouse_position(event: &MouseEvent) -> LogicalPosition<f64> {
let event: &MouseEventExt = event.unchecked_ref();
LogicalPosition {
x: event.offset_x(),
y: event.offset_y(),
}
LogicalPosition { x: event.offset_x(), y: event.offset_y() }
}
// TODO: Remove this when Firefox supports correct movement values in coalesced events.
@ -114,17 +110,15 @@ impl MouseDelta {
// for `pointerrawupdate` support. Presumably an implementation of `pointerrawupdate`
// should require correct movement values, otherwise uncoalesced events might be broken as
// well.
Self(
(!has_pointer_raw_support(window) && has_coalesced_events_support(event)).then(|| {
MouseDeltaInner {
old_position: mouse_position(event),
old_delta: LogicalPosition {
x: event.movement_x() as f64,
y: event.movement_y() as f64,
},
}
}),
)
Self((!has_pointer_raw_support(window) && has_coalesced_events_support(event)).then(|| {
MouseDeltaInner {
old_position: mouse_position(event),
old_delta: LogicalPosition {
x: event.movement_x() as f64,
y: event.movement_y() as f64,
},
}
}))
}
pub fn delta(&mut self, event: &MouseEvent) -> LogicalPosition<f64> {
@ -136,10 +130,7 @@ impl MouseDelta {
inner.old_delta = LogicalPosition::new(0., 0.);
LogicalPosition::new(x, y)
} else {
LogicalPosition {
x: event.movement_x() as f64,
y: event.movement_y() as f64,
}
LogicalPosition { x: event.movement_x() as f64, y: event.movement_y() as f64 }
}
}
}
@ -156,7 +147,7 @@ pub fn mouse_scroll_delta(
WheelEvent::DOM_DELTA_PIXEL => {
let delta = LogicalPosition::new(x, y).to_physical(super::scale_factor(window));
Some(MouseScrollDelta::PixelDelta(delta))
}
},
_ => None,
}
}
@ -192,7 +183,7 @@ pub fn key_location(event: &KeyboardEvent) -> KeyLocation {
location => {
tracing::warn!("Unexpected key location: {location}");
KeyLocation::Standard
}
},
}
}
@ -238,14 +229,9 @@ pub fn pointer_move_event(event: PointerEvent) -> impl Iterator<Item = PointerEv
// make a single iterator depending on the availability of coalesced events
if has_coalesced_events_support(&event) {
None.into_iter().chain(
Some(
event
.get_coalesced_events()
.into_iter()
.map(PointerEvent::unchecked_from_js),
)
.into_iter()
.flatten(),
Some(event.get_coalesced_events().into_iter().map(PointerEvent::unchecked_from_js))
.into_iter()
.flatten(),
)
} else {
Some(event).into_iter().chain(None.into_iter().flatten())

View file

@ -1,4 +1,5 @@
use wasm_bindgen::{prelude::Closure, JsCast};
use wasm_bindgen::prelude::Closure;
use wasm_bindgen::JsCast;
use web_sys::EventTarget;
pub struct EventListenerHandle<T: ?Sized> {
@ -16,11 +17,7 @@ impl<T: ?Sized> EventListenerHandle<T> {
target
.add_event_listener_with_callback(event_type, listener.as_ref().unchecked_ref())
.expect("Failed to add event listener");
EventListenerHandle {
target,
event_type,
listener,
}
EventListenerHandle { target, event_type, listener }
}
}

View file

@ -58,7 +58,7 @@ pub fn is_fullscreen(document: &Document, canvas: &HtmlCanvasElement) -> bool {
Some(element) => {
let canvas: &Element = canvas;
canvas == &element
}
},
None => false,
}
}

View file

@ -1,5 +1,6 @@
use js_sys::Array;
use wasm_bindgen::{prelude::Closure, JsCast};
use wasm_bindgen::prelude::Closure;
use wasm_bindgen::JsCast;
use web_sys::{Element, IntersectionObserver, IntersectionObserverEntry};
pub(super) struct IntersectionObserverHandle {
@ -21,10 +22,7 @@ impl IntersectionObserverHandle {
.expect("Invalid `options`");
observer.observe(element);
Self {
observer,
_closure: closure,
}
Self { observer, _closure: closure }
}
}

View file

@ -1,4 +1,5 @@
use wasm_bindgen::{prelude::Closure, JsCast};
use wasm_bindgen::prelude::Closure;
use wasm_bindgen::JsCast;
use web_sys::MediaQueryList;
pub(super) struct MediaQueryListHandle {
@ -41,8 +42,7 @@ impl Drop for MediaQueryListHandle {
}
fn remove_listener(mql: &MediaQueryList, listener: &Closure<dyn FnMut()>) {
mql.remove_listener_with_opt_callback(Some(listener.as_ref().unchecked_ref()))
.unwrap_or_else(|e| {
web_sys::console::error_2(&"Error removing media query listener".into(), &e)
});
mql.remove_listener_with_opt_callback(Some(listener.as_ref().unchecked_ref())).unwrap_or_else(
|e| web_sys::console::error_2(&"Error removing media query listener".into(), &e),
);
}

View file

@ -9,8 +9,7 @@ mod pointer;
mod resize_scaling;
mod schedule;
pub use self::canvas::Canvas;
pub use self::canvas::Style;
pub use self::canvas::{Canvas, Style};
pub use self::event::ButtonsState;
pub use self::event_handle::EventListenerHandle;
pub use self::resize_scaling::ResizeScaleHandle;
@ -40,10 +39,7 @@ pub fn on_page_transition(
let show_listener =
event_handle::EventListenerHandle::new(window.clone(), "pageshow", show_closure);
let hide_listener = event_handle::EventListenerHandle::new(window, "pagehide", hide_closure);
PageTransitionEventHandle {
_show_listener: show_listener,
_hide_listener: hide_listener,
}
PageTransitionEventHandle { _show_listener: show_listener, _hide_listener: hide_listener }
}
pub fn scale_factor(window: &web_sys::Window) -> f64 {
@ -154,11 +150,7 @@ pub fn style_size_property(style: &Style, property: &str) -> f64 {
}
pub fn is_dark_mode(window: &web_sys::Window) -> Option<bool> {
window
.match_media("(prefers-color-scheme: dark)")
.ok()
.flatten()
.map(|media| media.matches())
window.match_media("(prefers-color-scheme: dark)").ok().flatten().map(|media| media.matches())
}
pub fn is_visible(document: &Document) -> bool {

View file

@ -37,9 +37,8 @@ impl PointerHandler {
where
F: 'static + FnMut(ModifiersState, Option<i32>),
{
self.on_cursor_leave = Some(canvas_common.add_event(
"pointerout",
move |event: PointerEvent| {
self.on_cursor_leave =
Some(canvas_common.add_event("pointerout", move |event: PointerEvent| {
let modifiers = event::mouse_modifiers(&event);
// touch events are handled separately
@ -48,17 +47,15 @@ impl PointerHandler {
let pointer_id = (event.pointer_type() == "mouse").then(|| event.pointer_id());
handler(modifiers, pointer_id);
},
));
}));
}
pub fn on_cursor_enter<F>(&mut self, canvas_common: &Common, mut handler: F)
where
F: 'static + FnMut(ModifiersState, Option<i32>),
{
self.on_cursor_enter = Some(canvas_common.add_event(
"pointerover",
move |event: PointerEvent| {
self.on_cursor_enter =
Some(canvas_common.add_event("pointerover", move |event: PointerEvent| {
let modifiers = event::mouse_modifiers(&event);
// touch events are handled separately
@ -67,8 +64,7 @@ impl PointerHandler {
let pointer_id = (event.pointer_type() == "mouse").then(|| event.pointer_id());
handler(modifiers, pointer_id);
},
));
}));
}
pub fn on_mouse_release<MOD, M, T>(
@ -83,9 +79,8 @@ impl PointerHandler {
T: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, Force),
{
let window = canvas_common.window.clone();
self.on_pointer_release = Some(canvas_common.add_event(
"pointerup",
move |event: PointerEvent| {
self.on_pointer_release =
Some(canvas_common.add_event("pointerup", move |event: PointerEvent| {
let modifiers = event::mouse_modifiers(&event);
match event.pointer_type().as_str() {
@ -103,8 +98,7 @@ impl PointerHandler {
),
_ => modifier_handler(modifiers),
}
},
));
}));
}
pub fn on_mouse_press<MOD, M, T>(
@ -121,9 +115,8 @@ impl PointerHandler {
{
let window = canvas_common.window.clone();
let canvas = canvas_common.raw().clone();
self.on_pointer_press = Some(canvas_common.add_event(
"pointerdown",
move |event: PointerEvent| {
self.on_pointer_press =
Some(canvas_common.add_event("pointerdown", move |event: PointerEvent| {
if prevent_default.get() {
// prevent text selection
event.prevent_default();
@ -141,7 +134,7 @@ impl PointerHandler {
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
Force::Normalized(event.pressure() as f64),
);
}
},
"mouse" => {
mouse_handler(
modifiers,
@ -150,15 +143,15 @@ impl PointerHandler {
event::mouse_button(&event).expect("no mouse button pressed"),
);
// Error is swallowed here since the error would occur every time the mouse is
// clicked when the cursor is grabbed, and there is probably not a situation where
// this could fail, that we care if it fails.
// Error is swallowed here since the error would occur every time the mouse
// is clicked when the cursor is grabbed, and there
// is probably not a situation where this could
// fail, that we care if it fails.
let _e = canvas.set_pointer_capture(event.pointer_id());
}
},
_ => modifier_handler(modifiers),
}
},
));
}));
}
pub fn on_cursor_move<MOD, M, T, B>(
@ -178,9 +171,8 @@ impl PointerHandler {
{
let window = canvas_common.window.clone();
let canvas = canvas_common.raw().clone();
self.on_cursor_move = Some(canvas_common.add_event(
"pointermove",
move |event: PointerEvent| {
self.on_cursor_move =
Some(canvas_common.add_event("pointermove", move |event: PointerEvent| {
let modifiers = event::mouse_modifiers(&event);
let pointer_type = event.pointer_type();
@ -239,8 +231,7 @@ impl PointerHandler {
),
_ => unreachable!("didn't return early before"),
};
},
));
}));
}
pub fn on_touch_cancel<F>(&mut self, canvas_common: &Common, mut handler: F)
@ -248,9 +239,8 @@ impl PointerHandler {
F: 'static + FnMut(i32, PhysicalPosition<f64>, Force),
{
let window = canvas_common.window.clone();
self.on_touch_cancel = Some(canvas_common.add_event(
"pointercancel",
move |event: PointerEvent| {
self.on_touch_cancel =
Some(canvas_common.add_event("pointercancel", move |event: PointerEvent| {
if event.pointer_type() == "touch" {
handler(
event.pointer_id(),
@ -258,8 +248,7 @@ impl PointerHandler {
Force::Normalized(event.pressure() as f64),
);
}
},
));
}));
}
pub fn remove_listeners(&mut self) {

View file

@ -210,9 +210,8 @@ impl ResizeScaleInternal {
// This should never happen, but if it does then apparently the scale factor didn't change.
if mql.matches() {
warn!(
"media query tracking scale factor was triggered without a change:\n\
Media Query: {}\n\
Current Scale: {scale}",
"media query tracking scale factor was triggered without a change:\nMedia Query: \
{}\nCurrent Scale: {scale}",
mql.media(),
);
return;
@ -240,10 +239,8 @@ impl ResizeScaleInternal {
.to_physical(backend::scale_factor(&self.window));
}
let entry: ResizeObserverSize = entry
.device_pixel_content_box_size()
.get(0)
.unchecked_into();
let entry: ResizeObserverSize =
entry.device_pixel_content_box_size().get(0).unchecked_into();
let writing_mode = self.style.get("writing-mode");
@ -259,14 +256,14 @@ impl ResizeScaleInternal {
_ if writing_mode.starts_with("horizontal") => true,
_ if writing_mode.starts_with("vertical") | writing_mode.starts_with("sideways") => {
false
}
},
// deprecated values
"lr" | "lr-tb" | "rl" => true,
"tb" | "tb-lr" | "tb-rl" => false,
_ => {
warn!("unrecognized `writing-mode`, assuming horizontal");
true
}
},
};
if horizontal {

View file

@ -89,10 +89,7 @@ impl Schedule {
.catch(handler);
});
Schedule {
_closure: closure,
inner: Inner::Scheduler { controller },
}
Schedule { _closure: closure, inner: Inner::Scheduler { controller } }
}
fn new_idle_callback<F>(window: web_sys::Window, f: F) -> Schedule
@ -104,10 +101,7 @@ impl Schedule {
.request_idle_callback(closure.as_ref().unchecked_ref())
.expect("Failed to request idle callback");
Schedule {
_closure: closure,
inner: Inner::IdleCallback { window, handle },
}
Schedule { _closure: closure, inner: Inner::IdleCallback { window, handle } }
}
fn new_timeout<F>(window: web_sys::Window, f: F, duration: Option<Duration>) -> Schedule
@ -122,9 +116,7 @@ impl Schedule {
let port_2 = channel.port2();
let timeout_closure = Closure::new(move || {
port_2
.post_message(&JsValue::UNDEFINED)
.expect("Failed to send message")
port_2.post_message(&JsValue::UNDEFINED).expect("Failed to send message")
});
let handle = if let Some(duration) = duration {
// `Duration::as_millis()` always rounds down (because of truncation), we want to round
@ -168,16 +160,11 @@ impl Drop for Schedule {
match &self.inner {
Inner::Scheduler { controller, .. } => controller.abort(),
Inner::IdleCallback { window, handle, .. } => window.cancel_idle_callback(*handle),
Inner::Timeout {
window,
handle,
port,
..
} => {
Inner::Timeout { window, handle, port, .. } => {
window.clear_timeout_with_handle(*handle);
port.close();
port.set_onmessage(None);
}
},
}
}
}

View file

@ -7,8 +7,9 @@ use crate::window::{
};
use super::main_thread::{MainThreadMarker, MainThreadSafe};
use super::monitor::MonitorHandle;
use super::r#async::Dispatcher;
use super::{backend, monitor::MonitorHandle, ActiveEventLoop, Fullscreen};
use super::{backend, ActiveEventLoop, Fullscreen};
use web_sys::HtmlCanvasElement;
use std::cell::RefCell;
@ -50,12 +51,7 @@ impl Window {
let runner = target.runner.clone();
let destroy_fn = Box::new(move || runner.notify_destroy_window(RootWI(id)));
let inner = Inner {
id,
window: window.clone(),
canvas,
destroy_fn: Some(destroy_fn),
};
let inner = Inner { id, window: window.clone(), canvas, destroy_fn: Some(destroy_fn) };
inner.set_title(&attr.title);
inner.set_maximized(attr.maximized);
@ -79,19 +75,15 @@ impl Window {
}
pub fn canvas(&self) -> Option<HtmlCanvasElement> {
self.inner
.value()
.map(|inner| inner.canvas.borrow().raw().clone())
self.inner.value().map(|inner| inner.canvas.borrow().raw().clone())
}
pub(crate) fn prevent_default(&self) -> bool {
self.inner
.queue(|inner| inner.canvas.borrow().prevent_default.get())
self.inner.queue(|inner| inner.canvas.borrow().prevent_default.get())
}
pub(crate) fn set_prevent_default(&self, prevent_default: bool) {
self.inner
.dispatch(move |inner| inner.canvas.borrow().prevent_default.set(prevent_default))
self.inner.dispatch(move |inner| inner.canvas.borrow().prevent_default.set(prevent_default))
}
#[cfg(feature = "rwh_06")]
@ -115,9 +107,7 @@ impl Window {
pub(crate) fn raw_display_handle_rwh_06(
&self,
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
Ok(rwh_06::RawDisplayHandle::Web(
rwh_06::WebDisplayHandle::new(),
))
Ok(rwh_06::RawDisplayHandle::Web(rwh_06::WebDisplayHandle::new()))
}
}
@ -146,11 +136,7 @@ impl Inner {
pub fn pre_present_notify(&self) {}
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
Ok(self
.canvas
.borrow()
.position()
.to_physical(self.scale_factor()))
Ok(self.canvas.borrow().position().to_physical(self.scale_factor()))
}
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
@ -247,13 +233,10 @@ impl Inner {
CursorGrabMode::Locked => true,
CursorGrabMode::Confined => {
return Err(ExternalError::NotSupported(NotSupportedError::new()))
}
},
};
self.canvas
.borrow()
.set_cursor_lock(lock)
.map_err(ExternalError::Os)
self.canvas.borrow().set_cursor_lock(lock).map_err(ExternalError::Os)
}
#[inline]
@ -489,11 +472,6 @@ impl PlatformSpecificWindowAttributes {
impl Default for PlatformSpecificWindowAttributes {
fn default() -> Self {
Self {
canvas: None,
prevent_default: true,
focusable: true,
append: false,
}
Self { canvas: None, prevent_default: true, focusable: true, append: false }
}
}