Compare commits

..

11 Commits

Author SHA1 Message Date
John Nunley
0871c849ef chore: Add words from markdown files
Signed-off-by: John Nunley <dev@notgull.net>
2024-03-02 22:30:34 -08:00
John Nunley
204dd734dd chore: Fix remaining typos in Rust file
Signed-off-by: John Nunley <dev@notgull.net>
2024-03-02 22:27:45 -08:00
John Nunley
4dc8878511 ci: Add spellcheck to CI
winit is a large codebase and manually checking for typos is infeasible.
This commit adds a spellcheck hook using cspell to the CI. That way we
can be sure that there are no typos in our code before we commit.

Signed-off-by: John Nunley <dev@notgull.net>
2024-03-02 09:40:20 -08:00
John Nunley
47e7d8b7fa chore: Use cspell to fix some typos
Signed-off-by: John Nunley <dev@notgull.net>
2024-03-02 09:38:54 -08:00
daxpedda
388c40b1e0 Bump version on master
This commit does not represent a release and only synchronizes CHANGELOG
from the latest release.
2024-03-02 13:22:36 +01:00
daxpedda
7a40aa43dc Web: fix crash with ControlFlow::Wait|WaitUntil 2024-03-02 12:26:26 +01:00
John Nunley
944347696a Replace log with tracing
Tracing is a modern replacement for the log crate that allows for
annotating log messages with the function that they come from.

