Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove lifetime from Event type #1456

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ log = "0.4"
serde = { version = "1", optional = true, features = ["serde_derive"] }
raw-window-handle = "0.3"
bitflags = "1"
scoped_arc_cell = { version = "0.1.0", path = "scoped_arc_cell" }

[dev-dependencies]
image = "0.23"
Expand Down
56 changes: 56 additions & 0 deletions examples/dpi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use winit::dpi::LogicalSize;
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};

/// Change the DPI settings in Windows while running this.
fn main() {
simple_logger::init().unwrap();
let event_loop = EventLoop::new();

let window = WindowBuilder::new()
.with_title("A fantastic window!")
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
.build(&event_loop)
.unwrap();

event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;

match event {
Event::WindowEvent {
event: WindowEvent::CloseRequested,
window_id,
} if window_id == window.id() => *control_flow = ControlFlow::Exit,
Event::MainEventsCleared => {
window.request_redraw();
}

// DPI changed happened!
Event::WindowEvent {
event:
WindowEvent::ScaleFactorChanged {
scale_factor,
new_inner_size,
},
..
} => {
dbg!((scale_factor, new_inner_size.get()));

let _os_suggested_value = new_inner_size
.replace(
LogicalSize {
width: 100,
height: 200,
}
.to_physical(scale_factor),
)
.unwrap();
}

_ => (),
}
});
}
4 changes: 1 addition & 3 deletions examples/multithreaded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,7 @@ fn main() {
}
_ => {
if let Some(tx) = window_senders.get(&window_id) {
if let Some(event) = event.to_static() {
tx.send(event).unwrap();
}
tx.send(event).unwrap();
}
}
},
Expand Down
9 changes: 9 additions & 0 deletions scoped_arc_cell/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "scoped_arc_cell"
version = "0.1.0"
authors = ["Osspial <osspial@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
crossbeam-utils = { version = "0.7", no-default-features = true }
116 changes: 116 additions & 0 deletions scoped_arc_cell/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
//! Shared mutable cell containing data, with the mutability tied to the liveliness of a lifetime ScopedMutabilityOwner struct.
//!
//! Use `scoped_arc_cell` to create a matching `ArcCell` and `ScopedMutabilityOwner` pair. The data can be shared by cloning the `ArcCell`.
//!
//! As long as the `ScopedMutabilityOwner` is alive, mutating the inner data will succeed. Once the `ScopedMutabilityOwner` has been `drop`ped, the calls will fail.

#![warn(missing_docs)]

use crossbeam_utils::atomic::AtomicCell;
use std::{
error::Error,
fmt::{self, Debug, Display, Formatter},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};

/// Create a matching `ArcCell` and `ScopedMutabilityOwner` pair wrapping some value.
///
/// See crate-level documentation for mutability rules.
pub fn scoped_arc_cell<T: Copy>(val: T) -> (ArcCell<T>, ScopedMutabilityOwner<T>) {
let aaaa = ScopedMutabilityOwner::new(val);
(aaaa.create_reference(), aaaa)
}

/// Container for shared atomic interior mutability.
///
/// See crate-level documentation for mutability rules.
#[derive(Debug, Clone)]
pub struct ArcCell<T: Copy> {
data: Arc<Data<T>>,
}

/// A type that owns the the mutability lifetime of the matching `ArcCell`.
///
/// See crate-level documentation for mutability rules.
#[derive(Debug)]
pub struct ScopedMutabilityOwner<T: Copy> {
/// TODO(tangmi): Osspial, this is semantically an Arc<Mutex<Cell<_>>>, but implemented with AtomicCell for perf/avoiding deadlock issues?
data: Arc<Data<T>>,
}

/// An error returned when trying to mutate a `ArcCell` that is read-only because the `ScopedMutabilityOwner` has already been `drop`ped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct StoreError<T>(pub T);

#[derive(Debug)]
struct Data<T: Copy> {
val: AtomicCell<T>,
is_read_only: AtomicBool,
}

impl<T: Copy> ArcCell<T> {
/// Replaces the contained value, and returns it.
pub fn replace(&self, val: T) -> Result<T, StoreError<T>> {
match self.data.is_read_only.load(Ordering::Acquire) {
false => Ok(self.data.val.swap(val)),
true => Err(StoreError(val)),
}
}

/// Returns a copy of the contained value.
pub fn get(&self) -> T {
self.data.val.load()
}

/// Returns a raw pointer to the underlying data in this cell.
pub fn as_ptr(&self) -> *mut T {
self.data.val.as_ptr()
}
}

/// Manually implement `PartialEq` to treat `Self` like just a `T`.
impl<T: Copy + PartialEq> PartialEq<ArcCell<T>> for ArcCell<T> {
fn eq(&self, other: &ArcCell<T>) -> bool {
// Note: does not compare `is_read_only` flag.
self.data.val.load() == other.data.val.load()
}
}

impl<T: Copy> ScopedMutabilityOwner<T> {
fn new(val: T) -> ScopedMutabilityOwner<T> {
let data = Arc::new(Data {
val: AtomicCell::new(val),
is_read_only: AtomicBool::new(false),
});
ScopedMutabilityOwner { data }
}

/// Create a new reference from the underlying data.
///
/// The data will remain immutably alive even after this struct's lifetime.
pub fn create_reference(&self) -> ArcCell<T> {
ArcCell {
data: self.data.clone(),
}
}
}

impl<T: Copy> Drop for ScopedMutabilityOwner<T> {
fn drop(&mut self) {
self.data.is_read_only.store(true, Ordering::Release);
}
}

impl<T: Debug> Error for StoreError<T> {}

impl<T> Display for StoreError<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"the ScopedMutabilityOwner was destroyed, making this ArcCell read-only"
)
}
}
Loading