Skip to content

Commit

Permalink
Migrate from lazy_static to once_cell
Browse files Browse the repository at this point in the history
  • Loading branch information
james7132 authored Jun 8, 2022
1 parent 4c39b31 commit 2c01e9e
Show file tree
Hide file tree
Showing 18 changed files with 486 additions and 528 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ wayland-csd-adwaita-notitle = ["sctk-adwaita"]

[dependencies]
instant = { version = "0.1", features = ["wasm-bindgen"] }
lazy_static = "1"
once_cell = "1.12"
log = "0.4"
serde = { version = "1", optional = true, features = ["serde_derive"] }
raw-window-handle = "0.4.2"
Expand Down
3 changes: 0 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,6 @@
#![deny(rust_2018_idioms)]
#![deny(rustdoc::broken_intra_doc_links)]

#[allow(unused_imports)]
#[macro_use]
extern crate lazy_static;
#[allow(unused_imports)]
#[macro_use]
extern crate log;
Expand Down
47 changes: 25 additions & 22 deletions src/platform_impl/android/mod.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,41 @@
#![cfg(target_os = "android")]

use crate::{
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
error,
event::{self, VirtualKeyCode},
event_loop::{self, ControlFlow},
monitor, window,
use std::{
collections::VecDeque,
sync::{Arc, Mutex, RwLock},
time::{Duration, Instant},
};

use ndk::{
configuration::Configuration,
event::{InputEvent, KeyAction, Keycode, MotionAction},
looper::{ForeignLooper, Poll, ThreadLooper},
};
use ndk_glue::{Event, Rect};
use once_cell::sync::Lazy;
use raw_window_handle::{AndroidNdkHandle, RawWindowHandle};
use std::{
collections::VecDeque,
sync::{Arc, Mutex, RwLock},
time::{Duration, Instant},

use crate::{
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
error,
event::{self, VirtualKeyCode},
event_loop::{self, ControlFlow},
monitor, window,
};

lazy_static! {
static ref CONFIG: RwLock<Configuration> = RwLock::new(Configuration::from_asset_manager(
static CONFIG: Lazy<RwLock<Configuration>> = Lazy::new(|| {
RwLock::new(Configuration::from_asset_manager(
#[allow(deprecated)] // TODO: rust-windowing/winit#2196
&ndk_glue::native_activity().asset_manager()
));
// If this is `Some()` a `Poll::Wake` is considered an `EventSource::Internal` with the event
// contained in the `Option`. The event is moved outside of the `Option` replacing it with a
// `None`.
//
// This allows us to inject event into the event loop without going through `ndk-glue` and
// calling unsafe function that should only be called by Android.
static ref INTERNAL_EVENT: RwLock<Option<InternalEvent>> = RwLock::new(None);
}
&ndk_glue::native_activity().asset_manager(),
))
});
// If this is `Some()` a `Poll::Wake` is considered an `EventSource::Internal` with the event
// contained in the `Option`. The event is moved outside of the `Option` replacing it with a
// `None`.
//
// This allows us to inject event into the event loop without going through `ndk-glue` and
// calling unsafe function that should only be called by Android.
static INTERNAL_EVENT: Lazy<RwLock<Option<InternalEvent>>> = Lazy::new(|| RwLock::new(None));

enum InternalEvent {
RedrawRequested,
Expand Down
45 changes: 22 additions & 23 deletions src/platform_impl/ios/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::{
};

use objc::runtime::{BOOL, YES};
use once_cell::sync::Lazy;

use crate::{
dpi::LogicalSize,
Expand Down Expand Up @@ -1016,29 +1017,27 @@ impl NSOperatingSystemVersion {
}

pub fn os_capabilities() -> OSCapabilities {
lazy_static! {
static ref OS_CAPABILITIES: OSCapabilities = {
let version: NSOperatingSystemVersion = unsafe {
let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
let atleast_ios_8: BOOL = msg_send![
process_info,
respondsToSelector: sel!(operatingSystemVersion)
];
// winit requires atleast iOS 8 because no one has put the time into supporting earlier os versions.
// Older iOS versions are increasingly difficult to test. For example, Xcode 11 does not support
// debugging on devices with an iOS version of less than 8. Another example, in order to use an iOS
// simulator older than iOS 8, you must download an older version of Xcode (<9), and at least Xcode 7
// has been tested to not even run on macOS 10.15 - Xcode 8 might?
//
// The minimum required iOS version is likely to grow in the future.
assert!(
atleast_ios_8 == YES,
"`winit` requires iOS version 8 or greater"
);
msg_send![process_info, operatingSystemVersion]
};
version.into()
static OS_CAPABILITIES: Lazy<OSCapabilities> = Lazy::new(|| {
let version: NSOperatingSystemVersion = unsafe {
let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
let atleast_ios_8: BOOL = msg_send![
process_info,
respondsToSelector: sel!(operatingSystemVersion)
];
// winit requires atleast iOS 8 because no one has put the time into supporting earlier os versions.
// Older iOS versions are increasingly difficult to test. For example, Xcode 11 does not support
// debugging on devices with an iOS version of less than 8. Another example, in order to use an iOS
// simulator older than iOS 8, you must download an older version of Xcode (<9), and at least Xcode 7
// has been tested to not even run on macOS 10.15 - Xcode 8 might?
//
// The minimum required iOS version is likely to grow in the future.
assert!(
atleast_ios_8 == YES,
"`winit` requires iOS version 8 or greater"
);
msg_send![process_info, operatingSystemVersion]
};
}
version.into()
});
OS_CAPABILITIES.clone()
}
8 changes: 4 additions & 4 deletions src/platform_impl/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ use std::{collections::VecDeque, env, fmt};
#[cfg(feature = "x11")]
use std::{ffi::CStr, mem::MaybeUninit, os::raw::*, sync::Arc};

#[cfg(feature = "x11")]
use once_cell::sync::Lazy;
#[cfg(feature = "x11")]
use parking_lot::Mutex;
use raw_window_handle::RawWindowHandle;
Expand Down Expand Up @@ -135,10 +137,8 @@ impl Default for PlatformSpecificWindowBuilderAttributes {
}

#[cfg(feature = "x11")]
lazy_static! {
pub static ref X11_BACKEND: Mutex<Result<Arc<XConnection>, XNotSupported>> =
Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new));
}
pub static X11_BACKEND: Lazy<Mutex<Result<Arc<XConnection>, XNotSupported>>> =
Lazy::new(|| Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new)));

#[derive(Debug, Clone)]
pub enum OsError {
Expand Down
5 changes: 2 additions & 3 deletions src/platform_impl/linux/x11/ime/input_method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@ use std::{
sync::Arc,
};

use once_cell::sync::Lazy;
use parking_lot::Mutex;

use super::{ffi, util, XConnection, XError};

lazy_static! {
static ref GLOBAL_LOCK: Mutex<()> = Default::default();
}
static GLOBAL_LOCK: Lazy<Mutex<()>> = Lazy::new(Default::default);

unsafe fn open_im(xconn: &Arc<XConnection>, locale_modifiers: &CStr) -> Option<ffi::XIM> {
let _lock = GLOBAL_LOCK.lock();
Expand Down
5 changes: 2 additions & 3 deletions src/platform_impl/linux/x11/monitor.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::os::raw::*;

use once_cell::sync::Lazy;
use parking_lot::Mutex;

use super::{
Expand All @@ -18,9 +19,7 @@ use crate::{
// Used for testing. This should always be committed as false.
const DISABLE_MONITOR_LIST_CACHING: bool = false;

lazy_static! {
static ref MONITORS: Mutex<Option<Vec<MonitorHandle>>> = Mutex::default();
}
static MONITORS: Lazy<Mutex<Option<Vec<MonitorHandle>>>> = Lazy::new(Mutex::default);

pub fn invalidate_cached_monitor_list() -> Option<Vec<MonitorHandle>> {
// We update this lazily.
Expand Down
5 changes: 2 additions & 3 deletions src/platform_impl/linux/x11/util/atom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ use std::{
os::raw::*,
};

use once_cell::sync::Lazy;
use parking_lot::Mutex;

use super::*;

type AtomCache = HashMap<CString, ffi::Atom>;

lazy_static! {
static ref ATOM_CACHE: Mutex<AtomCache> = Mutex::new(HashMap::with_capacity(2048));
}
static ATOM_CACHE: Lazy<Mutex<AtomCache>> = Lazy::new(|| Mutex::new(HashMap::with_capacity(2048)));

impl XConnection {
pub fn get_atom<T: AsRef<CStr> + Debug>(&self, name: T) -> ffi::Atom {
Expand Down
8 changes: 4 additions & 4 deletions src/platform_impl/linux/x11/util/wm.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use once_cell::sync::Lazy;
use parking_lot::Mutex;

use super::*;

// This info is global to the window manager.
lazy_static! {
static ref SUPPORTED_HINTS: Mutex<Vec<ffi::Atom>> = Mutex::new(Vec::with_capacity(0));
static ref WM_NAME: Mutex<Option<String>> = Mutex::new(None);
}
static SUPPORTED_HINTS: Lazy<Mutex<Vec<ffi::Atom>>> =
Lazy::new(|| Mutex::new(Vec::with_capacity(0)));
static WM_NAME: Lazy<Mutex<Option<String>>> = Lazy::new(|| Mutex::new(None));

pub fn hint_is_supported(hint: ffi::Atom) -> bool {
(*SUPPORTED_HINTS.lock()).contains(&hint)
Expand Down
21 changes: 10 additions & 11 deletions src/platform_impl/macos/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use objc::{
declare::ClassDecl,
runtime::{Class, Object, Sel},
};
use once_cell::sync::Lazy;

use super::{app_state::AppState, event::EventWrapper, util, DEVICE_ID};
use crate::event::{DeviceEvent, ElementState, Event};
Expand All @@ -16,19 +17,17 @@ pub struct AppClass(pub *const Class);
unsafe impl Send for AppClass {}
unsafe impl Sync for AppClass {}

lazy_static! {
pub static ref APP_CLASS: AppClass = unsafe {
let superclass = class!(NSApplication);
let mut decl = ClassDecl::new("WinitApp", superclass).unwrap();
pub static APP_CLASS: Lazy<AppClass> = Lazy::new(|| unsafe {
let superclass = class!(NSApplication);
let mut decl = ClassDecl::new("WinitApp", superclass).unwrap();

decl.add_method(
sel!(sendEvent:),
send_event as extern "C" fn(&Object, Sel, id),
);
decl.add_method(
sel!(sendEvent:),
send_event as extern "C" fn(&Object, Sel, id),
);

AppClass(decl.register())
};
}
AppClass(decl.register())
});

// Normally, holding Cmd + any key never sends us a `keyUp` event for that key.
// Overriding `sendEvent:` like this fixes that. (https://stackoverflow.com/a/15294196)
Expand Down
38 changes: 19 additions & 19 deletions src/platform_impl/macos/app_delegate.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use crate::{platform::macos::ActivationPolicy, platform_impl::platform::app_state::AppState};
use std::{
cell::{RefCell, RefMut},
os::raw::c_void,
};

use cocoa::base::id;
use objc::{
declare::ClassDecl,
runtime::{Class, Object, Sel},
};
use std::{
cell::{RefCell, RefMut},
os::raw::c_void,
};
use once_cell::sync::Lazy;

use crate::{platform::macos::ActivationPolicy, platform_impl::platform::app_state::AppState};

static AUX_DELEGATE_STATE_NAME: &str = "auxState";

Expand All @@ -21,23 +23,21 @@ pub struct AppDelegateClass(pub *const Class);
unsafe impl Send for AppDelegateClass {}
unsafe impl Sync for AppDelegateClass {}

lazy_static! {
pub static ref APP_DELEGATE_CLASS: AppDelegateClass = unsafe {
let superclass = class!(NSResponder);
let mut decl = ClassDecl::new("WinitAppDelegate", superclass).unwrap();
pub static APP_DELEGATE_CLASS: Lazy<AppDelegateClass> = Lazy::new(|| unsafe {
let superclass = class!(NSResponder);
let mut decl = ClassDecl::new("WinitAppDelegate", superclass).unwrap();

decl.add_class_method(sel!(new), new as extern "C" fn(&Class, Sel) -> id);
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel));
decl.add_class_method(sel!(new), new as extern "C" fn(&Class, Sel) -> id);
decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel));

decl.add_method(
sel!(applicationDidFinishLaunching:),
did_finish_launching as extern "C" fn(&Object, Sel, id),
);
decl.add_ivar::<*mut c_void>(AUX_DELEGATE_STATE_NAME);
decl.add_method(
sel!(applicationDidFinishLaunching:),
did_finish_launching as extern "C" fn(&Object, Sel, id),
);
decl.add_ivar::<*mut c_void>(AUX_DELEGATE_STATE_NAME);

AppDelegateClass(decl.register())
};
}
AppDelegateClass(decl.register())
});

/// Safety: Assumes that Object is an instance of APP_DELEGATE_CLASS
pub unsafe fn get_aux_state_mut(this: &Object) -> RefMut<'_, AuxDelegateState> {
Expand Down
5 changes: 2 additions & 3 deletions src/platform_impl/macos/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use objc::{
rc::autoreleasepool,
runtime::{Object, BOOL, NO, YES},
};
use once_cell::sync::Lazy;

use crate::{
dpi::LogicalSize,
Expand All @@ -41,9 +42,7 @@ use crate::{
window::WindowId,
};

lazy_static! {
static ref HANDLER: Handler = Default::default();
}
static HANDLER: Lazy<Handler> = Lazy::new(Default::default);

impl<'a, Never> Event<'a, Never> {
fn userify<T: 'static>(self) -> Event<'a, T> {
Expand Down
Loading

0 comments on commit 2c01e9e

Please sign in to comment.