Signed-off-by: John Nunley <dev@notgull.net>
Closes: #3482
2024-03-01 20:45:31 +04:00
Kirill Chibisov
96172693fe Bump version on master
This commit does not represent a release and only synchronizes CHANGELOG
from the latest release.
2024-03-01 15:21:06 +04:00
Mads Marquart
32004405ee Add documentation example of ignoring key repeats (#3538) 2024-03-01 11:27:47 +01:00
Kirill Chibisov
22e932b5ab On X11, fix use after free during xinput2 processing
Fixes #3536.
2024-03-01 13:40:20 +04:00
John Nunley
3d4c53459a On X11, filter out tiny device mouse events
Usually, if mouse events are equal to (0, 0) we filter them out.
However, if the event is very close to zero it will still be given to
the user. In some cases this can be caused by bad float math on the X11
server side.

Fix it by filtering absolute values smaller than floating point epsilon.

Signed-off-by: John Nunley <dev@notgull.net>
Closes: #3500
2024-03-01 13:11:28 +04:00
84 changed files with 1823 additions and 725 deletions

13
.cspell.json Normal file
View File

@@ -0,0 +1,13 @@
{
"$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json",
"version": "0.2",
"dictionaryDefinitions": [
{
"name": "project-words",
"path": "./project-words.txt",
"addWords": true
}
],
"dictionaries": ["project-words"],
"ignorePaths": ["/target", "/project-words.txt"]
}

View File

@@ -7,7 +7,7 @@ on:
jobs: jobs:
fmt: fmt:
name: Check formatting name: Tidy Code
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
@@ -16,10 +16,13 @@ jobs:
components: rustfmt components: rustfmt
- name: Check Formatting - name: Check Formatting
run: cargo fmt -- --check run: cargo fmt -- --check
- name: Check Spelling
run: npx -y cspell --no-progress --no-summary '**/*.rs' '**/*.md'
tests: tests:
name: Test ${{ matrix.toolchain }} ${{ matrix.platform.name }} name: Test ${{ matrix.toolchain }} ${{ matrix.platform.name }}
runs-on: ${{ matrix.platform.os }} runs-on: ${{ matrix.platform.os }}
needs: fmt
strategy: strategy:
fail-fast: false fail-fast: false

View File

@@ -46,6 +46,16 @@ Unreleased` header.
- **Breaking:** Changed the signature of `EventLoop::with_user_event` to return a builder. - **Breaking:** Changed the signature of `EventLoop::with_user_event` to return a builder.
- **Breaking:** Removed `EventLoopBuilder::with_user_event`, the functionality is now available in `EventLoop::with_user_event`. - **Breaking:** Removed `EventLoopBuilder::with_user_event`, the functionality is now available in `EventLoop::with_user_event`.
- Add `Window::default_attributes` to get default `WindowAttributes`. - Add `Window::default_attributes` to get default `WindowAttributes`.
- `log` has been replaced with `tracing`. The old behavior can be emulated by setting the `log` feature on the `tracing` crate.
# 0.29.13
- On Web, fix possible crash with `ControlFlow::Wait` and `ControlFlow::WaitUntil`.
# 0.29.12
- On X11, fix use after free during xinput2 handling.
- On X11, filter close to zero values in mouse device events
# 0.29.11 # 0.29.11

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "winit" name = "winit"
version = "0.29.11" version = "0.29.13"
authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"] authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"]
description = "Cross-platform window creation library." description = "Cross-platform window creation library."
keywords = ["windowing"] keywords = ["windowing"]
@@ -64,17 +64,18 @@ cfg_aliases = "0.2.0"
[dependencies] [dependencies]
bitflags = "2" bitflags = "2"
cursor-icon = "1.1.0" cursor-icon = "1.1.0"
log = "0.4"
rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true } rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true }
rwh_05 = { package = "raw-window-handle", version = "0.5.2", features = ["std"], optional = true } rwh_05 = { package = "raw-window-handle", version = "0.5.2", features = ["std"], optional = true }
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"], optional = true } rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"], optional = true }
serde = { workspace = true, optional = true } serde = { workspace = true, optional = true }
smol_str = "0.2.0" smol_str = "0.2.0"
dpi = { path = "dpi" } dpi = { path = "dpi" }
tracing = { version = "0.1.40", default_features = false }
[dev-dependencies] [dev-dependencies]
image = { version = "0.24.0", default-features = false, features = ["png"] } image = { version = "0.24.0", default-features = false, features = ["png"] }
simple_logger = { version = "4.2.0", default_features = false } tracing = { version = "0.1.40", default_features = false, features = ["log"] }
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
winit = { path = ".", features = ["rwh_05"] } winit = { path = ".", features = ["rwh_05"] }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies] [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies]
@@ -257,7 +258,7 @@ web-sys = { version = "0.3.22", features = ['CanvasRenderingContext2d'] }
[[example]] [[example]]
doc-scrape-examples = true doc-scrape-examples = true
name = "full" name = "window"
[workspace] [workspace]
resolver = "2" resolver = "2"

View File

@@ -8,7 +8,7 @@
```toml ```toml
[dependencies] [dependencies]
winit = "0.29.11" winit = "0.29.13"
``` ```
## [Documentation](https://docs.rs/winit) ## [Documentation](https://docs.rs/winit)

View File

@@ -6,7 +6,6 @@ use std::time;
#[cfg(web_platform)] #[cfg(web_platform)]
use web_time as time; use web_time as time;
use simple_logger::SimpleLogger;
use winit::{ use winit::{
event::{ElementState, Event, KeyEvent, WindowEvent}, event::{ElementState, Event, KeyEvent, WindowEvent},
event_loop::{ControlFlow, EventLoop}, event_loop::{ControlFlow, EventLoop},
@@ -28,7 +27,7 @@ const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100); const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
fn main() -> Result<(), impl std::error::Error> { fn main() -> Result<(), impl std::error::Error> {
SimpleLogger::new().init().unwrap(); tracing_subscriber::fmt::init();
println!("Press '1' to switch to Wait mode."); println!("Press '1' to switch to Wait mode.");
println!("Press '2' to switch to WaitUntil mode."); println!("Press '2' to switch to WaitUntil mode.");

View File

@@ -1,62 +0,0 @@
use std::error::Error;
use winit::{
event::{Event, StartCause},
event_loop::{ActiveEventLoop, EventLoop},
};
fn main() -> Result<(), Box<dyn Error>> {
let event_loop = EventLoop::new()?;
Ok(event_loop.run(|event, event_loop| match event {
Event::NewEvents(StartCause::Init) => {
dump_monitors(event_loop);
event_loop.exit()
}
_ => {}
})?)
}
fn dump_monitors(event_loop: &ActiveEventLoop) {
println!("Monitors information");
let primary_monitor = event_loop.primary_monitor();
for monitor in event_loop.available_monitors() {
let intro = if primary_monitor.as_ref() == Some(&monitor) {
"Primary monitor"
} else {
"Monitor"
};
if let Some(name) = monitor.name() {
println!("{intro}: {name}");
} else {
println!("{intro}: [no name]");
}
let size = monitor.size();
print!(" Current mode: {}x{}", size.width, size.height);
if let Some(m_hz) = monitor.refresh_rate_millihertz() {
println!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
} else {
println!();
}
let position = monitor.position();
println!(" Position: {}, {}", position.x, position.y);
println!(" Scale factor: {}", monitor.scale_factor());
println!(" Available modes (width x height x bit-depth):");
for mode in monitor.video_modes() {
let size = mode.size();
let m_hz = mode.refresh_rate_millihertz();
println!(
" {:04}x{:04}x{:02} @ {:>3}.{} Hz",
size.width,
size.height,
mode.bit_depth(),
m_hz / 1000,
m_hz % 1000
);
}
}
}

View File

@@ -11,7 +11,6 @@
fn main() -> std::process::ExitCode { fn main() -> std::process::ExitCode {
use std::{process::ExitCode, thread::sleep, time::Duration}; use std::{process::ExitCode, thread::sleep, time::Duration};
use simple_logger::SimpleLogger;
use winit::{ use winit::{
event::{Event, WindowEvent}, event::{Event, WindowEvent},
event_loop::EventLoop, event_loop::EventLoop,
@@ -24,7 +23,7 @@ fn main() -> std::process::ExitCode {
let mut event_loop = EventLoop::new().unwrap(); let mut event_loop = EventLoop::new().unwrap();
SimpleLogger::new().init().unwrap(); tracing_subscriber::fmt::init();
let mut window = None; let mut window = None;

View File

@@ -5,8 +5,6 @@
fn main() -> Result<(), impl std::error::Error> { fn main() -> Result<(), impl std::error::Error> {
use std::time::Duration; use std::time::Duration;
use simple_logger::SimpleLogger;
use winit::{ use winit::{
error::EventLoopError, error::EventLoopError,
event::{Event, WindowEvent}, event::{Event, WindowEvent},
@@ -24,7 +22,7 @@ fn main() -> Result<(), impl std::error::Error> {
window: Option<Window>, window: Option<Window>,
} }
SimpleLogger::new().init().unwrap(); tracing_subscriber::fmt::init();
let mut event_loop = EventLoop::new().unwrap(); let mut event_loop = EventLoop::new().unwrap();
fn run_app(event_loop: &mut EventLoop<()>, idx: usize) -> Result<(), EventLoopError> { fn run_app(event_loop: &mut EventLoop<()>, idx: usize) -> Result<(), EventLoopError> {

File diff suppressed because it is too large Load Diff

View File

@@ -3,8 +3,6 @@ use std::error::Error;
#[cfg(x11_platform)] #[cfg(x11_platform)]
fn main() -> Result<(), Box<dyn Error>> { fn main() -> Result<(), Box<dyn Error>> {
use simple_logger::SimpleLogger;
use winit::{ use winit::{
event::{Event, WindowEvent}, event::{Event, WindowEvent},
event_loop::EventLoop, event_loop::EventLoop,
@@ -21,7 +19,7 @@ fn main() -> Result<(), Box<dyn Error>> {
.ok_or("Expected a 32-bit X11 window ID as the first argument.")? .ok_or("Expected a 32-bit X11 window ID as the first argument.")?
.parse::<u32>()?; .parse::<u32>()?;
SimpleLogger::new().init().unwrap(); tracing_subscriber::fmt::init();
let event_loop = EventLoop::new()?; let event_loop = EventLoop::new()?;
let mut window = None; let mut window = None;

707
project-words.txt Normal file
View File

@@ -0,0 +1,707 @@
ABNT
ACCEPTFILES
ALTERASE
APPCOMMAND
APPSTARTING
APPWINDOW
ASYNCWINDOWPOS
ATOK
AZERTY
Abortable
Artur
Autorotate
BACKTAB
BADFLAGS
BADMODE
BADPARAM
BASSBOOST
BITSPERPEL
BKSP
BLURBEHIND
BOTTOMLEFT
BOTTOMRIGHT
BRIGHTNESSDOW
BRIGHTNESSU
BYCOMMAND
Backquote
Bangou
Blackbox
CAEAGL
CANDIDATEFORM
CAPTURECHANGED
CFUUID
CLIPSIBLINGS
CLOEXEC
CLOSECD
CODEOWNERS
COLORSYNC
COMPATTR
COMPOSITIONFORM
COMPSTR
CREATESTRUCTW
CRSEL
CRTC
CTYPE
CURSORPOS
CUSEL
CXVIRTUALSCREEN
CYCLEWINDOWS
CYVIRTUALSCREEN
Calculater
Codeinput
Colormap
Compiz
Condvar
Crtc
DEADCHAR
DEFAULTSIZE
DEFAULTTONEAREST
DEFAULTTONULL
DEFAULTTOPRIMARY
DELETEFILE
DEVICEINFO
DEVICELALTKEYMASK
DEVICELCMDKEYMASK
DEVICELCTLKEYMASK
DEVICELSHIFTKEYMASK
DEVICENAME
DEVICERALTKEYMASK
DEVICERCMDKEYMASK
DEVICERCTLKEYMASK
DEVICERSHIFTKEYMASK
DEVMODEW
DEVNOTIFY
DISP
DISPLAYFREQUENCY
DPAD
DPICHANGED
DROPEFFECT
DVASPECT
DWMCOMPOSITIONCHANGED
DWMWA
Deque
Dflt
EINTR
EINVAL
EJECTCD
EJECTCLOSECD
ENDCALL
ENDCOMPOSITION
ENLW
ENTERSIZEMOVE
ERCIM
EREOF
EWMH
EXITSIZEMOVE
EXSEL
EXSTYLE
EXTENDEDKEY
Eisu
Eisuu
Endcall
Endianness
FASTFORWARD
FLASHW
FLASHWINFO
FORMATETC
FORWARDMAIL
FRAMECHANGED
FVWM
GAMEPAD
GETHIGHCONTRAST
GETMINMAXINFO
GIDC
GLES
GWLP
HANGEUL
HANJA
HCURSOR
HDROP
HEADSETHOOK
HGLOBAL
HICON
HIGHCONTRASTA
HIGHCONTRASTON
HIMC
HINSTANCE
HMODULE
HORZ
HRAWINPUT
HTBOTTOM
HTBOTTOMLEFT
HTBOTTOMRIGHT
HTCAPTION
HTCLIENT
HTLEFT
HTRIGHT
HTTOP
HTTOPLEFT
HTTOPRIGHT
HWHEEL
Hanja
Hankaku
Headsethook
Henkan
Himetric
Hotspot
IACE
IBEAM
ICCCM
ICONINFO
IMEs
IMMENABLED
INPUTSINK
INTERNALPAINT
IOYUV
Impls
Ivars
JISHO
JUNJA
Junja
KBDILLUMDOWN
KBDILLUMTOGGLE
KBDILLUMUP
KEYDOWN
KEYFIRST
KEYLAST
KEYMAP
KEYUP
KILLFOCUS
KPJPCOMMA
KPLEFTPAREN
KPPLUSMINUS
KPRIGHTPAREN
Kanna
Keymap
Koho
LALT
LBUTTON
LBUTTONDOWN
LBUTTONUP
LCONTROL
LCTRL
LEFTALIGN
LOADFROMFILE
LOGPIXELSX
LOYA
LRESULT
LSHIFT
LSUPER
LWIN
Lcdfilter
Libera
MASSHOU
MAXIMIZABLE
MAXIMIZEBOX
MBUTTON
MBUTTONDOWN
MBUTTONUP
MENUCHAR
MICMUTE
MINIMIZABLE
MINIMIZEBOX
MINMAXINFO
MODECHANGE
MONITORINFO
MONITORINFOEXW
MOUSEHWHEEL
MOUSELEAVE
MOUSEMOVE
MOUSEWHEEL
MOVERESIZE
MSDOS
MSRV
Massyo
Miniaturizable
Mmap
Modifiermap
Muhenkan
Multitouch
NCACTIVATE
NCCALCSIZE
NCDESTROY
NCHITTEST
NCLBUTTONDOWN
NEXTTRACK
NOACTIVATE
NOMOVE
NONAME
NONCONVERT
NOREMOVE
NOREPOSITION
NOSIZE
NOTCONVERTED
NOTOPMOST
NOZORDER
NTSTATUS
NUMLOCK
Nesw
Nonnull
Nunley
OSVERSIONINFOW
OVERLAPPEDWINDOW
Overscan
PAUSECD
PCSTR
PCWSTR
PELSHEIGHT
PELSWIDTH
PGDN
PGUP
PINP
PLAYCD
POINTERDOWN
POINTERUP
POINTERUPDATE
POINTL
PQRS
PREVIOUSTRACK
PROCESSKEY
Pboard
Peekable
Pels
Pictsymbols
Pixmap
Premultiply
QERTZ
QWERTZ
RALT
RAWINPUT
RAWINPUTDEVICE
RAWINPUTDEVICELIST
RAWINPUTHEADER
RAWKEYBOARD
RBUTTON
RBUTTONDOWN
RBUTTONUP
RCONTROL
RCTRL
RDWR
RESULTSTR
RETURNCMD
RFKILL
RGBA
RIDEV
RIDI
RMENU
ROYA
RRRRRGGGGGBBBBB
RRRRRRRRGGGGGGGGBBBBBBBB
RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB
RSHIFT
RSUPER
RUSTDOCFLAGS
RWIN
Raii
Reentrancy
Reparent
Romaji
SCREENSAVE
SCROLLDOWN
SCROLLUP
SENDFILE
SETCONTEXT
SETCURSOR
SETFOCUS
SETICON
SETTINGCHANGE
SHOULDAPPSUSEDARKMODE
SHOWNOACTIVATE
SHOWUICOMPOSITIONWINDOW
SIGILL
SIGSEGV
SIZEALL
SIZEBOX
SIZENESW
SIZENS
SIZENWSE
SIZEWE
STARTCOMPOSITION
STATDATA
STGMEDIUM
SWITCHVIDEOMODE
SYSCHAR
SYSCOMMAND
SYSDEADCHAR
SYSKEYDOWN
SYSKEYUP
SYSMENU
Smol
Sonoma
Subcompositor
Sublayer
Subviews
Sysrq
THUMBSTICK
TIMERNOFG
TOOLWINDOW
TOPLEFT
TOPRIGHT
TOUCHEVENTF
TOUCHINPUT
TOUROKU
TRACKMOUSEEVENT
TYMED
TYPEHID
TYPEKEYBOARD
TYPEMOUSE
Thumbl
Thumbr
Tomiĉo
UNICHAR
USEDARKMODECOLORS
UXTHEME
Unadjust
Unadvise
Ungrab
Unminimizing
VKEY
VKEYS
Viewporter
Visualid
Vulkan
WINDOWCOMPOSITIONATTRIB
WINDOWCOMPOSITIONATTRIBDATA
WINDOWEDGE
WINDOWPLACEMENT
WINDOWPOS
WINDOWPOSCHANGED
WINDOWPOSCHANGING
WLAN
WNDPROC
WSCTRL
WXYZ
XBUTTONDOWN
XBUTTONUP
XEMBED
XFER
XKBCH
XKBH
XKBXH
XMODIFIERS
XSETTINGS
XVIRTUALSCREEN
Xcursor
Xdnd
Xfer
Xids
Xorg
Xutf
YVIRTUALSCREEN
Zenkaku
aarch
abortable
adwaita
ahash
altgr
apartmentthreaded
argb
armv
atleast
attribs
autoreleasepool
autoreleases
autorotate
beachball
beforeunload
behaviour
bfcache
bgra
bindgen
bitflags
bitmaprenderer
blackbox
blurregion
borderless
busybutclickable
bytemuck
bytewise
calloop
callstack
cdylib
cgfloat
clicky
clipchildren
clonable
clsctx
clsid
codepaths
coinit
colormap
contextmenu
crossfont
crtc
crtcs
curr
darkmode
dbus
deminiaturize
deviceid
dlopen
docsrs
donotround
doubletap
downscaling
dppx
dwmsbt
dwmwcp
elwt
emscripten
endianness
entrancy
entrantly
evdev
eventloop
evlp
evtype
exclam
excludefromcapture
fcitx
forcetouch
fpath
fract
fsecs
fullscreen
fullscreened
fullsize
gamepads
getpid
gettid
glutin
gotchyas
hdrop
henkan
hidpi
himc
himetric
hinstance
hittest
hiword
hmenu
hmonitor
horz
hotplug
hotspot
hotx
hredraw
hresult
htotal
hwnd
ibus
icrate
impls
initer
inputmethod
isize
ivars
kcav
kchibisov
keybdinput
keybinds
keyevent
keyeventf
keymap
keypermod
keypresses
keysym
keysyms
kunddaliya
kwin
lcddefault
lgid
libc
libwayland
libxkbcommon
lindex
lmenu
longjmp
longsolidusoverlay
lowline
loword
lparam
lpfn
lpsz
lshift
macbooks
madsmtm
mainloop
maintainership
mainwindow
mapvk
memmap
millihertz
minwindef
mkdid
mkwid
modifierless
modifiermap
msiglreith
muhenkan
multitouch
nanos
nccreate
netwm
newtype
nodename
nonminimal
noredirectionbitmap
notgull
notitle
nsec
nsscreen
nsstring
nsview
ntdll
numpad
numpads
objc
offcenter
onpointerrawupdate
opengl
oppsite
orbclient
ossi
overscan
overtyping
pagehide
pageshow
physicalkey
pixmap
pointercancel
pointermove
pointerout
pointerover
pointerrawupdate
polonius
ppmm
preedit
premultiply
primarylangid
pthread
qhandle
randr
reallocs
rects
reentrancy
reparent
reparenting
replugs
repr
resizeable
retval
rgba
rgrc
rightclick
riid
roundsmall
rshift
runloop
rustc
rustdoc
rustix
scancode
scancodes
sctk
serde
setjmp
setlocale
shcore
smithay
smol
softbuffer
sourceid
splitn
standardised
stdweb
struct
structfield
subcompositor
subframework
subsec
subviews
syms
syscall
systembackdrop
sythesize
sythesized
sythetic
tabbedwindow
tabindex
throghout
timespec
titlebar
touchpad
touchstart
trackpad
transientwindow
tymed
uapi
uiscreen
uiscreens
ulong
unaccel
unaccelerated
uncoalesced
unconfine
undropped
unfocusing
ungrab
ungrabs
uninit
uninitialize
unmark
unmaximized
unminimize
unobserve
unparameterised
unref
unresizable
usedefault
userdata
uxtheme
viewporter
visibilitychange
visualid
visualtype
vkey
vredraw
vsync
vtbl
vtotal
vulkano
wakeup
wakeups
wantpalm
wgpu
winapi
windef
winit
winuser
wndclassexw
wparam
wrongcompobj
xbutton
xconn
xconnection
xcursor
xdisplay
xevent
xext
xfiltered
xfixes
xhot
ximage
xkbcommon
xkbext
xlib
xmodifiers
xmonad
xpresent
xrandr
xrender
xresources
xscrnsaver
xsettings
xwindow
yeong
yhot

View File

@@ -88,6 +88,15 @@ impl CustomCursor {
hotspot_x: u16, hotspot_x: u16,
hotspot_y: u16, hotspot_y: u16,
) -> Result<CustomCursorSource, BadImage> { ) -> Result<CustomCursorSource, BadImage> {
let _span = tracing::debug_span!(
"winit::Cursor::from_rgba",
width,
height,
hotspot_x,
hotspot_y
)
.entered();
Ok(CustomCursorSource { Ok(CustomCursorSource {
inner: PlatformCustomCursorSource::from_rgba( inner: PlatformCustomCursorSource::from_rgba(
rgba.into(), rgba.into(),

View File

@@ -561,7 +561,7 @@ pub enum WindowEvent {
/// The window has been occluded (completely hidden from view). /// The window has been occluded (completely hidden from view).
/// ///
/// This is different to window visibility as it depends on whether the window is closed, /// This is different to window visibility as it depends on whether the window is closed,
/// minimised, set invisible, or fully occluded by another window. /// minimized, set invisible, or fully occluded by another window.
/// ///
/// ## Platform-specific /// ## Platform-specific
/// ///
@@ -781,6 +781,31 @@ pub struct KeyEvent {
/// On some systems, holding down a key for some period of time causes that key to be repeated /// On some systems, holding down a key for some period of time causes that key to be repeated
/// as though it were being pressed and released repeatedly. This field is `true` if and only if /// as though it were being pressed and released repeatedly. This field is `true` if and only if
/// this event is the result of one of those repeats. /// this event is the result of one of those repeats.
///
/// # Example
///
/// In games, you often want to ignore repeated key events - this can be
/// done by ignoring events where this property is set.
///
/// ```
/// use winit::event::{WindowEvent, KeyEvent, ElementState};
/// use winit::keyboard::{KeyCode, PhysicalKey};
/// # let window_event = WindowEvent::RedrawRequested; // To make the example compile
/// match window_event {
/// WindowEvent::KeyboardInput {
/// event: KeyEvent {
/// physical_key: PhysicalKey::Code(KeyCode::KeyW),
/// state: ElementState::Pressed,
/// repeat: false,
/// ..
/// },
/// ..
/// } => {
/// // The physical key `W` was pressed, and it was not a repeat
/// }
/// _ => {} // Handle other events
/// }
/// ```
pub repeat: bool, pub repeat: bool,
/// Platform-specific key event information. /// Platform-specific key event information.

View File

@@ -80,7 +80,7 @@ impl<T> EventLoopBuilder<T> {
/// ***For cross-platform compatibility, the [`EventLoop`] must be created on the main thread, /// ***For cross-platform compatibility, the [`EventLoop`] must be created on the main thread,
/// and only once per application.*** /// and only once per application.***
/// ///
/// Calling this function will result in display backend initialisation. /// Calling this function will result in display backend initialization.
/// ///
/// ## Panics /// ## Panics
/// ///
@@ -109,6 +109,8 @@ impl<T> EventLoopBuilder<T> {
)] )]
#[inline] #[inline]
pub fn build(&mut self) -> Result<EventLoop<T>, EventLoopError> { pub fn build(&mut self) -> Result<EventLoop<T>, EventLoopError> {
let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered();
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) { if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
return Err(EventLoopError::RecreationAttempt); return Err(EventLoopError::RecreationAttempt);
} }
@@ -248,6 +250,8 @@ impl<T> EventLoop<T> {
where where
F: FnMut(Event<T>, &ActiveEventLoop), F: FnMut(Event<T>, &ActiveEventLoop),
{ {
let _span = tracing::debug_span!("winit::EventLoop::run").entered();
self.event_loop.run(event_handler) self.event_loop.run(event_handler)
} }
@@ -274,6 +278,12 @@ impl<T> EventLoop<T> {
/// ///
/// [`DeviceEvent`]: crate::event::DeviceEvent /// [`DeviceEvent`]: crate::event::DeviceEvent
pub fn listen_device_events(&self, allowed: DeviceEvents) { pub fn listen_device_events(&self, allowed: DeviceEvents) {
let _span = tracing::debug_span!(
"winit::EventLoop::listen_device_events",
allowed = ?allowed
)
.entered();
self.event_loop self.event_loop
.window_target() .window_target()
.p .p
@@ -295,6 +305,12 @@ impl<T> EventLoop<T> {
#[deprecated = "use `ActiveEventLoop::create_window` instead"] #[deprecated = "use `ActiveEventLoop::create_window` instead"]
#[inline] #[inline]
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> { pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
let _span = tracing::debug_span!(
"winit::EventLoop::create_window",
window_attributes = ?window_attributes
)
.entered();
let window = let window =
platform_impl::Window::new(&self.event_loop.window_target().p, window_attributes)?; platform_impl::Window::new(&self.event_loop.window_target().p, window_attributes)?;
Ok(Window { window }) Ok(Window { window })
@@ -363,18 +379,28 @@ impl ActiveEventLoop {
/// see the web platform module for more information. /// see the web platform module for more information.
#[inline] #[inline]
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> { pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
let _span = tracing::debug_span!(
"winit::ActiveEventLoop::create_window",
window_attributes = ?window_attributes
)
.entered();
let window = platform_impl::Window::new(&self.p, window_attributes)?; let window = platform_impl::Window::new(&self.p, window_attributes)?;
Ok(Window { window }) Ok(Window { window })
} }
/// Create custom cursor. /// Create custom cursor.
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor { pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
let _span = tracing::debug_span!("winit::ActiveEventLoop::create_custom_cursor",).entered();
self.p.create_custom_cursor(custom_cursor) self.p.create_custom_cursor(custom_cursor)
} }
/// Returns the list of all the monitors available on the system. /// Returns the list of all the monitors available on the system.
#[inline] #[inline]
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> { pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
let _span = tracing::debug_span!("winit::ActiveEventLoop::available_monitors",).entered();
#[allow(clippy::useless_conversion)] // false positive on some platforms #[allow(clippy::useless_conversion)] // false positive on some platforms
self.p self.p
.available_monitors() .available_monitors()
@@ -391,6 +417,8 @@ impl ActiveEventLoop {
/// **Wayland / Web:** Always returns `None`. /// **Wayland / Web:** Always returns `None`.
#[inline] #[inline]
pub fn primary_monitor(&self) -> Option<MonitorHandle> { pub fn primary_monitor(&self) -> Option<MonitorHandle> {
let _span = tracing::debug_span!("winit::ActiveEventLoop::primary_monitor",).entered();
self.p self.p
.primary_monitor() .primary_monitor()
.map(|inner| MonitorHandle { inner }) .map(|inner| MonitorHandle { inner })
@@ -408,6 +436,12 @@ impl ActiveEventLoop {
/// ///
/// [`DeviceEvent`]: crate::event::DeviceEvent /// [`DeviceEvent`]: crate::event::DeviceEvent
pub fn listen_device_events(&self, allowed: DeviceEvents) { pub fn listen_device_events(&self, allowed: DeviceEvents) {
let _span = tracing::debug_span!(
"winit::ActiveEventLoop::listen_device_events",
allowed = ?allowed
)
.entered();
self.p.listen_device_events(allowed); self.p.listen_device_events(allowed);
} }
@@ -425,6 +459,8 @@ impl ActiveEventLoop {
/// ///
/// See [`LoopExiting`](Event::LoopExiting). /// See [`LoopExiting`](Event::LoopExiting).
pub fn exit(&self) { pub fn exit(&self) {
let _span = tracing::debug_span!("winit::ActiveEventLoop::exit",).entered();
self.p.exit() self.p.exit()
} }
@@ -530,6 +566,8 @@ impl<T: 'static> EventLoopProxy<T> {
/// ///
/// [`UserEvent(event)`]: Event::UserEvent /// [`UserEvent(event)`]: Event::UserEvent
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
let _span = tracing::debug_span!("winit::EventLoopProxy::send_event",).entered();
self.event_loop_proxy.send_event(event) self.event_loop_proxy.send_event(event)
} }
} }

View File

@@ -118,6 +118,8 @@ impl Icon {
/// The length of `rgba` must be divisible by 4, and `width * height` must equal /// The length of `rgba` must be divisible by 4, and `width * height` must equal
/// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error. /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> { pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
let _span = tracing::debug_span!("winit::Icon::from_rgba", width, height).entered();
Ok(Icon { Ok(Icon {
inner: PlatformIcon::from_rgba(rgba, width, height)?, inner: PlatformIcon::from_rgba(rgba, width, height)?,
}) })

View File

@@ -1229,7 +1229,7 @@ pub enum NamedKey {
Dimmer, Dimmer,
/// Swap video sources. (`VK_DISPLAY_SWAP`) /// Swap video sources. (`VK_DISPLAY_SWAP`)
DisplaySwap, DisplaySwap,
/// Select Digital Video Rrecorder. (`KEYCODE_DVR`) /// Select Digital Video Recorder. (`KEYCODE_DVR`)
DVR, DVR,
/// Exit the current application. (`VK_EXIT`) /// Exit the current application. (`VK_EXIT`)
Exit, Exit,

View File

@@ -45,13 +45,13 @@
//! | Base Class | Feature Flag | Notes | //! | Base Class | Feature Flag | Notes |
//! | :--------------: | :---------------: | :-----: | //! | :--------------: | :---------------: | :-----: |
//! | `NativeActivity` | `android-native-activity` | Built-in to Android - it is possible to use without compiling any Java or Kotlin code. Java or Kotlin code may be needed to subclass `NativeActivity` to access some platform features. It does not derive from the [`AndroidAppCompat`] base class.| //! | `NativeActivity` | `android-native-activity` | Built-in to Android - it is possible to use without compiling any Java or Kotlin code. Java or Kotlin code may be needed to subclass `NativeActivity` to access some platform features. It does not derive from the [`AndroidAppCompat`] base class.|
//! | [`GameActivity`] | `android-game-activity` | Derives from [`AndroidAppCompat`], a defacto standard `Activity` base class that helps support a wider range of Android versions. Requires a build system that can compile Java or Kotlin and fetch Android dependencies from a [Maven repository][agdk_jetpack] (or link with an embedded [release][agdk_releases] of [`GameActivity`]) | //! | [`GameActivity`] | `android-game-activity` | Derives from [`AndroidAppCompat`], a defacto standard `Activity` base class that helps support a wider range of Android versions. Requires a build system that can compile Java or Kotlin and fetch Android dependencies from a [Maven repository][android_jet] (or link with an embedded [release][android_releases] of [`GameActivity`]) |
//! //!
//! [`GameActivity`]: https://developer.android.com/games/agdk/game-activity //! [`GameActivity`]: https://developer.android.com/games/agdk/game-activity
//! [`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input //! [`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input
//! [`AndroidAppCompat`]: https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity //! [`AndroidAppCompat`]: https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity
//! [agdk_jetpack]: https://developer.android.com/jetpack/androidx/releases/games //! [android_jet]: https://developer.android.com/jetpack/androidx/releases/games
//! [agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries //! [android_releases]: https://developer.android.com/games/agdk/download#agdk-libraries
//! [Gradle]: https://developer.android.com/studio/build //! [Gradle]: https://developer.android.com/studio/build
//! //!
//! For more details, refer to these `android-activity` [example applications](https://github.com/rust-mobile/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).
@@ -60,7 +60,7 @@
//! //!
//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building with `cargo apk`, then the minimal changes would be: //! 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` //! 1. Remove `ndk-glue` from your `Cargo.toml`
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.11", features = [ "android-native-activity" ] }` //! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.13", 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). //! 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). //! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).

View File

@@ -94,7 +94,7 @@ impl ActiveEventLoop {
/// ///
/// let mut event_loop = EventLoop::new().unwrap(); /// let mut event_loop = EventLoop::new().unwrap();
/// event_loop.run_on_demand(|_, _| { /// event_loop.run_on_demand(|_, _| {
/// // Attempt to run the event loop re-entrantly; this must fail. /// // Attempt to run the event loop in a re-entrant manner; this must fail.
/// event_loop.run_on_demand(|_, _| {}); /// event_loop.run_on_demand(|_, _| {});
/// }); /// });
/// ``` /// ```

View File

@@ -29,11 +29,11 @@ pub trait PhysicalKeyExtScancode {
impl PhysicalKeyExtScancode for PhysicalKey { impl PhysicalKeyExtScancode for PhysicalKey {
fn to_scancode(self) -> Option<u32> { fn to_scancode(self) -> Option<u32> {
crate::platform_impl::physicalkey_to_scancode(self) crate::platform_impl::physical_key_to_scancode(self)
} }
fn from_scancode(scancode: u32) -> PhysicalKey { fn from_scancode(scancode: u32) -> PhysicalKey {
crate::platform_impl::scancode_to_physicalkey(scancode) crate::platform_impl::scancode_to_physical_key(scancode)
} }
} }

View File

@@ -2,7 +2,7 @@
//! //!
//! The [`ActivationToken`] is essential to ensure that your newly //! The [`ActivationToken`] is essential to ensure that your newly
//! created window will obtain the focus, otherwise the user could //! created window will obtain the focus, otherwise the user could
//! be requered to click on the window. //! be required to click on the window.
//! //!
//! Such token is usually delivered via the environment variable and //! Such token is usually delivered via the environment variable and
//! could be read from it with the [`EventLoopExtStartupNotify::read_token_from_env`]. //! could be read from it with the [`EventLoopExtStartupNotify::read_token_from_env`].

View File

@@ -330,7 +330,7 @@ impl fmt::Display for BadAnimation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Self::Empty => write!(f, "No cursors supplied"), Self::Empty => write!(f, "No cursors supplied"),
Self::Animation => write!(f, "A supplied cursor is an animtion"), Self::Animation => write!(f, "A supplied cursor is an animation"),
} }
} }
} }

View File

@@ -157,11 +157,11 @@ pub trait EventLoopBuilderExtWindows {
/// #[cfg(target_os = "windows")] /// #[cfg(target_os = "windows")]
/// builder.with_msg_hook(|msg|{ /// builder.with_msg_hook(|msg|{
/// let msg = msg as *const MSG; /// let msg = msg as *const MSG;
/// # let accels: Vec<ACCEL> = Vec::new(); /// # let accelerators: Vec<ACCEL> = Vec::new();
/// let translated = unsafe { /// let translated = unsafe {
/// TranslateAcceleratorW( /// TranslateAcceleratorW(
/// (*msg).hwnd, /// (*msg).hwnd,
/// CreateAcceleratorTableW(accels.as_ptr() as _, 1), /// CreateAcceleratorTableW(accelerators.as_ptr() as _, 1),
/// msg, /// msg,
/// ) == 1 /// ) == 1
/// }; /// };

View File

@@ -16,14 +16,14 @@ use crate::dpi::Size;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum WindowType { pub enum WindowType {
/// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the
/// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxy-ing
/// root window clicks. /// root window clicks.
Desktop, Desktop,
/// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows. /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows.
Dock, Dock,
/// Toolbar windows. "Torn off" from the main application. /// Toolbar windows. "Torn off" from the main application.
Toolbar, Toolbar,
/// Pinnable menu windows. "Torn off" from the main application. /// Pin-able menu windows. "Torn off" from the main application.
Menu, Menu,
/// A small persistent utility window, such as a palette or toolbox. /// A small persistent utility window, such as a palette or toolbox.
Utility, Utility,

View File

@@ -174,7 +174,7 @@ pub fn character_map_and_combine_key(
let key_map = match app.device_key_character_map(device_id) { let key_map = match app.device_key_character_map(device_id) {
Ok(key_map) => key_map, Ok(key_map) => key_map,
Err(err) => { Err(err) => {
log::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}"); tracing::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
return None; return None;
} }
}; };
@@ -188,7 +188,7 @@ pub fn character_map_and_combine_key(
Ok(Some(key)) => Some(key), Ok(Some(key)) => Some(key),
Ok(None) => None, Ok(None) => None,
Err(err) => { Err(err) => {
log::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}"); tracing::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
None None
} }
} }
@@ -213,7 +213,7 @@ pub fn character_map_and_combine_key(
None None
} }
Err(err) => { Err(err) => {
log::warn!("KeyEvent: Failed to get key map character: {err:?}"); tracing::warn!("KeyEvent: Failed to get key map character: {err:?}");
*combining_accent = None; *combining_accent = None;
None None
} }

View File

@@ -16,7 +16,7 @@ use android_activity::input::{InputEvent, KeyAction, Keycode, MotionAction};
use android_activity::{ use android_activity::{
AndroidApp, AndroidAppWaker, ConfigurationRef, InputStatus, MainEvent, Rect, AndroidApp, AndroidAppWaker, ConfigurationRef, InputStatus, MainEvent, Rect,
}; };
use log::{debug, trace, warn}; use tracing::{debug, trace, warn};
use crate::{ use crate::{
cursor::Cursor, cursor::Cursor,
@@ -330,7 +330,7 @@ impl<T: 'static> EventLoop<T> {
} }
}, },
Err(err) => { Err(err) => {
log::warn!("Failed to get input events iterator: {err:?}"); tracing::warn!("Failed to get input events iterator: {err:?}");
} }
} }
@@ -1014,7 +1014,7 @@ impl Window {
if let Some(native_window) = self.app.native_window().as_ref() { if let Some(native_window) = self.app.native_window().as_ref() {
native_window.raw_window_handle() native_window.raw_window_handle()
} else { } else {
log::error!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events."); tracing::error!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events.");
Err(rwh_06::HandleError::Unavailable) Err(rwh_06::HandleError::Unavailable)
} }
} }

View File

