mirror of
https://github.com/rust-windowing/winit.git
synced 2026-06-26 22:53:15 -04:00
Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b6c8ef323 | ||
|
|
2e63493776 | ||
|
|
d2acea95cc | ||
|
|
454dc56a6e | ||
|
|
016fd47d0d | ||
|
|
8ce5f6ea41 | ||
|
|
64084c5cf0 | ||
|
|
96d29ab26c | ||
|
|
3e42fa364c | ||
|
|
cb855b87cc | ||
|
|
9c033ce101 | ||
|
|
54ad02e4b9 | ||
|
|
00fe65630e | ||
|
|
961b675d34 | ||
|
|
bcd2fba4a0 | ||
|
|
0135fe51ae | ||
|
|
ed600e415a | ||
|
|
ad892c6949 | ||
|
|
a6b25643ad | ||
|
|
bc5b6ff8ce | ||
|
|
ba6254bc25 | ||
|
|
bd2d2760f0 | ||
|
|
3de08204d3 | ||
|
|
c9030f06c0 | ||
|
|
3035546b17 | ||
|
|
57cb3126d6 | ||
|
|
221b2e71cd | ||
|
|
0dc376a9ef | ||
|
|
85052c09bb | ||
|
|
be63581654 | ||
|
|
45b5f3b031 | ||
|
|
0270516067 | ||
|
|
a90cd1c9ad |
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@@ -81,7 +81,7 @@ jobs:
|
||||
|
||||
- name: Generate lockfile
|
||||
# Also updates the crates.io index
|
||||
run: cargo generate-lockfile
|
||||
run: cargo generate-lockfile && cargo update -p ahash --precise 0.8.7 && cargo update -p bumpalo --precise 3.14.0
|
||||
|
||||
- name: Install GCC Multilib
|
||||
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
|
||||
|
||||
36
CHANGELOG.md
36
CHANGELOG.md
@@ -11,6 +11,42 @@ Unreleased` header.
|
||||
|
||||
# Unreleased
|
||||
|
||||
# 0.29.11
|
||||
|
||||
- On Wayland, fix DeviceEvent::Motion not being sent
|
||||
- On X11, don't require XIM to run.
|
||||
- On X11, fix xkb state not being updated correctly sometimes leading to wrong input.
|
||||
- Fix compatibility with 32-bit platforms without 64-bit atomics.
|
||||
- On macOS, fix incorrect IME cursor rect origin.
|
||||
- On X11, fix swapped instance and general class names.
|
||||
- On Windows, fixed a race condition when sending an event through the loop proxy.
|
||||
- On Wayland, disable `Occluded` event handling.
|
||||
- On X11, reload dpi on `_XSETTINGS_SETTINGS` update.
|
||||
- On X11, fix deadlock when adjusting DPI and resizing at the same time.
|
||||
- On Wayland, fix `Focused(false)` being send when other seats still have window focused.
|
||||
- On Wayland, fix `Window::set_{min,max}_inner_size` not always applied.
|
||||
- On Windows, fix inconsistent resizing behavior with multi-monitor setups when repositioning outside the event loop.
|
||||
- On Wayland, fix `WAYLAND_SOCKET` not used when detecting platform.
|
||||
- On Orbital, fix `logical_key` and `text` not reported in `KeyEvent`.
|
||||
- On Orbital, implement `KeyEventExtModifierSupplement`.
|
||||
- On Orbital, map keys to `NamedKey` when possible.
|
||||
- On Orbital, implement `set_cursor_grab`.
|
||||
- On Orbital, implement `set_cursor_visible`.
|
||||
- On Orbital, implement `drag_window`.
|
||||
- On Orbital, implement `drag_resize_window`.
|
||||
- On Orbital, implement `set_transparent`.
|
||||
- On Orbital, implement `set_visible`.
|
||||
- On Orbital, implement `is_visible`.
|
||||
- On Orbital, implement `set_resizable`.
|
||||
- On Orbital, implement `is_resizable`.
|
||||
- On Orbital, implement `set_maximized`.
|
||||
- On Orbital, implement `is_maximized`.
|
||||
- On Orbital, implement `set_decorations`.
|
||||
- On Orbital, implement `is_decorated`.
|
||||
- On Orbital, implement `set_window_level`.
|
||||
- On Orbital, emit `DeviceEvent::MouseMotion`.
|
||||
- On Wayland, fix title in CSD not updated from `AboutToWait`.
|
||||
|
||||
# 0.29.10
|
||||
|
||||
- On Web, account for canvas being focused already before event loop starts.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "winit"
|
||||
version = "0.29.10"
|
||||
version = "0.29.11"
|
||||
authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
||||
description = "Cross-platform window creation library."
|
||||
edition = "2021"
|
||||
@@ -167,7 +167,7 @@ wayland-protocols = { version = "0.31.0", features = [ "staging"], optional = tr
|
||||
wayland-protocols-plasma = { version = "0.2.0", features = [ "client" ], optional = true }
|
||||
x11-dl = { version = "2.18.5", optional = true }
|
||||
x11rb = { version = "0.13.0", default-features = false, features = ["allow-unsafe-code", "dl-libxcb", "randr", "resource_manager", "xinput", "xkb"], optional = true }
|
||||
xkbcommon-dl = "0.4.0"
|
||||
xkbcommon-dl = "0.4.2"
|
||||
|
||||
[target.'cfg(target_os = "redox")'.dependencies]
|
||||
orbclient = { version = "0.3.42", default-features = false }
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
winit = "0.29.10"
|
||||
winit = "0.29.11"
|
||||
```
|
||||
|
||||
## [Documentation](https://docs.rs/winit)
|
||||
@@ -150,13 +150,13 @@ class. Your application _must_ specify the base class it needs via a feature fla
|
||||
[agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries
|
||||
[Gradle]: https://developer.android.com/studio/build
|
||||
|
||||
For more details, refer to these `android-activity` [example applications](https://github.com/rib/android-activity/tree/main/examples).
|
||||
For more details, refer to these `android-activity` [example applications](https://github.com/rust-mobile/android-activity/tree/main/examples).
|
||||
|
||||
##### Converting from `ndk-glue` to `android-activity`
|
||||
|
||||
If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building with `cargo apk`, then the minimal changes would be:
|
||||
1. Remove `ndk-glue` from your `Cargo.toml`
|
||||
2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.10", features = [ "android-native-activity" ] }`
|
||||
2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.11", features = [ "android-native-activity" ] }`
|
||||
3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize logging as above).
|
||||
4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ mod platform {
|
||||
// ManuallyDrop to prevent destructors from running.
|
||||
//
|
||||
// A static, thread-local map of graphics contexts to open windows.
|
||||
static GC: ManuallyDrop<RefCell<Option<GraphicsContext>>> = ManuallyDrop::new(RefCell::new(None));
|
||||
static GC: ManuallyDrop<RefCell<Option<GraphicsContext>>> = const { ManuallyDrop::new(RefCell::new(None)) };
|
||||
}
|
||||
|
||||
/// The graphics context used to draw to a window.
|
||||
|
||||
@@ -7,7 +7,6 @@ pub fn main() {
|
||||
#[cfg(wasm_platform)]
|
||||
mod wasm {
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen::JsCast;
|
||||
use web_sys::HtmlCanvasElement;
|
||||
use winit::{
|
||||
dpi::PhysicalSize,
|
||||
|
||||
@@ -574,7 +574,7 @@ pub enum WindowEvent {
|
||||
/// ### Others
|
||||
///
|
||||
/// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`].
|
||||
/// - **Android / Windows / Orbital:** Unsupported.
|
||||
/// - **Android / Wayland / Windows / Orbital:** Unsupported.
|
||||
///
|
||||
/// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
|
||||
/// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::{error, fmt};
|
||||
|
||||
#[cfg(not(wasm_platform))]
|
||||
@@ -459,16 +459,16 @@ pub enum DeviceEvents {
|
||||
/// executed and removed from the list.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AsyncRequestSerial {
|
||||
serial: u64,
|
||||
serial: usize,
|
||||
}
|
||||
|
||||
impl AsyncRequestSerial {
|
||||
// TODO(kchibisov) remove `cfg` when the clipboard will be added.
|
||||
// TODO(kchibisov): Remove `cfg` when the clipboard will be added.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn get() -> Self {
|
||||
static CURRENT_SERIAL: AtomicU64 = AtomicU64::new(0);
|
||||
// NOTE: we rely on wrap around here, while the user may just request
|
||||
// in the loop u64::MAX times that's issue is considered on them.
|
||||
static CURRENT_SERIAL: AtomicUsize = AtomicUsize::new(0);
|
||||
// NOTE: We rely on wrap around here, while the user may just request
|
||||
// in the loop usize::MAX times that's issue is considered on them.
|
||||
let serial = CURRENT_SERIAL.fetch_add(1, Ordering::Relaxed);
|
||||
Self { serial }
|
||||
}
|
||||
|
||||
@@ -53,5 +53,13 @@ pub mod run_on_demand;
|
||||
))]
|
||||
pub mod pump_events;
|
||||
|
||||
#[cfg(any(
|
||||
windows_platform,
|
||||
macos_platform,
|
||||
x11_platform,
|
||||
wayland_platform,
|
||||
orbital_platform,
|
||||
docsrs
|
||||
))]
|
||||
pub mod modifier_supplement;
|
||||
pub mod scancode;
|
||||
|
||||
@@ -96,7 +96,7 @@ pub trait WindowBuilderExtX11 {
|
||||
/// Build window with the given `general` and `instance` names.
|
||||
///
|
||||
/// The `general` sets general class of `WM_CLASS(STRING)`, while `instance` set the
|
||||
/// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "general", "instance"`.
|
||||
/// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "instance", "general"`.
|
||||
///
|
||||
/// For details about application ID conventions, see the
|
||||
/// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)]
|
||||
|
||||
use std::convert::TryInto;
|
||||
|
||||
use icrate::Foundation::{NSInteger, NSUInteger};
|
||||
use objc2::encode::{Encode, Encoding};
|
||||
|
||||
|
||||
@@ -1,2 +1 @@
|
||||
pub mod keymap;
|
||||
pub mod xkb_state;
|
||||
pub mod xkb;
|
||||
|
||||
124
src/platform_impl/linux/common/xkb/compose.rs
Normal file
124
src/platform_impl/linux/common/xkb/compose.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
//! XKB compose handling.
|
||||
|
||||
use std::env;
|
||||
use std::ffi::CString;
|
||||
use std::ops::Deref;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use super::XkbContext;
|
||||
use super::XKBCH;
|
||||
use smol_str::SmolStr;
|
||||
use xkbcommon_dl::{
|
||||
xkb_compose_compile_flags, xkb_compose_feed_result, xkb_compose_state, xkb_compose_state_flags,
|
||||
xkb_compose_status, xkb_compose_table, xkb_keysym_t,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbComposeTable {
|
||||
table: NonNull<xkb_compose_table>,
|
||||
}
|
||||
|
||||
impl XkbComposeTable {
|
||||
pub fn new(context: &XkbContext) -> Option<Self> {
|
||||
let locale = env::var_os("LC_ALL")
|
||||
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||
.or_else(|| env::var_os("LC_CTYPE"))
|
||||
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||
.or_else(|| env::var_os("LANG"))
|
||||
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||
.unwrap_or_else(|| "C".into());
|
||||
let locale = CString::new(locale.into_vec()).unwrap();
|
||||
|
||||
let table = unsafe {
|
||||
(XKBCH.xkb_compose_table_new_from_locale)(
|
||||
context.as_ptr(),
|
||||
locale.as_ptr(),
|
||||
xkb_compose_compile_flags::XKB_COMPOSE_COMPILE_NO_FLAGS,
|
||||
)
|
||||
};
|
||||
|
||||
let table = NonNull::new(table)?;
|
||||
Some(Self { table })
|
||||
}
|
||||
|
||||
/// Create new state with the given compose table.
|
||||
pub fn new_state(&self) -> Option<XkbComposeState> {
|
||||
let state = unsafe {
|
||||
(XKBCH.xkb_compose_state_new)(
|
||||
self.table.as_ptr(),
|
||||
xkb_compose_state_flags::XKB_COMPOSE_STATE_NO_FLAGS,
|
||||
)
|
||||
};
|
||||
|
||||
let state = NonNull::new(state)?;
|
||||
Some(XkbComposeState { state })
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for XkbComposeTable {
|
||||
type Target = NonNull<xkb_compose_table>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.table
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbComposeTable {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBCH.xkb_compose_table_unref)(self.table.as_ptr());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbComposeState {
|
||||
state: NonNull<xkb_compose_state>,
|
||||
}
|
||||
|
||||
impl XkbComposeState {
|
||||
pub fn get_string(&mut self, scratch_buffer: &mut Vec<u8>) -> Option<SmolStr> {
|
||||
super::make_string_with(scratch_buffer, |ptr, len| unsafe {
|
||||
(XKBCH.xkb_compose_state_get_utf8)(self.state.as_ptr(), ptr, len)
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn feed(&mut self, keysym: xkb_keysym_t) -> ComposeStatus {
|
||||
let feed_result = unsafe { (XKBCH.xkb_compose_state_feed)(self.state.as_ptr(), keysym) };
|
||||
match feed_result {
|
||||
xkb_compose_feed_result::XKB_COMPOSE_FEED_IGNORED => ComposeStatus::Ignored,
|
||||
xkb_compose_feed_result::XKB_COMPOSE_FEED_ACCEPTED => {
|
||||
ComposeStatus::Accepted(self.status())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn reset(&mut self) {
|
||||
unsafe {
|
||||
(XKBCH.xkb_compose_state_reset)(self.state.as_ptr());
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn status(&mut self) -> xkb_compose_status {
|
||||
unsafe { (XKBCH.xkb_compose_state_get_status)(self.state.as_ptr()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbComposeState {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBCH.xkb_compose_state_unref)(self.state.as_ptr());
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum ComposeStatus {
|
||||
Accepted(xkb_compose_status),
|
||||
Ignored,
|
||||
None,
|
||||
}
|
||||
@@ -1,6 +1,24 @@
|
||||
//! Convert XKB keys to Winit keys.
|
||||
//! XKB keymap.
|
||||
|
||||
use std::ffi::c_char;
|
||||
use std::ops::Deref;
|
||||
use std::ptr::{self, NonNull};
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
use x11_dl::xlib_xcb::xcb_connection_t;
|
||||
#[cfg(wayland_platform)]
|
||||
use {memmap2::MmapOptions, std::os::unix::io::OwnedFd};
|
||||
|
||||
use xkb::XKB_MOD_INVALID;
|
||||
use xkbcommon_dl::{
|
||||
self as xkb, xkb_keycode_t, xkb_keymap, xkb_keymap_compile_flags, xkb_keysym_t,
|
||||
xkb_layout_index_t, xkb_mod_index_t,
|
||||
};
|
||||
|
||||
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
||||
#[cfg(x11_platform)]
|
||||
use crate::platform_impl::common::xkb::XKBXH;
|
||||
use crate::platform_impl::common::xkb::{XkbContext, XKBH};
|
||||
|
||||
/// Map the raw X11-style keycode to the `KeyCode` enum.
|
||||
///
|
||||
@@ -894,3 +912,140 @@ pub fn keysym_location(keysym: u32) -> KeyLocation {
|
||||
_ => KeyLocation::Standard,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbKeymap {
|
||||
keymap: NonNull<xkb_keymap>,
|
||||
_mods_indices: ModsIndices,
|
||||
pub _core_keyboard_id: i32,
|
||||
}
|
||||
|
||||
impl XkbKeymap {
|
||||
#[cfg(wayland_platform)]
|
||||
pub fn from_fd(context: &XkbContext, fd: OwnedFd, size: usize) -> Option<Self> {
|
||||
let map = unsafe { MmapOptions::new().len(size).map_copy_read_only(&fd).ok()? };
|
||||
|
||||
let keymap = unsafe {
|
||||
let keymap = (XKBH.xkb_keymap_new_from_string)(
|
||||
(*context).as_ptr(),
|
||||
map.as_ptr() as *const _,
|
||||
xkb::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
|
||||
xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||
);
|
||||
NonNull::new(keymap)?
|
||||
};
|
||||
|
||||
Some(Self::new_inner(keymap, 0))
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn from_x11_keymap(
|
||||
context: &XkbContext,
|
||||
xcb: *mut xcb_connection_t,
|
||||
core_keyboard_id: i32,
|
||||
) -> Option<Self> {
|
||||
let keymap = unsafe {
|
||||
(XKBXH.xkb_x11_keymap_new_from_device)(
|
||||
context.as_ptr(),
|
||||
xcb,
|
||||
core_keyboard_id,
|
||||
xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||
)
|
||||
};
|
||||
let keymap = NonNull::new(keymap)?;
|
||||
Some(Self::new_inner(keymap, core_keyboard_id))
|
||||
}
|
||||
|
||||
fn new_inner(keymap: NonNull<xkb_keymap>, _core_keyboard_id: i32) -> Self {
|
||||
let mods_indices = ModsIndices {
|
||||
shift: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_SHIFT),
|
||||
caps: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_CAPS),
|
||||
ctrl: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_CTRL),
|
||||
alt: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_ALT),
|
||||
num: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_NUM),
|
||||
mod3: mod_index_for_name(keymap, b"Mod3\0"),
|
||||
logo: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_LOGO),
|
||||
mod5: mod_index_for_name(keymap, b"Mod5\0"),
|
||||
};
|
||||
|
||||
Self {
|
||||
keymap,
|
||||
_mods_indices: mods_indices,
|
||||
_core_keyboard_id,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn mods_indices(&self) -> ModsIndices {
|
||||
self._mods_indices
|
||||
}
|
||||
|
||||
pub fn first_keysym_by_level(
|
||||
&mut self,
|
||||
layout: xkb_layout_index_t,
|
||||
keycode: xkb_keycode_t,
|
||||
) -> xkb_keysym_t {
|
||||
unsafe {
|
||||
let mut keysyms = ptr::null();
|
||||
let count = (XKBH.xkb_keymap_key_get_syms_by_level)(
|
||||
self.keymap.as_ptr(),
|
||||
keycode,
|
||||
layout,
|
||||
// NOTE: The level should be zero to ignore modifiers.
|
||||
0,
|
||||
&mut keysyms,
|
||||
);
|
||||
|
||||
if count == 1 {
|
||||
*keysyms
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check whether the given key repeats.
|
||||
pub fn key_repeats(&mut self, keycode: xkb_keycode_t) -> bool {
|
||||
unsafe { (XKBH.xkb_keymap_key_repeats)(self.keymap.as_ptr(), keycode) == 1 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbKeymap {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBH.xkb_keymap_unref)(self.keymap.as_ptr());
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for XkbKeymap {
|
||||
type Target = NonNull<xkb_keymap>;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.keymap
|
||||
}
|
||||
}
|
||||
|
||||
/// Modifier index in the keymap.
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
pub struct ModsIndices {
|
||||
pub shift: Option<xkb_mod_index_t>,
|
||||
pub caps: Option<xkb_mod_index_t>,
|
||||
pub ctrl: Option<xkb_mod_index_t>,
|
||||
pub alt: Option<xkb_mod_index_t>,
|
||||
pub num: Option<xkb_mod_index_t>,
|
||||
pub mod3: Option<xkb_mod_index_t>,
|
||||
pub logo: Option<xkb_mod_index_t>,
|
||||
pub mod5: Option<xkb_mod_index_t>,
|
||||
}
|
||||
|
||||
fn mod_index_for_name(keymap: NonNull<xkb_keymap>, name: &[u8]) -> Option<xkb_mod_index_t> {
|
||||
unsafe {
|
||||
let mod_index =
|
||||
(XKBH.xkb_keymap_mod_get_index)(keymap.as_ptr(), name.as_ptr() as *const c_char);
|
||||
if mod_index == XKB_MOD_INVALID {
|
||||
None
|
||||
} else {
|
||||
Some(mod_index)
|
||||
}
|
||||
}
|
||||
}
|
||||
460
src/platform_impl/linux/common/xkb/mod.rs
Normal file
460
src/platform_impl/linux/common/xkb/mod.rs
Normal file
@@ -0,0 +1,460 @@
|
||||
use std::ops::Deref;
|
||||
use std::os::raw::c_char;
|
||||
use std::ptr::{self, NonNull};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use log::warn;
|
||||
use once_cell::sync::Lazy;
|
||||
use smol_str::SmolStr;
|
||||
#[cfg(wayland_platform)]
|
||||
use std::os::unix::io::OwnedFd;
|
||||
use xkbcommon_dl::{
|
||||
self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle,
|
||||
xkbcommon_handle, XkbCommon, XkbCommonCompose,
|
||||
};
|
||||
#[cfg(x11_platform)]
|
||||
use {x11_dl::xlib_xcb::xcb_connection_t, xkbcommon_dl::x11::xkbcommon_x11_handle};
|
||||
|
||||
use crate::event::ElementState;
|
||||
use crate::event::KeyEvent;
|
||||
use crate::keyboard::{Key, KeyLocation};
|
||||
use crate::platform_impl::KeyEventExtra;
|
||||
|
||||
mod compose;
|
||||
mod keymap;
|
||||
mod state;
|
||||
|
||||
use compose::{ComposeStatus, XkbComposeState, XkbComposeTable};
|
||||
use keymap::XkbKeymap;
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub use keymap::raw_keycode_to_physicalkey;
|
||||
pub use keymap::{physicalkey_to_scancode, scancode_to_keycode};
|
||||
pub use state::XkbState;
|
||||
|
||||
// TODO: Wire this up without using a static `AtomicBool`.
|
||||
static RESET_DEAD_KEYS: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
static XKBH: Lazy<&'static XkbCommon> = Lazy::new(xkbcommon_handle);
|
||||
static XKBCH: Lazy<&'static XkbCommonCompose> = Lazy::new(xkbcommon_compose_handle);
|
||||
#[cfg(feature = "x11")]
|
||||
static XKBXH: Lazy<&'static xkb::x11::XkbCommonX11> = Lazy::new(xkbcommon_x11_handle);
|
||||
|
||||
#[inline(always)]
|
||||
pub fn reset_dead_keys() {
|
||||
RESET_DEAD_KEYS.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
/// libxkbcommon is not available
|
||||
XKBNotFound,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Context {
|
||||
// NOTE: field order matters.
|
||||
#[cfg(x11_platform)]
|
||||
pub core_keyboard_id: i32,
|
||||
state: Option<XkbState>,
|
||||
keymap: Option<XkbKeymap>,
|
||||
compose_state1: Option<XkbComposeState>,
|
||||
compose_state2: Option<XkbComposeState>,
|
||||
_compose_table: Option<XkbComposeTable>,
|
||||
context: XkbContext,
|
||||
scratch_buffer: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new() -> Result<Self, Error> {
|
||||
if xkb::xkbcommon_option().is_none() {
|
||||
return Err(Error::XKBNotFound);
|
||||
}
|
||||
|
||||
let context = XkbContext::new()?;
|
||||
let mut compose_table = XkbComposeTable::new(&context);
|
||||
let mut compose_state1 = compose_table.as_ref().and_then(|table| table.new_state());
|
||||
let mut compose_state2 = compose_table.as_ref().and_then(|table| table.new_state());
|
||||
|
||||
// Disable compose if anything compose related failed to initialize.
|
||||
if compose_table.is_none() || compose_state1.is_none() || compose_state2.is_none() {
|
||||
compose_state2 = None;
|
||||
compose_state1 = None;
|
||||
compose_table = None;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
state: None,
|
||||
keymap: None,
|
||||
compose_state1,
|
||||
compose_state2,
|
||||
#[cfg(x11_platform)]
|
||||
core_keyboard_id: 0,
|
||||
_compose_table: compose_table,
|
||||
context,
|
||||
scratch_buffer: Vec::with_capacity(8),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
pub fn from_x11_xkb(xcb: *mut xcb_connection_t) -> Result<Self, Error> {
|
||||
let result = unsafe {
|
||||
(XKBXH.xkb_x11_setup_xkb_extension)(
|
||||
xcb,
|
||||
1,
|
||||
2,
|
||||
xkbcommon_dl::x11::xkb_x11_setup_xkb_extension_flags::XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS,
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
|
||||
if result != 1 {
|
||||
return Err(Error::XKBNotFound);
|
||||
}
|
||||
|
||||
let mut this = Self::new()?;
|
||||
this.core_keyboard_id = unsafe { (XKBXH.xkb_x11_get_core_keyboard_device_id)(xcb) };
|
||||
this.set_keymap_from_x11(xcb);
|
||||
Ok(this)
|
||||
}
|
||||
|
||||
pub fn state_mut(&mut self) -> Option<&mut XkbState> {
|
||||
self.state.as_mut()
|
||||
}
|
||||
|
||||
pub fn keymap_mut(&mut self) -> Option<&mut XkbKeymap> {
|
||||
self.keymap.as_mut()
|
||||
}
|
||||
|
||||
#[cfg(wayland_platform)]
|
||||
pub fn set_keymap_from_fd(&mut self, fd: OwnedFd, size: usize) {
|
||||
let keymap = XkbKeymap::from_fd(&self.context, fd, size);
|
||||
let state = keymap.as_ref().and_then(XkbState::new_wayland);
|
||||
if keymap.is_none() || state.is_none() {
|
||||
warn!("failed to update xkb keymap");
|
||||
}
|
||||
self.state = state;
|
||||
self.keymap = keymap;
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn set_keymap_from_x11(&mut self, xcb: *mut xcb_connection_t) {
|
||||
let keymap = XkbKeymap::from_x11_keymap(&self.context, xcb, self.core_keyboard_id);
|
||||
let state = keymap
|
||||
.as_ref()
|
||||
.and_then(|keymap| XkbState::new_x11(xcb, keymap));
|
||||
if keymap.is_none() || state.is_none() {
|
||||
warn!("failed to update xkb keymap");
|
||||
}
|
||||
self.state = state;
|
||||
self.keymap = keymap;
|
||||
}
|
||||
|
||||
/// Key builder context with the user provided xkb state.
|
||||
pub fn key_context(&mut self) -> Option<KeyContext<'_>> {
|
||||
let state = self.state.as_mut()?;
|
||||
let keymap = self.keymap.as_mut()?;
|
||||
let compose_state1 = self.compose_state1.as_mut();
|
||||
let compose_state2 = self.compose_state2.as_mut();
|
||||
let scratch_buffer = &mut self.scratch_buffer;
|
||||
Some(KeyContext {
|
||||
state,
|
||||
keymap,
|
||||
compose_state1,
|
||||
compose_state2,
|
||||
scratch_buffer,
|
||||
})
|
||||
}
|
||||
|
||||
/// Key builder context with the user provided xkb state.
|
||||
///
|
||||
/// Should be used when the original context must not be altered.
|
||||
#[cfg(x11_platform)]
|
||||
pub fn key_context_with_state<'a>(
|
||||
&'a mut self,
|
||||
state: &'a mut XkbState,
|
||||
) -> Option<KeyContext<'a>> {
|
||||
let keymap = self.keymap.as_mut()?;
|
||||
let compose_state1 = self.compose_state1.as_mut();
|
||||
let compose_state2 = self.compose_state2.as_mut();
|
||||
let scratch_buffer = &mut self.scratch_buffer;
|
||||
Some(KeyContext {
|
||||
state,
|
||||
keymap,
|
||||
compose_state1,
|
||||
compose_state2,
|
||||
scratch_buffer,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct KeyContext<'a> {
|
||||
pub state: &'a mut XkbState,
|
||||
pub keymap: &'a mut XkbKeymap,
|
||||
compose_state1: Option<&'a mut XkbComposeState>,
|
||||
compose_state2: Option<&'a mut XkbComposeState>,
|
||||
scratch_buffer: &'a mut Vec<u8>,
|
||||
}
|
||||
|
||||
impl<'a> KeyContext<'a> {
|
||||
pub fn process_key_event(
|
||||
&mut self,
|
||||
keycode: u32,
|
||||
state: ElementState,
|
||||
repeat: bool,
|
||||
) -> KeyEvent {
|
||||
let mut event =
|
||||
KeyEventResults::new(self, keycode, !repeat && state == ElementState::Pressed);
|
||||
let physical_key = keymap::raw_keycode_to_physicalkey(keycode);
|
||||
let (logical_key, location) = event.key();
|
||||
let text = event.text();
|
||||
let (key_without_modifiers, _) = event.key_without_modifiers();
|
||||
let text_with_all_modifiers = event.text_with_all_modifiers();
|
||||
|
||||
let platform_specific = KeyEventExtra {
|
||||
text_with_all_modifiers,
|
||||
key_without_modifiers,
|
||||
};
|
||||
|
||||
KeyEvent {
|
||||
physical_key,
|
||||
logical_key,
|
||||
text,
|
||||
location,
|
||||
state,
|
||||
repeat,
|
||||
platform_specific,
|
||||
}
|
||||
}
|
||||
|
||||
fn keysym_to_utf8_raw(&mut self, keysym: u32) -> Option<SmolStr> {
|
||||
self.scratch_buffer.clear();
|
||||
self.scratch_buffer.reserve(8);
|
||||
loop {
|
||||
let bytes_written = unsafe {
|
||||
(XKBH.xkb_keysym_to_utf8)(
|
||||
keysym,
|
||||
self.scratch_buffer.as_mut_ptr().cast(),
|
||||
self.scratch_buffer.capacity(),
|
||||
)
|
||||
};
|
||||
if bytes_written == 0 {
|
||||
return None;
|
||||
} else if bytes_written == -1 {
|
||||
self.scratch_buffer.reserve(8);
|
||||
} else {
|
||||
unsafe {
|
||||
self.scratch_buffer
|
||||
.set_len(bytes_written.try_into().unwrap())
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the null-terminator
|
||||
self.scratch_buffer.pop();
|
||||
byte_slice_to_smol_str(self.scratch_buffer)
|
||||
}
|
||||
}
|
||||
|
||||
struct KeyEventResults<'a, 'b> {
|
||||
context: &'a mut KeyContext<'b>,
|
||||
keycode: u32,
|
||||
keysym: u32,
|
||||
compose: ComposeStatus,
|
||||
}
|
||||
|
||||
impl<'a, 'b> KeyEventResults<'a, 'b> {
|
||||
fn new(context: &'a mut KeyContext<'b>, keycode: u32, compose: bool) -> Self {
|
||||
let keysym = context.state.get_one_sym_raw(keycode);
|
||||
|
||||
let compose = if let Some(state) = context.compose_state1.as_mut().filter(|_| compose) {
|
||||
if RESET_DEAD_KEYS.swap(false, Ordering::SeqCst) {
|
||||
state.reset();
|
||||
context.compose_state2.as_mut().unwrap().reset();
|
||||
}
|
||||
state.feed(keysym)
|
||||
} else {
|
||||
ComposeStatus::None
|
||||
};
|
||||
|
||||
KeyEventResults {
|
||||
context,
|
||||
keycode,
|
||||
keysym,
|
||||
compose,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key(&mut self) -> (Key, KeyLocation) {
|
||||
let (key, location) = match self.keysym_to_key(self.keysym) {
|
||||
Ok(known) => return known,
|
||||
Err(undefined) => undefined,
|
||||
};
|
||||
|
||||
if let ComposeStatus::Accepted(xkb_compose_status::XKB_COMPOSE_COMPOSING) = self.compose {
|
||||
let compose_state = self.context.compose_state2.as_mut().unwrap();
|
||||
// When pressing a dead key twice, the non-combining variant of that character will
|
||||
// be produced. Since this function only concerns itself with a single keypress, we
|
||||
// simulate this double press here by feeding the keysym to the compose state
|
||||
// twice.
|
||||
|
||||
compose_state.feed(self.keysym);
|
||||
if matches!(compose_state.feed(self.keysym), ComposeStatus::Accepted(_)) {
|
||||
// Extracting only a single `char` here *should* be fine, assuming that no
|
||||
// dead key's non-combining variant ever occupies more than one `char`.
|
||||
let text = compose_state.get_string(self.context.scratch_buffer);
|
||||
let key = Key::Dead(text.and_then(|s| s.chars().next()));
|
||||
(key, location)
|
||||
} else {
|
||||
(key, location)
|
||||
}
|
||||
} else {
|
||||
let key = self
|
||||
.composed_text()
|
||||
.unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym))
|
||||
.map(Key::Character)
|
||||
.unwrap_or(key);
|
||||
(key, location)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key_without_modifiers(&mut self) -> (Key, KeyLocation) {
|
||||
// This will become a pointer to an array which libxkbcommon owns, so we don't need to deallocate it.
|
||||
let layout = self.context.state.layout(self.keycode);
|
||||
let keysym = self
|
||||
.context
|
||||
.keymap
|
||||
.first_keysym_by_level(layout, self.keycode);
|
||||
|
||||
match self.keysym_to_key(keysym) {
|
||||
Ok((key, location)) => (key, location),
|
||||
Err((key, location)) => {
|
||||
let key = self
|
||||
.context
|
||||
.keysym_to_utf8_raw(keysym)
|
||||
.map(Key::Character)
|
||||
.unwrap_or(key);
|
||||
(key, location)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn keysym_to_key(&self, keysym: u32) -> Result<(Key, KeyLocation), (Key, KeyLocation)> {
|
||||
let location = keymap::keysym_location(keysym);
|
||||
let key = keymap::keysym_to_key(keysym);
|
||||
if matches!(key, Key::Unidentified(_)) {
|
||||
Err((key, location))
|
||||
} else {
|
||||
Ok((key, location))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text(&mut self) -> Option<SmolStr> {
|
||||
self.composed_text()
|
||||
.unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym))
|
||||
}
|
||||
|
||||
// The current behaviour makes it so composing a character overrides attempts to input a
|
||||
// control character with the `Ctrl` key. We can potentially add a configuration option
|
||||
// if someone specifically wants the oppsite behaviour.
|
||||
pub fn text_with_all_modifiers(&mut self) -> Option<SmolStr> {
|
||||
match self.composed_text() {
|
||||
Ok(text) => text,
|
||||
Err(_) => self
|
||||
.context
|
||||
.state
|
||||
.get_utf8_raw(self.keycode, self.context.scratch_buffer),
|
||||
}
|
||||
}
|
||||
|
||||
fn composed_text(&mut self) -> Result<Option<SmolStr>, ()> {
|
||||
match self.compose {
|
||||
ComposeStatus::Accepted(xkb_compose_status::XKB_COMPOSE_COMPOSED) => {
|
||||
let state = self.context.compose_state1.as_mut().unwrap();
|
||||
Ok(state.get_string(self.context.scratch_buffer))
|
||||
}
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbContext {
|
||||
context: NonNull<xkb_context>,
|
||||
}
|
||||
|
||||
impl XkbContext {
|
||||
pub fn new() -> Result<Self, Error> {
|
||||
let context = unsafe { (XKBH.xkb_context_new)(xkb_context_flags::XKB_CONTEXT_NO_FLAGS) };
|
||||
|
||||
let context = match NonNull::new(context) {
|
||||
Some(context) => context,
|
||||
None => return Err(Error::XKBNotFound),
|
||||
};
|
||||
|
||||
Ok(Self { context })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbContext {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBH.xkb_context_unref)(self.context.as_ptr());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for XkbContext {
|
||||
type Target = NonNull<xkb_context>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.context
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared logic for constructing a string with `xkb_compose_state_get_utf8` and
|
||||
/// `xkb_state_key_get_utf8`.
|
||||
fn make_string_with<F>(scratch_buffer: &mut Vec<u8>, mut f: F) -> Option<SmolStr>
|
||||
where
|
||||
F: FnMut(*mut c_char, usize) -> i32,
|
||||
{
|
||||
let size = f(ptr::null_mut(), 0);
|
||||
if size == 0 {
|
||||
return None;
|
||||
}
|
||||
let size = usize::try_from(size).unwrap();
|
||||
scratch_buffer.clear();
|
||||
// The allocated buffer must include space for the null-terminator.
|
||||
scratch_buffer.reserve(size + 1);
|
||||
unsafe {
|
||||
let written = f(
|
||||
scratch_buffer.as_mut_ptr().cast(),
|
||||
scratch_buffer.capacity(),
|
||||
);
|
||||
if usize::try_from(written).unwrap() != size {
|
||||
// This will likely never happen.
|
||||
return None;
|
||||
}
|
||||
scratch_buffer.set_len(size);
|
||||
};
|
||||
|
||||
byte_slice_to_smol_str(scratch_buffer)
|
||||
}
|
||||
|
||||
// NOTE: This is track_caller so we can have more informative line numbers when logging
|
||||
#[track_caller]
|
||||
fn byte_slice_to_smol_str(bytes: &[u8]) -> Option<SmolStr> {
|
||||
std::str::from_utf8(bytes)
|
||||
.map(SmolStr::new)
|
||||
.map_err(|e| {
|
||||
log::warn!(
|
||||
"UTF-8 received from libxkbcommon ({:?}) was invalid: {e}",
|
||||
bytes
|
||||
)
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
189
src/platform_impl/linux/common/xkb/state.rs
Normal file
189
src/platform_impl/linux/common/xkb/state.rs
Normal file
@@ -0,0 +1,189 @@
|
||||
//! XKB state.
|
||||
|
||||
use std::os::raw::c_char;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use smol_str::SmolStr;
|
||||
#[cfg(x11_platform)]
|
||||
use x11_dl::xlib_xcb::xcb_connection_t;
|
||||
use xkbcommon_dl::{
|
||||
self as xkb, xkb_keycode_t, xkb_keysym_t, xkb_layout_index_t, xkb_state, xkb_state_component,
|
||||
};
|
||||
|
||||
use crate::platform_impl::common::xkb::keymap::XkbKeymap;
|
||||
#[cfg(x11_platform)]
|
||||
use crate::platform_impl::common::xkb::XKBXH;
|
||||
use crate::platform_impl::common::xkb::{make_string_with, XKBH};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbState {
|
||||
state: NonNull<xkb_state>,
|
||||
modifiers: ModifiersState,
|
||||
}
|
||||
|
||||
impl XkbState {
|
||||
#[cfg(wayland_platform)]
|
||||
pub fn new_wayland(keymap: &XkbKeymap) -> Option<Self> {
|
||||
let state = NonNull::new(unsafe { (XKBH.xkb_state_new)(keymap.as_ptr()) })?;
|
||||
Some(Self::new_inner(state))
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn new_x11(xcb: *mut xcb_connection_t, keymap: &XkbKeymap) -> Option<Self> {
|
||||
let state = unsafe {
|
||||
(XKBXH.xkb_x11_state_new_from_device)(keymap.as_ptr(), xcb, keymap._core_keyboard_id)
|
||||
};
|
||||
let state = NonNull::new(state)?;
|
||||
Some(Self::new_inner(state))
|
||||
}
|
||||
|
||||
fn new_inner(state: NonNull<xkb_state>) -> Self {
|
||||
let modifiers = ModifiersState::default();
|
||||
let mut this = Self { state, modifiers };
|
||||
this.reload_modifiers();
|
||||
this
|
||||
}
|
||||
|
||||
pub fn get_one_sym_raw(&mut self, keycode: xkb_keycode_t) -> xkb_keysym_t {
|
||||
unsafe { (XKBH.xkb_state_key_get_one_sym)(self.state.as_ptr(), keycode) }
|
||||
}
|
||||
|
||||
pub fn layout(&mut self, key: xkb_keycode_t) -> xkb_layout_index_t {
|
||||
unsafe { (XKBH.xkb_state_key_get_layout)(self.state.as_ptr(), key) }
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn depressed_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_serialize_mods)(
|
||||
self.state.as_ptr(),
|
||||
xkb_state_component::XKB_STATE_MODS_DEPRESSED,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn latched_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_serialize_mods)(
|
||||
self.state.as_ptr(),
|
||||
xkb_state_component::XKB_STATE_MODS_LATCHED,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
pub fn locked_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_serialize_mods)(
|
||||
self.state.as_ptr(),
|
||||
xkb_state_component::XKB_STATE_MODS_LOCKED,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_utf8_raw(
|
||||
&mut self,
|
||||
keycode: xkb_keycode_t,
|
||||
scratch_buffer: &mut Vec<u8>,
|
||||
) -> Option<SmolStr> {
|
||||
make_string_with(scratch_buffer, |ptr, len| unsafe {
|
||||
(XKBH.xkb_state_key_get_utf8)(self.state.as_ptr(), keycode, ptr, len)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn modifiers(&self) -> ModifiersState {
|
||||
self.modifiers
|
||||
}
|
||||
|
||||
pub fn update_modifiers(
|
||||
&mut self,
|
||||
mods_depressed: u32,
|
||||
mods_latched: u32,
|
||||
mods_locked: u32,
|
||||
depressed_group: u32,
|
||||
latched_group: u32,
|
||||
locked_group: u32,
|
||||
) {
|
||||
let mask = unsafe {
|
||||
(XKBH.xkb_state_update_mask)(
|
||||
self.state.as_ptr(),
|
||||
mods_depressed,
|
||||
mods_latched,
|
||||
mods_locked,
|
||||
depressed_group,
|
||||
latched_group,
|
||||
locked_group,
|
||||
)
|
||||
};
|
||||
|
||||
if mask.contains(xkb_state_component::XKB_STATE_MODS_EFFECTIVE) {
|
||||
// Effective value of mods have changed, we need to update our state.
|
||||
self.reload_modifiers();
|
||||
}
|
||||
}
|
||||
|
||||
/// Reload the modifiers.
|
||||
fn reload_modifiers(&mut self) {
|
||||
self.modifiers.ctrl = self.mod_name_is_active(xkb::XKB_MOD_NAME_CTRL);
|
||||
self.modifiers.alt = self.mod_name_is_active(xkb::XKB_MOD_NAME_ALT);
|
||||
self.modifiers.shift = self.mod_name_is_active(xkb::XKB_MOD_NAME_SHIFT);
|
||||
self.modifiers.caps_lock = self.mod_name_is_active(xkb::XKB_MOD_NAME_CAPS);
|
||||
self.modifiers.logo = self.mod_name_is_active(xkb::XKB_MOD_NAME_LOGO);
|
||||
self.modifiers.num_lock = self.mod_name_is_active(xkb::XKB_MOD_NAME_NUM);
|
||||
}
|
||||
|
||||
/// Check if the modifier is active within xkb.
|
||||
fn mod_name_is_active(&mut self, name: &[u8]) -> bool {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_mod_name_is_active)(
|
||||
self.state.as_ptr(),
|
||||
name.as_ptr() as *const c_char,
|
||||
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||
) > 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for XkbState {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(XKBH.xkb_state_unref)(self.state.as_ptr());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the current state of the keyboard modifiers
|
||||
///
|
||||
/// Each field of this struct represents a modifier and is `true` if this modifier is active.
|
||||
///
|
||||
/// For some modifiers, this means that the key is currently pressed, others are toggled
|
||||
/// (like caps lock).
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ModifiersState {
|
||||
/// The "control" key
|
||||
pub ctrl: bool,
|
||||
/// The "alt" key
|
||||
pub alt: bool,
|
||||
/// The "shift" key
|
||||
pub shift: bool,
|
||||
/// The "Caps lock" key
|
||||
pub caps_lock: bool,
|
||||
/// The "logo" key
|
||||
///
|
||||
/// Also known as the "windows" key on most keyboards
|
||||
pub logo: bool,
|
||||
/// The "Num lock" key
|
||||
pub num_lock: bool,
|
||||
}
|
||||
|
||||
impl From<ModifiersState> for crate::keyboard::ModifiersState {
|
||||
fn from(mods: ModifiersState) -> crate::keyboard::ModifiersState {
|
||||
let mut to_mods = crate::keyboard::ModifiersState::empty();
|
||||
to_mods.set(crate::keyboard::ModifiersState::SHIFT, mods.shift);
|
||||
to_mods.set(crate::keyboard::ModifiersState::CONTROL, mods.ctrl);
|
||||
to_mods.set(crate::keyboard::ModifiersState::ALT, mods.alt);
|
||||
to_mods.set(crate::keyboard::ModifiersState::SUPER, mods.logo);
|
||||
to_mods
|
||||
}
|
||||
}
|
||||
@@ -498,7 +498,7 @@ impl<'a> KeyEventResults<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn physical_key(&mut self) -> PhysicalKey {
|
||||
fn physical_key(&self) -> PhysicalKey {
|
||||
keymap::raw_keycode_to_physicalkey(self.keycode)
|
||||
}
|
||||
|
||||
@@ -553,6 +553,7 @@ impl<'a> KeyEventResults<'a> {
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
self.keysym_to_key(keysym)
|
||||
.unwrap_or_else(|(key, location)| {
|
||||
(
|
||||
@@ -565,7 +566,7 @@ impl<'a> KeyEventResults<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
fn keysym_to_key(&mut self, keysym: u32) -> Result<(Key, KeyLocation), (Key, KeyLocation)> {
|
||||
fn keysym_to_key(&self, keysym: u32) -> Result<(Key, KeyLocation), (Key, KeyLocation)> {
|
||||
let location = super::keymap::keysym_location(keysym);
|
||||
let key = super::keymap::keysym_to_key(keysym);
|
||||
if matches!(key, Key::Unidentified(_)) {
|
||||
|
||||
@@ -521,7 +521,7 @@ impl Window {
|
||||
|
||||
#[inline]
|
||||
pub fn reset_dead_keys(&self) {
|
||||
common::xkb_state::reset_dead_keys()
|
||||
common::xkb::reset_dead_keys()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -659,11 +659,11 @@ impl KeyEventExtModifierSupplement for KeyEvent {
|
||||
|
||||
impl PhysicalKeyExtScancode for PhysicalKey {
|
||||
fn from_scancode(scancode: u32) -> PhysicalKey {
|
||||
common::keymap::scancode_to_keycode(scancode)
|
||||
common::xkb::scancode_to_keycode(scancode)
|
||||
}
|
||||
|
||||
fn to_scancode(self) -> Option<u32> {
|
||||
common::keymap::physicalkey_to_scancode(self)
|
||||
common::xkb::physicalkey_to_scancode(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -757,8 +757,11 @@ impl<T: 'static> EventLoop<T> {
|
||||
let backend = match (
|
||||
attributes.forced_backend,
|
||||
env::var("WAYLAND_DISPLAY")
|
||||
.map(|var| !var.is_empty())
|
||||
.unwrap_or(false),
|
||||
.ok()
|
||||
.filter(|var| !var.is_empty())
|
||||
.or_else(|| env::var("WAYLAND_SOCKET").ok())
|
||||
.filter(|var| !var.is_empty())
|
||||
.is_some(),
|
||||
env::var("DISPLAY")
|
||||
.map(|var| !var.is_empty())
|
||||
.unwrap_or(false),
|
||||
@@ -772,10 +775,15 @@ impl<T: 'static> EventLoop<T> {
|
||||
#[cfg(x11_platform)]
|
||||
(None, _, true) => Backend::X,
|
||||
// No backend is present.
|
||||
_ => {
|
||||
return Err(EventLoopError::Os(os_error!(OsError::Misc(
|
||||
"neither WAYLAND_DISPLAY nor DISPLAY is set."
|
||||
))));
|
||||
(_, wayland_display, x11_display) => {
|
||||
let msg = if wayland_display && !cfg!(wayland_platform) {
|
||||
"DISPLAY is not set; note: enable the `winit/wayland` feature to support Wayland"
|
||||
} else if x11_display && !cfg!(x11_platform) {
|
||||
"neither WAYLAND_DISPLAY nor WAYLAND_SOCKET is set; note: enable the `winit/x11` feature to support X11"
|
||||
} else {
|
||||
"neither WAYLAND_DISPLAY nor WAYLAND_SOCKET nor DISPLAY is set."
|
||||
};
|
||||
return Err(EventLoopError::Os(os_error!(OsError::Misc(msg))));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -930,10 +938,12 @@ impl<T> EventLoopWindowTarget<T> {
|
||||
x11_or_wayland!(match self; Self(evlp) => evlp.exiting())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn set_exit_code(&self, code: i32) {
|
||||
x11_or_wayland!(match self; Self(evlp) => evlp.set_exit_code(code))
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn exit_code(&self) -> Option<i32> {
|
||||
x11_or_wayland!(match self; Self(evlp) => evlp.exit_code())
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ use std::sync::atomic::Ordering;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use sctk::reexports::calloop;
|
||||
use sctk::reexports::calloop::Error as CalloopError;
|
||||
use sctk::reexports::calloop_wayland_source::WaylandSource;
|
||||
use sctk::reexports::client::globals;
|
||||
@@ -466,19 +465,19 @@ impl<T: 'static> EventLoop<T> {
|
||||
window_ids.extend(state.window_requests.get_mut().keys());
|
||||
});
|
||||
|
||||
for window_id in window_ids.drain(..) {
|
||||
for window_id in window_ids.iter() {
|
||||
let event = self.with_state(|state| {
|
||||
let window_requests = state.window_requests.get_mut();
|
||||
if window_requests.get(&window_id).unwrap().take_closed() {
|
||||
mem::drop(window_requests.remove(&window_id));
|
||||
mem::drop(state.windows.get_mut().remove(&window_id));
|
||||
if window_requests.get(window_id).unwrap().take_closed() {
|
||||
mem::drop(window_requests.remove(window_id));
|
||||
mem::drop(state.windows.get_mut().remove(window_id));
|
||||
return Some(WindowEvent::Destroyed);
|
||||
}
|
||||
|
||||
let mut window = state
|
||||
.windows
|
||||
.get_mut()
|
||||
.get_mut(&window_id)
|
||||
.get_mut(window_id)
|
||||
.unwrap()
|
||||
.lock()
|
||||
.unwrap();
|
||||
@@ -490,7 +489,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
// Reset the frame callbacks state.
|
||||
window.frame_callback_reset();
|
||||
let mut redraw_requested = window_requests
|
||||
.get(&window_id)
|
||||
.get(window_id)
|
||||
.unwrap()
|
||||
.take_redraw_requested();
|
||||
|
||||
@@ -503,7 +502,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
if let Some(event) = event {
|
||||
callback(
|
||||
Event::WindowEvent {
|
||||
window_id: crate::window::WindowId(window_id),
|
||||
window_id: crate::window::WindowId(*window_id),
|
||||
event,
|
||||
},
|
||||
&self.window_target,
|
||||
@@ -519,6 +518,42 @@ impl<T: 'static> EventLoop<T> {
|
||||
// This is always the last event we dispatch before poll again
|
||||
callback(Event::AboutToWait, &self.window_target);
|
||||
|
||||
// Update the window frames and schedule redraws.
|
||||
let mut wake_up = false;
|
||||
for window_id in window_ids.drain(..) {
|
||||
wake_up |= self.with_state(|state| match state.windows.get_mut().get_mut(&window_id) {
|
||||
Some(window) => {
|
||||
let refresh = window.lock().unwrap().refresh_frame();
|
||||
if refresh {
|
||||
state
|
||||
.window_requests
|
||||
.get_mut()
|
||||
.get_mut(&window_id)
|
||||
.unwrap()
|
||||
.redraw_requested
|
||||
.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
refresh
|
||||
}
|
||||
None => false,
|
||||
});
|
||||
}
|
||||
|
||||
// Wakeup event loop if needed.
|
||||
//
|
||||
// If the user draws from the `AboutToWait` this is likely not required, however
|
||||
// we can't do much about it.
|
||||
if wake_up {
|
||||
match &self.window_target.p {
|
||||
PlatformEventLoopWindowTarget::Wayland(window_target) => {
|
||||
window_target.event_loop_awakener.ping();
|
||||
}
|
||||
#[cfg(x11_platform)]
|
||||
PlatformEventLoopWindowTarget::X(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
std::mem::swap(&mut self.compositor_updates, &mut compositor_updates);
|
||||
std::mem::swap(&mut self.buffer_sink, &mut buffer_sink);
|
||||
std::mem::swap(&mut self.window_ids, &mut window_ids);
|
||||
|
||||
@@ -17,7 +17,7 @@ use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
|
||||
use crate::event::{ElementState, WindowEvent};
|
||||
use crate::keyboard::ModifiersState;
|
||||
|
||||
use crate::platform_impl::common::xkb_state::KbdState;
|
||||
use crate::platform_impl::common::xkb::Context;
|
||||
use crate::platform_impl::wayland::event_loop::sink::EventSink;
|
||||
use crate::platform_impl::wayland::seat::WinitSeatState;
|
||||
use crate::platform_impl::wayland::state::WinitState;
|
||||
@@ -43,14 +43,10 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
WlKeymapFormat::NoKeymap => {
|
||||
warn!("non-xkb compatible keymap")
|
||||
}
|
||||
WlKeymapFormat::XkbV1 => unsafe {
|
||||
seat_state
|
||||
.keyboard_state
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.xkb_state
|
||||
.init_with_fd(fd, size as usize);
|
||||
},
|
||||
WlKeymapFormat::XkbV1 => {
|
||||
let context = &mut seat_state.keyboard_state.as_mut().unwrap().xkb_context;
|
||||
context.set_keymap_from_fd(fd, size as usize);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
},
|
||||
WEnum::Unknown(value) => {
|
||||
@@ -61,8 +57,13 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
let window_id = wayland::make_wid(&surface);
|
||||
|
||||
// Mark the window as focused.
|
||||
match state.windows.get_mut().get(&window_id) {
|
||||
Some(window) => window.lock().unwrap().set_has_focus(true),
|
||||
let was_unfocused = match state.windows.get_mut().get(&window_id) {
|
||||
Some(window) => {
|
||||
let mut window = window.lock().unwrap();
|
||||
let was_unfocused = !window.has_focus();
|
||||
window.add_seat_focus(data.seat.id());
|
||||
was_unfocused
|
||||
}
|
||||
None => return,
|
||||
};
|
||||
|
||||
@@ -73,13 +74,15 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
keyboard_state.loop_handle.remove(token);
|
||||
}
|
||||
|
||||
// The keyboard focus is considered as general focus.
|
||||
state
|
||||
.events_sink
|
||||
.push_window_event(WindowEvent::Focused(true), window_id);
|
||||
|
||||
*data.window_id.lock().unwrap() = Some(window_id);
|
||||
|
||||
// The keyboard focus is considered as general focus.
|
||||
if was_unfocused {
|
||||
state
|
||||
.events_sink
|
||||
.push_window_event(WindowEvent::Focused(true), window_id);
|
||||
}
|
||||
|
||||
// HACK: this is just for GNOME not fixing their ordering issue of modifiers.
|
||||
if std::mem::take(&mut seat_state.modifiers_pending) {
|
||||
state.events_sink.push_window_event(
|
||||
@@ -101,24 +104,30 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
|
||||
// NOTE: The check whether the window exists is essential as we might get a
|
||||
// nil surface, regardless of what protocol says.
|
||||
match state.windows.get_mut().get(&window_id) {
|
||||
Some(window) => window.lock().unwrap().set_has_focus(false),
|
||||
let focused = match state.windows.get_mut().get(&window_id) {
|
||||
Some(window) => {
|
||||
let mut window = window.lock().unwrap();
|
||||
window.remove_seat_focus(&data.seat.id());
|
||||
window.has_focus()
|
||||
}
|
||||
None => return,
|
||||
};
|
||||
|
||||
// Notify that no modifiers are being pressed.
|
||||
state.events_sink.push_window_event(
|
||||
WindowEvent::ModifiersChanged(ModifiersState::empty().into()),
|
||||
window_id,
|
||||
);
|
||||
|
||||
// We don't need to update it above, because the next `Enter` will overwrite
|
||||
// anyway.
|
||||
*data.window_id.lock().unwrap() = None;
|
||||
|
||||
state
|
||||
.events_sink
|
||||
.push_window_event(WindowEvent::Focused(false), window_id);
|
||||
if !focused {
|
||||
// Notify that no modifiers are being pressed.
|
||||
state.events_sink.push_window_event(
|
||||
WindowEvent::ModifiersChanged(ModifiersState::empty().into()),
|
||||
window_id,
|
||||
);
|
||||
|
||||
state
|
||||
.events_sink
|
||||
.push_window_event(WindowEvent::Focused(false), window_id);
|
||||
}
|
||||
}
|
||||
WlKeyboardEvent::Key {
|
||||
key,
|
||||
@@ -142,7 +151,12 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
RepeatInfo::Disable => return,
|
||||
};
|
||||
|
||||
if !keyboard_state.xkb_state.key_repeats(key) {
|
||||
if !keyboard_state
|
||||
.xkb_context
|
||||
.keymap_mut()
|
||||
.unwrap()
|
||||
.key_repeats(key)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -208,7 +222,11 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
|
||||
let keyboard_state = seat_state.keyboard_state.as_mut().unwrap();
|
||||
if keyboard_state.repeat_info != RepeatInfo::Disable
|
||||
&& keyboard_state.xkb_state.key_repeats(key)
|
||||
&& keyboard_state
|
||||
.xkb_context
|
||||
.keymap_mut()
|
||||
.unwrap()
|
||||
.key_repeats(key)
|
||||
&& Some(key) == keyboard_state.current_repeat
|
||||
{
|
||||
keyboard_state.current_repeat = None;
|
||||
@@ -224,9 +242,14 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
group,
|
||||
..
|
||||
} => {
|
||||
let xkb_state = &mut seat_state.keyboard_state.as_mut().unwrap().xkb_state;
|
||||
let xkb_context = &mut seat_state.keyboard_state.as_mut().unwrap().xkb_context;
|
||||
let xkb_state = match xkb_context.state_mut() {
|
||||
Some(state) => state,
|
||||
None => return,
|
||||
};
|
||||
|
||||
xkb_state.update_modifiers(mods_depressed, mods_latched, mods_locked, 0, 0, group);
|
||||
seat_state.modifiers = xkb_state.mods_state().into();
|
||||
seat_state.modifiers = xkb_state.modifiers().into();
|
||||
|
||||
// HACK: part of the workaround from `WlKeyboardEvent::Enter`.
|
||||
let window_id = match *data.window_id.lock().unwrap() {
|
||||
@@ -272,7 +295,7 @@ pub struct KeyboardState {
|
||||
pub loop_handle: LoopHandle<'static, WinitState>,
|
||||
|
||||
/// The state of the keyboard.
|
||||
pub xkb_state: KbdState,
|
||||
pub xkb_context: Context,
|
||||
|
||||
/// The information about the repeat rate obtained from the compositor.
|
||||
pub repeat_info: RepeatInfo,
|
||||
@@ -289,7 +312,7 @@ impl KeyboardState {
|
||||
Self {
|
||||
keyboard,
|
||||
loop_handle,
|
||||
xkb_state: KbdState::new().unwrap(),
|
||||
xkb_context: Context::new().unwrap(),
|
||||
repeat_info: RepeatInfo::default(),
|
||||
repeat_token: None,
|
||||
current_repeat: None,
|
||||
@@ -372,16 +395,13 @@ fn key_input(
|
||||
let keyboard_state = seat_state.keyboard_state.as_mut().unwrap();
|
||||
|
||||
let device_id = crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(DeviceId));
|
||||
let event = keyboard_state
|
||||
.xkb_state
|
||||
.process_key_event(keycode, state, repeat);
|
||||
|
||||
event_sink.push_window_event(
|
||||
WindowEvent::KeyboardInput {
|
||||
if let Some(mut key_context) = keyboard_state.xkb_context.key_context() {
|
||||
let event = key_context.process_key_event(keycode, state, repeat);
|
||||
let event = WindowEvent::KeyboardInput {
|
||||
device_id,
|
||||
event,
|
||||
is_synthetic: false,
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
};
|
||||
event_sink.push_window_event(event, window_id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use std::sync::Arc;
|
||||
|
||||
use ahash::AHashMap;
|
||||
|
||||
use sctk::reexports::client::backend::ObjectId;
|
||||
use sctk::reexports::client::protocol::wl_seat::WlSeat;
|
||||
use sctk::reexports::client::protocol::wl_touch::WlTouch;
|
||||
use sctk::reexports::client::{Connection, Proxy, QueueHandle};
|
||||
@@ -13,6 +14,7 @@ use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::
|
||||
use sctk::seat::pointer::{ThemeSpec, ThemedPointer};
|
||||
use sctk::seat::{Capability as SeatCapability, SeatHandler, SeatState};
|
||||
|
||||
use crate::event::WindowEvent;
|
||||
use crate::keyboard::ModifiersState;
|
||||
use crate::platform_impl::wayland::state::WinitState;
|
||||
|
||||
@@ -143,6 +145,10 @@ impl SeatHandler for WinitState {
|
||||
) {
|
||||
let seat_state = self.seats.get_mut(&seat.id()).unwrap();
|
||||
|
||||
if let Some(text_input) = seat_state.text_input.take() {
|
||||
text_input.destroy();
|
||||
}
|
||||
|
||||
match capability {
|
||||
SeatCapability::Touch => {
|
||||
if let Some(touch) = seat_state.touch.take() {
|
||||
@@ -174,13 +180,10 @@ impl SeatHandler for WinitState {
|
||||
}
|
||||
SeatCapability::Keyboard => {
|
||||
seat_state.keyboard_state = None;
|
||||
self.on_keyboard_destroy(&seat.id());
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
if let Some(text_input) = seat_state.text_input.take() {
|
||||
text_input.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
fn new_seat(
|
||||
@@ -199,6 +202,21 @@ impl SeatHandler for WinitState {
|
||||
seat: WlSeat,
|
||||
) {
|
||||
let _ = self.seats.remove(&seat.id());
|
||||
self.on_keyboard_destroy(&seat.id());
|
||||
}
|
||||
}
|
||||
|
||||
impl WinitState {
|
||||
fn on_keyboard_destroy(&mut self, seat: &ObjectId) {
|
||||
for (window_id, window) in self.windows.get_mut() {
|
||||
let mut window = window.lock().unwrap();
|
||||
let had_focus = window.has_focus();
|
||||
window.remove_seat_focus(seat);
|
||||
if had_focus != window.has_focus() {
|
||||
self.events_sink
|
||||
.push_window_event(WindowEvent::Focused(false), *window_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,19 +60,34 @@ impl Dispatch<ZwpRelativePointerV1, GlobalData, WinitState> for RelativePointerS
|
||||
_conn: &Connection,
|
||||
_qhandle: &QueueHandle<WinitState>,
|
||||
) {
|
||||
if let zwp_relative_pointer_v1::Event::RelativeMotion {
|
||||
dx_unaccel,
|
||||
dy_unaccel,
|
||||
..
|
||||
} = event
|
||||
{
|
||||
state.events_sink.push_device_event(
|
||||
DeviceEvent::MouseMotion {
|
||||
delta: (dx_unaccel, dy_unaccel),
|
||||
},
|
||||
super::DeviceId,
|
||||
);
|
||||
}
|
||||
let (dx_unaccel, dy_unaccel) = match event {
|
||||
zwp_relative_pointer_v1::Event::RelativeMotion {
|
||||
dx_unaccel,
|
||||
dy_unaccel,
|
||||
..
|
||||
} => (dx_unaccel, dy_unaccel),
|
||||
_ => return,
|
||||
};
|
||||
state.events_sink.push_device_event(
|
||||
DeviceEvent::Motion {
|
||||
axis: 0,
|
||||
value: dx_unaccel,
|
||||
},
|
||||
super::DeviceId,
|
||||
);
|
||||
state.events_sink.push_device_event(
|
||||
DeviceEvent::Motion {
|
||||
axis: 1,
|
||||
value: dy_unaccel,
|
||||
},
|
||||
super::DeviceId,
|
||||
);
|
||||
state.events_sink.push_device_event(
|
||||
DeviceEvent::MouseMotion {
|
||||
delta: (dx_unaccel, dy_unaccel),
|
||||
},
|
||||
super::DeviceId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -288,12 +288,19 @@ impl WindowHandler for WinitState {
|
||||
.expect("got configure for dead window.")
|
||||
.lock()
|
||||
.unwrap()
|
||||
.configure(
|
||||
configure,
|
||||
&self.shm,
|
||||
&self.subcompositor_state,
|
||||
&mut self.events_sink,
|
||||
);
|
||||
.configure(configure, &self.shm, &self.subcompositor_state);
|
||||
|
||||
// NOTE: configure demands wl_surface::commit, however winit doesn't commit on behalf of the
|
||||
// users, since it can break a lot of things, thus it'll ask users to redraw instead.
|
||||
self.window_requests
|
||||
.get_mut()
|
||||
.get(&window_id)
|
||||
.unwrap()
|
||||
.redraw_requested
|
||||
.store(true, Ordering::Relaxed);
|
||||
|
||||
// Manually mark that we've got an event, since configure may not generate a resize.
|
||||
self.dispatched_events = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use sctk::reexports::calloop;
|
||||
use sctk::reexports::client::protocol::wl_display::WlDisplay;
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::Proxy;
|
||||
@@ -327,7 +326,9 @@ impl Window {
|
||||
self.window_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_min_inner_size(min_size)
|
||||
.set_min_inner_size(min_size);
|
||||
// NOTE: Requires commit to be applied.
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
/// Set the maximum inner size for the window.
|
||||
@@ -338,7 +339,9 @@ impl Window {
|
||||
self.window_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_max_inner_size(max_size)
|
||||
.set_max_inner_size(max_size);
|
||||
// NOTE: Requires commit to be applied.
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -387,7 +390,10 @@ impl Window {
|
||||
|
||||
#[inline]
|
||||
pub fn set_resizable(&self, resizable: bool) {
|
||||
self.window_state.lock().unwrap().set_resizable(resizable);
|
||||
if self.window_state.lock().unwrap().set_resizable(resizable) {
|
||||
// NOTE: Requires commit to be applied.
|
||||
self.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -4,8 +4,10 @@ use std::num::NonZeroU32;
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use ahash::HashSet;
|
||||
use log::{info, warn};
|
||||
|
||||
use sctk::reexports::client::backend::ObjectId;
|
||||
use sctk::reexports::client::protocol::wl_seat::WlSeat;
|
||||
use sctk::reexports::client::protocol::wl_shm::WlShm;
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
@@ -29,10 +31,8 @@ use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur;
|
||||
|
||||
use crate::dpi::{LogicalPosition, LogicalSize, PhysicalSize, Size};
|
||||
use crate::error::{ExternalError, NotSupportedError};
|
||||
use crate::event::WindowEvent;
|
||||
use crate::platform_impl::wayland::event_loop::sink::EventSink;
|
||||
use crate::platform_impl::wayland::logical_to_physical_rounded;
|
||||
use crate::platform_impl::wayland::types::kwin_blur::KWinBlurManager;
|
||||
use crate::platform_impl::wayland::{logical_to_physical_rounded, make_wid};
|
||||
use crate::platform_impl::WindowId;
|
||||
use crate::window::{CursorGrabMode, CursorIcon, ImePurpose, ResizeDirection, Theme};
|
||||
|
||||
@@ -87,8 +87,10 @@ pub struct WindowState {
|
||||
/// Whether the frame is resizable.
|
||||
resizable: bool,
|
||||
|
||||
/// Whether the window has focus.
|
||||
has_focus: bool,
|
||||
// NOTE: we can't use simple counter, since it's racy when seat getting destroyed and new
|
||||
// is created, since add/removed stuff could be delivered a bit out of order.
|
||||
/// Seats that has keyboard focus on that window.
|
||||
seat_focus: HashSet<ObjectId>,
|
||||
|
||||
/// The scale factor of the window.
|
||||
scale_factor: f64,
|
||||
@@ -184,7 +186,7 @@ impl WindowState {
|
||||
fractional_scale,
|
||||
frame: None,
|
||||
frame_callback_state: FrameCallbackState::None,
|
||||
has_focus: false,
|
||||
seat_focus: Default::default(),
|
||||
has_pending_move: None,
|
||||
ime_allowed: false,
|
||||
ime_purpose: ImePurpose::Normal,
|
||||
@@ -255,7 +257,6 @@ impl WindowState {
|
||||
configure: WindowConfigure,
|
||||
shm: &Shm,
|
||||
subcompositor: &Option<Arc<SubcompositorState>>,
|
||||
event_sink: &mut EventSink,
|
||||
) -> bool {
|
||||
// NOTE: when using fractional scaling or wl_compositor@v6 the scaling
|
||||
// should be delivered before the first configure, thus apply it to
|
||||
@@ -299,19 +300,6 @@ impl WindowState {
|
||||
|
||||
let stateless = Self::is_stateless(&configure);
|
||||
|
||||
// Emit `Occluded` event on suspension change.
|
||||
let occluded = configure.state.contains(XdgWindowState::SUSPENDED);
|
||||
if self
|
||||
.last_configure
|
||||
.as_ref()
|
||||
.map(|c| c.state.contains(XdgWindowState::SUSPENDED))
|
||||
.unwrap_or(false)
|
||||
!= occluded
|
||||
{
|
||||
let window_id = make_wid(self.window.wl_surface());
|
||||
event_sink.push_window_event(WindowEvent::Occluded(occluded), window_id);
|
||||
}
|
||||
|
||||
let (mut new_size, constrain) = if let Some(frame) = self.frame.as_mut() {
|
||||
// Configure the window states.
|
||||
frame.update_state(configure.state);
|
||||
@@ -510,10 +498,12 @@ impl WindowState {
|
||||
}
|
||||
|
||||
/// Set the resizable state on the window.
|
||||
///
|
||||
/// Returns `true` when the state was applied.
|
||||
#[inline]
|
||||
pub fn set_resizable(&mut self, resizable: bool) {
|
||||
pub fn set_resizable(&mut self, resizable: bool) -> bool {
|
||||
if self.resizable == resizable {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
self.resizable = resizable;
|
||||
@@ -529,12 +519,14 @@ impl WindowState {
|
||||
if let Some(frame) = self.frame.as_mut() {
|
||||
frame.set_resizable(resizable);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the window is focused.
|
||||
/// Whether the window is focused by any seat.
|
||||
#[inline]
|
||||
pub fn has_focus(&self) -> bool {
|
||||
self.has_focus
|
||||
!self.seat_focus.is_empty()
|
||||
}
|
||||
|
||||
/// Whether the IME is allowed.
|
||||
@@ -896,12 +888,16 @@ impl WindowState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark that the window has focus.
|
||||
///
|
||||
/// Should be used from routine that sends focused event.
|
||||
/// Add seat focus for the window.
|
||||
#[inline]
|
||||
pub fn set_has_focus(&mut self, has_focus: bool) {
|
||||
self.has_focus = has_focus;
|
||||
pub fn add_seat_focus(&mut self, seat: ObjectId) {
|
||||
self.seat_focus.insert(seat);
|
||||
}
|
||||
|
||||
/// Remove seat focus from the window.
|
||||
#[inline]
|
||||
pub fn remove_seat_focus(&mut self, seat: &ObjectId) {
|
||||
self.seat_focus.remove(seat);
|
||||
}
|
||||
|
||||
/// Returns `true` if the requested state was applied.
|
||||
|
||||
@@ -6,7 +6,7 @@ macro_rules! atom_manager {
|
||||
($($name:ident $(:$lit:literal)?),*) => {
|
||||
x11rb::atom_manager! {
|
||||
/// The atoms used by `winit`
|
||||
pub(crate) Atoms: AtomsCookie {
|
||||
pub Atoms: AtomsCookie {
|
||||
$($name $(:$lit)?,)*
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ macro_rules! atom_manager {
|
||||
/// Indices into the `Atoms` struct.
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub(crate) enum AtomName {
|
||||
pub enum AtomName {
|
||||
$($name,)*
|
||||
}
|
||||
|
||||
@@ -100,7 +100,8 @@ atom_manager! {
|
||||
_NET_FRAME_EXTENTS,
|
||||
_NET_SUPPORTED,
|
||||
_NET_SUPPORTING_WM_CHECK,
|
||||
_XEMBED
|
||||
_XEMBED,
|
||||
_XSETTINGS_SETTINGS
|
||||
}
|
||||
|
||||
impl Index<AtomName> for Atoms {
|
||||
|
||||
@@ -41,7 +41,7 @@ impl From<io::Error> for DndDataParseError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Dnd {
|
||||
pub struct Dnd {
|
||||
xconn: Arc<XConnection>,
|
||||
// Populated by XdndEnter event handler
|
||||
pub version: Option<c_long>,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,49 @@
|
||||
#![cfg(x11_platform)]
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::ffi::CStr;
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::ops::Deref;
|
||||
use std::os::raw::*;
|
||||
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
||||
use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{ptr, slice, str};
|
||||
|
||||
pub use self::xdisplay::{XError, XNotSupported};
|
||||
|
||||
use calloop::generic::Generic;
|
||||
use calloop::EventLoop as Loop;
|
||||
use calloop::{ping::Ping, Readiness};
|
||||
use libc::{setlocale, LC_CTYPE};
|
||||
use log::warn;
|
||||
|
||||
use x11rb::connection::RequestConnection;
|
||||
use x11rb::errors::{ConnectError, ConnectionError, IdsExhausted, ReplyError};
|
||||
use x11rb::protocol::xinput::{self, ConnectionExt as _};
|
||||
use x11rb::protocol::xkb;
|
||||
use x11rb::protocol::xproto::{self, ConnectionExt as _};
|
||||
use x11rb::x11_utils::X11Error as LogicalError;
|
||||
use x11rb::xcb_ffi::ReplyOrIdError;
|
||||
|
||||
use super::{ControlFlow, OsError};
|
||||
use crate::{
|
||||
error::{EventLoopError, OsError as RootOsError},
|
||||
event::{Event, StartCause, WindowEvent},
|
||||
event_loop::{DeviceEvents, EventLoopClosed, EventLoopWindowTarget as RootELW},
|
||||
platform::pump_events::PumpStatus,
|
||||
platform_impl::common::xkb::Context,
|
||||
platform_impl::{
|
||||
platform::{min_timeout, WindowId},
|
||||
PlatformSpecificWindowBuilderAttributes,
|
||||
},
|
||||
window::WindowAttributes,
|
||||
};
|
||||
|
||||
mod activation;
|
||||
mod atoms;
|
||||
mod dnd;
|
||||
@@ -10,73 +54,15 @@ mod monitor;
|
||||
pub mod util;
|
||||
mod window;
|
||||
mod xdisplay;
|
||||
|
||||
pub(crate) use self::{
|
||||
monitor::{MonitorHandle, VideoMode},
|
||||
window::UnownedWindow,
|
||||
xdisplay::XConnection,
|
||||
};
|
||||
|
||||
pub use self::xdisplay::{XError, XNotSupported};
|
||||
|
||||
use calloop::generic::Generic;
|
||||
use calloop::EventLoop as Loop;
|
||||
use calloop::{ping::Ping, Readiness};
|
||||
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::{HashMap, HashSet},
|
||||
ffi::CStr,
|
||||
fmt,
|
||||
mem::MaybeUninit,
|
||||
ops::Deref,
|
||||
os::{
|
||||
raw::*,
|
||||
unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd},
|
||||
},
|
||||
ptr,
|
||||
rc::Rc,
|
||||
slice, str,
|
||||
sync::mpsc::{Receiver, Sender, TryRecvError},
|
||||
sync::{mpsc, Arc, Weak},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use libc::{self, setlocale, LC_CTYPE};
|
||||
mod xsettings;
|
||||
|
||||
use atoms::*;
|
||||
|
||||
use x11rb::x11_utils::X11Error as LogicalError;
|
||||
use x11rb::{
|
||||
connection::RequestConnection,
|
||||
protocol::{
|
||||
xinput::{self, ConnectionExt as _},
|
||||
xkb,
|
||||
xproto::{self, ConnectionExt as _},
|
||||
},
|
||||
};
|
||||
use x11rb::{
|
||||
errors::{ConnectError, ConnectionError, IdsExhausted, ReplyError},
|
||||
xcb_ffi::ReplyOrIdError,
|
||||
};
|
||||
|
||||
use self::{
|
||||
dnd::{Dnd, DndState},
|
||||
event_processor::EventProcessor,
|
||||
ime::{Ime, ImeCreationError, ImeReceiver, ImeRequest, ImeSender},
|
||||
};
|
||||
use super::{common::xkb_state::KbdState, ControlFlow, OsError};
|
||||
use crate::{
|
||||
error::{EventLoopError, OsError as RootOsError},
|
||||
event::{Event, StartCause, WindowEvent},
|
||||
event_loop::{DeviceEvents, EventLoopClosed, EventLoopWindowTarget as RootELW},
|
||||
platform::pump_events::PumpStatus,
|
||||
platform_impl::{
|
||||
platform::{min_timeout, WindowId},
|
||||
PlatformSpecificWindowBuilderAttributes,
|
||||
},
|
||||
window::WindowAttributes,
|
||||
};
|
||||
use dnd::{Dnd, DndState};
|
||||
use event_processor::{EventProcessor, MAX_MOD_REPLAY_LEN};
|
||||
use ime::{Ime, ImeCreationError, ImeReceiver, ImeRequest, ImeSender};
|
||||
pub(crate) use monitor::{MonitorHandle, VideoMode};
|
||||
use window::UnownedWindow;
|
||||
pub(crate) use xdisplay::XConnection;
|
||||
|
||||
// Xinput constants not defined in x11rb
|
||||
const ALL_DEVICES: u16 = 0;
|
||||
@@ -151,7 +137,7 @@ pub struct EventLoopWindowTarget<T> {
|
||||
control_flow: Cell<ControlFlow>,
|
||||
exit: Cell<Option<i32>>,
|
||||
root: xproto::Window,
|
||||
ime: RefCell<Ime>,
|
||||
ime: Option<RefCell<Ime>>,
|
||||
windows: RefCell<HashMap<WindowId, Weak<UnownedWindow>>>,
|
||||
redraw_sender: WakeSender<WindowId>,
|
||||
activation_sender: WakeSender<ActivationToken>,
|
||||
@@ -168,7 +154,6 @@ pub struct EventLoop<T: 'static> {
|
||||
user_receiver: PeekableReceiver<T>,
|
||||
activation_receiver: PeekableReceiver<ActivationToken>,
|
||||
user_sender: Sender<T>,
|
||||
target: Rc<RootELW<T>>,
|
||||
|
||||
/// The current state of the event loop.
|
||||
state: EventLoopState,
|
||||
@@ -229,13 +214,15 @@ impl<T: 'static> EventLoop<T> {
|
||||
setlocale(LC_CTYPE, default_locale);
|
||||
}
|
||||
}
|
||||
let ime = RefCell::new({
|
||||
let result = Ime::new(Arc::clone(&xconn), ime_event_sender);
|
||||
if let Err(ImeCreationError::OpenFailure(ref state)) = result {
|
||||
panic!("Failed to open input method: {state:#?}");
|
||||
}
|
||||
result.expect("Failed to set input method destruction callback")
|
||||
});
|
||||
|
||||
let ime = Ime::new(Arc::clone(&xconn), ime_event_sender);
|
||||
if let Err(ImeCreationError::OpenFailure(state)) = ime.as_ref() {
|
||||
warn!("Failed to open input method: {state:#?}");
|
||||
} else if let Err(err) = ime.as_ref() {
|
||||
warn!("Failed to set input method destruction callback: {err:?}");
|
||||
}
|
||||
|
||||
let ime = ime.ok().map(RefCell::new);
|
||||
|
||||
let randr_event_offset = xconn
|
||||
.select_xrandr_input(root)
|
||||
@@ -299,8 +286,11 @@ impl<T: 'static> EventLoop<T> {
|
||||
// Create a channel for sending user events.
|
||||
let (user_sender, user_channel) = mpsc::channel();
|
||||
|
||||
let kb_state =
|
||||
KbdState::from_x11_xkb(xconn.xcb_connection().get_raw_xcb_connection()).unwrap();
|
||||
let xkb_context =
|
||||
Context::from_x11_xkb(xconn.xcb_connection().get_raw_xcb_connection()).unwrap();
|
||||
|
||||
let mut xmodmap = util::ModifierKeymap::new();
|
||||
xmodmap.reload_from_x_connection(&xconn);
|
||||
|
||||
let window_target = EventLoopWindowTarget {
|
||||
ime,
|
||||
@@ -327,21 +317,23 @@ impl<T: 'static> EventLoop<T> {
|
||||
// Set initial device event filter.
|
||||
window_target.update_listen_device_events(true);
|
||||
|
||||
let target = Rc::new(RootELW {
|
||||
let root_window_target = RootELW {
|
||||
p: super::EventLoopWindowTarget::X(window_target),
|
||||
_marker: ::std::marker::PhantomData,
|
||||
});
|
||||
_marker: PhantomData,
|
||||
};
|
||||
|
||||
let event_processor = EventProcessor {
|
||||
target: target.clone(),
|
||||
target: root_window_target,
|
||||
dnd,
|
||||
devices: Default::default(),
|
||||
randr_event_offset,
|
||||
ime_receiver,
|
||||
ime_event_receiver,
|
||||
xi2ext,
|
||||
xfiltered_modifiers: VecDeque::with_capacity(MAX_MOD_REPLAY_LEN),
|
||||
xmodmap,
|
||||
xkbext,
|
||||
kb_state,
|
||||
xkb_context,
|
||||
num_touch: 0,
|
||||
held_key_press: None,
|
||||
first_touch: None,
|
||||
@@ -352,8 +344,9 @@ impl<T: 'static> EventLoop<T> {
|
||||
|
||||
// Register for device hotplug events
|
||||
// (The request buffer is flushed during `init_device`)
|
||||
get_xtarget(&target)
|
||||
.xconn
|
||||
let xconn = &EventProcessor::window_target(&event_processor.target).xconn;
|
||||
|
||||
xconn
|
||||
.select_xinput_events(
|
||||
root,
|
||||
ALL_DEVICES,
|
||||
@@ -361,8 +354,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
)
|
||||
.expect_then_ignore_error("Failed to register for XInput2 device hotplug events");
|
||||
|
||||
get_xtarget(&target)
|
||||
.xconn
|
||||
xconn
|
||||
.select_xkb_events(
|
||||
0x100, // Use the "core keyboard device"
|
||||
xkb::EventType::NEW_KEYBOARD_NOTIFY
|
||||
@@ -382,7 +374,6 @@ impl<T: 'static> EventLoop<T> {
|
||||
activation_receiver: PeekableReceiver::from_recv(activation_token_channel),
|
||||
user_receiver: PeekableReceiver::from_recv(user_channel),
|
||||
user_sender,
|
||||
target,
|
||||
state: EventLoopState {
|
||||
x11_readiness: Readiness::EMPTY,
|
||||
},
|
||||
@@ -399,7 +390,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
}
|
||||
|
||||
pub(crate) fn window_target(&self) -> &RootELW<T> {
|
||||
&self.target
|
||||
&self.event_processor.target
|
||||
}
|
||||
|
||||
pub fn run_on_demand<F>(&mut self, mut event_handler: F) -> Result<(), EventLoopError>
|
||||
@@ -428,7 +419,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
// `run_on_demand` calls but if they have only just dropped their
|
||||
// windows we need to make sure those last requests are sent to the
|
||||
// X Server.
|
||||
let wt = get_xtarget(&self.target);
|
||||
let wt = EventProcessor::window_target(&self.event_processor.target);
|
||||
wt.x_connection().sync_with_server().map_err(|x_err| {
|
||||
EventLoopError::Os(os_error!(OsError::XError(Arc::new(X11Error::Xlib(x_err)))))
|
||||
})?;
|
||||
@@ -551,12 +542,12 @@ impl<T: 'static> EventLoop<T> {
|
||||
where
|
||||
F: FnMut(Event<T>, &RootELW<T>),
|
||||
{
|
||||
callback(crate::event::Event::NewEvents(cause), &self.target);
|
||||
callback(Event::NewEvents(cause), &self.event_processor.target);
|
||||
|
||||
// NB: For consistency all platforms must emit a 'resumed' event even though X11
|
||||
// applications don't themselves have a formal suspend/resume lifecycle.
|
||||
if cause == StartCause::Init {
|
||||
callback(crate::event::Event::Resumed, &self.target);
|
||||
callback(Event::Resumed, &self.event_processor.target);
|
||||
}
|
||||
|
||||
// Process all pending events
|
||||
@@ -571,16 +562,16 @@ impl<T: 'static> EventLoop<T> {
|
||||
});
|
||||
|
||||
match token {
|
||||
Some(Ok(token)) => callback(
|
||||
crate::event::Event::WindowEvent {
|
||||
Some(Ok(token)) => {
|
||||
let event = Event::WindowEvent {
|
||||
window_id: crate::window::WindowId(window_id),
|
||||
event: crate::event::WindowEvent::ActivationTokenDone {
|
||||
event: WindowEvent::ActivationTokenDone {
|
||||
serial,
|
||||
token: crate::window::ActivationToken::_new(token),
|
||||
},
|
||||
},
|
||||
&self.target,
|
||||
),
|
||||
};
|
||||
callback(event, &self.event_processor.target)
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
log::error!("Failed to get activation token: {}", e);
|
||||
}
|
||||
@@ -591,7 +582,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
// Empty the user event buffer
|
||||
{
|
||||
while let Ok(event) = self.user_receiver.try_recv() {
|
||||
callback(crate::event::Event::UserEvent(event), &self.target);
|
||||
callback(Event::UserEvent(event), &self.event_processor.target);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -610,14 +601,14 @@ impl<T: 'static> EventLoop<T> {
|
||||
window_id,
|
||||
event: WindowEvent::RedrawRequested,
|
||||
},
|
||||
&self.target,
|
||||
&self.event_processor.target,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// This is always the last event we dispatch before poll again
|
||||
{
|
||||
callback(crate::event::Event::AboutToWait, &self.target);
|
||||
callback(Event::AboutToWait, &self.event_processor.target);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -625,40 +616,44 @@ impl<T: 'static> EventLoop<T> {
|
||||
where
|
||||
F: FnMut(Event<T>, &RootELW<T>),
|
||||
{
|
||||
let target = &self.target;
|
||||
let mut xev = MaybeUninit::uninit();
|
||||
let wt = get_xtarget(&self.target);
|
||||
|
||||
while unsafe { self.event_processor.poll_one_event(xev.as_mut_ptr()) } {
|
||||
let mut xev = unsafe { xev.assume_init() };
|
||||
self.event_processor.process_event(&mut xev, |event| {
|
||||
if let Event::WindowEvent {
|
||||
window_id: crate::window::WindowId(wid),
|
||||
event: WindowEvent::RedrawRequested,
|
||||
} = event
|
||||
{
|
||||
wt.redraw_sender.send(wid).unwrap();
|
||||
} else {
|
||||
callback(event, target);
|
||||
}
|
||||
});
|
||||
self.event_processor
|
||||
.process_event(&mut xev, |window_target, event| {
|
||||
if let Event::WindowEvent {
|
||||
window_id: crate::window::WindowId(wid),
|
||||
event: WindowEvent::RedrawRequested,
|
||||
} = event
|
||||
{
|
||||
let window_target = EventProcessor::window_target(window_target);
|
||||
window_target.redraw_sender.send(wid).unwrap();
|
||||
} else {
|
||||
callback(event, window_target);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn control_flow(&self) -> ControlFlow {
|
||||
self.target.p.control_flow()
|
||||
let window_target = EventProcessor::window_target(&self.event_processor.target);
|
||||
window_target.control_flow()
|
||||
}
|
||||
|
||||
fn exiting(&self) -> bool {
|
||||
self.target.p.exiting()
|
||||
let window_target = EventProcessor::window_target(&self.event_processor.target);
|
||||
window_target.exiting()
|
||||
}
|
||||
|
||||
fn set_exit_code(&self, code: i32) {
|
||||
self.target.p.set_exit_code(code)
|
||||
let window_target = EventProcessor::window_target(&self.event_processor.target);
|
||||
window_target.set_exit_code(code);
|
||||
}
|
||||
|
||||
fn exit_code(&self) -> Option<i32> {
|
||||
self.target.p.exit_code()
|
||||
let window_target = EventProcessor::window_target(&self.event_processor.target);
|
||||
window_target.exit_code()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -674,14 +669,6 @@ impl<T> AsRawFd for EventLoop<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_xtarget<T>(target: &RootELW<T>) -> &EventLoopWindowTarget<T> {
|
||||
match target.p {
|
||||
super::EventLoopWindowTarget::X(ref target) => target,
|
||||
#[cfg(wayland_platform)]
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoopWindowTarget<T> {
|
||||
/// Returns the `XConnection` of this events loop.
|
||||
#[inline]
|
||||
@@ -898,6 +885,9 @@ pub enum X11Error {
|
||||
|
||||
/// Could not find a matching X11 visual for this visualid
|
||||
NoSuchVisual(xproto::Visualid),
|
||||
|
||||
/// Unable to parse xsettings.
|
||||
XsettingsParse(xsettings::ParserError),
|
||||
}
|
||||
|
||||
impl fmt::Display for X11Error {
|
||||
@@ -922,6 +912,9 @@ impl fmt::Display for X11Error {
|
||||
visualid
|
||||
)
|
||||
}
|
||||
X11Error::XsettingsParse(err) => {
|
||||
write!(f, "Failed to parse xsettings: {:?}", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -990,6 +983,12 @@ impl From<ReplyOrIdError> for X11Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<xsettings::ParserError> for X11Error {
|
||||
fn from(value: xsettings::ParserError) -> Self {
|
||||
Self::XsettingsParse(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// The underlying x11rb connection that we are using.
|
||||
type X11rbConnection = x11rb::xcb_ffi::XCBConnection;
|
||||
|
||||
@@ -1044,7 +1043,7 @@ fn mkdid(w: xinput::DeviceId) -> crate::event::DeviceId {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Device {
|
||||
pub struct Device {
|
||||
_name: String,
|
||||
scroll_axes: Vec<(i32, ScrollAxis)>,
|
||||
// For master devices, this is the paired device (pointer <-> keyboard).
|
||||
|
||||
@@ -324,7 +324,7 @@ impl XConnection {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ScreenResources {
|
||||
pub struct ScreenResources {
|
||||
/// List of attached modes.
|
||||
modes: Vec<randr::ModeInfo>,
|
||||
|
||||
|
||||
1
src/platform_impl/linux/x11/tests/xsettings.dat
Normal file
1
src/platform_impl/linux/x11/tests/xsettings.dat
Normal file
File diff suppressed because one or more lines are too long
@@ -83,14 +83,6 @@ impl FrameExtents {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LogicalFrameExtents {
|
||||
pub left: f64,
|
||||
pub right: f64,
|
||||
pub top: f64,
|
||||
pub bottom: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum FrameExtentsHeuristicPath {
|
||||
Supported,
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
// Welcome to the util module, where we try to keep you from shooting yourself in the foot.
|
||||
// *results may vary
|
||||
|
||||
use std::{
|
||||
mem::{self, MaybeUninit},
|
||||
ops::BitAnd,
|
||||
os::raw::*,
|
||||
};
|
||||
|
||||
mod client_msg;
|
||||
mod cursor;
|
||||
mod geometry;
|
||||
@@ -12,13 +18,10 @@ pub(crate) mod memory;
|
||||
mod randr;
|
||||
mod window_property;
|
||||
mod wm;
|
||||
mod xmodmap;
|
||||
|
||||
pub use self::{geometry::*, hint::*, input::*, window_property::*, wm::*};
|
||||
|
||||
use std::{
|
||||
mem::{self, MaybeUninit},
|
||||
ops::BitAnd,
|
||||
os::raw::*,
|
||||
pub use self::{
|
||||
geometry::*, hint::*, input::*, window_property::*, wm::*, xmodmap::ModifierKeymap,
|
||||
};
|
||||
|
||||
use super::{atoms::*, ffi, VoidCookie, X11Error, XConnection, XError};
|
||||
|
||||
@@ -37,6 +37,17 @@ pub fn calc_dpi_factor(
|
||||
impl XConnection {
|
||||
// Retrieve DPI from Xft.dpi property
|
||||
pub fn get_xft_dpi(&self) -> Option<f64> {
|
||||
// Try to get it from XSETTINGS first.
|
||||
if let Some(xsettings_screen) = self.xsettings_screen() {
|
||||
match self.xsettings_dpi(xsettings_screen) {
|
||||
Ok(Some(dpi)) => return Some(dpi),
|
||||
Ok(None) => {}
|
||||
Err(err) => {
|
||||
log::warn!("failed to fetch XSettings: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.database()
|
||||
.get_string("Xft.dpi", "")
|
||||
.and_then(|s| f64::from_str(s).ok())
|
||||
|
||||
56
src/platform_impl/linux/x11/util/xmodmap.rs
Normal file
56
src/platform_impl/linux/x11/util/xmodmap.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
use std::collections::HashSet;
|
||||
use std::slice;
|
||||
|
||||
use x11_dl::xlib::{KeyCode as XKeyCode, XModifierKeymap};
|
||||
|
||||
// Offsets within XModifierKeymap to each set of keycodes.
|
||||
// We are only interested in Shift, Control, Alt, and Logo.
|
||||
//
|
||||
// There are 8 sets total. The order of keycode sets is:
|
||||
// Shift, Lock, Control, Mod1 (Alt), Mod2, Mod3, Mod4 (Logo), Mod5
|
||||
//
|
||||
// https://tronche.com/gui/x/xlib/input/XSetModifierMapping.html
|
||||
const NUM_MODS: usize = 8;
|
||||
|
||||
/// Track which keys are modifiers, so we can properly replay them when they were filtered.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ModifierKeymap {
|
||||
// Maps keycodes to modifiers
|
||||
modifers: HashSet<XKeyCode>,
|
||||
}
|
||||
|
||||
impl ModifierKeymap {
|
||||
pub fn new() -> ModifierKeymap {
|
||||
ModifierKeymap::default()
|
||||
}
|
||||
|
||||
pub fn is_modifier(&self, keycode: XKeyCode) -> bool {
|
||||
self.modifers.contains(&keycode)
|
||||
}
|
||||
|
||||
pub fn reload_from_x_connection(&mut self, xconn: &super::XConnection) {
|
||||
unsafe {
|
||||
let keymap = (xconn.xlib.XGetModifierMapping)(xconn.display);
|
||||
|
||||
if keymap.is_null() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.reset_from_x_keymap(&*keymap);
|
||||
|
||||
(xconn.xlib.XFreeModifiermap)(keymap);
|
||||
}
|
||||
}
|
||||
|
||||
fn reset_from_x_keymap(&mut self, keymap: &XModifierKeymap) {
|
||||
let keys_per_mod = keymap.max_keypermod as usize;
|
||||
|
||||
let keys = unsafe {
|
||||
slice::from_raw_parts(keymap.modifiermap as *const _, keys_per_mod * NUM_MODS)
|
||||
};
|
||||
self.modifers.clear();
|
||||
for key in keys {
|
||||
self.modifers.insert(*key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,7 +118,7 @@ impl SharedState {
|
||||
unsafe impl Send for UnownedWindow {}
|
||||
unsafe impl Sync for UnownedWindow {}
|
||||
|
||||
pub(crate) struct UnownedWindow {
|
||||
pub struct UnownedWindow {
|
||||
pub(crate) xconn: Arc<XConnection>, // never changes
|
||||
xwindow: xproto::Window, // never changes
|
||||
#[allow(dead_code)]
|
||||
@@ -396,7 +396,7 @@ impl UnownedWindow {
|
||||
|
||||
// WM_CLASS must be set *before* mapping the window, as per ICCCM!
|
||||
{
|
||||
let (class, instance) = if let Some(name) = pl_attribs.name {
|
||||
let (instance, class) = if let Some(name) = pl_attribs.name {
|
||||
(name.instance, name.general)
|
||||
} else {
|
||||
let class = env::args_os()
|
||||
@@ -541,9 +541,9 @@ impl UnownedWindow {
|
||||
leap!(xconn.select_xinput_events(window.xwindow, super::ALL_MASTER_DEVICES, mask))
|
||||
.ignore_error();
|
||||
|
||||
{
|
||||
let result = event_loop
|
||||
.ime
|
||||
// Try to create input context for the window.
|
||||
if let Some(ime) = event_loop.ime.as_ref() {
|
||||
let result = ime
|
||||
.borrow_mut()
|
||||
.create_context(window.xwindow as ffi::Window, false);
|
||||
leap!(result);
|
||||
|
||||
@@ -13,13 +13,16 @@ use crate::window::CursorIcon;
|
||||
use super::{atoms::Atoms, ffi, monitor::MonitorHandle};
|
||||
use x11rb::{
|
||||
connection::Connection,
|
||||
protocol::{randr::ConnectionExt as _, xproto},
|
||||
protocol::{
|
||||
randr::ConnectionExt as _,
|
||||
xproto::{self, ConnectionExt},
|
||||
},
|
||||
resource_manager,
|
||||
xcb_ffi::XCBConnection,
|
||||
};
|
||||
|
||||
/// A connection to an X server.
|
||||
pub(crate) struct XConnection {
|
||||
pub struct XConnection {
|
||||
pub xlib: ffi::Xlib,
|
||||
pub xcursor: ffi::Xcursor,
|
||||
|
||||
@@ -55,6 +58,9 @@ pub(crate) struct XConnection {
|
||||
/// RandR version.
|
||||
randr_version: (u32, u32),
|
||||
|
||||
/// Atom for the XSettings screen.
|
||||
xsettings_screen: Option<xproto::Atom>,
|
||||
|
||||
pub latest_error: Mutex<Option<XError>>,
|
||||
pub cursor_cache: Mutex<HashMap<Option<CursorIcon>, ffi::Cursor>>,
|
||||
}
|
||||
@@ -102,12 +108,6 @@ impl XConnection {
|
||||
// Get the default screen.
|
||||
let default_screen = unsafe { (xlib.XDefaultScreen)(display) } as usize;
|
||||
|
||||
// Fetch the atoms.
|
||||
let atoms = Atoms::new(&xcb)
|
||||
.map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?
|
||||
.reply()
|
||||
.map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?;
|
||||
|
||||
// Load the database.
|
||||
let database = resource_manager::new_from_default(&xcb)
|
||||
.map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?;
|
||||
@@ -119,6 +119,17 @@ impl XConnection {
|
||||
.reply()
|
||||
.expect("failed to query XRandR version");
|
||||
|
||||
let xsettings_screen = Self::new_xsettings_screen(&xcb, default_screen);
|
||||
if xsettings_screen.is_none() {
|
||||
log::warn!("error setting XSETTINGS; Xft options won't reload automatically")
|
||||
}
|
||||
|
||||
// Fetch atoms.
|
||||
let atoms = Atoms::new(&xcb)
|
||||
.map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?
|
||||
.reply()
|
||||
.map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?;
|
||||
|
||||
Ok(XConnection {
|
||||
xlib,
|
||||
xcursor,
|
||||
@@ -133,9 +144,41 @@ impl XConnection {
|
||||
database: RwLock::new(database),
|
||||
cursor_cache: Default::default(),
|
||||
randr_version: (randr_version.major_version, randr_version.minor_version),
|
||||
xsettings_screen,
|
||||
})
|
||||
}
|
||||
|
||||
fn new_xsettings_screen(xcb: &XCBConnection, default_screen: usize) -> Option<xproto::Atom> {
|
||||
// Fetch the _XSETTINGS_S[screen number] atom.
|
||||
let xsettings_screen = xcb
|
||||
.intern_atom(false, format!("_XSETTINGS_S{}", default_screen).as_bytes())
|
||||
.ok()?
|
||||
.reply()
|
||||
.ok()?
|
||||
.atom;
|
||||
|
||||
// Get PropertyNotify events from the XSETTINGS window.
|
||||
// TODO: The XSETTINGS window here can change. In the future, listen for DestroyNotify on this window
|
||||
// in order to accomodate for a changed window here.
|
||||
let selector_window = xcb
|
||||
.get_selection_owner(xsettings_screen)
|
||||
.ok()?
|
||||
.reply()
|
||||
.ok()?
|
||||
.owner;
|
||||
|
||||
xcb.change_window_attributes(
|
||||
selector_window,
|
||||
&xproto::ChangeWindowAttributesAux::new()
|
||||
.event_mask(xproto::EventMask::PROPERTY_CHANGE),
|
||||
)
|
||||
.ok()?
|
||||
.check()
|
||||
.ok()?;
|
||||
|
||||
Some(xsettings_screen)
|
||||
}
|
||||
|
||||
/// Checks whether an error has been triggered by the previous function calls.
|
||||
#[inline]
|
||||
pub fn check_errors(&self) -> Result<(), XError> {
|
||||
@@ -221,6 +264,12 @@ impl XConnection {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the atom for Xsettings.
|
||||
#[inline]
|
||||
pub fn xsettings_screen(&self) -> Option<xproto::Atom> {
|
||||
self.xsettings_screen
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for XConnection {
|
||||
|
||||
345
src/platform_impl/linux/x11/xsettings.rs
Normal file
345
src/platform_impl/linux/x11/xsettings.rs
Normal file
@@ -0,0 +1,345 @@
|
||||
//! Parser for the xsettings data format.
|
||||
//!
|
||||
//! Some of this code is referenced from [here].
|
||||
//!
|
||||
//! [here]: https://github.com/derat/xsettingsd
|
||||
|
||||
use std::iter;
|
||||
use std::num::NonZeroUsize;
|
||||
|
||||
use x11rb::protocol::xproto::{self, ConnectionExt};
|
||||
|
||||
use super::{atoms::*, XConnection};
|
||||
|
||||
type Result<T> = core::result::Result<T, ParserError>;
|
||||
|
||||
const DPI_NAME: &[u8] = b"Xft/DPI";
|
||||
const DPI_MULTIPLIER: f64 = 1024.0;
|
||||
const LITTLE_ENDIAN: u8 = b'l';
|
||||
const BIG_ENDIAN: u8 = b'B';
|
||||
|
||||
impl XConnection {
|
||||
/// Get the DPI from XSettings.
|
||||
pub(crate) fn xsettings_dpi(
|
||||
&self,
|
||||
xsettings_screen: xproto::Atom,
|
||||
) -> core::result::Result<Option<f64>, super::X11Error> {
|
||||
let atoms = self.atoms();
|
||||
|
||||
// Get the current owner of the screen's settings.
|
||||
let owner = self
|
||||
.xcb_connection()
|
||||
.get_selection_owner(xsettings_screen)?
|
||||
.reply()?;
|
||||
|
||||
// Read the _XSETTINGS_SETTINGS property.
|
||||
let data: Vec<u8> = self
|
||||
.get_property(
|
||||
owner.owner,
|
||||
atoms[_XSETTINGS_SETTINGS],
|
||||
atoms[_XSETTINGS_SETTINGS],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Parse the property.
|
||||
let dpi_setting = read_settings(&data)?
|
||||
.find(|res| res.as_ref().map_or(true, |s| s.name == DPI_NAME))
|
||||
.transpose()?;
|
||||
if let Some(dpi_setting) = dpi_setting {
|
||||
let base_dpi = match dpi_setting.data {
|
||||
SettingData::Integer(dpi) => dpi as f64,
|
||||
SettingData::String(_) => {
|
||||
return Err(ParserError::BadType(SettingType::String).into())
|
||||
}
|
||||
SettingData::Color(_) => {
|
||||
return Err(ParserError::BadType(SettingType::Color).into())
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Some(base_dpi / DPI_MULTIPLIER))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read over the settings in the block of data.
|
||||
fn read_settings(data: &[u8]) -> Result<impl Iterator<Item = Result<Setting<'_>>> + '_> {
|
||||
// Create a parser. This automatically parses the first 8 bytes for metadata.
|
||||
let mut parser = Parser::new(data)?;
|
||||
|
||||
// Read the total number of settings.
|
||||
let total_settings = parser.i32()?;
|
||||
|
||||
// Iterate over the settings.
|
||||
let iter = iter::repeat_with(move || Setting::parse(&mut parser)).take(total_settings as usize);
|
||||
Ok(iter)
|
||||
}
|
||||
|
||||
/// A setting in the settings list.
|
||||
struct Setting<'a> {
|
||||
/// The name of the setting.
|
||||
name: &'a [u8],
|
||||
|
||||
/// The data contained in the setting.
|
||||
data: SettingData<'a>,
|
||||
}
|
||||
|
||||
/// The data contained in a setting.
|
||||
enum SettingData<'a> {
|
||||
Integer(i32),
|
||||
String(#[allow(dead_code)] &'a [u8]),
|
||||
Color(#[allow(dead_code)] [i16; 4]),
|
||||
}
|
||||
|
||||
impl<'a> Setting<'a> {
|
||||
/// Parse a new `SettingData`.
|
||||
fn parse(parser: &mut Parser<'a>) -> Result<Self> {
|
||||
// Read the type.
|
||||
let ty: SettingType = parser.i8()?.try_into()?;
|
||||
|
||||
// Read another byte of padding.
|
||||
parser.advance(1)?;
|
||||
|
||||
// Read the name of the setting.
|
||||
let name_len = parser.i16()?;
|
||||
let name = parser.advance(name_len as usize)?;
|
||||
parser.pad(name.len(), 4)?;
|
||||
|
||||
// Ignore the serial number.
|
||||
parser.advance(4)?;
|
||||
|
||||
let data = match ty {
|
||||
SettingType::Integer => {
|
||||
// Read a 32-bit integer.
|
||||
SettingData::Integer(parser.i32()?)
|
||||
}
|
||||
|
||||
SettingType::String => {
|
||||
// Read the data.
|
||||
let data_len = parser.i32()?;
|
||||
let data = parser.advance(data_len as usize)?;
|
||||
parser.pad(data.len(), 4)?;
|
||||
|
||||
SettingData::String(data)
|
||||
}
|
||||
|
||||
SettingType::Color => {
|
||||
// Read i16's of color.
|
||||
let (red, blue, green, alpha) =
|
||||
(parser.i16()?, parser.i16()?, parser.i16()?, parser.i16()?);
|
||||
|
||||
SettingData::Color([red, blue, green, alpha])
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Setting { name, data })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SettingType {
|
||||
Integer = 0,
|
||||
String = 1,
|
||||
Color = 2,
|
||||
}
|
||||
|
||||
impl TryFrom<i8> for SettingType {
|
||||
type Error = ParserError;
|
||||
|
||||
fn try_from(value: i8) -> Result<Self> {
|
||||
Ok(match value {
|
||||
0 => Self::Integer,
|
||||
1 => Self::String,
|
||||
2 => Self::Color,
|
||||
x => return Err(ParserError::InvalidType(x)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Parser for the incoming byte stream.
|
||||
struct Parser<'a> {
|
||||
bytes: &'a [u8],
|
||||
endianness: Endianness,
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// Create a new parser.
|
||||
fn new(bytes: &'a [u8]) -> Result<Self> {
|
||||
let (endianness, bytes) = bytes
|
||||
.split_first()
|
||||
.ok_or_else(|| ParserError::ran_out(1, 0))?;
|
||||
let endianness = match *endianness {
|
||||
BIG_ENDIAN => Endianness::Big,
|
||||
LITTLE_ENDIAN => Endianness::Little,
|
||||
_ => Endianness::native(),
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
// Ignore three bytes of padding and the four-byte serial.
|
||||
bytes: bytes
|
||||
.get(7..)
|
||||
.ok_or_else(|| ParserError::ran_out(7, bytes.len()))?,
|
||||
endianness,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get a slice of bytes.
|
||||
fn advance(&mut self, n: usize) -> Result<&'a [u8]> {
|
||||
if n == 0 {
|
||||
return Ok(&[]);
|
||||
}
|
||||
|
||||
if n > self.bytes.len() {
|
||||
Err(ParserError::ran_out(n, self.bytes.len()))
|
||||
} else {
|
||||
let (part, rem) = self.bytes.split_at(n);
|
||||
self.bytes = rem;
|
||||
Ok(part)
|
||||
}
|
||||
}
|
||||
|
||||
/// Skip some padding.
|
||||
fn pad(&mut self, size: usize, pad: usize) -> Result<()> {
|
||||
let advance = (pad - (size % pad)) % pad;
|
||||
self.advance(advance)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get a single byte.
|
||||
fn i8(&mut self) -> Result<i8> {
|
||||
self.advance(1).map(|s| s[0] as i8)
|
||||
}
|
||||
|
||||
/// Get two bytes.
|
||||
fn i16(&mut self) -> Result<i16> {
|
||||
self.advance(2).map(|s| {
|
||||
let bytes: &[u8; 2] = s.try_into().unwrap();
|
||||
match self.endianness {
|
||||
Endianness::Big => i16::from_be_bytes(*bytes),
|
||||
Endianness::Little => i16::from_le_bytes(*bytes),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Get four bytes.
|
||||
fn i32(&mut self) -> Result<i32> {
|
||||
self.advance(4).map(|s| {
|
||||
let bytes: &[u8; 4] = s.try_into().unwrap();
|
||||
match self.endianness {
|
||||
Endianness::Big => i32::from_be_bytes(*bytes),
|
||||
Endianness::Little => i32::from_le_bytes(*bytes),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Endianness of the incoming data.
|
||||
enum Endianness {
|
||||
Little,
|
||||
Big,
|
||||
}
|
||||
|
||||
impl Endianness {
|
||||
#[cfg(target_endian = "little")]
|
||||
fn native() -> Self {
|
||||
Endianness::Little
|
||||
}
|
||||
|
||||
#[cfg(target_endian = "big")]
|
||||
fn native() -> Self {
|
||||
Endianness::Big
|
||||
}
|
||||
}
|
||||
|
||||
/// Parser errors.
|
||||
#[derive(Debug)]
|
||||
pub enum ParserError {
|
||||
/// Ran out of bytes.
|
||||
NoMoreBytes {
|
||||
expected: NonZeroUsize,
|
||||
found: usize,
|
||||
},
|
||||
|
||||
/// Invalid type.
|
||||
InvalidType(i8),
|
||||
|
||||
/// Bad setting type.
|
||||
BadType(SettingType),
|
||||
}
|
||||
|
||||
impl ParserError {
|
||||
fn ran_out(expected: usize, found: usize) -> ParserError {
|
||||
let expected = NonZeroUsize::new(expected).unwrap();
|
||||
Self::NoMoreBytes { expected, found }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! Tests for the XSETTINGS parser.
|
||||
|
||||
use super::*;
|
||||
|
||||
const XSETTINGS: &str = include_str!("tests/xsettings.dat");
|
||||
|
||||
#[test]
|
||||
fn empty() {
|
||||
let err = match read_settings(&[]) {
|
||||
Ok(_) => panic!(),
|
||||
Err(err) => err,
|
||||
};
|
||||
match err {
|
||||
ParserError::NoMoreBytes { expected, found } => {
|
||||
assert_eq!(expected.get(), 1);
|
||||
assert_eq!(found, 0);
|
||||
}
|
||||
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_xsettings() {
|
||||
let data = XSETTINGS
|
||||
.trim()
|
||||
.split(',')
|
||||
.map(|tok| {
|
||||
let val = tok.strip_prefix("0x").unwrap();
|
||||
u8::from_str_radix(val, 16).unwrap()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let settings = read_settings(&data)
|
||||
.unwrap()
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.unwrap();
|
||||
|
||||
let dpi = settings.iter().find(|s| s.name == b"Xft/DPI").unwrap();
|
||||
assert_int(&dpi.data, 96 * 1024);
|
||||
let hinting = settings.iter().find(|s| s.name == b"Xft/Hinting").unwrap();
|
||||
assert_int(&hinting.data, 1);
|
||||
|
||||
let rgba = settings.iter().find(|s| s.name == b"Xft/RGBA").unwrap();
|
||||
assert_string(&rgba.data, "rgb");
|
||||
let lcd = settings
|
||||
.iter()
|
||||
.find(|s| s.name == b"Xft/Lcdfilter")
|
||||
.unwrap();
|
||||
assert_string(&lcd.data, "lcddefault");
|
||||
}
|
||||
|
||||
fn assert_string(dat: &SettingData<'_>, s: &str) {
|
||||
match dat {
|
||||
SettingData::String(left) => assert_eq!(*left, s.as_bytes()),
|
||||
_ => panic!("invalid data type"),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_int(dat: &SettingData<'_>, i: i32) {
|
||||
match dat {
|
||||
SettingData::Integer(left) => assert_eq!(*left, i),
|
||||
_ => panic!("invalid data type"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
use std::{
|
||||
self,
|
||||
ffi::c_void,
|
||||
panic::{AssertUnwindSafe, UnwindSafe},
|
||||
ptr,
|
||||
|
||||
@@ -410,9 +410,9 @@ declare_class!(
|
||||
let content_rect = window.contentRectForFrameRect(window.frame());
|
||||
let base_x = content_rect.origin.x as f64;
|
||||
let base_y = (content_rect.origin.y + content_rect.size.height) as f64;
|
||||
let x = base_x + self.state.ime_position.get().x;
|
||||
let y = base_y - self.state.ime_position.get().y;
|
||||
let LogicalSize { width, height } = self.state.ime_size.get();
|
||||
let x = base_x + self.state.ime_position.get().x;
|
||||
let y = base_y - self.state.ime_position.get().y - height;
|
||||
NSRect::new(NSPoint::new(x as _, y as _), NSSize::new(width, height))
|
||||
}
|
||||
|
||||
|
||||
@@ -8,17 +8,18 @@ use std::{
|
||||
};
|
||||
|
||||
use orbclient::{
|
||||
ButtonEvent, EventOption, FocusEvent, HoverEvent, KeyEvent, MouseEvent, MoveEvent, QuitEvent,
|
||||
ResizeEvent, ScrollEvent, TextInputEvent,
|
||||
ButtonEvent, EventOption, FocusEvent, HoverEvent, KeyEvent, MouseEvent, MouseRelativeEvent,
|
||||
MoveEvent, QuitEvent, ResizeEvent, ScrollEvent, TextInputEvent,
|
||||
};
|
||||
use smol_str::SmolStr;
|
||||
|
||||
use crate::{
|
||||
error::EventLoopError,
|
||||
event::{self, Ime, Modifiers, StartCause},
|
||||
event_loop::{self, ControlFlow, DeviceEvents},
|
||||
keyboard::{
|
||||
Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NativeKey, NativeKeyCode,
|
||||
PhysicalKey,
|
||||
Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey,
|
||||
NativeKeyCode, PhysicalKey,
|
||||
},
|
||||
window::WindowId as RootWindowId,
|
||||
};
|
||||
@@ -28,90 +29,107 @@ use super::{
|
||||
RedoxSocket, TimeSocket, WindowId, WindowProperties,
|
||||
};
|
||||
|
||||
fn convert_scancode(scancode: u8) -> PhysicalKey {
|
||||
PhysicalKey::Code(match scancode {
|
||||
orbclient::K_A => KeyCode::KeyA,
|
||||
orbclient::K_B => KeyCode::KeyB,
|
||||
orbclient::K_C => KeyCode::KeyC,
|
||||
orbclient::K_D => KeyCode::KeyD,
|
||||
orbclient::K_E => KeyCode::KeyE,
|
||||
orbclient::K_F => KeyCode::KeyF,
|
||||
orbclient::K_G => KeyCode::KeyG,
|
||||
orbclient::K_H => KeyCode::KeyH,
|
||||
orbclient::K_I => KeyCode::KeyI,
|
||||
orbclient::K_J => KeyCode::KeyJ,
|
||||
orbclient::K_K => KeyCode::KeyK,
|
||||
orbclient::K_L => KeyCode::KeyL,
|
||||
orbclient::K_M => KeyCode::KeyM,
|
||||
orbclient::K_N => KeyCode::KeyN,
|
||||
orbclient::K_O => KeyCode::KeyO,
|
||||
orbclient::K_P => KeyCode::KeyP,
|
||||
orbclient::K_Q => KeyCode::KeyQ,
|
||||
orbclient::K_R => KeyCode::KeyR,
|
||||
orbclient::K_S => KeyCode::KeyS,
|
||||
orbclient::K_T => KeyCode::KeyT,
|
||||
orbclient::K_U => KeyCode::KeyU,
|
||||
orbclient::K_V => KeyCode::KeyV,
|
||||
orbclient::K_W => KeyCode::KeyW,
|
||||
orbclient::K_X => KeyCode::KeyX,
|
||||
orbclient::K_Y => KeyCode::KeyY,
|
||||
orbclient::K_Z => KeyCode::KeyZ,
|
||||
orbclient::K_0 => KeyCode::Digit0,
|
||||
orbclient::K_1 => KeyCode::Digit1,
|
||||
orbclient::K_2 => KeyCode::Digit2,
|
||||
orbclient::K_3 => KeyCode::Digit3,
|
||||
orbclient::K_4 => KeyCode::Digit4,
|
||||
orbclient::K_5 => KeyCode::Digit5,
|
||||
orbclient::K_6 => KeyCode::Digit6,
|
||||
orbclient::K_7 => KeyCode::Digit7,
|
||||
orbclient::K_8 => KeyCode::Digit8,
|
||||
orbclient::K_9 => KeyCode::Digit9,
|
||||
fn convert_scancode(scancode: u8) -> (PhysicalKey, Option<NamedKey>) {
|
||||
// Key constants from https://docs.rs/orbclient/latest/orbclient/event/index.html
|
||||
let (key_code, named_key_opt) = match scancode {
|
||||
orbclient::K_A => (KeyCode::KeyA, None),
|
||||
orbclient::K_B => (KeyCode::KeyB, None),
|
||||
orbclient::K_C => (KeyCode::KeyC, None),
|
||||
orbclient::K_D => (KeyCode::KeyD, None),
|
||||
orbclient::K_E => (KeyCode::KeyE, None),
|
||||
orbclient::K_F => (KeyCode::KeyF, None),
|
||||
orbclient::K_G => (KeyCode::KeyG, None),
|
||||
orbclient::K_H => (KeyCode::KeyH, None),
|
||||
orbclient::K_I => (KeyCode::KeyI, None),
|
||||
orbclient::K_J => (KeyCode::KeyJ, None),
|
||||
orbclient::K_K => (KeyCode::KeyK, None),
|
||||
orbclient::K_L => (KeyCode::KeyL, None),
|
||||
orbclient::K_M => (KeyCode::KeyM, None),
|
||||
orbclient::K_N => (KeyCode::KeyN, None),
|
||||
orbclient::K_O => (KeyCode::KeyO, None),
|
||||
orbclient::K_P => (KeyCode::KeyP, None),
|
||||
orbclient::K_Q => (KeyCode::KeyQ, None),
|
||||
orbclient::K_R => (KeyCode::KeyR, None),
|
||||
orbclient::K_S => (KeyCode::KeyS, None),
|
||||
orbclient::K_T => (KeyCode::KeyT, None),
|
||||
orbclient::K_U => (KeyCode::KeyU, None),
|
||||
orbclient::K_V => (KeyCode::KeyV, None),
|
||||
orbclient::K_W => (KeyCode::KeyW, None),
|
||||
orbclient::K_X => (KeyCode::KeyX, None),
|
||||
orbclient::K_Y => (KeyCode::KeyY, None),
|
||||
orbclient::K_Z => (KeyCode::KeyZ, None),
|
||||
orbclient::K_0 => (KeyCode::Digit0, None),
|
||||
orbclient::K_1 => (KeyCode::Digit1, None),
|
||||
orbclient::K_2 => (KeyCode::Digit2, None),
|
||||
orbclient::K_3 => (KeyCode::Digit3, None),
|
||||
orbclient::K_4 => (KeyCode::Digit4, None),
|
||||
orbclient::K_5 => (KeyCode::Digit5, None),
|
||||
orbclient::K_6 => (KeyCode::Digit6, None),
|
||||
orbclient::K_7 => (KeyCode::Digit7, None),
|
||||
orbclient::K_8 => (KeyCode::Digit8, None),
|
||||
orbclient::K_9 => (KeyCode::Digit9, None),
|
||||
|
||||
orbclient::K_TICK => KeyCode::Backquote,
|
||||
orbclient::K_MINUS => KeyCode::Minus,
|
||||
orbclient::K_EQUALS => KeyCode::Equal,
|
||||
orbclient::K_BACKSLASH => KeyCode::Backslash,
|
||||
orbclient::K_BRACE_OPEN => KeyCode::BracketLeft,
|
||||
orbclient::K_BRACE_CLOSE => KeyCode::BracketRight,
|
||||
orbclient::K_SEMICOLON => KeyCode::Semicolon,
|
||||
orbclient::K_QUOTE => KeyCode::Quote,
|
||||
orbclient::K_COMMA => KeyCode::Comma,
|
||||
orbclient::K_PERIOD => KeyCode::Period,
|
||||
orbclient::K_SLASH => KeyCode::Slash,
|
||||
orbclient::K_BKSP => KeyCode::Backspace,
|
||||
orbclient::K_SPACE => KeyCode::Space,
|
||||
orbclient::K_TAB => KeyCode::Tab,
|
||||
//orbclient::K_CAPS => KeyCode::CAPS,
|
||||
orbclient::K_LEFT_SHIFT => KeyCode::ShiftLeft,
|
||||
orbclient::K_RIGHT_SHIFT => KeyCode::ShiftRight,
|
||||
orbclient::K_CTRL => KeyCode::ControlLeft,
|
||||
orbclient::K_ALT => KeyCode::AltLeft,
|
||||
orbclient::K_ENTER => KeyCode::Enter,
|
||||
orbclient::K_ESC => KeyCode::Escape,
|
||||
orbclient::K_F1 => KeyCode::F1,
|
||||
orbclient::K_F2 => KeyCode::F2,
|
||||
orbclient::K_F3 => KeyCode::F3,
|
||||
orbclient::K_F4 => KeyCode::F4,
|
||||
orbclient::K_F5 => KeyCode::F5,
|
||||
orbclient::K_F6 => KeyCode::F6,
|
||||
orbclient::K_F7 => KeyCode::F7,
|
||||
orbclient::K_F8 => KeyCode::F8,
|
||||
orbclient::K_F9 => KeyCode::F9,
|
||||
orbclient::K_F10 => KeyCode::F10,
|
||||
orbclient::K_HOME => KeyCode::Home,
|
||||
orbclient::K_UP => KeyCode::ArrowUp,
|
||||
orbclient::K_PGUP => KeyCode::PageUp,
|
||||
orbclient::K_LEFT => KeyCode::ArrowLeft,
|
||||
orbclient::K_RIGHT => KeyCode::ArrowRight,
|
||||
orbclient::K_END => KeyCode::End,
|
||||
orbclient::K_DOWN => KeyCode::ArrowDown,
|
||||
orbclient::K_PGDN => KeyCode::PageDown,
|
||||
orbclient::K_DEL => KeyCode::Delete,
|
||||
orbclient::K_F11 => KeyCode::F11,
|
||||
orbclient::K_F12 => KeyCode::F12,
|
||||
orbclient::K_ALT => (KeyCode::AltLeft, Some(NamedKey::Alt)),
|
||||
orbclient::K_ALT_GR => (KeyCode::AltRight, Some(NamedKey::AltGraph)),
|
||||
orbclient::K_BACKSLASH => (KeyCode::Backslash, None),
|
||||
orbclient::K_BKSP => (KeyCode::Backspace, Some(NamedKey::Backspace)),
|
||||
orbclient::K_BRACE_CLOSE => (KeyCode::BracketRight, None),
|
||||
orbclient::K_BRACE_OPEN => (KeyCode::BracketLeft, None),
|
||||
orbclient::K_CAPS => (KeyCode::CapsLock, Some(NamedKey::CapsLock)),
|
||||
orbclient::K_COMMA => (KeyCode::Comma, None),
|
||||
orbclient::K_CTRL => (KeyCode::ControlLeft, Some(NamedKey::Control)),
|
||||
orbclient::K_DEL => (KeyCode::Delete, Some(NamedKey::Delete)),
|
||||
orbclient::K_DOWN => (KeyCode::ArrowDown, Some(NamedKey::ArrowDown)),
|
||||
orbclient::K_END => (KeyCode::End, Some(NamedKey::End)),
|
||||
orbclient::K_ENTER => (KeyCode::Enter, Some(NamedKey::Enter)),
|
||||
orbclient::K_EQUALS => (KeyCode::Equal, None),
|
||||
orbclient::K_ESC => (KeyCode::Escape, Some(NamedKey::Escape)),
|
||||
orbclient::K_F1 => (KeyCode::F1, Some(NamedKey::F1)),
|
||||
orbclient::K_F2 => (KeyCode::F2, Some(NamedKey::F2)),
|
||||
orbclient::K_F3 => (KeyCode::F3, Some(NamedKey::F3)),
|
||||
orbclient::K_F4 => (KeyCode::F4, Some(NamedKey::F4)),
|
||||
orbclient::K_F5 => (KeyCode::F5, Some(NamedKey::F5)),
|
||||
orbclient::K_F6 => (KeyCode::F6, Some(NamedKey::F6)),
|
||||
orbclient::K_F7 => (KeyCode::F7, Some(NamedKey::F7)),
|
||||
orbclient::K_F8 => (KeyCode::F8, Some(NamedKey::F8)),
|
||||
orbclient::K_F9 => (KeyCode::F9, Some(NamedKey::F9)),
|
||||
orbclient::K_F10 => (KeyCode::F10, Some(NamedKey::F10)),
|
||||
orbclient::K_F11 => (KeyCode::F11, Some(NamedKey::F11)),
|
||||
orbclient::K_F12 => (KeyCode::F12, Some(NamedKey::F12)),
|
||||
orbclient::K_HOME => (KeyCode::Home, Some(NamedKey::Home)),
|
||||
orbclient::K_LEFT => (KeyCode::ArrowLeft, Some(NamedKey::ArrowLeft)),
|
||||
orbclient::K_LEFT_SHIFT => (KeyCode::ShiftLeft, Some(NamedKey::Shift)),
|
||||
orbclient::K_MINUS => (KeyCode::Minus, None),
|
||||
orbclient::K_NUM_0 => (KeyCode::Numpad0, None),
|
||||
orbclient::K_NUM_1 => (KeyCode::Numpad1, None),
|
||||
orbclient::K_NUM_2 => (KeyCode::Numpad2, None),
|
||||
orbclient::K_NUM_3 => (KeyCode::Numpad3, None),
|
||||
orbclient::K_NUM_4 => (KeyCode::Numpad4, None),
|
||||
orbclient::K_NUM_5 => (KeyCode::Numpad5, None),
|
||||
orbclient::K_NUM_6 => (KeyCode::Numpad6, None),
|
||||
orbclient::K_NUM_7 => (KeyCode::Numpad7, None),
|
||||
orbclient::K_NUM_8 => (KeyCode::Numpad8, None),
|
||||
orbclient::K_NUM_9 => (KeyCode::Numpad9, None),
|
||||
orbclient::K_PERIOD => (KeyCode::Period, None),
|
||||
orbclient::K_PGDN => (KeyCode::PageDown, Some(NamedKey::PageDown)),
|
||||
orbclient::K_PGUP => (KeyCode::PageUp, Some(NamedKey::PageUp)),
|
||||
orbclient::K_QUOTE => (KeyCode::Quote, None),
|
||||
orbclient::K_RIGHT => (KeyCode::ArrowRight, Some(NamedKey::ArrowRight)),
|
||||
orbclient::K_RIGHT_SHIFT => (KeyCode::ShiftRight, Some(NamedKey::Shift)),
|
||||
orbclient::K_SEMICOLON => (KeyCode::Semicolon, None),
|
||||
orbclient::K_SLASH => (KeyCode::Slash, None),
|
||||
orbclient::K_SPACE => (KeyCode::Space, Some(NamedKey::Space)),
|
||||
orbclient::K_SUPER => (KeyCode::SuperLeft, Some(NamedKey::Super)),
|
||||
orbclient::K_TAB => (KeyCode::Tab, Some(NamedKey::Tab)),
|
||||
orbclient::K_TICK => (KeyCode::Backquote, None),
|
||||
orbclient::K_UP => (KeyCode::ArrowUp, Some(NamedKey::ArrowUp)),
|
||||
orbclient::K_VOLUME_DOWN => (KeyCode::AudioVolumeDown, Some(NamedKey::AudioVolumeDown)),
|
||||
orbclient::K_VOLUME_TOGGLE => (KeyCode::AudioVolumeMute, Some(NamedKey::AudioVolumeMute)),
|
||||
orbclient::K_VOLUME_UP => (KeyCode::AudioVolumeUp, Some(NamedKey::AudioVolumeUp)),
|
||||
|
||||
_ => return PhysicalKey::Unidentified(NativeKeyCode::Unidentified),
|
||||
})
|
||||
_ => return (PhysicalKey::Unidentified(NativeKeyCode::Unidentified), None),
|
||||
};
|
||||
(PhysicalKey::Code(key_code), named_key_opt)
|
||||
}
|
||||
|
||||
fn element_state(pressed: bool) -> event::ElementState {
|
||||
@@ -153,6 +171,22 @@ struct EventState {
|
||||
}
|
||||
|
||||
impl EventState {
|
||||
fn character_all_modifiers(&self, character: char) -> char {
|
||||
// Modify character if Ctrl is pressed
|
||||
#[allow(clippy::collapsible_if)]
|
||||
if self.keyboard.contains(KeyboardModifierState::LCTRL)
|
||||
|| self.keyboard.contains(KeyboardModifierState::RCTRL)
|
||||
{
|
||||
if character.is_ascii_lowercase() {
|
||||
return ((character as u8 - b'a') + 1) as char;
|
||||
}
|
||||
//TODO: more control key variants?
|
||||
}
|
||||
|
||||
// Return character as-is if no special handling required
|
||||
character
|
||||
}
|
||||
|
||||
fn key(&mut self, key: PhysicalKey, pressed: bool) {
|
||||
let code = match key {
|
||||
PhysicalKey::Code(code) => code,
|
||||
@@ -333,39 +367,75 @@ impl<T: 'static> EventLoop<T> {
|
||||
{
|
||||
match event_option {
|
||||
EventOption::Key(KeyEvent {
|
||||
character: _,
|
||||
character,
|
||||
scancode,
|
||||
pressed,
|
||||
}) => {
|
||||
if scancode != 0 {
|
||||
let physical_key = convert_scancode(scancode);
|
||||
let modifiers_before = event_state.keyboard;
|
||||
event_state.key(physical_key, pressed);
|
||||
// Convert scancode
|
||||
let (physical_key, named_key_opt) = convert_scancode(scancode);
|
||||
|
||||
// Get previous modifiers and update modifiers based on physical key
|
||||
let modifiers_before = event_state.keyboard;
|
||||
event_state.key(physical_key, pressed);
|
||||
|
||||
// Default to unidentified key with no text
|
||||
let mut logical_key = Key::Unidentified(NativeKey::Unidentified);
|
||||
let mut key_without_modifiers = logical_key.clone();
|
||||
let mut text = None;
|
||||
let mut text_with_all_modifiers = None;
|
||||
|
||||
// Set key and text based on character
|
||||
if character != '\0' {
|
||||
let mut tmp = [0u8; 4];
|
||||
let character_str = character.encode_utf8(&mut tmp);
|
||||
// The key with Shift and Caps Lock applied (but not Ctrl)
|
||||
logical_key = Key::Character(character_str.into());
|
||||
// The key without Shift or Caps Lock applied
|
||||
key_without_modifiers =
|
||||
Key::Character(SmolStr::from_iter(character.to_lowercase()));
|
||||
if pressed {
|
||||
// The key with Shift and Caps Lock applied (but not Ctrl)
|
||||
text = Some(character_str.into());
|
||||
// The key with Shift, Caps Lock, and Ctrl applied
|
||||
let character_all_modifiers =
|
||||
event_state.character_all_modifiers(character);
|
||||
text_with_all_modifiers =
|
||||
Some(character_all_modifiers.encode_utf8(&mut tmp).into())
|
||||
}
|
||||
};
|
||||
|
||||
// Override key if a named key was found (this is to allow Enter to replace '\n')
|
||||
if let Some(named_key) = named_key_opt {
|
||||
logical_key = Key::Named(named_key);
|
||||
key_without_modifiers = logical_key.clone();
|
||||
}
|
||||
|
||||
event_handler(event::Event::WindowEvent {
|
||||
window_id: RootWindowId(window_id),
|
||||
event: event::WindowEvent::KeyboardInput {
|
||||
device_id: event::DeviceId(DeviceId),
|
||||
event: event::KeyEvent {
|
||||
logical_key,
|
||||
physical_key,
|
||||
location: KeyLocation::Standard,
|
||||
state: element_state(pressed),
|
||||
repeat: false,
|
||||
text,
|
||||
platform_specific: KeyEventExtra {
|
||||
key_without_modifiers,
|
||||
text_with_all_modifiers,
|
||||
},
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
});
|
||||
|
||||
// If the state of the modifiers has changed, send the event.
|
||||
if modifiers_before != event_state.keyboard {
|
||||
event_handler(event::Event::WindowEvent {
|
||||
window_id: RootWindowId(window_id),
|
||||
event: event::WindowEvent::KeyboardInput {
|
||||
device_id: event::DeviceId(DeviceId),
|
||||
event: event::KeyEvent {
|
||||
logical_key: Key::Unidentified(NativeKey::Unidentified),
|
||||
physical_key,
|
||||
location: KeyLocation::Standard,
|
||||
state: element_state(pressed),
|
||||
repeat: false,
|
||||
text: None,
|
||||
|
||||
platform_specific: KeyEventExtra {},
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
});
|
||||
|
||||
// If the state of the modifiers has changed, send the event.
|
||||
if modifiers_before != event_state.keyboard {
|
||||
event_handler(event::Event::WindowEvent {
|
||||
window_id: RootWindowId(window_id),
|
||||
event: event::WindowEvent::ModifiersChanged(event_state.modifiers()),
|
||||
})
|
||||
}
|
||||
event: event::WindowEvent::ModifiersChanged(event_state.modifiers()),
|
||||
})
|
||||
}
|
||||
}
|
||||
EventOption::TextInput(TextInputEvent { character }) => {
|
||||
@@ -387,6 +457,14 @@ impl<T: 'static> EventLoop<T> {
|
||||
},
|
||||
});
|
||||
}
|
||||
EventOption::MouseRelative(MouseRelativeEvent { dx, dy }) => {
|
||||
event_handler(event::Event::DeviceEvent {
|
||||
device_id: event::DeviceId(DeviceId),
|
||||
event: event::DeviceEvent::MouseMotion {
|
||||
delta: (dx as f64, dy as f64),
|
||||
},
|
||||
});
|
||||
}
|
||||
EventOption::Button(ButtonEvent {
|
||||
left,
|
||||
middle,
|
||||
@@ -440,7 +518,7 @@ impl<T: 'static> EventLoop<T> {
|
||||
// Acknowledge resize after event loop.
|
||||
event_state.resize_opt = Some((width, height));
|
||||
}
|
||||
//TODO: Clipboard
|
||||
//TODO: Screen, Clipboard, Drop
|
||||
EventOption::Hover(HoverEvent { entered }) => {
|
||||
if entered {
|
||||
event_handler(event::Event::WindowEvent {
|
||||
|
||||
@@ -4,7 +4,12 @@ use std::fmt::{self, Display, Formatter};
|
||||
use std::str;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use smol_str::SmolStr;
|
||||
|
||||
use crate::{
|
||||
dpi::{PhysicalPosition, PhysicalSize},
|
||||
keyboard::Key,
|
||||
};
|
||||
|
||||
pub use self::event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget};
|
||||
mod event_loop;
|
||||
@@ -259,5 +264,8 @@ impl VideoMode {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct KeyEventExtra {}
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
|
||||
pub struct KeyEventExtra {
|
||||
pub key_without_modifiers: Key,
|
||||
pub text_with_all_modifiers: Option<SmolStr>,
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ use crate::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
EventLoopWindowTarget, MonitorHandle, PlatformSpecificWindowBuilderAttributes, RedoxSocket,
|
||||
TimeSocket, WindowId, WindowProperties,
|
||||
EventLoopWindowTarget, MonitorHandle, OsError, PlatformSpecificWindowBuilderAttributes,
|
||||
RedoxSocket, TimeSocket, WindowId, WindowProperties,
|
||||
};
|
||||
|
||||
// These values match the values uses in the `window_new` function in orbital:
|
||||
@@ -21,7 +21,9 @@ use super::{
|
||||
const ORBITAL_FLAG_ASYNC: char = 'a';
|
||||
const ORBITAL_FLAG_BACK: char = 'b';
|
||||
const ORBITAL_FLAG_FRONT: char = 'f';
|
||||
const ORBITAL_FLAG_HIDDEN: char = 'h';
|
||||
const ORBITAL_FLAG_BORDERLESS: char = 'l';
|
||||
const ORBITAL_FLAG_MAXIMIZED: char = 'm';
|
||||
const ORBITAL_FLAG_RESIZABLE: char = 'r';
|
||||
const ORBITAL_FLAG_TRANSPARENT: char = 't';
|
||||
|
||||
@@ -58,11 +60,15 @@ impl Window {
|
||||
// Async by default.
|
||||
let mut flag_str = ORBITAL_FLAG_ASYNC.to_string();
|
||||
|
||||
if attrs.maximized {
|
||||
flag_str.push(ORBITAL_FLAG_MAXIMIZED);
|
||||
}
|
||||
|
||||
if attrs.resizable {
|
||||
flag_str.push(ORBITAL_FLAG_RESIZABLE);
|
||||
}
|
||||
|
||||
//TODO: maximized, fullscreen, visible
|
||||
//TODO: fullscreen
|
||||
|
||||
if attrs.transparent {
|
||||
flag_str.push(ORBITAL_FLAG_TRANSPARENT);
|
||||
@@ -72,6 +78,10 @@ impl Window {
|
||||
flag_str.push(ORBITAL_FLAG_BORDERLESS);
|
||||
}
|
||||
|
||||
if !attrs.visible {
|
||||
flag_str.push(ORBITAL_FLAG_HIDDEN);
|
||||
}
|
||||
|
||||
match attrs.window_level {
|
||||
window::WindowLevel::AlwaysOnBottom => {
|
||||
flag_str.push(ORBITAL_FLAG_BACK);
|
||||
@@ -130,6 +140,23 @@ impl Window {
|
||||
f(self)
|
||||
}
|
||||
|
||||
fn get_flag(&self, flag: char) -> Result<bool, error::ExternalError> {
|
||||
let mut buf: [u8; 4096] = [0; 4096];
|
||||
let path = self
|
||||
.window_socket
|
||||
.fpath(&mut buf)
|
||||
.map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?;
|
||||
let properties = WindowProperties::new(path);
|
||||
Ok(properties.flags.contains(flag))
|
||||
}
|
||||
|
||||
fn set_flag(&self, flag: char, value: bool) -> Result<(), error::ExternalError> {
|
||||
self.window_socket
|
||||
.write(format!("F,{flag},{}", if value { 1 } else { 0 }).as_bytes())
|
||||
.map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn id(&self) -> WindowId {
|
||||
WindowId {
|
||||
@@ -255,17 +282,21 @@ impl Window {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_transparent(&self, _transparent: bool) {}
|
||||
pub fn set_transparent(&self, transparent: bool) {
|
||||
let _ = self.set_flag(ORBITAL_FLAG_TRANSPARENT, transparent);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_blur(&self, _blur: bool) {}
|
||||
|
||||
#[inline]
|
||||
pub fn set_visible(&self, _visibility: bool) {}
|
||||
pub fn set_visible(&self, visible: bool) {
|
||||
let _ = self.set_flag(ORBITAL_FLAG_HIDDEN, !visible);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_visible(&self) -> Option<bool> {
|
||||
None
|
||||
Some(!self.get_flag(ORBITAL_FLAG_HIDDEN).unwrap_or(false))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -277,17 +308,13 @@ impl Window {
|
||||
pub fn set_resize_increments(&self, _increments: Option<Size>) {}
|
||||
|
||||
#[inline]
|
||||
pub fn set_resizable(&self, _resizeable: bool) {}
|
||||
pub fn set_resizable(&self, resizeable: bool) {
|
||||
let _ = self.set_flag(ORBITAL_FLAG_RESIZABLE, resizeable);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_resizable(&self) -> bool {
|
||||
let mut buf: [u8; 4096] = [0; 4096];
|
||||
let path = self
|
||||
.window_socket
|
||||
.fpath(&mut buf)
|
||||
.expect("failed to read properties");
|
||||
let properties = WindowProperties::new(path);
|
||||
properties.flags.contains(ORBITAL_FLAG_RESIZABLE)
|
||||
self.get_flag(ORBITAL_FLAG_RESIZABLE).unwrap_or(false)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -299,11 +326,13 @@ impl Window {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_maximized(&self, _maximized: bool) {}
|
||||
pub fn set_maximized(&self, maximized: bool) {
|
||||
let _ = self.set_flag(ORBITAL_FLAG_MAXIMIZED, maximized);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_maximized(&self) -> bool {
|
||||
false
|
||||
self.get_flag(ORBITAL_FLAG_MAXIMIZED).unwrap_or(false)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -315,21 +344,30 @@ impl Window {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_decorations(&self, _decorations: bool) {}
|
||||
|
||||
#[inline]
|
||||
pub fn is_decorated(&self) -> bool {
|
||||
let mut buf: [u8; 4096] = [0; 4096];
|
||||
let path = self
|
||||
.window_socket
|
||||
.fpath(&mut buf)
|
||||
.expect("failed to read properties");
|
||||
let properties = WindowProperties::new(path);
|
||||
!properties.flags.contains(ORBITAL_FLAG_BORDERLESS)
|
||||
pub fn set_decorations(&self, decorations: bool) {
|
||||
let _ = self.set_flag(ORBITAL_FLAG_BORDERLESS, !decorations);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_window_level(&self, _level: window::WindowLevel) {}
|
||||
pub fn is_decorated(&self) -> bool {
|
||||
!self.get_flag(ORBITAL_FLAG_BORDERLESS).unwrap_or(false)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_window_level(&self, level: window::WindowLevel) {
|
||||
match level {
|
||||
window::WindowLevel::AlwaysOnBottom => {
|
||||
let _ = self.set_flag(ORBITAL_FLAG_BACK, true);
|
||||
}
|
||||
window::WindowLevel::Normal => {
|
||||
let _ = self.set_flag(ORBITAL_FLAG_BACK, false);
|
||||
let _ = self.set_flag(ORBITAL_FLAG_FRONT, false);
|
||||
}
|
||||
window::WindowLevel::AlwaysOnTop => {
|
||||
let _ = self.set_flag(ORBITAL_FLAG_FRONT, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_window_icon(&self, _window_icon: Option<crate::icon::Icon>) {}
|
||||
@@ -360,30 +398,58 @@ impl Window {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_grab(&self, _: window::CursorGrabMode) -> Result<(), error::ExternalError> {
|
||||
Err(error::ExternalError::NotSupported(
|
||||
error::NotSupportedError::new(),
|
||||
))
|
||||
pub fn set_cursor_grab(
|
||||
&self,
|
||||
mode: window::CursorGrabMode,
|
||||
) -> Result<(), error::ExternalError> {
|
||||
let (grab, relative) = match mode {
|
||||
window::CursorGrabMode::None => (false, false),
|
||||
window::CursorGrabMode::Confined => (true, false),
|
||||
window::CursorGrabMode::Locked => (true, true),
|
||||
};
|
||||
self.window_socket
|
||||
.write(format!("M,G,{}", if grab { 1 } else { 0 }).as_bytes())
|
||||
.map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?;
|
||||
self.window_socket
|
||||
.write(format!("M,R,{}", if relative { 1 } else { 0 }).as_bytes())
|
||||
.map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_visible(&self, _: bool) {}
|
||||
pub fn set_cursor_visible(&self, visible: bool) {
|
||||
let _ = self
|
||||
.window_socket
|
||||
.write(format!("M,C,{}", if visible { 1 } else { 0 }).as_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn drag_window(&self) -> Result<(), error::ExternalError> {
|
||||
Err(error::ExternalError::NotSupported(
|
||||
error::NotSupportedError::new(),
|
||||
))
|
||||
self.window_socket
|
||||
.write(b"D")
|
||||
.map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn drag_resize_window(
|
||||
&self,
|
||||
_direction: window::ResizeDirection,
|
||||
direction: window::ResizeDirection,
|
||||
) -> Result<(), error::ExternalError> {
|
||||
Err(error::ExternalError::NotSupported(
|
||||
error::NotSupportedError::new(),
|
||||
))
|
||||
let arg = match direction {
|
||||
window::ResizeDirection::East => "R",
|
||||
window::ResizeDirection::North => "T",
|
||||
window::ResizeDirection::NorthEast => "T,R",
|
||||
window::ResizeDirection::NorthWest => "T,L",
|
||||
window::ResizeDirection::South => "B",
|
||||
window::ResizeDirection::SouthEast => "B,R",
|
||||
window::ResizeDirection::SouthWest => "B,L",
|
||||
window::ResizeDirection::West => "L",
|
||||
};
|
||||
self.window_socket
|
||||
.write(format!("D,{}", arg).as_bytes())
|
||||
.map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -14,7 +14,6 @@ use crate::window::WindowId;
|
||||
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
clone::Clone,
|
||||
collections::{HashSet, VecDeque},
|
||||
iter,
|
||||
ops::Deref,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::clone::Clone;
|
||||
use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque};
|
||||
use std::iter;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
// incoming events (from the registered handlers) and ensuring they are passed to the user in a
|
||||
// compliant way.
|
||||
|
||||
// TODO: FP, remove when <https://github.com/rust-lang/rust/issues/121621> is fixed.
|
||||
#![allow(unknown_lints, non_local_definitions)]
|
||||
|
||||
mod r#async;
|
||||
mod device;
|
||||
mod error;
|
||||
|
||||
@@ -4,7 +4,6 @@ use crate::keyboard::{Key, KeyLocation, ModifiersState, NamedKey, PhysicalKey};
|
||||
|
||||
use once_cell::unsync::OnceCell;
|
||||
use smol_str::SmolStr;
|
||||
use std::convert::TryInto;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
use wasm_bindgen::{JsCast, JsValue};
|
||||
use web_sys::{KeyboardEvent, MouseEvent, PointerEvent, WheelEvent};
|
||||
@@ -257,7 +256,7 @@ pub fn pointer_move_event(event: PointerEvent) -> impl Iterator<Item = PointerEv
|
||||
// See <https://github.com/rust-windowing/winit/issues/2875>.
|
||||
pub fn has_pointer_raw_support(window: &web_sys::Window) -> bool {
|
||||
thread_local! {
|
||||
static POINTER_RAW_SUPPORT: OnceCell<bool> = OnceCell::new();
|
||||
static POINTER_RAW_SUPPORT: OnceCell<bool> = const { OnceCell::new() };
|
||||
}
|
||||
|
||||
POINTER_RAW_SUPPORT.with(|support| {
|
||||
@@ -280,7 +279,7 @@ pub fn has_pointer_raw_support(window: &web_sys::Window) -> bool {
|
||||
// See <https://bugs.webkit.org/show_bug.cgi?id=210454>.
|
||||
pub fn has_coalesced_events_support(event: &PointerEvent) -> bool {
|
||||
thread_local! {
|
||||
static COALESCED_EVENTS_SUPPORT: OnceCell<bool> = OnceCell::new();
|
||||
static COALESCED_EVENTS_SUPPORT: OnceCell<bool> = const { OnceCell::new() };
|
||||
}
|
||||
|
||||
COALESCED_EVENTS_SUPPORT.with(|support| {
|
||||
|
||||
@@ -11,7 +11,7 @@ use web_sys::{Document, Element, HtmlCanvasElement};
|
||||
use super::EventListenerHandle;
|
||||
|
||||
thread_local! {
|
||||
static FULLSCREEN_API_SUPPORT: OnceCell<bool> = OnceCell::new();
|
||||
static FULLSCREEN_API_SUPPORT: OnceCell<bool> = const { OnceCell::new() };
|
||||
}
|
||||
|
||||
pub struct FullscreenHandler {
|
||||
|
||||
@@ -126,7 +126,7 @@ impl ResizeScaleInternal {
|
||||
(-webkit-device-pixel-ratio: {current_scale})",
|
||||
);
|
||||
let mql = MediaQueryListHandle::new(window, &media_query, closure);
|
||||
assert!(
|
||||
debug_assert!(
|
||||
mql.mql().matches(),
|
||||
"created media query doesn't match, {current_scale} != {}",
|
||||
super::scale_factor(window)
|
||||
|
||||
@@ -199,7 +199,7 @@ fn duration_millis_ceil(duration: Duration) -> u32 {
|
||||
|
||||
fn has_scheduler_support(window: &web_sys::Window) -> bool {
|
||||
thread_local! {
|
||||
static SCHEDULER_SUPPORT: OnceCell<bool> = OnceCell::new();
|
||||
static SCHEDULER_SUPPORT: OnceCell<bool> = const { OnceCell::new() };
|
||||
}
|
||||
|
||||
SCHEDULER_SUPPORT.with(|support| {
|
||||
@@ -221,7 +221,7 @@ fn has_scheduler_support(window: &web_sys::Window) -> bool {
|
||||
|
||||
fn has_idle_callback_support(window: &web_sys::Window) -> bool {
|
||||
thread_local! {
|
||||
static IDLE_CALLBACK_SUPPORT: OnceCell<bool> = OnceCell::new();
|
||||
static IDLE_CALLBACK_SUPPORT: OnceCell<bool> = const { OnceCell::new() };
|
||||
}
|
||||
|
||||
IDLE_CALLBACK_SUPPORT.with(|support| {
|
||||
|
||||
@@ -696,14 +696,13 @@ impl<T: 'static> Clone for EventLoopProxy<T> {
|
||||
|
||||
impl<T: 'static> EventLoopProxy<T> {
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
unsafe {
|
||||
if PostMessageW(self.target_window, USER_EVENT_MSG_ID.get(), 0, 0) != false.into() {
|
||||
self.event_send.send(event).ok();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(EventLoopClosed(event))
|
||||
}
|
||||
}
|
||||
self.event_send
|
||||
.send(event)
|
||||
.map(|result| {
|
||||
unsafe { PostMessageW(self.target_window, USER_EVENT_MSG_ID.get(), 0, 0) };
|
||||
result
|
||||
})
|
||||
.map_err(|e| EventLoopClosed(e.0))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -403,23 +403,29 @@ impl<T> BufferedEvent<T> {
|
||||
match self {
|
||||
Self::Event(event) => dispatch(event),
|
||||
Self::ScaleFactorChanged(window_id, scale_factor, new_inner_size) => {
|
||||
let new_inner_size = Arc::new(Mutex::new(new_inner_size));
|
||||
let user_new_innner_size = Arc::new(Mutex::new(new_inner_size));
|
||||
dispatch(Event::WindowEvent {
|
||||
window_id,
|
||||
event: WindowEvent::ScaleFactorChanged {
|
||||
scale_factor,
|
||||
inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&new_inner_size)),
|
||||
inner_size_writer: InnerSizeWriter::new(Arc::downgrade(
|
||||
&user_new_innner_size,
|
||||
)),
|
||||
},
|
||||
});
|
||||
let inner_size = *new_inner_size.lock().unwrap();
|
||||
drop(new_inner_size);
|
||||
let inner_size = *user_new_innner_size.lock().unwrap();
|
||||
|
||||
let window_flags = unsafe {
|
||||
let userdata =
|
||||
get_window_long(window_id.0.into(), GWL_USERDATA) as *mut WindowData<T>;
|
||||
(*userdata).window_state_lock().window_flags
|
||||
};
|
||||
window_flags.set_size((window_id.0).0, inner_size);
|
||||
drop(user_new_innner_size);
|
||||
|
||||
if inner_size != new_inner_size {
|
||||
let window_flags = unsafe {
|
||||
let userdata =
|
||||
get_window_long(window_id.0.into(), GWL_USERDATA) as *mut WindowData<T>;
|
||||
(*userdata).window_state_lock().window_flags
|
||||
};
|
||||
|
||||
window_flags.set_size((window_id.0).0, inner_size);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,12 +52,6 @@ impl Default for PlatformSpecificWindowBuilderAttributes {
|
||||
unsafe impl Send for PlatformSpecificWindowBuilderAttributes {}
|
||||
unsafe impl Sync for PlatformSpecificWindowBuilderAttributes {}
|
||||
|
||||
// Cursor name in UTF-16. Used to set cursor in `WM_SETCURSOR`.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Cursor(pub *const u16);
|
||||
unsafe impl Send for Cursor {}
|
||||
unsafe impl Sync for Cursor {}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId(u32);
|
||||
|
||||
|
||||
@@ -1210,28 +1210,17 @@ impl<'a, T: 'static> InitData<'a, T> {
|
||||
|
||||
win.set_enabled_buttons(attributes.enabled_buttons);
|
||||
|
||||
if attributes.fullscreen.0.is_some() {
|
||||
win.set_fullscreen(attributes.fullscreen.0.map(Into::into));
|
||||
unsafe { force_window_active(win.window) };
|
||||
} else {
|
||||
let size = attributes
|
||||
.inner_size
|
||||
.unwrap_or_else(|| PhysicalSize::new(800, 600).into());
|
||||
let max_size = attributes
|
||||
.max_inner_size
|
||||
.unwrap_or_else(|| PhysicalSize::new(f64::MAX, f64::MAX).into());
|
||||
let min_size = attributes
|
||||
.min_inner_size
|
||||
.unwrap_or_else(|| PhysicalSize::new(0, 0).into());
|
||||
let clamped_size = Size::clamp(size, min_size, max_size, win.scale_factor());
|
||||
win.request_inner_size(clamped_size);
|
||||
|
||||
if attributes.maximized {
|
||||
// Need to set MAXIMIZED after setting `inner_size` as
|
||||
// `Window::request_inner_size` changes MAXIMIZED to false.
|
||||
win.set_maximized(true);
|
||||
}
|
||||
}
|
||||
let size = attributes
|
||||
.inner_size
|
||||
.unwrap_or_else(|| PhysicalSize::new(800, 600).into());
|
||||
let max_size = attributes
|
||||
.max_inner_size
|
||||
.unwrap_or_else(|| PhysicalSize::new(f64::MAX, f64::MAX).into());
|
||||
let min_size = attributes
|
||||
.min_inner_size
|
||||
.unwrap_or_else(|| PhysicalSize::new(0, 0).into());
|
||||
let clamped_size = Size::clamp(size, min_size, max_size, win.scale_factor());
|
||||
win.request_inner_size(clamped_size);
|
||||
|
||||
// let margins = MARGINS {
|
||||
// cxLeftWidth: 1,
|
||||
@@ -1312,6 +1301,9 @@ where
|
||||
#[cfg(not(feature = "rwh_06"))]
|
||||
let parent = fallback_parent();
|
||||
|
||||
let fullscreen = attributes.fullscreen.clone();
|
||||
let maximized = attributes.maximized;
|
||||
|
||||
let mut initdata = InitData {
|
||||
event_loop,
|
||||
attributes,
|
||||
@@ -1349,7 +1341,18 @@ where
|
||||
|
||||
// If the handle is non-null, then window creation must have succeeded, which means
|
||||
// that we *must* have populated the `InitData.window` field.
|
||||
Ok(initdata.window.unwrap())
|
||||
let win = initdata.window.unwrap();
|
||||
|
||||
// Need to set FULLSCREEN or MAXIMIZED after CreateWindowEx
|
||||
// This is because if the size is changed in WM_CREATE, the restored size will be stored in that size.
|
||||
if fullscreen.0.is_some() {
|
||||
win.set_fullscreen(fullscreen.0.map(Into::into));
|
||||
unsafe { force_window_active(win.window) };
|
||||
} else if maximized {
|
||||
win.set_maximized(true);
|
||||
}
|
||||
|
||||
Ok(win)
|
||||
}
|
||||
|
||||
unsafe fn register_window_class<T: 'static>(class_name: &[u16]) {
|
||||
|
||||
@@ -907,7 +907,7 @@ impl Window {
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Web / iOS / Android / Orbital:** Unsupported.
|
||||
/// - **Web / iOS / Android:** Unsupported.
|
||||
/// - **X11:** Can only be set while building the window, with [`WindowBuilder::with_transparent`].
|
||||
#[inline]
|
||||
pub fn set_transparent(&self, transparent: bool) {
|
||||
@@ -1040,7 +1040,7 @@ impl Window {
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **iOS / Android / Web / Orbital:** Unsupported.
|
||||
/// - **iOS / Android / Web:** Unsupported.
|
||||
#[inline]
|
||||
pub fn set_maximized(&self, maximized: bool) {
|
||||
self.window
|
||||
@@ -1051,7 +1051,7 @@ impl Window {
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **iOS / Android / Web / Orbital:** Unsupported.
|
||||
/// - **iOS / Android / Web:** Unsupported.
|
||||
#[inline]
|
||||
pub fn is_maximized(&self) -> bool {
|
||||
self.window.maybe_wait_on_main(|w| w.is_maximized())
|
||||
@@ -1363,7 +1363,8 @@ impl Window {
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **iOS / Android / Web / Wayland / Orbital:** Always returns an [`ExternalError::NotSupported`].
|
||||
/// - **Wayland**: Cursor must be in [`CursorGrabMode::Locked`].
|
||||
/// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`].
|
||||
#[inline]
|
||||
pub fn set_cursor_position<P: Into<Position>>(&self, position: P) -> Result<(), ExternalError> {
|
||||
let position = position.into();
|
||||
@@ -1371,7 +1372,7 @@ impl Window {
|
||||
.maybe_wait_on_main(|w| w.set_cursor_position(position))
|
||||
}
|
||||
|
||||
/// Set grabbing [mode]([`CursorGrabMode`]) on the cursor preventing it from leaving the window.
|
||||
/// Set grabbing [mode](CursorGrabMode) on the cursor preventing it from leaving the window.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
@@ -1402,7 +1403,7 @@ impl Window {
|
||||
/// - **Wayland:** The cursor is only hidden within the confines of the window.
|
||||
/// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
|
||||
/// outside of the window.
|
||||
/// - **iOS / Android / Orbital:** Unsupported.
|
||||
/// - **iOS / Android:** Unsupported.
|
||||
#[inline]
|
||||
pub fn set_cursor_visible(&self, visible: bool) {
|
||||
self.window
|
||||
@@ -1419,7 +1420,7 @@ impl Window {
|
||||
/// - **X11:** Un-grabs the cursor.
|
||||
/// - **Wayland:** Requires the cursor to be inside the window to be dragged.
|
||||
/// - **macOS:** May prevent the button release event to be triggered.
|
||||
/// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`].
|
||||
/// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`].
|
||||
#[inline]
|
||||
pub fn drag_window(&self) -> Result<(), ExternalError> {
|
||||
self.window.maybe_wait_on_main(|w| w.drag_window())
|
||||
@@ -1433,7 +1434,7 @@ impl Window {
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **macOS:** Always returns an [`ExternalError::NotSupported`]
|
||||
/// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`].
|
||||
/// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`].
|
||||
#[inline]
|
||||
pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> {
|
||||
self.window
|
||||
@@ -1587,7 +1588,7 @@ pub enum CursorGrabMode {
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **macOS:** Not implemented. Always returns [`ExternalError::NotSupported`] for now.
|
||||
/// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`].
|
||||
/// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`].
|
||||
Confined,
|
||||
|
||||
/// The cursor is locked inside the window area to the certain position.
|
||||
@@ -1598,7 +1599,7 @@ pub enum CursorGrabMode {
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **X11 / Windows:** Not implemented. Always returns [`ExternalError::NotSupported`] for now.
|
||||
/// - **iOS / Android / Orbital:** Always returns an [`ExternalError::NotSupported`].
|
||||
/// - **iOS / Android:** Always returns an [`ExternalError::NotSupported`].
|
||||
Locked,
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user