Skip to content
Merged
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
7 changes: 0 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 1 addition & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ x11 = [ "dep:gdkx11-sys", "dep:x11-dl" ]
members = [ "tao-macros" ]

[dependencies]
lazy_static = "1"
libc = "0.2"
log = "0.4"
once_cell = "1"
serde = { version = "1", optional = true, features = [ "serde_derive" ] }
rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true }
rwh_05 = { package = "raw-window-handle", version = "0.5", features = [ "std" ], optional = true }
Expand Down Expand Up @@ -96,9 +96,6 @@ windows-core = "0.61"
"Win32_UI_WindowsAndMessaging"
]

[target."cfg(any(target_os = \"android\", target_os = \"windows\"))".dependencies]
once_cell = "1"

[target."cfg(target_os = \"android\")".dependencies]
jni = "0.21"
ndk = "0.9"
Expand Down
2 changes: 1 addition & 1 deletion examples/window_run_return.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn main() {

if let Event::WindowEvent { event, .. } = &event {
// Print only Window events to reduce noise
println!("{:?}", event);
println!("{event:?}");
}

match event {
Expand Down
10 changes: 10 additions & 0 deletions src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,16 @@ impl<T> EventLoopBuilder<T> {
#[inline]
pub fn build(&mut self) -> EventLoop<T> {
EventLoop {
#[cfg_attr(
any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
),
allow(clippy::unnecessary_mut_passed)
)]
event_loop: platform_impl::EventLoop::new(&mut self.platform_specific),
_marker: PhantomData,
}
Expand Down
3 changes: 0 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,6 @@ pub use rwh_05;
#[cfg(feature = "rwh_06")]
pub use rwh_06;

#[allow(unused_imports)]
#[macro_use]
extern crate lazy_static;
#[allow(unused_imports)]
#[macro_use]
extern crate log;
Expand Down
2 changes: 1 addition & 1 deletion src/platform/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl WindowExtUnix for Window {
window: gtk::ApplicationWindow,
) -> Result<Window, OsError> {
let window = UnixWindow::new_from_gtk_window(&event_loop_window_target.p, window)?;
Ok(Window { window: window })
Ok(Window { window })
}

fn set_badge_count(&self, count: Option<i64>, desktop_filename: Option<String>) {
Expand Down
5 changes: 2 additions & 3 deletions src/platform_impl/android/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use ndk::{
event::{InputEvent, KeyAction, MotionAction},
looper::{ForeignLooper, Poll, ThreadLooper},
};
use once_cell::sync::Lazy;
use std::{
collections::VecDeque,
sync::RwLock,
Expand All @@ -26,9 +27,7 @@ use std::{
pub mod ndk_glue;
use ndk_glue::{Event, Rect};

lazy_static! {
static ref CONFIG: RwLock<Configuration> = RwLock::new(Configuration::new());
}
static CONFIG: Lazy<RwLock<Configuration>> = Lazy::new(|| RwLock::new(Configuration::new()));

enum EventSource {
Callback,
Expand Down
44 changes: 20 additions & 24 deletions src/platform_impl/ios/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use std::{
};

use objc2::runtime::AnyObject;
use once_cell::sync::Lazy;

use crate::{
dpi::LogicalSize,
Expand Down Expand Up @@ -1005,29 +1006,24 @@ 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)
];
// tao 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,
"`tao` 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)
];
// tao 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, "`tao` requires iOS version 8 or greater");
msg_send![process_info, operatingSystemVersion]
};
version.into()
});
OS_CAPABILITIES.clone()
}
43 changes: 20 additions & 23 deletions src/platform_impl/linux/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,35 +45,32 @@ pub fn spawn(device_tx: glib::Sender<DeviceEvent>) {
}