@@ -622,9 +622,9 @@ pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
match wrapper { match wrapper {
EventWrapper::StaticEvent(event) => { EventWrapper::StaticEvent(event) => {
if !processing_redraws && event.is_redraw() { if !processing_redraws && event.is_redraw() {
log::info!("processing `RedrawRequested` during the main event loop"); tracing::info!("processing `RedrawRequested` during the main event loop");
} else if processing_redraws && !event.is_redraw() { } else if processing_redraws && !event.is_redraw() {
log::warn!( tracing::warn!(
"processing non `RedrawRequested` event after the main event loop: {:#?}", "processing non `RedrawRequested` event after the main event loop: {:#?}",
event event
); );
@@ -676,9 +676,9 @@ pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
match wrapper { match wrapper {
EventWrapper::StaticEvent(event) => { EventWrapper::StaticEvent(event) => {
if !processing_redraws && event.is_redraw() { if !processing_redraws && event.is_redraw() {
log::info!("processing `RedrawRequested` during the main event loop"); tracing::info!("processing `RedrawRequested` during the main event loop");
} else if processing_redraws && !event.is_redraw() { } else if processing_redraws && !event.is_redraw() {
log::warn!( tracing::warn!(
"processing non-`RedrawRequested` event after the main event loop: {:#?}", "processing non-`RedrawRequested` event after the main event loop: {:#?}",
event event
); );
@@ -911,7 +911,7 @@ macro_rules! os_capabilities {
impl OSCapabilities {$( impl OSCapabilities {$(
$(#[$attr])* $(#[$attr])*
pub fn $error_name(&self, extra_msg: &str) { pub fn $error_name(&self, extra_msg: &str) {
log::warn!( tracing::warn!(
concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"), concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"),
$major, $minor, self.os_version.majorVersion, self.os_version.minorVersion, self.os_version.patchVersion, $major, $minor, self.os_version.majorVersion, self.os_version.minorVersion, self.os_version.patchVersion,
extra_msg extra_msg

View File

@@ -85,7 +85,7 @@ impl ActiveEventLoop {
pub(crate) fn exit(&self) { pub(crate) fn exit(&self) {
// https://developer.apple.com/library/archive/qa/qa1561/_index.html // https://developer.apple.com/library/archive/qa/qa1561/_index.html
// it is not possible to quit an iOS app gracefully and programmatically // it is not possible to quit an iOS app gracefully and programmatically
log::warn!("`ControlFlow::Exit` ignored on iOS"); tracing::warn!("`ControlFlow::Exit` ignored on iOS");
} }
pub(crate) fn exiting(&self) -> bool { pub(crate) fn exiting(&self) -> bool {

View File

@@ -3,10 +3,10 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use icrate::Foundation::{CGFloat, CGPoint, CGRect, CGSize, MainThreadBound, MainThreadMarker}; use icrate::Foundation::{CGFloat, CGPoint, CGRect, CGSize, MainThreadBound, MainThreadMarker};
use log::{debug, warn};
use objc2::rc::Id; use objc2::rc::Id;
use objc2::runtime::{AnyObject, NSObject}; use objc2::runtime::{AnyObject, NSObject};
use objc2::{class, declare_class, msg_send, msg_send_id, mutability, ClassType, DeclaredClass}; use objc2::{class, declare_class, msg_send, msg_send_id, mutability, ClassType, DeclaredClass};
use tracing::{debug, warn};
use super::app_state::EventWrapper; use super::app_state::EventWrapper;
use super::uikit::{ use super::uikit::{

View File

@@ -24,13 +24,13 @@ use crate::platform_impl::common::xkb::{XkbContext, XKBH};
/// ///
/// X11-style keycodes are offset by 8 from the keycodes the Linux kernel uses. /// X11-style keycodes are offset by 8 from the keycodes the Linux kernel uses.
pub fn raw_keycode_to_physicalkey(keycode: u32) -> PhysicalKey { pub fn raw_keycode_to_physicalkey(keycode: u32) -> PhysicalKey {
scancode_to_physicalkey(keycode.saturating_sub(8)) scancode_to_physical_key(keycode.saturating_sub(8))
} }
/// Map the linux scancode to Keycode. /// Map the linux scancode to Keycode.
/// ///
/// Both X11 and Wayland use keys with `+ 8` offset to linux scancode. /// Both X11 and Wayland use keys with `+ 8` offset to linux scancode.
pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { pub fn scancode_to_physical_key(scancode: u32) -> PhysicalKey {
// The keycode values are taken from linux/include/uapi/linux/input-event-codes.h, as // The keycode values are taken from linux/include/uapi/linux/input-event-codes.h, as
// libxkbcommon's documentation seems to suggest that the keycode values we're interested in // libxkbcommon's documentation seems to suggest that the keycode values we're interested in
// are defined by the Linux kernel. If Winit programs end up being run on other Unix-likes, // are defined by the Linux kernel. If Winit programs end up being run on other Unix-likes,
@@ -287,7 +287,7 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
}) })
} }
pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> { pub fn physical_key_to_scancode(key: PhysicalKey) -> Option<u32> {
let code = match key { let code = match key {
PhysicalKey::Code(code) => code, PhysicalKey::Code(code) => code,
PhysicalKey::Unidentified(code) => { PhysicalKey::Unidentified(code) => {

View File

@@ -4,10 +4,10 @@ use std::ptr::{self, NonNull};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use crate::utils::Lazy; use crate::utils::Lazy;
use log::warn;
use smol_str::SmolStr; use smol_str::SmolStr;
#[cfg(wayland_platform)] #[cfg(wayland_platform)]
use std::os::unix::io::OwnedFd; use std::os::unix::io::OwnedFd;
use tracing::warn;
use xkbcommon_dl::{ use xkbcommon_dl::{
self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle, self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle,
xkbcommon_handle, XkbCommon, XkbCommonCompose, xkbcommon_handle, XkbCommon, XkbCommonCompose,
@@ -29,7 +29,7 @@ use keymap::XkbKeymap;
#[cfg(x11_platform)] #[cfg(x11_platform)]
pub use keymap::raw_keycode_to_physicalkey; pub use keymap::raw_keycode_to_physicalkey;
pub use keymap::{physicalkey_to_scancode, scancode_to_physicalkey}; pub use keymap::{physical_key_to_scancode, scancode_to_physical_key};
pub use state::XkbState; pub use state::XkbState;
// TODO: Wire this up without using a static `AtomicBool`. // TODO: Wire this up without using a static `AtomicBool`.
@@ -451,7 +451,7 @@ fn byte_slice_to_smol_str(bytes: &[u8]) -> Option<SmolStr> {
std::str::from_utf8(bytes) std::str::from_utf8(bytes)
.map(SmolStr::new) .map(SmolStr::new)
.map_err(|e| { .map_err(|e| {
log::warn!( tracing::warn!(
"UTF-8 received from libxkbcommon ({:?}) was invalid: {e}", "UTF-8 received from libxkbcommon ({:?}) was invalid: {e}",
bytes bytes
) )

View File

@@ -34,7 +34,7 @@ use crate::{
}, },
}; };
pub(crate) use self::common::xkb::{physicalkey_to_scancode, scancode_to_physicalkey}; pub(crate) use self::common::xkb::{physical_key_to_scancode, scancode_to_physical_key};
pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource; pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource;
pub(crate) use crate::icon::RgbaIcon as PlatformIcon; pub(crate) use crate::icon::RgbaIcon as PlatformIcon;
pub(crate) use crate::platform_impl::Fullscreen; pub(crate) use crate::platform_impl::Fullscreen;
@@ -687,7 +687,7 @@ unsafe extern "C" fn x_error_callback(
// Don't log error. // Don't log error.
if !error_handled { if !error_handled {
log::error!("X11 error: {:#?}", error); tracing::error!("X11 error: {:#?}", error);
// XXX only update the error, if it wasn't handled by any of the hooks. // XXX only update the error, if it wasn't handled by any of the hooks.
*xconn.latest_error.lock().unwrap() = Some(error); *xconn.latest_error.lock().unwrap() = Some(error);
} }

View File

@@ -584,7 +584,7 @@ impl<T: 'static> EventLoop<T> {
}; };
self.event_loop.dispatch(timeout, state).map_err(|error| { self.event_loop.dispatch(timeout, state).map_err(|error| {
log::error!("Error dispatching event loop: {}", error); tracing::error!("Error dispatching event loop: {}", error);
error.into() error.into()
}) })
} }

View File

@@ -5,7 +5,7 @@ use std::time::Duration;
use calloop::timer::{TimeoutAction, Timer}; use calloop::timer::{TimeoutAction, Timer};
use calloop::{LoopHandle, RegistrationToken}; use calloop::{LoopHandle, RegistrationToken};
use log::warn; use tracing::warn;
use sctk::reexports::client::protocol::wl_keyboard::WlKeyboard; use sctk::reexports::client::protocol::wl_keyboard::WlKeyboard;
use sctk::reexports::client::protocol::wl_keyboard::{ use sctk::reexports::client::protocol::wl_keyboard::{
@@ -94,7 +94,7 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
WlKeyboardEvent::Leave { surface, .. } => { WlKeyboardEvent::Leave { surface, .. } => {
let window_id = wayland::make_wid(&surface); let window_id = wayland::make_wid(&surface);
// NOTE: we should drop the repeat regardless whethere it was for the present // NOTE: we should drop the repeat regardless whether it was for the present
// window of for the window which just went gone. // window of for the window which just went gone.
let keyboard_state = seat_state.keyboard_state.as_mut().unwrap(); let keyboard_state = seat_state.keyboard_state.as_mut().unwrap();
keyboard_state.current_repeat = None; keyboard_state.current_repeat = None;

View File

@@ -207,7 +207,7 @@ impl PointerHandler for WinitState {
pointer_data.phase = phase; pointer_data.phase = phase;
// Mice events have both pixel and discrete delta's at the same time. So prefer // Mice events have both pixel and discrete delta's at the same time. So prefer
// the descrite values if they are present. // the discrete values if they are present.
let delta = if has_discrete_scroll { let delta = if has_discrete_scroll {
// XXX Wayland sign convention is the inverse of winit. // XXX Wayland sign convention is the inverse of winit.
MouseScrollDelta::LineDelta( MouseScrollDelta::LineDelta(

View File

@@ -133,7 +133,7 @@ impl WinitState {
) { ) {
Ok(c) => Some(c), Ok(c) => Some(c),
Err(e) => { Err(e) => {
log::warn!("Subcompositor protocol not available, ignoring CSD: {e:?}"); tracing::warn!("Subcompositor protocol not available, ignoring CSD: {e:?}");
None None
} }
}; };

View File

@@ -14,7 +14,7 @@ use sctk::shell::xdg::window::Window as SctkWindow;
use sctk::shell::xdg::window::WindowDecorations; use sctk::shell::xdg::window::WindowDecorations;
use sctk::shell::WaylandSurface; use sctk::shell::WaylandSurface;
use log::warn; use tracing::warn;
use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}; use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size};
use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError}; use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError};

View File

@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex, Weak};
use std::time::Duration; use std::time::Duration;
use ahash::HashSet; use ahash::HashSet;
use log::{info, warn}; use tracing::{info, warn};
use sctk::reexports::client::backend::ObjectId; use sctk::reexports::client::backend::ObjectId;
use sctk::reexports::client::protocol::wl_seat::WlSeat; use sctk::reexports::client::protocol::wl_seat::WlSeat;
@@ -727,7 +727,7 @@ impl WindowState {
RootCustomCursor { RootCustomCursor {
inner: PlatformCustomCursor::X(_), inner: PlatformCustomCursor::X(_),
} => { } => {
log::error!("passed a X11 cursor to Wayland backend"); tracing::error!("passed a X11 cursor to Wayland backend");
return; return;
} }
}; };

View File

@@ -33,9 +33,10 @@ use crate::platform_impl::platform::common::xkb::Context;
use crate::platform_impl::platform::x11::ime::{ImeEvent, ImeEventReceiver, ImeRequest}; use crate::platform_impl::platform::x11::ime::{ImeEvent, ImeEventReceiver, ImeRequest};
use crate::platform_impl::platform::x11::ActiveEventLoop; use crate::platform_impl::platform::x11::ActiveEventLoop;
use crate::platform_impl::platform::ActiveEventLoop as PlatformActiveEventLoop; use crate::platform_impl::platform::ActiveEventLoop as PlatformActiveEventLoop;
use crate::platform_impl::x11::util::cookie::GenericEventCookie;
use crate::platform_impl::x11::{ use crate::platform_impl::x11::{
atoms::*, mkdid, mkwid, util, CookieResultExt, Device, DeviceId, DeviceInfo, Dnd, DndState, atoms::*, mkdid, mkwid, util, CookieResultExt, Device, DeviceId, DeviceInfo, Dnd, DndState,
GenericEventCookie, ImeReceiver, ScrollOrientation, UnownedWindow, WindowId, ImeReceiver, ScrollOrientation, UnownedWindow, WindowId,
}; };
/// The maximum amount of X modifiers to replay. /// The maximum amount of X modifiers to replay.
@@ -184,14 +185,15 @@ impl EventProcessor {
} }
xlib::GenericEvent => { xlib::GenericEvent => {
let wt = Self::window_target(&self.target); let wt = Self::window_target(&self.target);
let xev = match GenericEventCookie::from_event(&wt.xconn, *xev) { let xev: GenericEventCookie =
Some(xev) if xev.cookie.extension as u8 == self.xi2ext.major_opcode => { match GenericEventCookie::from_event(wt.xconn.clone(), *xev) {
xev.cookie Some(xev) if xev.extension() == self.xi2ext.major_opcode => xev,
}
_ => return, _ => return,
}; };
match xev.evtype { let evtype = xev.evtype();
match evtype {
ty @ xinput2::XI_ButtonPress | ty @ xinput2::XI_ButtonRelease => { ty @ xinput2::XI_ButtonPress | ty @ xinput2::XI_ButtonRelease => {
let state = if ty == xinput2::XI_ButtonPress { let state = if ty == xinput2::XI_ButtonPress {
ElementState::Pressed ElementState::Pressed
@@ -199,7 +201,7 @@ impl EventProcessor {
ElementState::Released ElementState::Released
}; };
let xev: &XIDeviceEvent = unsafe { &*(xev.data as *const _) }; let xev: &XIDeviceEvent = unsafe { xev.as_event() };
self.update_mods_from_xinput2_event( self.update_mods_from_xinput2_event(
&xev.mods, &xev.mods,
&xev.group, &xev.group,
@@ -209,7 +211,7 @@ impl EventProcessor {
self.xinput2_button_input(xev, state, &mut callback); self.xinput2_button_input(xev, state, &mut callback);
} }
xinput2::XI_Motion => { xinput2::XI_Motion => {
let xev: &XIDeviceEvent = unsafe { &*(xev.data as *const _) }; let xev: &XIDeviceEvent = unsafe { xev.as_event() };
self.update_mods_from_xinput2_event( self.update_mods_from_xinput2_event(
&xev.mods, &xev.mods,
&xev.group, &xev.group,
@@ -219,11 +221,11 @@ impl EventProcessor {
self.xinput2_mouse_motion(xev, &mut callback); self.xinput2_mouse_motion(xev, &mut callback);
} }
xinput2::XI_Enter => { xinput2::XI_Enter => {
let xev: &XIEnterEvent = unsafe { &*(xev.data as *const _) }; let xev: &XIEnterEvent = unsafe { xev.as_event() };
self.xinput2_mouse_enter(xev, &mut callback); self.xinput2_mouse_enter(xev, &mut callback);
} }
xinput2::XI_Leave => { xinput2::XI_Leave => {
let xev: &XILeaveEvent = unsafe { &*(xev.data as *const _) }; let xev: &XILeaveEvent = unsafe { xev.as_event() };
self.update_mods_from_xinput2_event( self.update_mods_from_xinput2_event(
&xev.mods, &xev.mods,
&xev.group, &xev.group,
@@ -233,51 +235,51 @@ impl EventProcessor {
self.xinput2_mouse_left(xev, &mut callback); self.xinput2_mouse_left(xev, &mut callback);
} }
xinput2::XI_FocusIn => { xinput2::XI_FocusIn => {
let xev: &XIFocusInEvent = unsafe { &*(xev.data as *const _) }; let xev: &XIFocusInEvent = unsafe { xev.as_event() };
self.xinput2_focused(xev, &mut callback); self.xinput2_focused(xev, &mut callback);
} }
xinput2::XI_FocusOut => { xinput2::XI_FocusOut => {
let xev: &XIFocusOutEvent = unsafe { &*(xev.data as *const _) }; let xev: &XIFocusOutEvent = unsafe { xev.as_event() };
self.xinput2_unfocused(xev, &mut callback); self.xinput2_unfocused(xev, &mut callback);
} }
xinput2::XI_TouchBegin | xinput2::XI_TouchUpdate | xinput2::XI_TouchEnd => { xinput2::XI_TouchBegin | xinput2::XI_TouchUpdate | xinput2::XI_TouchEnd => {
let phase = match xev.evtype { let phase = match evtype {
xinput2::XI_TouchBegin => TouchPhase::Started, xinput2::XI_TouchBegin => TouchPhase::Started,
xinput2::XI_TouchUpdate => TouchPhase::Moved, xinput2::XI_TouchUpdate => TouchPhase::Moved,
xinput2::XI_TouchEnd => TouchPhase::Ended, xinput2::XI_TouchEnd => TouchPhase::Ended,
_ => unreachable!(), _ => unreachable!(),
}; };
let xev: &XIDeviceEvent = unsafe { &*(xev.data as *const _) }; let xev: &XIDeviceEvent = unsafe { xev.as_event() };
self.xinput2_touch(xev, phase, &mut callback); self.xinput2_touch(xev, phase, &mut callback);
} }
xinput2::XI_RawButtonPress | xinput2::XI_RawButtonRelease => { xinput2::XI_RawButtonPress | xinput2::XI_RawButtonRelease => {
let state = match xev.evtype { let state = match evtype {
xinput2::XI_RawButtonPress => ElementState::Pressed, xinput2::XI_RawButtonPress => ElementState::Pressed,
xinput2::XI_RawButtonRelease => ElementState::Released, xinput2::XI_RawButtonRelease => ElementState::Released,
_ => unreachable!(), _ => unreachable!(),
}; };
let xev: &XIRawEvent = unsafe { &*(xev.data as *const _) }; let xev: &XIRawEvent = unsafe { xev.as_event() };
self.xinput2_raw_button_input(xev, state, &mut callback); self.xinput2_raw_button_input(xev, state, &mut callback);
} }
xinput2::XI_RawMotion => { xinput2::XI_RawMotion => {
let xev: &XIRawEvent = unsafe { &*(xev.data as *const _) }; let xev: &XIRawEvent = unsafe { xev.as_event() };
self.xinput2_raw_mouse_motion(xev, &mut callback); self.xinput2_raw_mouse_motion(xev, &mut callback);
} }
xinput2::XI_RawKeyPress | xinput2::XI_RawKeyRelease => { xinput2::XI_RawKeyPress | xinput2::XI_RawKeyRelease => {
let state = match xev.evtype { let state = match evtype {
xinput2::XI_RawKeyPress => ElementState::Pressed, xinput2::XI_RawKeyPress => ElementState::Pressed,
xinput2::XI_RawKeyRelease => ElementState::Released, xinput2::XI_RawKeyRelease => ElementState::Released,
_ => unreachable!(), _ => unreachable!(),
}; };
let xev: &xinput2::XIRawEvent = unsafe { &*(xev.data as *const _) }; let xev: &xinput2::XIRawEvent = unsafe { xev.as_event() };
self.xinput2_raw_key_input(xev, state, &mut callback); self.xinput2_raw_key_input(xev, state, &mut callback);
} }
xinput2::XI_HierarchyChanged => { xinput2::XI_HierarchyChanged => {
let xev: &XIHierarchyEvent = unsafe { &*(xev.data as *const _) }; let xev: &XIHierarchyEvent = unsafe { xev.as_event() };
self.xinput2_hierarchy_changed(xev, &mut callback); self.xinput2_hierarchy_changed(xev, &mut callback);
} }
_ => {} _ => {}
@@ -979,13 +981,13 @@ impl EventProcessor {
// Always update the modifiers when we're not replaying. // Always update the modifiers when we're not replaying.
if !replay { if !replay {
self.udpate_mods_from_core_event(window_id, xev.state as u16, &mut callback); self.update_mods_from_core_event(window_id, xev.state as u16, &mut callback);
} }
if keycode != 0 && !self.is_composing { if keycode != 0 && !self.is_composing {
// Don't alter the modifiers state from replaying. // Don't alter the modifiers state from replaying.
if replay { if replay {
self.send_synthic_modifier_from_core(window_id, xev.state as u16, &mut callback); self.send_synthetic_modifier_from_core(window_id, xev.state as u16, &mut callback);
} }
if let Some(mut key_processor) = self.xkb_context.key_context() { if let Some(mut key_processor) = self.xkb_context.key_context() {
@@ -1035,7 +1037,7 @@ impl EventProcessor {
} }
} }
fn send_synthic_modifier_from_core<T: 'static, F>( fn send_synthetic_modifier_from_core<T: 'static, F>(
&mut self, &mut self,
window_id: crate::window::WindowId, window_id: crate::window::WindowId,
state: u16, state: u16,
@@ -1518,8 +1520,8 @@ impl EventProcessor {
let mask = let mask =
unsafe { slice::from_raw_parts(xev.valuators.mask, xev.valuators.mask_len as usize) }; unsafe { slice::from_raw_parts(xev.valuators.mask, xev.valuators.mask_len as usize) };
let mut value = xev.raw_values; let mut value = xev.raw_values;
let mut mouse_delta = (0.0, 0.0); let mut mouse_delta = util::Delta::default();
let mut scroll_delta = (0.0, 0.0); let mut scroll_delta = util::Delta::default();
for i in 0..xev.valuators.mask_len * 8 { for i in 0..xev.valuators.mask_len * 8 {
if !xinput2::XIMaskIsSet(mask, i) { if !xinput2::XIMaskIsSet(mask, i) {
continue; continue;
@@ -1529,10 +1531,10 @@ impl EventProcessor {
// We assume that every XInput2 device with analog axes is a pointing device emitting // We assume that every XInput2 device with analog axes is a pointing device emitting
// relative coordinates. // relative coordinates.
match i { match i {
0 => mouse_delta.0 = x, 0 => mouse_delta.set_x(x),
1 => mouse_delta.1 = x, 1 => mouse_delta.set_y(x),
2 => scroll_delta.0 = x as f32, 2 => scroll_delta.set_x(x as f32),
3 => scroll_delta.1 = x as f32, 3 => scroll_delta.set_y(x as f32),
_ => {} _ => {}
} }
@@ -1548,7 +1550,7 @@ impl EventProcessor {
value = unsafe { value.offset(1) }; value = unsafe { value.offset(1) };
} }
if mouse_delta != (0.0, 0.0) { if let Some(mouse_delta) = mouse_delta.consume() {
let event = Event::DeviceEvent { let event = Event::DeviceEvent {
device_id: did, device_id: did,
event: DeviceEvent::MouseMotion { delta: mouse_delta }, event: DeviceEvent::MouseMotion { delta: mouse_delta },
@@ -1556,7 +1558,7 @@ impl EventProcessor {
callback(&self.target, event); callback(&self.target, event);
} }
if scroll_delta != (0.0, 0.0) { if let Some(scroll_delta) = scroll_delta.consume() {
let event = Event::DeviceEvent { let event = Event::DeviceEvent {
device_id: did, device_id: did,
event: DeviceEvent::MouseWheel { event: DeviceEvent::MouseWheel {
@@ -1776,7 +1778,7 @@ impl EventProcessor {
self.send_modifiers(window_id, mods.into(), true, &mut callback) self.send_modifiers(window_id, mods.into(), true, &mut callback)
} }
pub fn udpate_mods_from_core_event<T: 'static, F>( pub fn update_mods_from_core_event<T: 'static, F>(
&mut self, &mut self,
window_id: crate::window::WindowId, window_id: crate::window::WindowId,
state: u16, state: u16,

View File

@@ -166,7 +166,7 @@ unsafe fn replace_im(inner: *mut ImeInner) -> Result<(), ReplaceImError> {
pub unsafe extern "C" fn xim_instantiate_callback( pub unsafe extern "C" fn xim_instantiate_callback(
_display: *mut ffi::Display, _display: *mut ffi::Display,
client_data: ffi::XPointer, client_data: ffi::XPointer,
// This field is unsupplied. // This field is un-supplied.
_call_data: ffi::XPointer, _call_data: ffi::XPointer,
) { ) {
let inner: *mut ImeInner = client_data as _; let inner: *mut ImeInner = client_data as _;
@@ -193,7 +193,7 @@ pub unsafe extern "C" fn xim_instantiate_callback(
pub unsafe extern "C" fn xim_destroy_callback( pub unsafe extern "C" fn xim_destroy_callback(
_xim: ffi::XIM, _xim: ffi::XIM,
client_data: ffi::XPointer, client_data: ffi::XPointer,
// This field is unsupplied. // This field is un-supplied.
_call_data: ffi::XPointer, _call_data: ffi::XPointer,
) { ) {
let inner: *mut ImeInner = client_data as _; let inner: *mut ImeInner = client_data as _;

View File

@@ -86,8 +86,8 @@ extern "C" fn preedit_draw_callback(
let chg_range = let chg_range =
call_data.chg_first as usize..(call_data.chg_first + call_data.chg_length) as usize; call_data.chg_first as usize..(call_data.chg_first + call_data.chg_length) as usize;
if chg_range.start > client_data.text.len() || chg_range.end > client_data.text.len() { if chg_range.start > client_data.text.len() || chg_range.end > client_data.text.len() {
log::warn!( tracing::warn!(
"invalid chg range: buffer length={}, but chg_first={} chg_lengthg={}", "invalid chg range: buffer length={}, but chg_first={} chg_length={}",
client_data.text.len(), client_data.text.len(),
call_data.chg_first, call_data.chg_first,
call_data.chg_length call_data.chg_length

View File

@@ -170,7 +170,7 @@ impl From<util::GetPropertyError> for GetXimServersError {
} }
// The root window has a property named XIM_SERVERS, which contains a list of atoms representing // The root window has a property named XIM_SERVERS, which contains a list of atoms representing
// the availabile XIM servers. For instance, if you're using ibus, it would contain an atom named // the available XIM servers. For instance, if you're using ibus, it would contain an atom named
// "@server=ibus". It's possible for this property to contain multiple atoms, though presumably // "@server=ibus". It's possible for this property to contain multiple atoms, though presumably
// rare. Note that we replace "@server=" with "@im=" in order to match the format of locale // rare. Note that we replace "@server=" with "@im=" in order to match the format of locale
// modifiers, since we don't want a user who's looking at logs to ask "am I supposed to set // modifiers, since we don't want a user who's looking at logs to ask "am I supposed to set

View File

@@ -10,9 +10,9 @@ use std::sync::{
Arc, Arc,
}; };
use log::debug;
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::debug;
use super::{ffi, util, XConnection, XError}; use super::{ffi, util, XConnection, XError};

View File

@@ -18,7 +18,7 @@ use calloop::generic::Generic;
use calloop::EventLoop as Loop; use calloop::EventLoop as Loop;
use calloop::{ping::Ping, Readiness}; use calloop::{ping::Ping, Readiness};
use libc::{setlocale, LC_CTYPE}; use libc::{setlocale, LC_CTYPE};
use log::warn; use tracing::warn;
use x11rb::connection::RequestConnection; use x11rb::connection::RequestConnection;
use x11rb::errors::{ConnectError, ConnectionError, IdsExhausted, ReplyError}; use x11rb::errors::{ConnectError, ConnectionError, IdsExhausted, ReplyError};
@@ -66,6 +66,9 @@ const ALL_DEVICES: u16 = 0;
const ALL_MASTER_DEVICES: u16 = 1; const ALL_MASTER_DEVICES: u16 = 1;
const ICONIC_STATE: u32 = 3; const ICONIC_STATE: u32 = 3;
/// The underlying x11rb connection that we are using.
type X11rbConnection = x11rb::xcb_ffi::XCBConnection;
type X11Source = Generic<BorrowedFd<'static>>; type X11Source = Generic<BorrowedFd<'static>>;
struct WakeSender<T> { struct WakeSender<T> {
@@ -480,7 +483,7 @@ impl<T: 'static> EventLoop<T> {
.dispatch(timeout, &mut self.state) .dispatch(timeout, &mut self.state)
.map_err(std::io::Error::from) .map_err(std::io::Error::from)
{ {
log::error!("Failed to poll for events: {error:?}"); tracing::error!("Failed to poll for events: {error:?}");
let exit_code = error.raw_os_error().unwrap_or(1); let exit_code = error.raw_os_error().unwrap_or(1);
self.set_exit_code(exit_code); self.set_exit_code(exit_code);
return; return;
@@ -564,7 +567,7 @@ impl<T: 'static> EventLoop<T> {
callback(event, &self.event_processor.target) callback(event, &self.event_processor.target)
} }
Some(Err(e)) => { Some(Err(e)) => {
log::error!("Failed to get activation token: {}", e); tracing::error!("Failed to get activation token: {}", e);
} }
None => {} None => {}
} }
@@ -985,9 +988,6 @@ impl From<xsettings::ParserError> for X11Error {
} }
} }
/// The underlying x11rb connection that we are using.
type X11rbConnection = x11rb::xcb_ffi::XCBConnection;
/// Type alias for a void cookie. /// Type alias for a void cookie.
type VoidCookie<'a> = x11rb::cookie::VoidCookie<'a, X11rbConnection>; type VoidCookie<'a> = x11rb::cookie::VoidCookie<'a, X11rbConnection>;
@@ -1003,34 +1003,6 @@ impl<'a, E: fmt::Debug> CookieResultExt for Result<VoidCookie<'a>, E> {
} }
} }
/// XEvents of type GenericEvent store their actual data in an XGenericEventCookie data structure. This is a wrapper to
/// extract the cookie from a GenericEvent XEvent and release the cookie data once it has been processed
struct GenericEventCookie<'a> {
xconn: &'a XConnection,
cookie: ffi::XGenericEventCookie,
}
impl<'a> GenericEventCookie<'a> {
fn from_event(xconn: &XConnection, event: ffi::XEvent) -> Option<GenericEventCookie<'_>> {
unsafe {
let mut cookie: ffi::XGenericEventCookie = From::from(event);
if (xconn.xlib.XGetEventData)(xconn.display, &mut cookie) == ffi::True {
Some(GenericEventCookie { xconn, cookie })
} else {
None
}
}
}
}
impl<'a> Drop for GenericEventCookie<'a> {
fn drop(&mut self) {
unsafe {
(self.xconn.xlib.XFreeEventData)(self.xconn.display, &mut self.cookie);
}
}
}
fn mkwid(w: xproto::Window) -> crate::window::WindowId { fn mkwid(w: xproto::Window) -> crate::window::WindowId {
crate::window::WindowId(crate::platform_impl::platform::WindowId(w as _)) crate::window::WindowId(crate::platform_impl::platform::WindowId(w as _))
} }

View File

@@ -0,0 +1,55 @@
use std::ffi::c_int;
use std::sync::Arc;
use x11_dl::xlib::{self, XEvent, XGenericEventCookie};
use crate::platform_impl::x11::XConnection;
/// XEvents of type GenericEvent store their actual data in an XGenericEventCookie data structure.
/// This is a wrapper to extract the cookie from a GenericEvent XEvent and release the cookie data
/// once it has been processed
pub struct GenericEventCookie {
cookie: XGenericEventCookie,
xconn: Arc<XConnection>,
}
impl GenericEventCookie {
pub fn from_event(xconn: Arc<XConnection>, event: XEvent) -> Option<GenericEventCookie> {
unsafe {
let mut cookie: XGenericEventCookie = From::from(event);
if (xconn.xlib.XGetEventData)(xconn.display, &mut cookie) == xlib::True {
Some(GenericEventCookie { cookie, xconn })
} else {
None
}
}
}
#[inline]
pub fn extension(&self) -> u8 {
self.cookie.extension as u8
}
#[inline]
pub fn evtype(&self) -> c_int {
self.cookie.evtype
}
/// Borrow inner event data as `&T`.
///
/// ## SAFETY
///
/// The caller must ensure that the event has the `T` inside of it.
#[inline]
pub unsafe fn as_event<T>(&self) -> &T {
unsafe { &*(self.cookie.data as *const _) }
}
}
impl Drop for GenericEventCookie {
fn drop(&mut self) {
unsafe {
(self.xconn.xlib.XFreeEventData)(self.xconn.display, &mut self.cookie);
}
}
}

View File

@@ -44,7 +44,7 @@ impl AaRect {
pub struct Geometry { pub struct Geometry {
pub root: xproto::Window, pub root: xproto::Window,
// If you want positions relative to the root window, use translate_coords. // If you want positions relative to the root window, use translate_coords.
// Note that the overwhelming majority of window managers are reparenting WMs, thus the window // Note that the overwhelming majority of window managers are re-parenting WMs, thus the window
// ID we get from window creation is for a nested window used as the window's client area. If // ID we get from window creation is for a nested window used as the window's client area. If
// you call get_geometry with that window ID, then you'll get the position of that client area // you call get_geometry with that window ID, then you'll get the position of that client area
// window relative to the parent it's nested in (the frame), which isn't helpful if you want // window relative to the parent it's nested in (the frame), which isn't helpful if you want

View File

@@ -45,7 +45,7 @@ impl XConnection {
self.flush_requests()?; self.flush_requests()?;
Ok(true) Ok(true)
} else { } else {
log::error!("Could not select XKB events: The XKB extension is not initialized!"); tracing::error!("Could not select XKB events: The XKB extension is not initialized!");
Ok(false) Ok(false)
} }
} }

View File

@@ -8,6 +8,7 @@ use std::{
}; };
mod client_msg; mod client_msg;
pub mod cookie;
mod cursor; mod cursor;
mod geometry; mod geometry;
mod hint; mod hint;
@@ -15,13 +16,15 @@ mod icon;
mod input; mod input;
pub mod keys; pub mod keys;
pub(crate) mod memory; pub(crate) mod memory;
mod mouse;
mod randr; mod randr;
mod window_property; mod window_property;
mod wm; mod wm;
mod xmodmap; mod xmodmap;
pub use self::{ pub use self::{
cursor::*, geometry::*, hint::*, input::*, window_property::*, wm::*, xmodmap::ModifierKeymap, cursor::*, geometry::*, hint::*, input::*, mouse::*, window_property::*, wm::*,
xmodmap::ModifierKeymap,
}; };
use super::{atoms::*, ffi, VoidCookie, X11Error, XConnection, XError}; use super::{atoms::*, ffi, VoidCookie, X11Error, XConnection, XError};
@@ -45,7 +48,7 @@ where
} }
impl XConnection { impl XConnection {
// This is impoartant, so pay attention! // This is important, so pay attention!
// Xlib has an output buffer, and tries to hide the async nature of X from you. // Xlib has an output buffer, and tries to hide the async nature of X from you.
// This buffer contains the requests you make, and is flushed under various circumstances: // This buffer contains the requests you make, and is flushed under various circumstances:
// 1. `XPending`, `XNextEvent`, and `XWindowEvent` flush "as needed" // 1. `XPending`, `XNextEvent`, and `XWindowEvent` flush "as needed"

View File

@@ -0,0 +1,52 @@
//! Utilities for handling mouse events.
/// Recorded mouse delta designed to filter out noise.
pub struct Delta<T> {
x: T,
y: T,
}
impl<T: Default> Default for Delta<T> {
fn default() -> Self {
Self {
x: Default::default(),
y: Default::default(),
}
}
}
impl<T: Default> Delta<T> {
pub(crate) fn set_x(&mut self, x: T) {
self.x = x;
}
pub(crate) fn set_y(&mut self, y: T) {
self.y = y;
}
}
macro_rules! consume {
($this:expr, $ty:ty) => {{
let this = $this;
let (x, y) = match (this.x.abs() < <$ty>::EPSILON, this.y.abs() < <$ty>::EPSILON) {
(true, true) => return None,
(true, false) => (this.x, 0.0),
(false, true) => (0.0, this.y),
(false, false) => (this.x, this.y),
};
Some((x, y))
}};
}
impl Delta<f32> {
pub(crate) fn consume(self) -> Option<(f32, f32)> {
consume!(self, f32)
}
}
impl Delta<f64> {
pub(crate) fn consume(self) -> Option<(f64, f64)> {
consume!(self, f64)
}
}

View File

@@ -4,7 +4,7 @@ use super::*;
use crate::platform_impl::platform::x11::monitor; use crate::platform_impl::platform::x11::monitor;
use crate::{dpi::validate_scale_factor, platform_impl::platform::x11::VideoModeHandle}; use crate::{dpi::validate_scale_factor, platform_impl::platform::x11::VideoModeHandle};
use log::warn; use tracing::warn;
use x11rb::protocol::randr::{self, ConnectionExt as _}; use x11rb::protocol::randr::{self, ConnectionExt as _};
/// Represents values of `WINIT_HIDPI_FACTOR`. /// Represents values of `WINIT_HIDPI_FACTOR`.
@@ -44,7 +44,7 @@ impl XConnection {
Ok(Some(dpi)) => return Some(dpi), Ok(Some(dpi)) => return Some(dpi),
Ok(None) => {} Ok(None) => {}
Err(err) => { Err(err) => {
log::warn!("failed to fetch XSettings: {err}"); tracing::warn!("failed to fetch XSettings: {err}");
} }
} }
} }

View File

@@ -54,7 +54,7 @@ impl XConnection {
// Mutter/Muffin/Budgie doesn't have _NET_SUPPORTING_WM_CHECK in its _NET_SUPPORTED, despite // Mutter/Muffin/Budgie doesn't have _NET_SUPPORTING_WM_CHECK in its _NET_SUPPORTED, despite
// it working and being supported. This has been reported upstream, but due to the // it working and being supported. This has been reported upstream, but due to the
// inavailability of time machines, we'll just try to get _NET_SUPPORTING_WM_CHECK // unavailability of time machines, we'll just try to get _NET_SUPPORTING_WM_CHECK
// regardless of whether or not the WM claims to support it. // regardless of whether or not the WM claims to support it.
// //
// Blackbox 0.70 also incorrectly reports not supporting this, though that appears to be fixed // Blackbox 0.70 also incorrectly reports not supporting this, though that appears to be fixed

View File

@@ -16,7 +16,7 @@ const NUM_MODS: usize = 8;
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct ModifierKeymap { pub struct ModifierKeymap {
// Maps keycodes to modifiers // Maps keycodes to modifiers
modifers: HashSet<XKeyCode>, modifiers: HashSet<XKeyCode>,
} }
impl ModifierKeymap { impl ModifierKeymap {
@@ -25,7 +25,7 @@ impl ModifierKeymap {
} }
pub fn is_modifier(&self, keycode: XKeyCode) -> bool { pub fn is_modifier(&self, keycode: XKeyCode) -> bool {
self.modifers.contains(&keycode) self.modifiers.contains(&keycode)
} }
pub fn reload_from_x_connection(&mut self, xconn: &super::XConnection) { pub fn reload_from_x_connection(&mut self, xconn: &super::XConnection) {
@@ -48,9 +48,9 @@ impl ModifierKeymap {
let keys = unsafe { let keys = unsafe {
slice::from_raw_parts(keymap.modifiermap as *const _, keys_per_mod * NUM_MODS) slice::from_raw_parts(keymap.modifiermap as *const _, keys_per_mod * NUM_MODS)
}; };
self.modifers.clear(); self.modifiers.clear();
for key in keys { for key in keys {
self.modifers.insert(*key); self.modifiers.insert(*key);
} }
} }
} }

View File

@@ -7,7 +7,7 @@ use std::{
sync::{Arc, Mutex, MutexGuard}, sync::{Arc, Mutex, MutexGuard},
}; };
use log::{debug, info, warn}; use tracing::{debug, info, warn};
use x11rb::{ use x11rb::{
connection::Connection, connection::Connection,
properties::{WmHints, WmSizeHints, WmSizeHintsSpecification}, properties::{WmHints, WmSizeHints, WmSizeHintsSpecification},
@@ -391,7 +391,7 @@ impl UnownedWindow {
} }
{ {
// Enable drag and drop (TODO: extend API to make this toggleable) // Enable drag and drop (TODO: extend API to make this toggle-able)
{ {
let dnd_aware_atom = atoms[XdndAware]; let dnd_aware_atom = atoms[XdndAware];
let version = &[5u32]; // Latest version; hasn't changed since 2002 let version = &[5u32]; // Latest version; hasn't changed since 2002
@@ -1038,9 +1038,10 @@ impl UnownedWindow {
let vert_atom = atoms[_NET_WM_STATE_MAXIMIZED_VERT]; let vert_atom = atoms[_NET_WM_STATE_MAXIMIZED_VERT];
match state { match state {
Ok(atoms) => { Ok(atoms) => {
let horz_maximized = atoms.iter().any(|atom: &xproto::Atom| *atom == horz_atom); let horizontal_maximized =
atoms.iter().any(|atom: &xproto::Atom| *atom == horz_atom);
let vert_maximized = atoms.iter().any(|atom: &xproto::Atom| *atom == vert_atom); let vert_maximized = atoms.iter().any(|atom: &xproto::Atom| *atom == vert_atom);
horz_maximized && vert_maximized horizontal_maximized && vert_maximized
} }
_ => false, _ => false,
} }
@@ -1048,10 +1049,10 @@ impl UnownedWindow {
fn set_maximized_inner(&self, maximized: bool) -> Result<VoidCookie<'_>, X11Error> { fn set_maximized_inner(&self, maximized: bool) -> Result<VoidCookie<'_>, X11Error> {
let atoms = self.xconn.atoms(); let atoms = self.xconn.atoms();
let horz_atom = atoms[_NET_WM_STATE_MAXIMIZED_HORZ]; let horizontal_atom = atoms[_NET_WM_STATE_MAXIMIZED_HORZ];
let vert_atom = atoms[_NET_WM_STATE_MAXIMIZED_VERT]; let vert_atom = atoms[_NET_WM_STATE_MAXIMIZED_VERT];
self.set_netwm(maximized.into(), (horz_atom, vert_atom, 0, 0)) self.set_netwm(maximized.into(), (horizontal_atom, vert_atom, 0, 0))
} }
#[inline] #[inline]
@@ -1573,7 +1574,7 @@ impl UnownedWindow {
#[cfg(wayland_platform)] #[cfg(wayland_platform)]
Cursor::Custom(RootCustomCursor { Cursor::Custom(RootCustomCursor {
inner: PlatformCustomCursor::Wayland(_), inner: PlatformCustomCursor::Wayland(_),
}) => log::error!("passed a Wayland cursor to X11 backend"), }) => tracing::error!("passed a Wayland cursor to X11 backend"),
} }
} }
@@ -1857,7 +1858,7 @@ impl UnownedWindow {
) )
.expect_then_ignore_error("Failed to send client message"); .expect_then_ignore_error("Failed to send client message");
if let Err(e) = self.xconn.flush_requests() { if let Err(e) = self.xconn.flush_requests() {
log::error!( tracing::error!(
"`flush` returned an error when focusing the window. Error was: {}", "`flush` returned an error when focusing the window. Error was: {}",
e e
); );

View File

@@ -121,7 +121,7 @@ impl XConnection {
let xsettings_screen = Self::new_xsettings_screen(&xcb, default_screen); let xsettings_screen = Self::new_xsettings_screen(&xcb, default_screen);
if xsettings_screen.is_none() { if xsettings_screen.is_none() {
log::warn!("error setting XSETTINGS; Xft options won't reload automatically") tracing::warn!("error setting XSETTINGS; Xft options won't reload automatically")
} }
// Fetch atoms. // Fetch atoms.
@@ -159,7 +159,7 @@ impl XConnection {
// Get PropertyNotify events from the XSETTINGS window. // Get PropertyNotify events from the XSETTINGS window.
// TODO: The XSETTINGS window here can change. In the future, listen for DestroyNotify on this 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. // in order to accommodate for a changed window here.
let selector_window = xcb let selector_window = xcb
.get_selection_owner(xsettings_screen) .get_selection_owner(xsettings_screen)
.ok()? .ok()?

View File

@@ -471,10 +471,10 @@ fn window_activation_hack(app: &NSApplication) {
// This way we preserve the user's desired initial visibility status // This way we preserve the user's desired initial visibility status
// TODO: Also filter on the type/"level" of the window, and maybe other things? // TODO: Also filter on the type/"level" of the window, and maybe other things?
if window.isVisible() { if window.isVisible() {
log::trace!("Activating visible window"); tracing::trace!("Activating visible window");
window.makeKeyAndOrderFront(None); window.makeKeyAndOrderFront(None);
} else { } else {
log::trace!("Skipping activating invisible window"); tracing::trace!("Skipping activating invisible window");
} }
}) })
} }

View File

@@ -71,7 +71,7 @@ unsafe fn try_cursor_from_selector(sel: Sel) -> Option<Id<NSCursor>> {
let cursor: Id<NSCursor> = unsafe { msg_send_id![cls, performSelector: sel] }; let cursor: Id<NSCursor> = unsafe { msg_send_id![cls, performSelector: sel] };
Some(cursor) Some(cursor)
} else { } else {
log::warn!("cursor `{sel}` appears to be invalid"); tracing::warn!("cursor `{sel}` appears to be invalid");
None None
} }
} }

View File

@@ -36,14 +36,14 @@ pub fn get_modifierless_char(scancode: u16) -> Key {
unsafe { unsafe {
input_source = ffi::TISCopyCurrentKeyboardLayoutInputSource(); input_source = ffi::TISCopyCurrentKeyboardLayoutInputSource();
if input_source.is_null() { if input_source.is_null() {
log::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr"); tracing::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr");
return Key::Unidentified(NativeKey::MacOS(scancode)); return Key::Unidentified(NativeKey::MacOS(scancode));
} }
let layout_data = let layout_data =
ffi::TISGetInputSourceProperty(input_source, ffi::kTISPropertyUnicodeKeyLayoutData); ffi::TISGetInputSourceProperty(input_source, ffi::kTISPropertyUnicodeKeyLayoutData);
if layout_data.is_null() { if layout_data.is_null() {
CFRelease(input_source as *mut c_void); CFRelease(input_source as *mut c_void);
log::error!("`TISGetInputSourceProperty` returned null ptr"); tracing::error!("`TISGetInputSourceProperty` returned null ptr");
return Key::Unidentified(NativeKey::MacOS(scancode)); return Key::Unidentified(NativeKey::MacOS(scancode));
} }
layout = CFDataGetBytePtr(layout_data as CFDataRef) as *const ffi::UCKeyboardLayout; layout = CFDataGetBytePtr(layout_data as CFDataRef) as *const ffi::UCKeyboardLayout;
@@ -71,7 +71,7 @@ pub fn get_modifierless_char(scancode: u16) -> Key {
CFRelease(input_source as *mut c_void); CFRelease(input_source as *mut c_void);
} }
if translate_result != 0 { if translate_result != 0 {
log::error!( tracing::error!(
"`UCKeyTranslate` returned with the non-zero value: {}", "`UCKeyTranslate` returned with the non-zero value: {}",
translate_result translate_result
); );
@@ -113,7 +113,8 @@ pub(crate) fn create_key_event(
let state = if is_press { Pressed } else { Released }; let state = if is_press { Pressed } else { Released };
let scancode = unsafe { ns_event.keyCode() }; let scancode = unsafe { ns_event.keyCode() };
let mut physical_key = key_override.unwrap_or_else(|| scancode_to_physicalkey(scancode as u32)); let mut physical_key =
key_override.unwrap_or_else(|| scancode_to_physical_key(scancode as u32));
// NOTE: The logical key should heed both SHIFT and ALT if possible. // NOTE: The logical key should heed both SHIFT and ALT if possible.
// For instance: // For instance:
@@ -150,7 +151,7 @@ pub(crate) fn create_key_event(
let logical_key = match text_with_all_modifiers.as_ref() { let logical_key = match text_with_all_modifiers.as_ref() {
// Only checking for ctrl and cmd here, not checking for alt because we DO want to // Only checking for ctrl and cmd here, not checking for alt because we DO want to
// include its effect in the key. For example if -on the Germay layout- one // include its effect in the key. For example if -on the Germany layout- one
// presses alt+8, the logical key should be "{" // presses alt+8, the logical key should be "{"
// Also not checking if this is a release event because then this issue would // Also not checking if this is a release event because then this issue would
// still affect the key release. // still affect the key release.
@@ -415,7 +416,7 @@ pub(super) fn dummy_event() -> Option<Id<NSEvent>> {
} }
} }
pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> { pub(crate) fn physical_key_to_scancode(physical_key: PhysicalKey) -> Option<u32> {
let code = match physical_key { let code = match physical_key {
PhysicalKey::Code(code) => code, PhysicalKey::Code(code) => code,
PhysicalKey::Unidentified(_) => return None, PhysicalKey::Unidentified(_) => return None,
@@ -537,7 +538,7 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
} }
} }
pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { pub(crate) fn scancode_to_physical_key(scancode: u32) -> PhysicalKey {
PhysicalKey::Code(match scancode { PhysicalKey::Code(match scancode {
0x00 => KeyCode::KeyA, 0x00 => KeyCode::KeyA,
0x01 => KeyCode::KeyS, 0x01 => KeyCode::KeyS,

View File

@@ -71,7 +71,7 @@ impl EventHandler {
*data = None; *data = None;
} }
Ok(None) => { Ok(None) => {
log::error!("tried to clear handler, but no handler was set"); tracing::error!("tried to clear handler, but no handler was set");
} }
Err(_) => { Err(_) => {
// Note: This is not expected to ever happen, this // Note: This is not expected to ever happen, this
@@ -125,7 +125,7 @@ impl EventHandler {
// `NSApplication`, our app delegate and this handler are all // `NSApplication`, our app delegate and this handler are all
// global state and so it's not impossible that we could get // global state and so it's not impossible that we could get
// an event after the application has exited the `EventLoop`. // an event after the application has exited the `EventLoop`.
log::error!("tried to run event handler, but no handler was set"); tracing::error!("tried to run event handler, but no handler was set");
} }
Err(_) => { Err(_) => {
// Prevent re-entrancy. // Prevent re-entrancy.

View File

@@ -60,7 +60,7 @@ impl PanicInfo {
self.inner.set(inner); self.inner.set(inner);
result result
} }
/// Overwrites the curret state if the current state is not panicking /// Overwrites the current state if the current state is not panicking
pub fn set_panic(&self, p: Box<dyn Any + Send + 'static>) { pub fn set_panic(&self, p: Box<dyn Any + Send + 'static>) {
if !self.is_panicking() { if !self.is_panicking() {
self.inner.set(Some(p)); self.inner.set(Some(p));

View File

@@ -18,7 +18,7 @@ mod window_delegate;
use std::fmt; use std::fmt;
pub(crate) use self::{ pub(crate) use self::{
event::{physicalkey_to_scancode, scancode_to_physicalkey, KeyEventExtra}, event::{physical_key_to_scancode, scancode_to_physical_key, KeyEventExtra},
event_loop::{ event_loop::{
ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle,
PlatformSpecificEventLoopAttributes, PlatformSpecificEventLoopAttributes,

View File

@@ -1,5 +1,5 @@
use icrate::Foundation::{NSNotFound, NSRange, NSUInteger}; use icrate::Foundation::{NSNotFound, NSRange, NSUInteger};
use log::trace; use tracing::trace;
pub const EMPTY_RANGE: NSRange = NSRange { pub const EMPTY_RANGE: NSRange = NSRange {
location: NSNotFound as NSUInteger, location: NSNotFound as NSUInteger,
@@ -20,7 +20,7 @@ pub(crate) struct TraceGuard {
impl TraceGuard { impl TraceGuard {
#[inline] #[inline]
pub(crate) fn new(module_path: &'static str, called_from_fn: &'static str) -> Self { pub(crate) fn new(module_path: &'static str, called_from_fn: &'static str) -> Self {
trace!(target: module_path, "Triggered `{}`", called_from_fn); trace!(target = module_path, "Triggered `{}`", called_from_fn);
Self { Self {
module_path, module_path,
called_from_fn, called_from_fn,
@@ -31,6 +31,10 @@ impl TraceGuard {
impl Drop for TraceGuard { impl Drop for TraceGuard {
#[inline] #[inline]
fn drop(&mut self) { fn drop(&mut self) {
trace!(target: self.module_path, "Completed `{}`", self.called_from_fn); trace!(
target = self.module_path,
"Completed `{}`",
self.called_from_fn
);
} }
} }

View File

@@ -23,7 +23,7 @@ use super::app_delegate::ApplicationDelegate;
use super::cursor::{default_cursor, invisible_cursor}; use super::cursor::{default_cursor, invisible_cursor};
use super::event::{ use super::event::{
code_to_key, code_to_location, create_key_event, event_mods, lalt_pressed, ralt_pressed, code_to_key, code_to_location, create_key_event, event_mods, lalt_pressed, ralt_pressed,
scancode_to_physicalkey, scancode_to_physical_key,
}; };
use super::window::WinitWindow; use super::window::WinitWindow;
use super::{util, DEVICE_ID}; use super::{util, DEVICE_ID};
@@ -338,7 +338,7 @@ declare_class!(
// Leave the Preedit self.ivars() // Leave the Preedit self.ivars()
self.ivars().ime_state.set(ImeState::Ground); self.ivars().ime_state.set(ImeState::Ground);
} else { } else {
log::warn!("Expected to have IME enabled when receiving unmarkText"); tracing::warn!("Expected to have IME enabled when receiving unmarkText");
} }
} }
@@ -918,7 +918,7 @@ impl WinitView {
'send_event: { 'send_event: {
if is_flags_changed_event && unsafe { ns_event.keyCode() } != 0 { if is_flags_changed_event && unsafe { ns_event.keyCode() } != 0 {
let scancode = unsafe { ns_event.keyCode() }; let scancode = unsafe { ns_event.keyCode() };
let physical_key = scancode_to_physicalkey(scancode as u32); let physical_key = scancode_to_physical_key(scancode as u32);
// We'll correct the `is_press` later. // We'll correct the `is_press` later.
let mut event = create_key_event(ns_event, false, false, Some(physical_key)); let mut event = create_key_event(ns_event, false, false, Some(physical_key));

View File

@@ -594,7 +594,7 @@ fn new_window(attrs: &WindowAttributes, mtm: MainThreadMarker) -> Option<Id<Wini
view.setWantsBestResolutionOpenGLSurface(!attrs.platform_specific.disallow_hidpi); view.setWantsBestResolutionOpenGLSurface(!attrs.platform_specific.disallow_hidpi);
// On Mojave, views automatically become layer-backed shortly after being added to // On Mojave, views automatically become layer-backed shortly after being added to
// a window. Changing the layer-backedness of a view breaks the association between // a window. Changing the layer-backed-ness of a view breaks the association between
// the view and its associated OpenGL context. To work around this, on Mojave we // the view and its associated OpenGL context. To work around this, on Mojave we
// explicitly make the view layer-backed up front so that AppKit doesn't do it // explicitly make the view layer-backed up front so that AppKit doesn't do it
// itself and break the association with its context. // itself and break the association with its context.
@@ -1012,7 +1012,7 @@ impl WindowDelegate {
self.set_style_mask(mask); self.set_style_mask(mask);
// We edit the button directly instead of using `NSResizableWindowMask`, // We edit the button directly instead of using `NSResizableWindowMask`,
// since that mask also affect the resizability of the window (which is // since that mask also affect the resize ability of the window (which is
// controllable by other means in `winit`). // controllable by other means in `winit`).
if let Some(button) = self.window().standardWindowButton(NSWindowZoomButton) { if let Some(button) = self.window().standardWindowButton(NSWindowZoomButton) {
button.setEnabled(buttons.contains(WindowButtons::MAXIMIZE)); button.setEnabled(buttons.contains(WindowButtons::MAXIMIZE));

View File

@@ -537,7 +537,7 @@ impl<T: 'static> EventLoop<T> {
} }
} }
other => { other => {
log::warn!("unhandled event: {:?}", other); tracing::warn!("unhandled event: {:?}", other);
} }
} }
} }

View File

@@ -301,7 +301,9 @@ impl CursorHandler {
}; };
} }
ImageState::Failed(error) => { ImageState::Failed(error) => {
log::error!("trying to load custom cursor that has failed to load: {error}") tracing::error!(
"trying to load custom cursor that has failed to load: {error}"
)
} }
ImageState::Image(_) => { ImageState::Image(_) => {
drop(state); drop(state);
@@ -413,7 +415,7 @@ impl Inner {
self.set_style(); self.set_style();
} }
ImageState::Failed(error) => { ImageState::Failed(error) => {
log::error!("custom cursor failed to load: {error}"); tracing::error!("custom cursor failed to load: {error}");
self.cursor = previous.into() self.cursor = previous.into()
} }
ImageState::Loading { .. } => unreachable!("notified without being ready"), ImageState::Loading { .. } => unreachable!("notified without being ready"),

View File

@@ -321,8 +321,8 @@ impl Key {
} }
impl PhysicalKey { impl PhysicalKey {
pub fn from_key_code_attribute_value(kcav: &str) -> Self { pub fn from_key_code_attribute_value(k_code: &str) -> Self {
PhysicalKey::Code(match kcav { PhysicalKey::Code(match k_code {
"Backquote" => KeyCode::Backquote, "Backquote" => KeyCode::Backquote,
"Backslash" => KeyCode::Backslash, "Backslash" => KeyCode::Backslash,
"BracketLeft" => KeyCode::BracketLeft, "BracketLeft" => KeyCode::BracketLeft,

View File

@@ -190,7 +190,7 @@ pub fn key_location(event: &KeyboardEvent) -> KeyLocation {
KeyboardEvent::DOM_KEY_LOCATION_NUMPAD => KeyLocation::Numpad, KeyboardEvent::DOM_KEY_LOCATION_NUMPAD => KeyLocation::Numpad,
KeyboardEvent::DOM_KEY_LOCATION_STANDARD => KeyLocation::Standard, KeyboardEvent::DOM_KEY_LOCATION_STANDARD => KeyLocation::Standard,
location => { location => {
log::warn!("Unexpected key location: {location}"); tracing::warn!("Unexpected key location: {location}");
KeyLocation::Standard KeyLocation::Standard
} }
} }

View File

@@ -1,5 +1,5 @@
use js_sys::{Array, Object}; use js_sys::{Array, Object};
use log::warn; use tracing::warn;
use wasm_bindgen::prelude::{wasm_bindgen, Closure}; use wasm_bindgen::prelude::{wasm_bindgen, Closure};
use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen::{JsCast, JsValue};
use web_sys::{ use web_sys::{

View File

@@ -117,9 +117,7 @@ impl Schedule {
let channel = MessageChannel::new().unwrap(); let channel = MessageChannel::new().unwrap();
let closure = Closure::new(f); let closure = Closure::new(f);
let port_1 = channel.port1(); let port_1 = channel.port1();
port_1 port_1.set_onmessage(Some(closure.as_ref().unchecked_ref()));
.add_event_listener_with_callback("message", closure.as_ref().unchecked_ref())
.expect("Failed to set message handler");
port_1.start(); port_1.start();
let port_2 = channel.port2(); let port_2 = channel.port2();
@@ -178,6 +176,7 @@ impl Drop for Schedule {
} => { } => {
window.clear_timeout_with_handle(*handle); window.clear_timeout_with_handle(*handle);
port.close(); port.close();
port.set_onmessage(None);
} }
} }
} }

View File

@@ -117,13 +117,13 @@ fn set_dark_mode_for_window(hwnd: HWND, is_dark_mode: bool) -> bool {
if let Some(set_window_composition_attribute) = *SET_WINDOW_COMPOSITION_ATTRIBUTE { if let Some(set_window_composition_attribute) = *SET_WINDOW_COMPOSITION_ATTRIBUTE {
unsafe { unsafe {
// SetWindowCompositionAttribute needs a bigbool (i32), not bool. // SetWindowCompositionAttribute needs a big_bool (i32), not bool.
let mut is_dark_mode_bigbool = BOOL::from(is_dark_mode); let mut is_dark_mode_big_bool = BOOL::from(is_dark_mode);
let mut data = WINDOWCOMPOSITIONATTRIBDATA { let mut data = WINDOWCOMPOSITIONATTRIBDATA {
Attrib: WCA_USEDARKMODECOLORS, Attrib: WCA_USEDARKMODECOLORS,
pvData: &mut is_dark_mode_bigbool as *mut _ as _, pvData: &mut is_dark_mode_big_bool as *mut _ as _,
cbData: std::mem::size_of_val(&is_dark_mode_bigbool) as _, cbData: std::mem::size_of_val(&is_dark_mode_big_bool) as _,
}; };
let status = set_window_composition_attribute(hwnd, &mut data); let status = set_window_composition_attribute(hwnd, &mut data);

View File

@@ -17,7 +17,7 @@ use windows_sys::{
pub struct IUnknownVtbl { pub struct IUnknownVtbl {
pub QueryInterface: unsafe extern "system" fn( pub QueryInterface: unsafe extern "system" fn(
This: *mut IUnknown, This: *mut IUnknown,
riid: *const GUID, r_iid: *const GUID,
ppvObject: *mut *mut c_void, ppvObject: *mut *mut c_void,
) -> HRESULT, ) -> HRESULT,
pub AddRef: unsafe extern "system" fn(This: *mut IUnknown) -> u32, pub AddRef: unsafe extern "system" fn(This: *mut IUnknown) -> u32,
@@ -29,43 +29,45 @@ pub struct IDataObjectVtbl {
pub parent: IUnknownVtbl, pub parent: IUnknownVtbl,
pub GetData: unsafe extern "system" fn( pub GetData: unsafe extern "system" fn(
This: *mut IDataObject, This: *mut IDataObject,
pformatetcIn: *const FORMATETC, p_format_etc_In: *const FORMATETC,
pmedium: *mut STGMEDIUM, p_medium: *mut STGMEDIUM,
) -> HRESULT, ) -> HRESULT,
pub GetDataHere: unsafe extern "system" fn( pub GetDataHere: unsafe extern "system" fn(
This: *mut IDataObject, This: *mut IDataObject,
pformatetc: *const FORMATETC, p_format_etc: *const FORMATETC,
pmedium: *mut STGMEDIUM, p_medium: *mut STGMEDIUM,
) -> HRESULT,
QueryGetData: unsafe extern "system" fn(
This: *mut IDataObject,
p_format_etc: *const FORMATETC,
) -> HRESULT, ) -> HRESULT,
QueryGetData:
unsafe extern "system" fn(This: *mut IDataObject, pformatetc: *const FORMATETC) -> HRESULT,
pub GetCanonicalFormatEtc: unsafe extern "system" fn( pub GetCanonicalFormatEtc: unsafe extern "system" fn(
This: *mut IDataObject, This: *mut IDataObject,
pformatetcIn: *const FORMATETC, p_format_etc_In: *const FORMATETC,
pformatetcOut: *mut FORMATETC, p_format_etc_Out: *mut FORMATETC,
) -> HRESULT, ) -> HRESULT,
pub SetData: unsafe extern "system" fn( pub SetData: unsafe extern "system" fn(
This: *mut IDataObject, This: *mut IDataObject,
pformatetc: *const FORMATETC, p_format_etc: *const FORMATETC,
pformatetcOut: *const FORMATETC, p_format_etcOut: *const FORMATETC,
fRelease: BOOL, fRelease: BOOL,
) -> HRESULT, ) -> HRESULT,
pub EnumFormatEtc: unsafe extern "system" fn( pub EnumFormatEtc: unsafe extern "system" fn(
This: *mut IDataObject, This: *mut IDataObject,
dwDirection: u32, dwDirection: u32,
ppenumFormatEtc: *mut *mut IEnumFORMATETC, pp_enumFormatEtc: *mut *mut IEnumFORMATETC,
) -> HRESULT, ) -> HRESULT,
pub DAdvise: unsafe extern "system" fn( pub DAdvise: unsafe extern "system" fn(
This: *mut IDataObject, This: *mut IDataObject,
pformatetc: *const FORMATETC, p_format_etc: *const FORMATETC,
advf: u32, a_dvf: u32,
pAdvSInk: *const IAdviseSink, pAdvSInk: *const IAdviseSink,
pdwConnection: *mut u32, pdwConnection: *mut u32,
) -> HRESULT, ) -> HRESULT,
pub DUnadvise: unsafe extern "system" fn(This: *mut IDataObject, dwConnection: u32) -> HRESULT, pub DUnadvise: unsafe extern "system" fn(This: *mut IDataObject, dwConnection: u32) -> HRESULT,
pub EnumDAdvise: unsafe extern "system" fn( pub EnumDAdvise: unsafe extern "system" fn(
This: *mut IDataObject, This: *mut IDataObject,
ppenumAdvise: *const *const IEnumSTATDATA, pp_enumAdvise: *const *const IEnumSTATDATA,
) -> HRESULT, ) -> HRESULT,
} }

View File

@@ -18,7 +18,7 @@ use windows_sys::{
}, },
}; };
use log::debug; use tracing::debug;
use crate::platform_impl::platform::{ use crate::platform_impl::platform::{
definitions::{IDataObjectVtbl, IDropTarget, IDropTargetVtbl, IUnknownVtbl}, definitions::{IDataObjectVtbl, IDropTarget, IDropTargetVtbl, IUnknownVtbl},

View File

@@ -536,7 +536,7 @@ impl ActiveEventLoop {
let inner = match WinCursor::new(&source.inner.0) { let inner = match WinCursor::new(&source.inner.0) {
Ok(cursor) => cursor, Ok(cursor) => cursor,
Err(err) => { Err(err) => {
log::warn!("Failed to create custom cursor: {err}"); tracing::warn!("Failed to create custom cursor: {err}");
WinCursor::Failed WinCursor::Failed
} }
}; };
@@ -1021,10 +1021,10 @@ pub(super) unsafe extern "system" fn public_window_callback(
let userdata_ptr = match (userdata, msg) { let userdata_ptr = match (userdata, msg) {
(0, WM_NCCREATE) => { (0, WM_NCCREATE) => {
let createstruct = unsafe { &mut *(lparam as *mut CREATESTRUCTW) }; let create_struct = unsafe { &mut *(lparam as *mut CREATESTRUCTW) };
let initdata = unsafe { &mut *(createstruct.lpCreateParams as *mut InitData<'_>) }; let init_data = unsafe { &mut *(create_struct.lpCreateParams as *mut InitData<'_>) };
let result = match unsafe { initdata.on_nccreate(window) } { let result = match unsafe { init_data.on_nccreate(window) } {
Some(userdata) => unsafe { Some(userdata) => unsafe {
super::set_window_long(window, GWL_USERDATA, userdata as _); super::set_window_long(window, GWL_USERDATA, userdata as _);
DefWindowProcW(window, msg, wparam, lparam) DefWindowProcW(window, msg, wparam, lparam)
@@ -1038,11 +1038,11 @@ pub(super) unsafe extern "system" fn public_window_callback(
// but we'll make window creation fail here just in case. // but we'll make window creation fail here just in case.
(0, WM_CREATE) => return -1, (0, WM_CREATE) => return -1,
(_, WM_CREATE) => unsafe { (_, WM_CREATE) => unsafe {
let createstruct = &mut *(lparam as *mut CREATESTRUCTW); let create_struct = &mut *(lparam as *mut CREATESTRUCTW);
let initdata = createstruct.lpCreateParams; let init_data = create_struct.lpCreateParams;
let initdata = &mut *(initdata as *mut InitData<'_>); let init_data = &mut *(init_data as *mut InitData<'_>);
initdata.on_create(); init_data.on_create();
return DefWindowProcW(window, msg, wparam, lparam); return DefWindowProcW(window, msg, wparam, lparam);
}, },
(0, _) => return unsafe { DefWindowProcW(window, msg, wparam, lparam) }, (0, _) => return unsafe { DefWindowProcW(window, msg, wparam, lparam) },
@@ -1147,7 +1147,7 @@ unsafe fn public_window_callback_inner(
// on all 4 borders would result in the caption getting drawn by the DWM. // on all 4 borders would result in the caption getting drawn by the DWM.
// //
// Another option would be to allow the DWM to paint inside the client area. // Another option would be to allow the DWM to paint inside the client area.
// Unfortunately this results in janky resize behavior, where the compositor is // Unfortunately this results in inconsistent resize behavior, where the compositor is
// ahead of the window surface. Currently, there seems no option to achieve this // ahead of the window surface. Currently, there seems no option to achieve this
// with the Windows API. // with the Windows API.
params.rgrc[0].top += 1; params.rgrc[0].top += 1;
@@ -1312,10 +1312,10 @@ unsafe fn public_window_callback_inner(
WM_WINDOWPOSCHANGED => { WM_WINDOWPOSCHANGED => {
use crate::event::WindowEvent::Moved; use crate::event::WindowEvent::Moved;
let windowpos = lparam as *const WINDOWPOS; let window_pos = lparam as *const WINDOWPOS;
if unsafe { (*windowpos).flags & SWP_NOMOVE != SWP_NOMOVE } { if unsafe { (*window_pos).flags & SWP_NOMOVE != SWP_NOMOVE } {
let physical_position = let physical_position =
unsafe { PhysicalPosition::new((*windowpos).x, (*windowpos).y) }; unsafe { PhysicalPosition::new((*window_pos).x, (*window_pos).y) };
userdata.send_event(Event::WindowEvent { userdata.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)), window_id: RootWindowId(WindowId(window)),
event: Moved(physical_position), event: Moved(physical_position),
@@ -1817,18 +1817,18 @@ unsafe fn public_window_callback_inner(
} }
WM_TOUCH => { WM_TOUCH => {
let pcount = super::loword(wparam as u32) as usize; let p_count = super::loword(wparam as u32) as usize;
let mut inputs = Vec::with_capacity(pcount); let mut inputs = Vec::with_capacity(p_count);
let htouch = lparam; let h_touch = lparam;
if unsafe { if unsafe {
GetTouchInputInfo( GetTouchInputInfo(
htouch, h_touch,
pcount as u32, p_count as u32,
inputs.as_mut_ptr(), inputs.as_mut_ptr(),
mem::size_of::<TOUCHINPUT>() as i32, mem::size_of::<TOUCHINPUT>() as i32,
) > 0 ) > 0
} { } {
unsafe { inputs.set_len(pcount) }; unsafe { inputs.set_len(p_count) };
for input in &inputs { for input in &inputs {
let mut location = POINT { let mut location = POINT {
x: input.x / 100, x: input.x / 100,
@@ -1862,7 +1862,7 @@ unsafe fn public_window_callback_inner(
}); });
} }
} }
unsafe { CloseTouchInputHandle(htouch) }; unsafe { CloseTouchInputHandle(h_touch) };
result = ProcResult::Value(0); result = ProcResult::Value(0);
} }
@@ -2557,7 +2557,7 @@ unsafe fn handle_raw_input(userdata: &ThreadMsgTargetData, data: RAWINPUT) {
} }
enum PointerMoveKind { enum PointerMoveKind {
/// Pointer enterd to the window. /// Pointer entered to the window.
Enter, Enter,
/// Pointer leaved the window client area. /// Pointer leaved the window client area.
Leave, Leave,

View File

@@ -399,19 +399,19 @@ impl<T> BufferedEvent<T> {
match self { match self {
Self::Event(event) => dispatch(event), Self::Event(event) => dispatch(event),
Self::ScaleFactorChanged(window_id, scale_factor, new_inner_size) => { Self::ScaleFactorChanged(window_id, scale_factor, new_inner_size) => {
let user_new_innner_size = Arc::new(Mutex::new(new_inner_size)); let user_new_inner_size = Arc::new(Mutex::new(new_inner_size));
dispatch(Event::WindowEvent { dispatch(Event::WindowEvent {
window_id, window_id,
event: WindowEvent::ScaleFactorChanged { event: WindowEvent::ScaleFactorChanged {
scale_factor, scale_factor,
inner_size_writer: InnerSizeWriter::new(Arc::downgrade( inner_size_writer: InnerSizeWriter::new(Arc::downgrade(
&user_new_innner_size, &user_new_inner_size,
)), )),
}, },
}); });
let inner_size = *user_new_innner_size.lock().unwrap(); let inner_size = *user_new_inner_size.lock().unwrap();
drop(user_new_innner_size); drop(user_new_inner_size);
if inner_size != new_inner_size { if inner_size != new_inner_size {
let window_flags = unsafe { let window_flags = unsafe {

View File

@@ -45,12 +45,12 @@ impl ImeContext {
let mut boundary_before_char = 0; let mut boundary_before_char = 0;
for (attr, chr) in attrs.into_iter().zip(text.chars()) { for (attr, chr) in attrs.into_iter().zip(text.chars()) {
let char_is_targetted = let char_is_targeted =
attr as u32 == ATTR_TARGET_CONVERTED || attr as u32 == ATTR_TARGET_NOTCONVERTED; attr as u32 == ATTR_TARGET_CONVERTED || attr as u32 == ATTR_TARGET_NOTCONVERTED;
if first.is_none() && char_is_targetted { if first.is_none() && char_is_targeted {
first = Some(boundary_before_char); first = Some(boundary_before_char);
} else if first.is_some() && last.is_none() && !char_is_targetted { } else if first.is_some() && last.is_none() && !char_is_targeted {
last = Some(boundary_before_char); last = Some(boundary_before_char);
} }

View File

@@ -32,8 +32,8 @@ use windows_sys::Win32::{
}, },
}; };
use log::{trace, warn};
use smol_str::SmolStr; use smol_str::SmolStr;
use tracing::{trace, warn};
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use crate::{ use crate::{
@@ -42,7 +42,7 @@ use crate::{
platform_impl::platform::{ platform_impl::platform::{
event_loop::ProcResult, event_loop::ProcResult,
keyboard_layout::{Layout, LayoutCache, WindowsModifiers, LAYOUT_CACHE}, keyboard_layout::{Layout, LayoutCache, WindowsModifiers, LAYOUT_CACHE},
loword, primarylangid, KeyEventExtra, loword, primary_lang_id, KeyEventExtra,
}, },
}; };
@@ -112,7 +112,7 @@ impl KeyEventBuilder {
MatchResult::MessagesToDispatch(self.pending.complete_multi(key_events)) MatchResult::MessagesToDispatch(self.pending.complete_multi(key_events))
} }
WM_KILLFOCUS => { WM_KILLFOCUS => {
// sythesize keyup events // synthesize keyup events
let kbd_state = get_kbd_state(); let kbd_state = get_kbd_state();
let key_events = Self::synthesize_kbd_state(ElementState::Released, &kbd_state); let key_events = Self::synthesize_kbd_state(ElementState::Released, &kbd_state);
MatchResult::MessagesToDispatch(self.pending.complete_multi(key_events)) MatchResult::MessagesToDispatch(self.pending.complete_multi(key_events))
@@ -230,7 +230,7 @@ impl KeyEventBuilder {
.unwrap_or(false); .unwrap_or(false);
if more_char_coming { if more_char_coming {
// No need to produce an event just yet, because there are still more characters that // No need to produce an event just yet, because there are still more characters that
// need to appended to this keyobard event // need to appended to this keyboard event
MatchResult::TokenToRemove(pending_token) MatchResult::TokenToRemove(pending_token)
} else { } else {
let mut event_info = self.event_info.lock().unwrap(); let mut event_info = self.event_info.lock().unwrap();
@@ -328,7 +328,7 @@ impl KeyEventBuilder {
} }
} }
// Allowing nominimal_bool lint because the `is_key_pressed` macro triggers this warning // Allowing nonminimal_bool lint because the `is_key_pressed` macro triggers this warning
// and I don't know of another way to resolve it and also keeping the macro // and I don't know of another way to resolve it and also keeping the macro
#[allow(clippy::nonminimal_bool)] #[allow(clippy::nonminimal_bool)]
fn synthesize_kbd_state( fn synthesize_kbd_state(
@@ -454,7 +454,7 @@ impl KeyEventBuilder {
return None; return None;
} }
let scancode = scancode as ExScancode; let scancode = scancode as ExScancode;
let physical_key = scancode_to_physicalkey(scancode as u32); let physical_key = scancode_to_physical_key(scancode as u32);
let mods = if caps_lock_on { let mods = if caps_lock_on {
WindowsModifiers::CAPS_LOCK WindowsModifiers::CAPS_LOCK
} else { } else {
@@ -499,7 +499,7 @@ enum PartialText {
enum PartialLogicalKey { enum PartialLogicalKey {
/// Use the text provided by the WM_CHAR messages and report that as a `Character` variant. If /// Use the text provided by the WM_CHAR messages and report that as a `Character` variant. If
/// the text consists of multiple grapheme clusters (user-precieved characters) that means that /// the text consists of multiple grapheme clusters (user-perceived characters) that means that
/// dead key could not be combined with the second input, and in that case we should fall back /// dead key could not be combined with the second input, and in that case we should fall back
/// to using what would have without a dead-key input. /// to using what would have without a dead-key input.
TextOr(Key), TextOr(Key),
@@ -544,7 +544,7 @@ impl PartialKeyEventInfo {
} else { } else {
new_ex_scancode(lparam_struct.scancode, lparam_struct.extended) new_ex_scancode(lparam_struct.scancode, lparam_struct.extended)
}; };
let physical_key = scancode_to_physicalkey(scancode as u32); let physical_key = scancode_to_physical_key(scancode as u32);
let location = get_location(scancode, layout.hkl as HKL); let location = get_location(scancode, layout.hkl as HKL);
let kbd_state = get_kbd_state(); let kbd_state = get_kbd_state();
@@ -589,7 +589,7 @@ impl PartialKeyEventInfo {
// We convert dead keys into their character. // We convert dead keys into their character.
// The reason for this is that `key_without_modifiers` is designed for key-bindings, // The reason for this is that `key_without_modifiers` is designed for key-bindings,
// but the US International layout treats `'` (apostrophe) as a dead key and the // but the US International layout treats `'` (apostrophe) as a dead key and the
// reguar US layout treats it a character. In order for a single binding // regular US layout treats it a character. In order for a single binding
// configuration to work with both layouts, we forward each dead key as a character. // configuration to work with both layouts, we forward each dead key as a character.
Key::Dead(k) => { Key::Dead(k) => {
if let Some(ch) = k { if let Some(ch) = k {
@@ -741,15 +741,15 @@ fn get_async_kbd_state() -> [u8; 256] {
/// every AltGr key-press (and key-release). We check if the current event is a Ctrl event and if /// every AltGr key-press (and key-release). We check if the current event is a Ctrl event and if
/// the next event is a right Alt (AltGr) event. If this is the case, the current event must be the /// the next event is a right Alt (AltGr) event. If this is the case, the current event must be the
/// fake Ctrl event. /// fake Ctrl event.
fn is_current_fake(curr_info: &PartialKeyEventInfo, next_msg: MSG, layout: &Layout) -> bool { fn is_current_fake(current_info: &PartialKeyEventInfo, next_msg: MSG, layout: &Layout) -> bool {
let curr_is_ctrl = matches!( let current_is_ctrl = matches!(
curr_info.logical_key, current_info.logical_key,
PartialLogicalKey::This(Key::Named(NamedKey::Control)) PartialLogicalKey::This(Key::Named(NamedKey::Control))
); );
if layout.has_alt_graph { if layout.has_alt_graph {
let next_code = ex_scancode_from_lparam(next_msg.lParam); let next_code = ex_scancode_from_lparam(next_msg.lParam);
let next_is_altgr = next_code == 0xE038; // 0xE038 is right alt let next_is_altgr = next_code == 0xE038; // 0xE038 is right alt
if curr_is_ctrl && next_is_altgr { if current_is_ctrl && next_is_altgr {
return true; return true;
} }
} }
@@ -942,12 +942,12 @@ fn get_location(scancode: ExScancode, hkl: HKL) -> KeyLocation {
} }
} }
pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> { pub(crate) fn physical_key_to_scancode(physical_key: PhysicalKey) -> Option<u32> {
// See `scancode_to_physicalkey` for more info // See `scancode_to_physical_key` for more info
let hkl = unsafe { GetKeyboardLayout(0) }; let hkl = unsafe { GetKeyboardLayout(0) };
let primary_lang_id = primarylangid(loword(hkl as u32)); let primary_lang_id = primary_lang_id(loword(hkl as u32));
let is_korean = primary_lang_id as u32 == LANG_KOREAN; let is_korean = primary_lang_id as u32 == LANG_KOREAN;
let code = match physical_key { let code = match physical_key {
@@ -1124,7 +1124,7 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
} }
} }
pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { pub(crate) fn scancode_to_physical_key(scancode: u32) -> PhysicalKey {
// See: https://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html // See: https://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html
// and: https://www.w3.org/TR/uievents-code/ // and: https://www.w3.org/TR/uievents-code/
// and: The widget/NativeKeyToDOMCodeName.h file in the firefox source // and: The widget/NativeKeyToDOMCodeName.h file in the firefox source

View File

@@ -53,7 +53,7 @@ use windows_sys::Win32::{
use crate::{ use crate::{
keyboard::{Key, KeyCode, ModifiersState, NamedKey, NativeKey, PhysicalKey}, keyboard::{Key, KeyCode, ModifiersState, NamedKey, NativeKey, PhysicalKey},
platform_impl::{loword, primarylangid, scancode_to_physicalkey}, platform_impl::{loword, primary_lang_id, scancode_to_physical_key},
}; };
pub(crate) static LAYOUT_CACHE: Lazy<Mutex<LayoutCache>> = pub(crate) static LAYOUT_CACHE: Lazy<Mutex<LayoutCache>> =
@@ -121,12 +121,12 @@ impl WindowsModifiers {
let rshift = key_state[VK_RSHIFT as usize] & 0x80 != 0; let rshift = key_state[VK_RSHIFT as usize] & 0x80 != 0;
let control = key_state[VK_CONTROL as usize] & 0x80 != 0; let control = key_state[VK_CONTROL as usize] & 0x80 != 0;
let lcontrol = key_state[VK_LCONTROL as usize] & 0x80 != 0; let l_control = key_state[VK_LCONTROL as usize] & 0x80 != 0;
let rcontrol = key_state[VK_RCONTROL as usize] & 0x80 != 0; let r_control = key_state[VK_RCONTROL as usize] & 0x80 != 0;
let alt = key_state[VK_MENU as usize] & 0x80 != 0; let alt = key_state[VK_MENU as usize] & 0x80 != 0;
let lalt = key_state[VK_LMENU as usize] & 0x80 != 0; let l_alt = key_state[VK_LMENU as usize] & 0x80 != 0;
let ralt = key_state[VK_RMENU as usize] & 0x80 != 0; let r_alt = key_state[VK_RMENU as usize] & 0x80 != 0;
let caps = key_state[VK_CAPITAL as usize] & 0x01 != 0; let caps = key_state[VK_CAPITAL as usize] & 0x01 != 0;
@@ -134,10 +134,10 @@ impl WindowsModifiers {
if shift || lshift || rshift { if shift || lshift || rshift {
result.insert(WindowsModifiers::SHIFT); result.insert(WindowsModifiers::SHIFT);
} }
if control || lcontrol || rcontrol { if control || l_control || r_control {
result.insert(WindowsModifiers::CONTROL); result.insert(WindowsModifiers::CONTROL);
} }
if alt || lalt || ralt { if alt || l_alt || r_alt {
result.insert(WindowsModifiers::ALT); result.insert(WindowsModifiers::ALT);
} }
if caps { if caps {
@@ -335,7 +335,7 @@ impl LayoutCache {
if scancode == 0 { if scancode == 0 {
continue; continue;
} }
let keycode = match scancode_to_physicalkey(scancode) { let keycode = match scancode_to_physical_key(scancode) {
PhysicalKey::Code(code) => code, PhysicalKey::Code(code) => code,
// TODO: validate that we can skip on unidentified keys (probably never occurs?) // TODO: validate that we can skip on unidentified keys (probably never occurs?)
_ => continue, _ => continue,
@@ -387,7 +387,7 @@ impl LayoutCache {
} }
let native_code = NativeKey::Windows(vk as VIRTUAL_KEY); let native_code = NativeKey::Windows(vk as VIRTUAL_KEY);
let key_code = match scancode_to_physicalkey(scancode) { let key_code = match scancode_to_physical_key(scancode) {
PhysicalKey::Code(code) => code, PhysicalKey::Code(code) => code,
// TODO: validate that we can skip on unidentified keys (probably never occurs?) // TODO: validate that we can skip on unidentified keys (probably never occurs?)
_ => continue, _ => continue,
@@ -542,7 +542,7 @@ fn is_numpad_specific(vk: VIRTUAL_KEY) -> bool {
} }
fn keycode_to_vkey(keycode: KeyCode, hkl: u64) -> VIRTUAL_KEY { fn keycode_to_vkey(keycode: KeyCode, hkl: u64) -> VIRTUAL_KEY {
let primary_lang_id = primarylangid(loword(hkl as u32)); let primary_lang_id = primary_lang_id(loword(hkl as u32));
let is_korean = primary_lang_id as u32 == LANG_KOREAN; let is_korean = primary_lang_id as u32 == LANG_KOREAN;
let is_japanese = primary_lang_id as u32 == LANG_JAPANESE; let is_japanese = primary_lang_id as u32 == LANG_JAPANESE;
@@ -763,7 +763,7 @@ fn vkey_to_non_char_key(
// List of the Web key names and their corresponding platform-native key names: // List of the Web key names and their corresponding platform-native key names:
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
let primary_lang_id = primarylangid(loword(hkl as u32)); let primary_lang_id = primary_lang_id(loword(hkl as u32));
let is_korean = primary_lang_id as u32 == LANG_KOREAN; let is_korean = primary_lang_id as u32 == LANG_KOREAN;
let is_japanese = primary_lang_id as u32 == LANG_JAPANESE; let is_japanese = primary_lang_id as u32 == LANG_JAPANESE;

View File

@@ -12,7 +12,7 @@ pub(crate) use self::{
PlatformSpecificEventLoopAttributes, PlatformSpecificEventLoopAttributes,
}, },
icon::{SelectedCursor, WinIcon}, icon::{SelectedCursor, WinIcon},
keyboard::{physicalkey_to_scancode, scancode_to_physicalkey}, keyboard::{physical_key_to_scancode, scancode_to_physical_key},
monitor::{MonitorHandle, VideoModeHandle}, monitor::{MonitorHandle, VideoModeHandle},
window::Window, window::Window,
}; };
@@ -148,7 +148,7 @@ const fn get_y_lparam(x: u32) -> i16 {
} }
#[inline(always)] #[inline(always)]
pub(crate) const fn primarylangid(lgid: u16) -> u16 { pub(crate) const fn primary_lang_id(lgid: u16) -> u16 {
lgid & 0x3FF lgid & 0x3FF
} }
@@ -163,24 +163,26 @@ const fn hiword(x: u32) -> u16 {
} }
#[inline(always)] #[inline(always)]
unsafe fn get_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX) -> isize { unsafe fn get_window_long(hwnd: HWND, n_index: WINDOW_LONG_PTR_INDEX) -> isize {
#[cfg(target_pointer_width = "64")] #[cfg(target_pointer_width = "64")]
return unsafe { windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongPtrW(hwnd, nindex) }; return unsafe {
windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongPtrW(hwnd, n_index)
};
#[cfg(target_pointer_width = "32")] #[cfg(target_pointer_width = "32")]
return unsafe { return unsafe {
windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongW(hwnd, nindex) as isize windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongW(hwnd, n_index) as isize
}; };
} }
#[inline(always)] #[inline(always)]
unsafe fn set_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX, dwnewlong: isize) -> isize { unsafe fn set_window_long(hwnd: HWND, n_index: WINDOW_LONG_PTR_INDEX, new_long: isize) -> isize {
#[cfg(target_pointer_width = "64")] #[cfg(target_pointer_width = "64")]
return unsafe { return unsafe {
windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongPtrW(hwnd, nindex, dwnewlong) windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongPtrW(hwnd, n_index, new_long)
}; };
#[cfg(target_pointer_width = "32")] #[cfg(target_pointer_width = "32")]
return unsafe { return unsafe {
windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongW(hwnd, nindex, dwnewlong as i32) windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongW(hwnd, n_index, new_long as i32)
as isize as isize
}; };
} }

View File

@@ -236,7 +236,7 @@ impl MonitorHandle {
let monitor_info = match get_monitor_info(self.0) { let monitor_info = match get_monitor_info(self.0) {
Ok(monitor_info) => monitor_info, Ok(monitor_info) => monitor_info,
Err(error) => { Err(error) => {
log::warn!("Error from get_monitor_info: {error}"); tracing::warn!("Error from get_monitor_info: {error}");
return modes.into_iter().map(mod_map); return modes.into_iter().map(mod_map);
} }
}; };

View File

@@ -27,7 +27,7 @@ use windows_sys::Win32::{
}, },
}; };
use super::scancode_to_physicalkey; use super::scancode_to_physical_key;
use crate::{ use crate::{
event::ElementState, event::ElementState,
event_loop::DeviceEvents, event_loop::DeviceEvents,
@@ -152,7 +152,7 @@ pub fn register_all_mice_and_keyboards_for_raw_input(
mut window_handle: HWND, mut window_handle: HWND,
filter: DeviceEvents, filter: DeviceEvents,
) -> bool { ) -> bool {
// RIDEV_DEVNOTIFY: receive hotplug events // RIDEV_DEVNOTIFY: receive hot-plug events
// RIDEV_INPUTSINK: receive events even if we're not in the foreground // RIDEV_INPUTSINK: receive events even if we're not in the foreground
// RIDEV_REMOVE: don't receive device events (requires NULL hwndTarget) // RIDEV_REMOVE: don't receive device events (requires NULL hwndTarget)
let flags = match filter { let flags = match filter {
@@ -249,16 +249,16 @@ pub fn get_keyboard_physical_key(keyboard: RAWKEYBOARD) -> Option<PhysicalKey> {
if scancode == 0xE11D || scancode == 0xE02A { if scancode == 0xE11D || scancode == 0xE02A {
// At the hardware (or driver?) level, pressing the Pause key is equivalent to pressing // At the hardware (or driver?) level, pressing the Pause key is equivalent to pressing
// Ctrl+NumLock. // Ctrl+NumLock.
// This equvalence means that if the user presses Pause, the keyboard will emit two // This equivalence means that if the user presses Pause, the keyboard will emit two
// subsequent key presses: // subsequent key presses:
// 1, 0xE11D - Which is a left Ctrl (0x1D) with an extension flag (0xE100) // 1, 0xE11D - Which is a left Ctrl (0x1D) with an extension flag (0xE100)
// 2, 0x0045 - Which on its own can be interpreted as Pause // 2, 0x0045 - Which on its own can be interpreted as Pause
// //
// There's another combination which isn't quite an equivalence: // There's another combination which isn't quite an equivalence:
// PrtSc used to be Shift+Asterisk. This means that on some keyboards, presssing // PrtSc used to be Shift+Asterisk. This means that on some keyboards, pressing
// PrtSc (print screen) produces the following sequence: // PrtSc (print screen) produces the following sequence:
// 1, 0xE02A - Which is a left shift (0x2A) with an extension flag (0xE000) // 1, 0xE02A - Which is a left shift (0x2A) with an extension flag (0xE000)
// 2, 0xE037 - Which is a numpad multiply (0x37) with an exteion flag (0xE000). This on // 2, 0xE037 - Which is a numpad multiply (0x37) with an extension flag (0xE000). This on
// its own it can be interpreted as PrtSc // its own it can be interpreted as PrtSc
// //
// For this reason, if we encounter the first keypress, we simply ignore it, trusting // For this reason, if we encounter the first keypress, we simply ignore it, trusting
@@ -284,7 +284,7 @@ pub fn get_keyboard_physical_key(keyboard: RAWKEYBOARD) -> Option<PhysicalKey> {
// https://devblogs.microsoft.com/oldnewthing/20080211-00/?p=23503 // https://devblogs.microsoft.com/oldnewthing/20080211-00/?p=23503
PhysicalKey::Code(KeyCode::NumLock) PhysicalKey::Code(KeyCode::NumLock)
} else { } else {
scancode_to_physicalkey(scancode as u32) scancode_to_physical_key(scancode as u32)
}; };
if keyboard.VKey == VK_SHIFT { if keyboard.VKey == VK_SHIFT {
if let PhysicalKey::Code(code) = physical_key { if let PhysicalKey::Code(code) = physical_key {

View File

@@ -59,7 +59,7 @@ use windows_sys::Win32::{
}, },
}; };
use log::warn; use tracing::warn;
use crate::{ use crate::{
cursor::Cursor, cursor::Cursor,
@@ -1406,7 +1406,7 @@ unsafe fn init(
let menu = attributes.platform_specific.menu; let menu = attributes.platform_specific.menu;
let fullscreen = attributes.fullscreen.clone(); let fullscreen = attributes.fullscreen.clone();
let maximized = attributes.maximized; let maximized = attributes.maximized;
let mut initdata = InitData { let mut init_data = InitData {
event_loop, event_loop,
attributes, attributes,
window_flags, window_flags,
@@ -1427,7 +1427,7 @@ unsafe fn init(
parent.unwrap_or(0), parent.unwrap_or(0),
menu.unwrap_or(0), menu.unwrap_or(0),
util::get_instance_handle(), util::get_instance_handle(),
&mut initdata as *mut _ as *mut _, &mut init_data as *mut _ as *mut _,
) )
}; };
@@ -1442,7 +1442,7 @@ unsafe fn init(
// If the handle is non-null, then window creation must have succeeded, which means // If the handle is non-null, then window creation must have succeeded, which means
// that we *must* have populated the `InitData.window` field. // that we *must* have populated the `InitData.window` field.
let win = initdata.window.unwrap(); let win = init_data.window.unwrap();
// Need to set FULLSCREEN or MAXIMIZED after CreateWindowEx // 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. // This is because if the size is changed in WM_CREATE, the restored size will be stored in that size.

View File

@@ -416,7 +416,7 @@ impl WindowFlags {
0, 0,
); );
// This condition is necessary to avoid having an unrestorable window // This condition is necessary to avoid having an un-restorable window
if !new.contains(WindowFlags::MINIMIZED) { if !new.contains(WindowFlags::MINIMIZED) {
SetWindowLongW(window, GWL_STYLE, style as i32); SetWindowLongW(window, GWL_STYLE, style as i32);
SetWindowLongW(window, GWL_EXSTYLE, style_ex as i32); SetWindowLongW(window, GWL_EXSTYLE, style_ex as i32);
@@ -450,7 +450,7 @@ impl WindowFlags {
let mut style = GetWindowLongW(hwnd, GWL_STYLE) as u32; let mut style = GetWindowLongW(hwnd, GWL_STYLE) as u32;
let style_ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32; let style_ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32;
// Frameless style implemented by manually overriding the non-client area in `WM_NCCALCSIZE`. // Frame-less style implemented by manually overriding the non-client area in `WM_NCCALCSIZE`.
if !self.contains(WindowFlags::MARKER_DECORATIONS) { if !self.contains(WindowFlags::MARKER_DECORATIONS) {
style &= !(WS_CAPTION | WS_SIZEBOX); style &= !(WS_CAPTION | WS_SIZEBOX);
} }

View File

@@ -1,5 +1,5 @@
// A poly-fill for `lazy_cell` // A poly-fill for `lazy_cell`
// Replace with std::sync::LazyLock when https://github.com/rust-lang/rust/issues/109736 is stablized. // Replace with std::sync::LazyLock when https://github.com/rust-lang/rust/issues/109736 is stabilized.
// This isn't used on every platform, which can come up as dead code warnings. // This isn't used on every platform, which can come up as dead code warnings.
#![allow(dead_code)] #![allow(dead_code)]

View File

@@ -70,8 +70,8 @@ pub struct Window {
} }
impl fmt::Debug for Window { impl fmt::Debug for Window {
fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmtr.pad("Window { .. }") formatter.pad("Window { .. }")
} }
} }
@@ -528,6 +528,8 @@ impl Window {
/// Returns an identifier unique to the window. /// Returns an identifier unique to the window.
#[inline] #[inline]
pub fn id(&self) -> WindowId { pub fn id(&self) -> WindowId {
let _span = tracing::debug_span!("winit::Window::id",).entered();
self.window.maybe_wait_on_main(|w| WindowId(w.id())) self.window.maybe_wait_on_main(|w| WindowId(w.id()))
} }
@@ -591,6 +593,8 @@ impl Window {
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
#[inline] #[inline]
pub fn scale_factor(&self) -> f64 { pub fn scale_factor(&self) -> f64 {
let _span = tracing::debug_span!("winit::Window::scale_factor",).entered();
self.window.maybe_wait_on_main(|w| w.scale_factor()) self.window.maybe_wait_on_main(|w| w.scale_factor())
} }
@@ -622,6 +626,8 @@ impl Window {
/// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested
#[inline] #[inline]
pub fn request_redraw(&self) { pub fn request_redraw(&self) {
let _span = tracing::debug_span!("winit::Window::request_redraw",).entered();
self.window.maybe_queue_on_main(|w| w.request_redraw()) self.window.maybe_queue_on_main(|w| w.request_redraw())
} }
@@ -658,6 +664,8 @@ impl Window {
/// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested
#[inline] #[inline]
pub fn pre_present_notify(&self) { pub fn pre_present_notify(&self) {
let _span = tracing::debug_span!("winit::Window::pre_present_notify",).entered();
self.window.maybe_queue_on_main(|w| w.pre_present_notify()); self.window.maybe_queue_on_main(|w| w.pre_present_notify());
} }
@@ -674,6 +682,8 @@ impl Window {
// at least, then this function should be provided through a platform specific // at least, then this function should be provided through a platform specific
// extension trait // extension trait
pub fn reset_dead_keys(&self) { pub fn reset_dead_keys(&self) {
let _span = tracing::debug_span!("winit::Window::reset_dead_keys",).entered();
self.window.maybe_queue_on_main(|w| w.reset_dead_keys()) self.window.maybe_queue_on_main(|w| w.reset_dead_keys())
} }
} }
@@ -696,6 +706,8 @@ impl Window {
/// [safe area]: https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc /// [safe area]: https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc
#[inline] #[inline]
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
let _span = tracing::debug_span!("winit::Window::inner_position",).entered();
self.window.maybe_wait_on_main(|w| w.inner_position()) self.window.maybe_wait_on_main(|w| w.inner_position())
} }
@@ -717,6 +729,8 @@ impl Window {
/// - **Android / Wayland:** Always returns [`NotSupportedError`]. /// - **Android / Wayland:** Always returns [`NotSupportedError`].
#[inline] #[inline]
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
let _span = tracing::debug_span!("winit::Window::outer_position",).entered();
self.window.maybe_wait_on_main(|w| w.outer_position()) self.window.maybe_wait_on_main(|w| w.outer_position())
} }
@@ -749,6 +763,12 @@ impl Window {
#[inline] #[inline]
pub fn set_outer_position<P: Into<Position>>(&self, position: P) { pub fn set_outer_position<P: Into<Position>>(&self, position: P) {
let position = position.into(); let position = position.into();
let _span = tracing::debug_span!(
"winit::Window::set_outer_position",
position = ?position
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_outer_position(position)) .maybe_queue_on_main(move |w| w.set_outer_position(position))
} }
@@ -767,6 +787,8 @@ impl Window {
/// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
#[inline] #[inline]
pub fn inner_size(&self) -> PhysicalSize<u32> { pub fn inner_size(&self) -> PhysicalSize<u32> {
let _span = tracing::debug_span!("winit::Window::inner_size",).entered();
self.window.maybe_wait_on_main(|w| w.inner_size()) self.window.maybe_wait_on_main(|w| w.inner_size())
} }
@@ -808,6 +830,11 @@ impl Window {
#[must_use] #[must_use]
pub fn request_inner_size<S: Into<Size>>(&self, size: S) -> Option<PhysicalSize<u32>> { pub fn request_inner_size<S: Into<Size>>(&self, size: S) -> Option<PhysicalSize<u32>> {
let size = size.into(); let size = size.into();
let _span = tracing::debug_span!(
"winit::Window::request_inner_size",
size = ?size
)
.entered();
self.window self.window
.maybe_wait_on_main(|w| w.request_inner_size(size)) .maybe_wait_on_main(|w| w.request_inner_size(size))
} }
@@ -825,6 +852,7 @@ impl Window {
/// [`Window::inner_size`]._ /// [`Window::inner_size`]._
#[inline] #[inline]
pub fn outer_size(&self) -> PhysicalSize<u32> { pub fn outer_size(&self) -> PhysicalSize<u32> {
let _span = tracing::debug_span!("winit::Window::outer_size",).entered();
self.window.maybe_wait_on_main(|w| w.outer_size()) self.window.maybe_wait_on_main(|w| w.outer_size())
} }
@@ -848,6 +876,11 @@ impl Window {
#[inline] #[inline]
pub fn set_min_inner_size<S: Into<Size>>(&self, min_size: Option<S>) { pub fn set_min_inner_size<S: Into<Size>>(&self, min_size: Option<S>) {
let min_size = min_size.map(|s| s.into()); let min_size = min_size.map(|s| s.into());
let _span = tracing::debug_span!(
"winit::Window::set_min_inner_size",
min_size = ?min_size
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_min_inner_size(min_size)) .maybe_queue_on_main(move |w| w.set_min_inner_size(min_size))
} }
@@ -872,6 +905,11 @@ impl Window {
#[inline] #[inline]
pub fn set_max_inner_size<S: Into<Size>>(&self, max_size: Option<S>) { pub fn set_max_inner_size<S: Into<Size>>(&self, max_size: Option<S>) {
let max_size = max_size.map(|s| s.into()); let max_size = max_size.map(|s| s.into());
let _span = tracing::debug_span!(
"winit::Window::max_size",
max_size = ?max_size
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_max_inner_size(max_size)) .maybe_queue_on_main(move |w| w.set_max_inner_size(max_size))
} }
@@ -883,6 +921,7 @@ impl Window {
/// - **iOS / Android / Web / Wayland / Windows / Orbital:** Always returns [`None`]. /// - **iOS / Android / Web / Wayland / Windows / Orbital:** Always returns [`None`].
#[inline] #[inline]
pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> {
let _span = tracing::debug_span!("winit::Window::resize_increments",).entered();
self.window.maybe_wait_on_main(|w| w.resize_increments()) self.window.maybe_wait_on_main(|w| w.resize_increments())
} }
@@ -899,6 +938,11 @@ impl Window {
#[inline] #[inline]
pub fn set_resize_increments<S: Into<Size>>(&self, increments: Option<S>) { pub fn set_resize_increments<S: Into<Size>>(&self, increments: Option<S>) {
let increments = increments.map(Into::into); let increments = increments.map(Into::into);
let _span = tracing::debug_span!(
"winit::Window::set_resize_increments",
increments = ?increments
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_resize_increments(increments)) .maybe_queue_on_main(move |w| w.set_resize_increments(increments))
} }
@@ -913,6 +957,7 @@ impl Window {
/// - **iOS / Android:** Unsupported. /// - **iOS / Android:** Unsupported.
#[inline] #[inline]
pub fn set_title(&self, title: &str) { pub fn set_title(&self, title: &str) {
let _span = tracing::debug_span!("winit::Window::set_title", title).entered();
self.window.maybe_wait_on_main(|w| w.set_title(title)) self.window.maybe_wait_on_main(|w| w.set_title(title))
} }
@@ -931,6 +976,7 @@ impl Window {
/// - **X11:** Can only be set while building the window, with [`WindowAttributes::with_transparent`]. /// - **X11:** Can only be set while building the window, with [`WindowAttributes::with_transparent`].
#[inline] #[inline]
pub fn set_transparent(&self, transparent: bool) { pub fn set_transparent(&self, transparent: bool) {
let _span = tracing::debug_span!("winit::Window::set_transparent", transparent).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_transparent(transparent)) .maybe_queue_on_main(move |w| w.set_transparent(transparent))
} }
@@ -945,6 +991,7 @@ impl Window {
/// - **Wayland:** Only works with org_kde_kwin_blur_manager protocol. /// - **Wayland:** Only works with org_kde_kwin_blur_manager protocol.
#[inline] #[inline]
pub fn set_blur(&self, blur: bool) { pub fn set_blur(&self, blur: bool) {
let _span = tracing::debug_span!("winit::Window::set_blur", blur).entered();
self.window.maybe_queue_on_main(move |w| w.set_blur(blur)) self.window.maybe_queue_on_main(move |w| w.set_blur(blur))
} }
@@ -958,6 +1005,7 @@ impl Window {
/// - **iOS:** Can only be called on the main thread. /// - **iOS:** Can only be called on the main thread.
#[inline] #[inline]
pub fn set_visible(&self, visible: bool) { pub fn set_visible(&self, visible: bool) {
let _span = tracing::debug_span!("winit::Window::set_visible", visible).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_visible(visible)) .maybe_queue_on_main(move |w| w.set_visible(visible))
} }
@@ -972,12 +1020,13 @@ impl Window {
/// - **Wayland / iOS / Android / Web:** Unsupported. /// - **Wayland / iOS / Android / Web:** Unsupported.
#[inline] #[inline]
pub fn is_visible(&self) -> Option<bool> { pub fn is_visible(&self) -> Option<bool> {
let _span = tracing::debug_span!("winit::Window::is_visible",).entered();
self.window.maybe_wait_on_main(|w| w.is_visible()) self.window.maybe_wait_on_main(|w| w.is_visible())
} }
/// Sets whether the window is resizable or not. /// Sets whether the window is resizable or not.
/// ///
/// Note that making the window unresizable doesn't exempt you from handling [`WindowEvent::Resized`], as that /// Note that making the window un-resizable doesn't exempt you from handling [`WindowEvent::Resized`], as that
/// event can still be triggered by DPI scaling, entering fullscreen mode, etc. Also, the /// event can still be triggered by DPI scaling, entering fullscreen mode, etc. Also, the
/// window could still be resized by calling [`Window::request_inner_size`]. /// window could still be resized by calling [`Window::request_inner_size`].
/// ///
@@ -991,6 +1040,7 @@ impl Window {
/// [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized /// [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized
#[inline] #[inline]
pub fn set_resizable(&self, resizable: bool) { pub fn set_resizable(&self, resizable: bool) {
let _span = tracing::debug_span!("winit::Window::set_resizable", resizable).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_resizable(resizable)) .maybe_queue_on_main(move |w| w.set_resizable(resizable))
} }
@@ -1003,6 +1053,7 @@ impl Window {
/// - **iOS / Android / Web:** Unsupported. /// - **iOS / Android / Web:** Unsupported.
#[inline] #[inline]
pub fn is_resizable(&self) -> bool { pub fn is_resizable(&self) -> bool {
let _span = tracing::debug_span!("winit::Window::is_resizable",).entered();
self.window.maybe_wait_on_main(|w| w.is_resizable()) self.window.maybe_wait_on_main(|w| w.is_resizable())
} }
@@ -1013,6 +1064,11 @@ impl Window {
/// - **Wayland / X11 / Orbital:** Not implemented. /// - **Wayland / X11 / Orbital:** Not implemented.
/// - **Web / iOS / Android:** Unsupported. /// - **Web / iOS / Android:** Unsupported.
pub fn set_enabled_buttons(&self, buttons: WindowButtons) { pub fn set_enabled_buttons(&self, buttons: WindowButtons) {
let _span = tracing::debug_span!(
"winit::Window::set_enabled_buttons",
buttons = ?buttons
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_enabled_buttons(buttons)) .maybe_queue_on_main(move |w| w.set_enabled_buttons(buttons))
} }
@@ -1024,6 +1080,7 @@ impl Window {
/// - **Wayland / X11 / Orbital:** Not implemented. Always returns [`WindowButtons::all`]. /// - **Wayland / X11 / Orbital:** Not implemented. Always returns [`WindowButtons::all`].
/// - **Web / iOS / Android:** Unsupported. Always returns [`WindowButtons::all`]. /// - **Web / iOS / Android:** Unsupported. Always returns [`WindowButtons::all`].
pub fn enabled_buttons(&self) -> WindowButtons { pub fn enabled_buttons(&self) -> WindowButtons {
let _span = tracing::debug_span!("winit::Window::enabled_buttons",).entered();
self.window.maybe_wait_on_main(|w| w.enabled_buttons()) self.window.maybe_wait_on_main(|w| w.enabled_buttons())
} }
@@ -1035,6 +1092,7 @@ impl Window {
/// - **Wayland:** Un-minimize is unsupported. /// - **Wayland:** Un-minimize is unsupported.
#[inline] #[inline]
pub fn set_minimized(&self, minimized: bool) { pub fn set_minimized(&self, minimized: bool) {
let _span = tracing::debug_span!("winit::Window::set_minimized", minimized).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_minimized(minimized)) .maybe_queue_on_main(move |w| w.set_minimized(minimized))
} }
@@ -1053,6 +1111,7 @@ impl Window {
/// - **iOS / Android / Web / Orbital:** Unsupported. /// - **iOS / Android / Web / Orbital:** Unsupported.
#[inline] #[inline]
pub fn is_minimized(&self) -> Option<bool> { pub fn is_minimized(&self) -> Option<bool> {
let _span = tracing::debug_span!("winit::Window::is_minimized",).entered();
self.window.maybe_wait_on_main(|w| w.is_minimized()) self.window.maybe_wait_on_main(|w| w.is_minimized())
} }
@@ -1063,6 +1122,7 @@ impl Window {
/// - **iOS / Android / Web:** Unsupported. /// - **iOS / Android / Web:** Unsupported.
#[inline] #[inline]
pub fn set_maximized(&self, maximized: bool) { pub fn set_maximized(&self, maximized: bool) {
let _span = tracing::debug_span!("winit::Window::set_maximized", maximized).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_maximized(maximized)) .maybe_queue_on_main(move |w| w.set_maximized(maximized))
} }
@@ -1074,6 +1134,7 @@ impl Window {
/// - **iOS / Android / Web:** Unsupported. /// - **iOS / Android / Web:** Unsupported.
#[inline] #[inline]
pub fn is_maximized(&self) -> bool { pub fn is_maximized(&self) -> bool {
let _span = tracing::debug_span!("winit::Window::is_maximized",).entered();
self.window.maybe_wait_on_main(|w| w.is_maximized()) self.window.maybe_wait_on_main(|w| w.is_maximized())
} }
@@ -1102,6 +1163,11 @@ impl Window {
/// [transient activation]: https://developer.mozilla.org/en-US/docs/Glossary/Transient_activation /// [transient activation]: https://developer.mozilla.org/en-US/docs/Glossary/Transient_activation
#[inline] #[inline]
pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
let _span = tracing::debug_span!(
"winit::Window::set_fullscreen",
fullscreen = ?fullscreen
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_fullscreen(fullscreen.map(|f| f.into()))) .maybe_queue_on_main(move |w| w.set_fullscreen(fullscreen.map(|f| f.into())))
} }
@@ -1116,6 +1182,7 @@ impl Window {
/// - **Web:** Can only return `None` or `Borderless(None)`. /// - **Web:** Can only return `None` or `Borderless(None)`.
#[inline] #[inline]
pub fn fullscreen(&self) -> Option<Fullscreen> { pub fn fullscreen(&self) -> Option<Fullscreen> {
let _span = tracing::debug_span!("winit::Window::fullscreen",).entered();
self.window self.window
.maybe_wait_on_main(|w| w.fullscreen().map(|f| f.into())) .maybe_wait_on_main(|w| w.fullscreen().map(|f| f.into()))
} }
@@ -1131,6 +1198,7 @@ impl Window {
/// - **iOS / Android / Web:** No effect. /// - **iOS / Android / Web:** No effect.
#[inline] #[inline]
pub fn set_decorations(&self, decorations: bool) { pub fn set_decorations(&self, decorations: bool) {
let _span = tracing::debug_span!("winit::Window::set_decorations", decorations).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_decorations(decorations)) .maybe_queue_on_main(move |w| w.set_decorations(decorations))
} }
@@ -1145,6 +1213,7 @@ impl Window {
/// - **iOS / Android / Web:** Always returns `true`. /// - **iOS / Android / Web:** Always returns `true`.
#[inline] #[inline]
pub fn is_decorated(&self) -> bool { pub fn is_decorated(&self) -> bool {
let _span = tracing::debug_span!("winit::Window::is_decorated",).entered();
self.window.maybe_wait_on_main(|w| w.is_decorated()) self.window.maybe_wait_on_main(|w| w.is_decorated())
} }
@@ -1154,6 +1223,11 @@ impl Window {
/// ///
/// See [`WindowLevel`] for details. /// See [`WindowLevel`] for details.
pub fn set_window_level(&self, level: WindowLevel) { pub fn set_window_level(&self, level: WindowLevel) {
let _span = tracing::debug_span!(
"winit::Window::set_window_level",
level = ?level
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_window_level(level)) .maybe_queue_on_main(move |w| w.set_window_level(level))
} }
@@ -1174,6 +1248,7 @@ impl Window {
/// said, it's usually in the same ballpark as on Windows. /// said, it's usually in the same ballpark as on Windows.
#[inline] #[inline]
pub fn set_window_icon(&self, window_icon: Option<Icon>) { pub fn set_window_icon(&self, window_icon: Option<Icon>) {
let _span = tracing::debug_span!("winit::Window::set_window_icon",).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_window_icon(window_icon)) .maybe_queue_on_main(move |w| w.set_window_icon(window_icon))
} }
@@ -1216,6 +1291,12 @@ impl Window {
pub fn set_ime_cursor_area<P: Into<Position>, S: Into<Size>>(&self, position: P, size: S) { pub fn set_ime_cursor_area<P: Into<Position>, S: Into<Size>>(&self, position: P, size: S) {
let position = position.into(); let position = position.into();
let size = size.into(); let size = size.into();
let _span = tracing::debug_span!(
"winit::Window::set_ime_cursor_area",
position = ?position,
size = ?size,
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_ime_cursor_area(position, size)) .maybe_queue_on_main(move |w| w.set_ime_cursor_area(position, size))
} }
@@ -1242,6 +1323,7 @@ impl Window {
/// [`KeyboardInput`]: crate::event::WindowEvent::KeyboardInput /// [`KeyboardInput`]: crate::event::WindowEvent::KeyboardInput
#[inline] #[inline]
pub fn set_ime_allowed(&self, allowed: bool) { pub fn set_ime_allowed(&self, allowed: bool) {
let _span = tracing::debug_span!("winit::Window::set_ime_allowed", allowed).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_ime_allowed(allowed)) .maybe_queue_on_main(move |w| w.set_ime_allowed(allowed))
} }
@@ -1253,6 +1335,11 @@ impl Window {
/// - **iOS / Android / Web / Windows / X11 / macOS / Orbital:** Unsupported. /// - **iOS / Android / Web / Windows / X11 / macOS / Orbital:** Unsupported.
#[inline] #[inline]
pub fn set_ime_purpose(&self, purpose: ImePurpose) { pub fn set_ime_purpose(&self, purpose: ImePurpose) {
let _span = tracing::debug_span!(
"winit::Window::set_ime_purpose",
purpose = ?purpose
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_ime_purpose(purpose)) .maybe_queue_on_main(move |w| w.set_ime_purpose(purpose))
} }
@@ -1269,6 +1356,7 @@ impl Window {
/// - **iOS / Android / Wayland / Orbital:** Unsupported. /// - **iOS / Android / Wayland / Orbital:** Unsupported.
#[inline] #[inline]
pub fn focus_window(&self) { pub fn focus_window(&self) {
let _span = tracing::debug_span!("winit::Window::focus_window",).entered();
self.window.maybe_queue_on_main(|w| w.focus_window()) self.window.maybe_queue_on_main(|w| w.focus_window())
} }
@@ -1279,6 +1367,7 @@ impl Window {
/// [`WindowEvent::Focused`]: crate::event::WindowEvent::Focused /// [`WindowEvent::Focused`]: crate::event::WindowEvent::Focused
#[inline] #[inline]
pub fn has_focus(&self) -> bool { pub fn has_focus(&self) -> bool {
let _span = tracing::debug_span!("winit::Window::has_focus",).entered();
self.window.maybe_wait_on_main(|w| w.has_focus()) self.window.maybe_wait_on_main(|w| w.has_focus())
} }
@@ -1286,7 +1375,7 @@ impl Window {
/// is already focused. How requesting for user attention manifests is platform dependent, /// is already focused. How requesting for user attention manifests is platform dependent,
/// see [`UserAttentionType`] for details. /// see [`UserAttentionType`] for details.
/// ///
/// Providing `None` will unset the request for user attention. Unsetting the request for /// Providing `None` will unset the request for user attention. Un-setting the request for
/// user attention might not be done automatically by the WM when the window receives input. /// user attention might not be done automatically by the WM when the window receives input.
/// ///
/// ## Platform-specific /// ## Platform-specific
@@ -1297,6 +1386,11 @@ impl Window {
/// - **Wayland:** Requires `xdg_activation_v1` protocol, `None` has no effect. /// - **Wayland:** Requires `xdg_activation_v1` protocol, `None` has no effect.
#[inline] #[inline]
pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) {
let _span = tracing::debug_span!(
"winit::Window::request_user_attention",
request_type = ?request_type
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.request_user_attention(request_type)) .maybe_queue_on_main(move |w| w.request_user_attention(request_type))
} }
@@ -1312,6 +1406,11 @@ impl Window {
/// - **iOS / Android / Web / Orbital:** Unsupported. /// - **iOS / Android / Web / Orbital:** Unsupported.
#[inline] #[inline]
pub fn set_theme(&self, theme: Option<Theme>) { pub fn set_theme(&self, theme: Option<Theme>) {
let _span = tracing::debug_span!(
"winit::Window::set_theme",
theme = ?theme
)
.entered();
self.window.maybe_queue_on_main(move |w| w.set_theme(theme)) self.window.maybe_queue_on_main(move |w| w.set_theme(theme))
} }
@@ -1323,6 +1422,7 @@ impl Window {
/// - **iOS / Android / Wayland / x11 / Orbital:** Unsupported. /// - **iOS / Android / Wayland / x11 / Orbital:** Unsupported.
#[inline] #[inline]
pub fn theme(&self) -> Option<Theme> { pub fn theme(&self) -> Option<Theme> {
let _span = tracing::debug_span!("winit::Window::theme",).entered();
self.window.maybe_wait_on_main(|w| w.theme()) self.window.maybe_wait_on_main(|w| w.theme())
} }
@@ -1336,6 +1436,8 @@ impl Window {
/// ///
/// [`NSWindowSharingNone`]: https://developer.apple.com/documentation/appkit/nswindowsharingtype/nswindowsharingnone /// [`NSWindowSharingNone`]: https://developer.apple.com/documentation/appkit/nswindowsharingtype/nswindowsharingnone
pub fn set_content_protected(&self, protected: bool) { pub fn set_content_protected(&self, protected: bool) {
let _span =
tracing::debug_span!("winit::Window::set_content_protected", protected).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_content_protected(protected)) .maybe_queue_on_main(move |w| w.set_content_protected(protected))
} }
@@ -1347,6 +1449,7 @@ impl Window {
/// - **iOS / Android / x11 / Wayland / Web:** Unsupported. Always returns an empty string. /// - **iOS / Android / x11 / Wayland / Web:** Unsupported. Always returns an empty string.
#[inline] #[inline]
pub fn title(&self) -> String { pub fn title(&self) -> String {
let _span = tracing::debug_span!("winit::Window::title",).entered();
self.window.maybe_wait_on_main(|w| w.title()) self.window.maybe_wait_on_main(|w| w.title())
} }
} }
@@ -1363,6 +1466,7 @@ impl Window {
#[inline] #[inline]
pub fn set_cursor(&self, cursor: impl Into<Cursor>) { pub fn set_cursor(&self, cursor: impl Into<Cursor>) {
let cursor = cursor.into(); let cursor = cursor.into();
let _span = tracing::debug_span!("winit::Window::set_cursor",).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_cursor(cursor)) .maybe_queue_on_main(move |w| w.set_cursor(cursor))
} }
@@ -1395,6 +1499,11 @@ impl Window {
#[inline] #[inline]
pub fn set_cursor_position<P: Into<Position>>(&self, position: P) -> Result<(), ExternalError> { pub fn set_cursor_position<P: Into<Position>>(&self, position: P) -> Result<(), ExternalError> {
let position = position.into(); let position = position.into();
let _span = tracing::debug_span!(
"winit::Window::set_cursor_position",
position = ?position
)
.entered();
self.window self.window
.maybe_wait_on_main(|w| w.set_cursor_position(position)) .maybe_wait_on_main(|w| w.set_cursor_position(position))
} }
@@ -1415,6 +1524,11 @@ impl Window {
/// ``` /// ```
#[inline] #[inline]
pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> {
let _span = tracing::debug_span!(
"winit::Window::set_cursor_grab",
mode = ?mode
)
.entered();
self.window.maybe_wait_on_main(|w| w.set_cursor_grab(mode)) self.window.maybe_wait_on_main(|w| w.set_cursor_grab(mode))
} }
@@ -1432,6 +1546,7 @@ impl Window {
/// - **iOS / Android:** Unsupported. /// - **iOS / Android:** Unsupported.
#[inline] #[inline]
pub fn set_cursor_visible(&self, visible: bool) { pub fn set_cursor_visible(&self, visible: bool) {
let _span = tracing::debug_span!("winit::Window::set_cursor_visible", visible).entered();
self.window self.window
.maybe_queue_on_main(move |w| w.set_cursor_visible(visible)) .maybe_queue_on_main(move |w| w.set_cursor_visible(visible))
} }
@@ -1449,6 +1564,7 @@ impl Window {
/// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`]. /// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`].
#[inline] #[inline]
pub fn drag_window(&self) -> Result<(), ExternalError> { pub fn drag_window(&self) -> Result<(), ExternalError> {
let _span = tracing::debug_span!("winit::Window::drag_window",).entered();
self.window.maybe_wait_on_main(|w| w.drag_window()) self.window.maybe_wait_on_main(|w| w.drag_window())
} }
@@ -1463,6 +1579,11 @@ impl Window {
/// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`]. /// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`].
#[inline] #[inline]
pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> { pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> {
let _span = tracing::debug_span!(
"winit::Window::drag_resize_window",
direction = ?direction
)
.entered();
self.window self.window
.maybe_wait_on_main(|w| w.drag_resize_window(direction)) .maybe_wait_on_main(|w| w.drag_resize_window(direction))
} }
@@ -1478,6 +1599,11 @@ impl Window {
/// [window menu]: https://en.wikipedia.org/wiki/Common_menus_in_Microsoft_Windows#System_menu /// [window menu]: https://en.wikipedia.org/wiki/Common_menus_in_Microsoft_Windows#System_menu
pub fn show_window_menu(&self, position: impl Into<Position>) { pub fn show_window_menu(&self, position: impl Into<Position>) {
let position = position.into(); let position = position.into();
let _span = tracing::debug_span!(
"winit::Window::show_window_menu",
position = ?position
)
.entered();
self.window self.window
.maybe_queue_on_main(move |w| w.show_window_menu(position)) .maybe_queue_on_main(move |w| w.show_window_menu(position))
} }
@@ -1492,6 +1618,7 @@ impl Window {
/// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`]. /// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`].
#[inline] #[inline]
pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> {
let _span = tracing::debug_span!("winit::Window::set_cursor_hittest", hittest).entered();
self.window self.window
.maybe_wait_on_main(|w| w.set_cursor_hittest(hittest)) .maybe_wait_on_main(|w| w.set_cursor_hittest(hittest))
} }
@@ -1504,6 +1631,7 @@ impl Window {
/// Returns `None` if current monitor can't be detected. /// Returns `None` if current monitor can't be detected.
#[inline] #[inline]
pub fn current_monitor(&self) -> Option<MonitorHandle> { pub fn current_monitor(&self) -> Option<MonitorHandle> {
let _span = tracing::debug_span!("winit::Window::current_monitor",).entered();
self.window self.window
.maybe_wait_on_main(|w| w.current_monitor().map(|inner| MonitorHandle { inner })) .maybe_wait_on_main(|w| w.current_monitor().map(|inner| MonitorHandle { inner }))
} }
@@ -1515,6 +1643,7 @@ impl Window {
/// [`ActiveEventLoop::available_monitors`]: crate::event_loop::ActiveEventLoop::available_monitors /// [`ActiveEventLoop::available_monitors`]: crate::event_loop::ActiveEventLoop::available_monitors
#[inline] #[inline]
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> { pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
let _span = tracing::debug_span!("winit::Window::available_monitors",).entered();
self.window.maybe_wait_on_main(|w| { self.window.maybe_wait_on_main(|w| {
w.available_monitors() w.available_monitors()
.into_iter() .into_iter()
@@ -1535,6 +1664,7 @@ impl Window {
/// [`ActiveEventLoop::primary_monitor`]: crate::event_loop::ActiveEventLoop::primary_monitor /// [`ActiveEventLoop::primary_monitor`]: crate::event_loop::ActiveEventLoop::primary_monitor
#[inline] #[inline]
pub fn primary_monitor(&self) -> Option<MonitorHandle> { pub fn primary_monitor(&self) -> Option<MonitorHandle> {
let _span = tracing::debug_span!("winit::Window::primary_monitor",).entered();
self.window self.window
.maybe_wait_on_main(|w| w.primary_monitor().map(|inner| MonitorHandle { inner })) .maybe_wait_on_main(|w| w.primary_monitor().map(|inner| MonitorHandle { inner }))
} }