let event_type = event.get_type();
match event_type {
xlib::GenericEvent => {
let mut xev = event.generic_event_cookie;
if (xlib.XGetEventData)(display, &mut xev) == xlib::True {
match xev.evtype {
xinput2::XI_RawKeyPress | xinput2::XI_RawKeyRelease => {
let xev: &xinput2::XIRawEvent = &*(xev.data as *const _);
let physical_key = keycode_from_scancode(xev.detail as u32);
let state = match xev.evtype {
xinput2::XI_RawKeyPress => ElementState::Pressed,
xinput2::XI_RawKeyRelease => ElementState::Released,
_ => unreachable!(),
};
if event_type == xlib::GenericEvent {
let mut xev = event.generic_event_cookie;
if (xlib.XGetEventData)(display, &mut xev) == xlib::True {
match xev.evtype {
xinput2::XI_RawKeyPress | xinput2::XI_RawKeyRelease => {
let xev: &xinput2::XIRawEvent = &*(xev.data as *const _);
let physical_key = keycode_from_scancode(xev.detail as u32);
let state = match xev.evtype {
xinput2::XI_RawKeyPress => ElementState::Pressed,
xinput2::XI_RawKeyRelease => ElementState::Released,
_ => unreachable!(),
};

let event = RawKeyEvent {
physical_key,
state,
};
let event = RawKeyEvent {
physical_key,
state,
};

if let Err(e) = device_tx.send(DeviceEvent::Key(event)) {
log::info!("Failed to send device event {} since receiver is closed. Closing x11 thread along with it", e);
break;
}
if let Err(e) = device_tx.send(DeviceEvent::Key(event)) {
log::info!("Failed to send device event {} since receiver is closed. Closing x11 thread along with it", e);
break;
}
_ => {}
}
_ => {}
}
}
_ => {}
}
}
});
Expand Down
11 changes: 5 additions & 6 deletions src/platform_impl/linux/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,8 @@ impl<T> EventLoopWindowTarget<T> {
#[inline]
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
let monitor = self.display.primary_monitor();
monitor.and_then(|monitor| {
let handle = MonitorHandle { monitor };
Some(RootMonitorHandle { inner: handle })
monitor.map(|monitor| RootMonitorHandle {
inner: MonitorHandle { monitor },
})
}

Expand Down Expand Up @@ -910,7 +909,7 @@ impl<T: 'static> EventLoop<T> {
let background_color = unsafe {
window
.data::<Option<crate::window::RGBA>>("background_color")
.and_then(|c| c.as_ref().clone())
.and_then(|c| *c.as_ref())
};

let rgba = background_color
Expand Down Expand Up @@ -1010,7 +1009,7 @@ impl<T: 'static> EventLoop<T> {
/// There are a dew notibale event will sent to callback when state is transisted:
/// - On any state moves to `LoopDestroyed`, a `LoopDestroyed` event is sent.
/// - On `NewStart` to `EventQueue`, a `NewEvents` with corresponding `StartCause` depends on
/// current control flow is sent.
/// current control flow is sent.
/// - On `EventQueue` to `DrawQueue`, a `MainEventsCleared` event is sent.
/// - On `DrawQueue` back to `NewStart`, a `RedrawEventsCleared` event is sent.
pub(crate) fn run_return<F>(&mut self, mut callback: F) -> i32
Expand Down Expand Up @@ -1097,7 +1096,7 @@ impl<T: 'static> EventLoop<T> {
EventState::EventQueue => match control_flow {
ControlFlow::ExitWithCode(code) => {
callback(Event::LoopDestroyed, window_target, &mut control_flow);
break (code);
break code;
}
_ => match events.try_recv() {
Ok(event) => match event {
Expand Down
9 changes: 4 additions & 5 deletions src/platform_impl/linux/keyboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use gtk::{
gdk::{self, keys::constants::*, EventKey},
glib,
};
use once_cell::sync::Lazy;
use std::{
collections::HashSet,
ffi::c_void,
Expand All @@ -21,9 +22,7 @@ use std::{

pub type RawKey = gdk::keys::Key;

lazy_static! {
static ref KEY_STRINGS: Mutex<HashSet<&'static str>> = Mutex::new(HashSet::new());
}
static KEY_STRINGS: Lazy<Mutex<HashSet<&'static str>>> = Lazy::new(|| Mutex::new(HashSet::new()));

fn insert_or_get_key_str(string: String) -> &'static str {
let mut string_set = KEY_STRINGS.lock().unwrap();
Expand Down Expand Up @@ -188,15 +187,15 @@ pub(crate) fn make_key_event(
// a keyval (keysym in X) is a "logical" key name, such as GDK_Enter, GDK_a, GDK_space, etc.
let keyval_without_modifiers = key.keyval();
let keyval_with_modifiers =
hardware_keycode_to_keyval(scancode).unwrap_or_else(|| keyval_without_modifiers.clone());
hardware_keycode_to_keyval(scancode).unwrap_or(keyval_without_modifiers);
// get unicode value, with and without modifiers
let text_without_modifiers = keyval_with_modifiers.to_unicode();
let text_with_modifiers = keyval_without_modifiers.to_unicode();
// get physical key from the scancode (keycode)
let physical_key = key_override.unwrap_or_else(|| KeyCode::from_scancode(scancode as u32));

// extract key without modifier
let key_without_modifiers = raw_key_to_key(keyval_with_modifiers.clone()).unwrap_or_else(|| {
let key_without_modifiers = raw_key_to_key(keyval_with_modifiers).unwrap_or_else(|| {
if let Some(key) = text_without_modifiers {
if key >= ' ' && key != '\x7f' {
Key::Character(insert_or_get_key_str(key.to_string()))
Expand Down
9 changes: 2 additions & 7 deletions src/platform_impl/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,13 @@ pub struct KeyEventExtra {
}

#[non_exhaustive]
#[derive(Clone)]
#[derive(Clone, Default)]
pub enum Parent {
#[default]
None,
ChildOf(gtk::Window),
}

impl Default for Parent {
fn default() -> Self {
Parent::None
}
}

#[derive(Clone)]
pub struct PlatformSpecificWindowBuilderAttributes {
pub parent: Parent,
Expand Down
9 changes: 3 additions & 6 deletions src/platform_impl/linux/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ use std::{
cell::RefCell,
collections::VecDeque,
rc::Rc,
sync::{
atomic::{AtomicBool, AtomicI32, Ordering},
Arc,
},
sync::atomic::{AtomicBool, AtomicI32, Ordering},
};

use gtk::{
Expand Down Expand Up @@ -48,7 +45,7 @@ impl WindowId {

// Currently GTK doesn't provide feature for detect theme, so we need to check theme manually.
// ref: https://github.com/WebKit/WebKit/blob/e44ffaa0d999a9807f76f1805943eea204cfdfbc/Source/WebKit/UIProcess/API/gtk/PageClientImpl.cpp#L587
const GTK_THEME_SUFFIX_LIST: [&'static str; 3] = ["-dark", "-Dark", "-Darker"];
const GTK_THEME_SUFFIX_LIST: [&str; 3] = ["-dark", "-Dark", "-Darker"];

pub struct Window {
/// Window id.
Expand Down Expand Up @@ -233,7 +230,7 @@ impl Window {
// restore accept-focus after the window has been drawn
// if the window was initially created without focus and is supposed to be focusable
if attributes.focusable && !attributes.focused {
let signal_id = Arc::new(RefCell::new(None));
let signal_id = Rc::new(RefCell::new(None));
let signal_id_ = signal_id.clone();
let id = window.connect_draw(move |window, _| {
if let Some(id) = signal_id_.take() {
Expand Down
17 changes: 8 additions & 9 deletions src/platform_impl/macos/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{collections::VecDeque, ffi::CStr};

use objc2::runtime::{AnyClass as Class, ClassBuilder as ClassDecl, Sel};
use objc2_app_kit::{self as appkit, NSApplication, NSEvent, NSEventType};
use once_cell::sync::Lazy;

use super::{app_state::AppState, event::EventWrapper, util, DEVICE_ID};
use crate::event::{DeviceEvent, ElementState, Event};
Expand All @@ -14,17 +15,15 @@ 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(CStr::from_bytes_with_nul(b"TaoApp\0").unwrap(), superclass).unwrap();
pub static APP_CLASS: Lazy<AppClass> = Lazy::new(|| unsafe {
let superclass = class!(NSApplication);
let mut decl =
ClassDecl::new(CStr::from_bytes_with_nul(b"TaoApp\0").unwrap(), superclass).unwrap();

decl.add_method(sel!(sendEvent:), send_event as extern "C" fn(_, _, _));
decl.add_method(sel!(sendEvent:), send_event as extern "C" fn(_, _, _));

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
Loading
Loading