diff --git a/Cargo.toml b/Cargo.toml
index faccd6c..681e6df 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -150,5 +150,16 @@ name = "chd_extract"
path = "src/bin/chd_extract.rs"
required-features = ["chd"]
+# Mac App Store fix (guideline 2.5.1): eframe's winit (0.30) calls the private
+# SkyLight API `CGSSetWindowBackgroundBlurRadius`, whose symbol Apple's binary
+# scan rejects. Our vendored copy stubs WindowDelegate::set_blur to a no-op and
+# drops the private extern declarations; iris-gui never requests window blur,
+# so behaviour is unchanged. Only the 0.30.x requirement (eframe → egui-winit →
+# glutin-winit) matches this patch; iris's own winit 0.29 dependency is the
+# keyboard-KeyCode type only and creates no window in iris-gui, so its blur code
+# is dead-stripped. See rules/macos/appstore-private-api.md.
+[patch.crates-io]
+winit = { path = "third_party/winit-0.30.13" }
+
diff --git a/docs/appstore-review-response.md b/docs/appstore-review-response.md
new file mode 100644
index 0000000..6cd9444
--- /dev/null
+++ b/docs/appstore-review-response.md
@@ -0,0 +1,108 @@
+# App Store review response — IRIS (Submission 2ed07ab1…)
+
+Covers the two issues raised on the 1.0 (20260610.2118) review (June 16, 2026):
+
+1. **Guideline 2.5.1** — private API `_CGSSetWindowBackgroundBlurRadius`.
+2. **Guideline 2.4.5(i)** — entitlements without obvious matching functionality
+ (`com.apple.security.device.camera`, `com.apple.security.network.server`).
+
+---
+
+## 1. Guideline 2.5.1 — private API (fixed in binary)
+
+The symbol came from the `winit` windowing crate (pulled in by `eframe`), whose
+macOS backend calls `CGSSetWindowBackgroundBlurRadius` in `WindowDelegate::set_blur`.
+IRIS never requests window blur, but the symbol is linked in regardless and
+Apple's static scan flags it.
+
+**Fix:** vendored a patched `winit` (`third_party/winit-0.30.13/`, wired via
+`[patch.crates-io]` in the root `Cargo.toml`) that removes the private extern
+declarations and makes `set_blur` a no-op. Verified the symbol is gone from the
+linked binary:
+
+```
+nm -u target/release/iris-gui | grep CGSSetWindowBackgroundBlurRadius # → no output
+```
+
+(`_CGShieldingWindowLevel` remains; it is a public CoreGraphics API and was not
+flagged.) See `rules/macos/appstore-private-api.md`.
+
+A new binary is required for this fix, so we also strengthened the two
+entitlements below with visible, testable functionality rather than removing
+them.
+
+---
+
+## 2. Guideline 2.4.5(i) — entitlement justifications
+
+Both entitlements back real functionality. To make them easy to verify we added
+in-app features that exercise each one directly, without needing to boot IRIX.
+
+### `com.apple.security.device.camera`
+
+**What it's for:** IRIS emulates the SGI Indy's **IndyCam** / VINO video-input
+hardware. When the user selects the host camera as the video source, IRIS
+captures live frames from the Mac's camera (AVFoundation) and feeds them to the
+emulated VINO device. The matching `NSCameraUsageDescription` is in `Info.plist`.
+
+**How to test (reviewer steps):**
+1. Launch IRIS. In the launcher, open the **Video-In** tab.
+2. Click **📷 Test Camera**.
+3. macOS shows the camera-permission prompt; allow it.
+4. A live preview from the Mac camera appears, with a status line showing the
+ capture resolution and a rising frame count. Closing the window releases the
+ camera (indicator light turns off).
+
+> Paste-ready reply:
+>
+> IRIS emulates the SGI Indy IndyCam (VINO video-input) hardware. The camera
+> entitlement lets the app capture live video from the Mac's camera and feed it
+> to the emulated video-input device. You can verify this directly: open the
+> **Video-In** tab and click **Test Camera** — macOS will prompt for camera
+> access and the app then shows a live preview from the camera. The matching
+> NSCameraUsageDescription is included in Info.plist.
+
+### `com.apple.security.network.server`
+
+**What it's for:** two things —
+- The emulator exposes the emulated machine's **serial console** (IRIX ttyd1,
+ `127.0.0.1:8881`) and **PROM monitor** on loopback TCP, so a terminal can
+ attach to the guest console. The app's own **Serial console…** window connects
+ to this server (loopback), which is the visible end-to-end demonstration: the
+ emulator *listens* (network.server) and the viewer *connects* (network.client).
+- It binds **inbound port-forwards** into the emulated SGI Ethernet (SEEQ 8003)
+ when the user configures them on the Networking tab.
+
+(The clean-shutdown "Send IRIX halt" action no longer uses a socket — it now
+types at the console in-process — so the server entitlement is only used for the
+genuine server features above.)
+
+**How to test (reviewer steps):**
+1. Launch IRIS and **Start** a machine (the bundled config boots to the PROM).
+2. Open **Machine → Serial console…**.
+3. The window shows "● connected to 127.0.0.1:8881" and streams the live guest
+ serial console. Typing a line and pressing Enter sends it to the guest.
+ This confirms the app's loopback serial **server** is live and accepting a
+ connection.
+
+> Paste-ready reply:
+>
+> IRIS exposes the emulated workstation's serial console and PROM monitor as
+> loopback TCP servers (e.g. 127.0.0.1:8881) so a terminal can attach to the
+> guest console, and it binds user-configured inbound port-forwards into the
+> emulated Ethernet. You can verify this without external tools: Start a machine
+> and open **Machine → Serial console…** — the app connects to its own loopback
+> serial server and streams the live guest console, and you can type into it.
+
+---
+
+## Summary of binary changes in this resubmission
+
+- Vendored/patched `winit` to drop the private blur API (2.5.1). No window blur
+ was ever used.
+- Added **Video-In → Test Camera** (live host-camera preview) so the camera
+ entitlement is user-visible.
+- Added **Machine → Serial console…** (in-app loopback serial viewer) so the
+ network.server entitlement is user-visible.
+- Moved "Send IRIX halt" to an in-process console path (no longer opens a
+ loopback socket).
diff --git a/installer/iris-gui.entitlements b/installer/iris-gui.entitlements
index 7631742..71203c7 100644
--- a/installer/iris-gui.entitlements
+++ b/installer/iris-gui.entitlements
@@ -19,7 +19,11 @@
com.apple.security.cs.allow-jit
-
+
com.apple.security.device.camera
@@ -34,9 +38,15 @@
com.apple.security.files.bookmarks.app-scope
-
+
com.apple.security.network.client
+
com.apple.security.network.server
diff --git a/iris-gui/assets/nvram-default.bin b/iris-gui/assets/nvram-default.bin
new file mode 100644
index 0000000..264e632
Binary files /dev/null and b/iris-gui/assets/nvram-default.bin differ
diff --git a/iris-gui/src/camera_test.rs b/iris-gui/src/camera_test.rs
new file mode 100644
index 0000000..7843072
--- /dev/null
+++ b/iris-gui/src/camera_test.rs
@@ -0,0 +1,150 @@
+//! "Test Camera" support.
+//!
+//! Opens the host camera through the same [`iris::camera::CameraSource`] the
+//! VINO / IndyCam emulation uses, on a background thread, and parks the latest
+//! frame (converted to RGBA) plus a status line for the GUI to display. This
+//! gives the user — and an App Review tester — a way to confirm the host-camera
+//! capability works (it triggers the macOS camera-permission prompt and shows a
+//! live preview) without booting IRIX and configuring the VINO video source.
+//!
+//! Dropping `CameraTest` stops the worker, which drops the `CameraSource` and
+//! releases the camera (indicator light off).
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::thread::JoinHandle;
+
+use parking_lot::Mutex;
+
+use iris::camera::CameraSource;
+use iris::video_source::{Field, VideoSource, VideoStandard};
+
+#[derive(Default)]
+struct Shared {
+ /// One-line capture status (frame count, capture resolution, …).
+ status: String,
+ /// Set if the camera could not be opened (permission denied / no device).
+ error: Option,
+ /// Latest preview frame: (width, height, RGBA bytes).
+ frame: Option<(u32, u32, Vec)>,
+ /// Bumped on each new frame so the GUI can skip redundant texture uploads.
+ seq: u64,
+}
+
+pub struct CameraTest {
+ shared: Arc>,
+ running: Arc,
+ worker: Option>,
+}
+
+impl CameraTest {
+ /// Start capturing from host camera `index` using `standard`'s field size.
+ pub fn start(standard: VideoStandard, index: u32) -> Self {
+ let shared = Arc::new(Mutex::new(Shared {
+ status: "opening camera…".into(),
+ ..Shared::default()
+ }));
+ let running = Arc::new(AtomicBool::new(true));
+ let s2 = shared.clone();
+ let r2 = running.clone();
+
+ let worker = std::thread::Builder::new()
+ .name("iris-gui-camtest".into())
+ .spawn(move || {
+ let cam = match CameraSource::new_with_index(standard, index) {
+ Ok(c) => c,
+ Err(e) => {
+ s2.lock().error = Some(e);
+ return;
+ }
+ };
+ // next_field() paces itself to the field rate, so this loop
+ // runs at ~50–60 Hz without a manual sleep.
+ while r2.load(Ordering::Relaxed) {
+ let field = cam.next_field();
+ let rgba = uyvy_field_to_rgba(&field);
+ let status = cam.status();
+ let mut g = s2.lock();
+ g.status = status;
+ g.frame = Some((field.width, field.height, rgba));
+ g.seq = g.seq.wrapping_add(1);
+ g.error = None;
+ }
+ // `cam` drops here → camera stream closed, device released.
+ })
+ .expect("spawn camera-test worker");
+
+ Self { shared, running, worker: Some(worker) }
+ }
+
+ pub fn status(&self) -> String {
+ self.shared.lock().status.clone()
+ }
+
+ pub fn error(&self) -> Option {
+ self.shared.lock().error.clone()
+ }
+
+ /// Return the latest frame if it is newer than `last_seq` (which is then
+ /// advanced). `None` when there is nothing new to upload.
+ pub fn take_new_frame(&self, last_seq: &mut u64) -> Option<(u32, u32, Vec)> {
+ let g = self.shared.lock();
+ if g.seq != *last_seq {
+ *last_seq = g.seq;
+ g.frame.clone()
+ } else {
+ None
+ }
+ }
+}
+
+impl Drop for CameraTest {
+ fn drop(&mut self) {
+ self.running.store(false, Ordering::Relaxed);
+ if let Some(w) = self.worker.take() {
+ let _ = w.join();
+ }
+ }
+}
+
+/// Convert one packed UYVY 4:2:2 field to RGBA8 (BT.601 limited range).
+/// Each 4-byte group `U Y0 V Y1` yields two pixels sharing the U/V chroma.
+fn uyvy_field_to_rgba(field: &Field) -> Vec {
+ let w = field.width as usize;
+ let h = field.height as usize;
+ let src = &field.pixels;
+ let mut out = vec![0u8; w * h * 4];
+
+ for y in 0..h {
+ let row = y * w * 2;
+ for pair in 0..(w / 2) {
+ let i = row + pair * 4;
+ if i + 3 >= src.len() {
+ break;
+ }
+ let u = src[i] as i32;
+ let y0 = src[i + 1] as i32;
+ let v = src[i + 2] as i32;
+ let y1 = src[i + 3] as i32;
+
+ let o = (y * w + pair * 2) * 4;
+ yuv_to_rgba(y0, u, v, &mut out[o..o + 4]);
+ yuv_to_rgba(y1, u, v, &mut out[o + 4..o + 8]);
+ }
+ }
+ out
+}
+
+#[inline]
+fn yuv_to_rgba(y: i32, u: i32, v: i32, out: &mut [u8]) {
+ let c = y - 16;
+ let d = u - 128;
+ let e = v - 128;
+ let r = (298 * c + 409 * e + 128) >> 8;
+ let g = (298 * c - 100 * d - 208 * e + 128) >> 8;
+ let b = (298 * c + 516 * d + 128) >> 8;
+ out[0] = r.clamp(0, 255) as u8;
+ out[1] = g.clamp(0, 255) as u8;
+ out[2] = b.clamp(0, 255) as u8;
+ out[3] = 255;
+}
diff --git a/iris-gui/src/config_ui.rs b/iris-gui/src/config_ui.rs
index 5f057d2..acfbbeb 100644
--- a/iris-gui/src/config_ui.rs
+++ b/iris-gui/src/config_ui.rs
@@ -93,6 +93,10 @@ pub enum ConfigAction {
/// and, if accepted, clear `cfg.prom` (an empty path falls back to the
/// built-in PROM in `iris::prom::Prom::from_file_or_embedded`).
RequestEmbeddedProm,
+ /// User clicked "Test Camera" on the Video-In tab; the app should open the
+ /// host camera and show a live preview (using the current `[vino]` standard
+ /// and camera index).
+ TestCamera,
}
pub fn show_tab(ui: &mut Ui, tab: Tab, cfg: &mut MachineConfig, jit: &mut JitEnv) -> ConfigAction {
@@ -102,7 +106,7 @@ pub fn show_tab(ui: &mut Ui, tab: Tab, cfg: &mut MachineConfig, jit: &mut JitEnv
Tab::Network => { show_network(ui, cfg); ConfigAction::None }
Tab::Memory => { show_memory(ui, cfg); ConfigAction::None }
Tab::Display => { show_display(ui, cfg); ConfigAction::None }
- Tab::VideoIn => { show_vino(ui, cfg); ConfigAction::None }
+ Tab::VideoIn => show_vino(ui, cfg),
Tab::Debug => { show_debug(ui, cfg, jit); ConfigAction::None }
Tab::Ci => { show_ci(ui, cfg); ConfigAction::None }
}).inner
@@ -370,7 +374,8 @@ fn show_network(ui: &mut Ui, cfg: &mut MachineConfig) {
}
}
-fn show_vino(ui: &mut Ui, cfg: &mut MachineConfig) {
+fn show_vino(ui: &mut Ui, cfg: &mut MachineConfig) -> ConfigAction {
+ let mut action = ConfigAction::None;
ui.heading("Video-In (IndyCam)");
Grid::new("vino_grid").num_columns(2).striped(true).show(ui, |ui| {
ui.label("Source");
@@ -407,6 +412,42 @@ fn show_vino(ui: &mut Ui, cfg: &mut MachineConfig) {
ui.add(DragValue::new(&mut cfg.vino.camera_index).range(0..=15));
ui.end_row();
});
+
+ // Live host-camera test: opens the selected camera directly (no IRIX boot
+ // needed) so the user can confirm the capture path works — and, on macOS,
+ // grant the camera permission. This exercises the same host-capture code
+ // the VINO/IndyCam source uses.
+ ui.add_space(8.0);
+ if build_features::CAMERA {
+ ui.horizontal(|ui| {
+ if ui.button("📷 Test Camera").clicked() {
+ action = ConfigAction::TestCamera;
+ }
+ ui.label(
+ RichText::new(format!(
+ "Preview host camera #{} live ({}).",
+ cfg.vino.camera_index,
+ match cfg.vino.standard { VinoStandard::Ntsc => "NTSC", VinoStandard::Pal => "PAL" },
+ ))
+ .weak(),
+ );
+ });
+ ui.label(
+ RichText::new(
+ "On first use macOS will ask for camera permission. The camera \
+ is released when you close the preview.",
+ )
+ .weak()
+ .small(),
+ );
+ } else {
+ ui.label(
+ RichText::new("Camera test unavailable — this build was compiled without --features camera.")
+ .weak(),
+ );
+ }
+
+ action
}
fn show_debug(ui: &mut Ui, cfg: &mut MachineConfig, jit: &mut JitEnv) {
diff --git a/iris-gui/src/dialogs/create_disk.rs b/iris-gui/src/dialogs/create_disk.rs
index 0f02c53..c8cd272 100644
--- a/iris-gui/src/dialogs/create_disk.rs
+++ b/iris-gui/src/dialogs/create_disk.rs
@@ -2,7 +2,6 @@ use eframe::egui::{self, Color32, Grid, RichText, Slider, TextEdit};
use std::path::PathBuf;
/// Modal that creates a blank zero-filled disk image for a chosen SCSI ID.
-/// Mirrors snow's DiskImageDialog.
pub struct CreateDiskDialog {
open: bool,
scsi_id: u8,
@@ -25,7 +24,9 @@ impl Default for CreateDiskDialog {
impl CreateDiskDialog {
pub fn open_for(&mut self, scsi_id: u8) {
self.scsi_id = scsi_id;
- self.filename = format!("scsi{scsi_id}.raw");
+ // Absolute, app-managed default location (writable in the App Store
+ // sandbox too) so a new disk never lands in the working dir.
+ self.filename = crate::settings::GuiSettings::default_disk_path(scsi_id);
self.size_mb = 1024.0;
self.result = None;
self.open = true;
@@ -46,11 +47,16 @@ impl CreateDiskDialog {
ui.horizontal(|ui| {
ui.add(TextEdit::singleline(&mut self.filename).desired_width(220.0));
if ui.button("📁").clicked() {
- if let Some(p) = rfd::FileDialog::new()
- .add_filter("Disk image", &["raw", "img"])
- .set_file_name(&self.filename)
- .save_file()
- {
+ let cur = std::path::Path::new(&self.filename);
+ let mut dlg = rfd::FileDialog::new().add_filter("Disk image", &["raw", "img"]);
+ if let Some(dir) = cur.parent().filter(|d| !d.as_os_str().is_empty()) {
+ let _ = std::fs::create_dir_all(dir);
+ dlg = dlg.set_directory(dir);
+ }
+ if let Some(name) = cur.file_name().and_then(|s| s.to_str()) {
+ dlg = dlg.set_file_name(name);
+ }
+ if let Some(p) = dlg.save_file() {
self.filename = p.to_string_lossy().into_owned();
}
}
@@ -70,8 +76,12 @@ impl CreateDiskDialog {
if ui.add(egui::Button::new("Create")
.fill(Color32::from_rgb(60, 110, 60))).clicked()
{
- // Create file on disk now.
+ // Create file on disk now (making the parent dir first,
+ // e.g. the managed /disks on first use).
let path = PathBuf::from(&self.filename);
+ if let Some(parent) = path.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
let size_bytes = (self.size_mb * 1024.0 * 1024.0) as u64;
match std::fs::File::create(&path)
.and_then(|f| f.set_len(size_bytes))
diff --git a/iris-gui/src/dialogs/new_machine.rs b/iris-gui/src/dialogs/new_machine.rs
index 0462f54..d50fd28 100644
--- a/iris-gui/src/dialogs/new_machine.rs
+++ b/iris-gui/src/dialogs/new_machine.rs
@@ -1,7 +1,7 @@
use eframe::egui::{self, Color32, ComboBox, Grid, RichText, TextEdit};
use iris::config::{MachineConfig, ScsiDeviceConfig, VALID_BANK_SIZES};
-/// "New machine" startup dialog — analogous to snow's ModelSelectionDialog.
+/// "New machine" startup dialog.
/// Pops up at first run (or on `File → New machine…`) to bootstrap a config.
pub struct NewMachineDialog {
open: bool,
@@ -32,11 +32,11 @@ impl Default for NewMachineDialog {
name: "indy".into(),
prom_path: "prom.bin".into(),
use_embedded_prom: true,
- nvram_path: "nvram.bin".into(),
+ nvram_path: crate::settings::GuiSettings::default_nvram_path(),
ram_total_mb: 256,
ram_advanced: false,
ram_banks: [128, 128, 0, 0],
- scsi1_path: "scsi1.raw".into(),
+ scsi1_path: crate::settings::GuiSettings::default_disk_path(1),
create_blank_scsi1: false,
cdrom4_path: String::new(),
attach_cdrom: false,
diff --git a/iris-gui/src/framebuffer.rs b/iris-gui/src/framebuffer.rs
index 02edaf8..522af68 100644
--- a/iris-gui/src/framebuffer.rs
+++ b/iris-gui/src/framebuffer.rs
@@ -44,6 +44,14 @@ impl FrameSink {
/// copying the whole buffer on every repaint when nothing is new.
pub fn snapshot(&self) -> Frame { self.frame.lock().clone() }
+ /// Reset to the "no frame yet" state (seq 0, blank frame). Call before a
+ /// fresh run starts rendering so a restart shows the "waiting for first
+ /// frame" placeholder instead of the previous run's last frame.
+ pub fn reset(&self) {
+ *self.frame.lock() = Frame::default();
+ self.seq.store(0, Ordering::Release);
+ }
+
fn lock(&self) -> MutexGuard<'_, Frame> { self.frame.lock() }
}
diff --git a/iris-gui/src/handle.rs b/iris-gui/src/handle.rs
index 5313edc..e9c696b 100644
--- a/iris-gui/src/handle.rs
+++ b/iris-gui/src/handle.rs
@@ -12,6 +12,9 @@ use std::thread::JoinHandle;
pub enum Cmd {
Start(Box),
Stop,
+ /// Type `halt\n` at the IRIX serial console in-process (no loopback socket)
+ /// for a clean guest shutdown.
+ HaltIrix,
SaveState(String),
RestoreState(String),
Screenshot(PathBuf),
@@ -45,6 +48,10 @@ pub struct Status {
pub dirty_cow: usize,
/// Approximate instructions/sec (millions).
pub mips: f32,
+ /// The CPU is not executing: either stopped (soft power-off) or idle at the
+ /// PROM after an IRIX `halt` (0 MIPS). When set, the guest has shut down and
+ /// stopping the machine can't corrupt a disk — see [`crate::safe_stop`].
+ pub cpu_halted: bool,
}
pub struct EmulatorHandle {
@@ -105,6 +112,7 @@ impl EmulatorHandle {
// events, so merge rather than replace to avoid clobbering them.
self.status.mips = s.mips;
self.status.dirty_cow = s.dirty_cow;
+ self.status.cpu_halted = s.cpu_halted;
}
match &evt {
Evt::Started => self.status.running = true,
@@ -174,7 +182,12 @@ fn worker_loop(
let mips = (dc as f64 / dt / 1_000_000.0 * 10.0).round() as f32 / 10.0;
prev_cycles = cur;
prev_tick = now;
- let _ = evt_tx.send(Evt::Status(Status { mips, ..Status::default() }));
+ // The guest has shut down when the CPU thread has stopped
+ // (soft power-off calls Machine::stop) or has retired no
+ // instructions this window (halted/idle at the PROM, 0 MIPS).
+ let cpu_stopped = machine.as_ref().map_or(true, |m| !m.cpu_is_running());
+ let cpu_halted = cpu_stopped || mips == 0.0;
+ let _ = evt_tx.send(Evt::Status(Status { mips, cpu_halted, ..Status::default() }));
}
}
continue;
@@ -184,6 +197,10 @@ fn worker_loop(
let _ = evt_tx.send(Evt::Error("emulator already running".into()));
continue;
}
+ // Clear the previous run's last frame so the restarted machine
+ // shows the "waiting for first REX3 frame" placeholder instead
+ // of the stale screen until its first frame is rendered.
+ frame_sink.reset();
// Wrap construction in catch_unwind: Machine::new and
// friends may panic on missing files, bad images, etc.
// We surface those as Evt::Error toasts instead of
@@ -228,6 +245,12 @@ fn worker_loop(
}
}
}
+ Ok(Cmd::HaltIrix) => {
+ match machine.as_ref() {
+ Some(m) => m.inject_serial_console(b"halt\n"),
+ None => { let _ = evt_tx.send(Evt::Error("halt: not running".into())); }
+ }
+ }
Ok(Cmd::Stop) => {
if let Some(m) = machine.take() {
*ps2_slot.lock() = None;
diff --git a/iris-gui/src/input.rs b/iris-gui/src/input.rs
index e7fe4c1..5ed314a 100644
--- a/iris-gui/src/input.rs
+++ b/iris-gui/src/input.rs
@@ -18,11 +18,13 @@
//! captured we forward nothing, so menu clicks and typing into the config
//! side panel stay with egui.
//!
-//! The framebuffer panel calls `pump(...)` each frame with the rect the REX3
-//! image occupies in screen space (used only to decide where a capturing
-//! click counts).
+//! The framebuffer panel calls `pump(...)` each frame, passing whether the REX3
+//! image widget itself was clicked this frame. Using the widget's own
+//! `Response::clicked()` (rather than a raw point-in-rect test) means egui's
+//! hit-testing already routed clicks on open menus / popups to those widgets,
+//! so navigating menus over the display never gets "eaten" into a capture.
-use egui::{CursorGrab, Event, Key, Modifiers, MouseWheelUnit, PointerButton, Rect, ViewportCommand};
+use egui::{CursorGrab, Event, Key, Modifiers, MouseWheelUnit, PointerButton, ViewportCommand};
use iris::ps2::Ps2Controller;
use winit::keyboard::KeyCode;
@@ -39,7 +41,7 @@ impl Default for InputState {
}
}
-pub fn pump(ctx: &egui::Context, fb_rect: Rect, ps2: &Ps2Controller, state: &mut InputState, scroll_pixels_per_line: f64) {
+pub fn pump(ctx: &egui::Context, fb_clicked: bool, ps2: &Ps2Controller, state: &mut InputState, scroll_pixels_per_line: f64) {
// Collect everything we need inside the input borrow, then act afterwards
// (sending viewport commands / PS2 writes outside the `input()` closure).
let mut want_enter = false;
@@ -53,14 +55,11 @@ pub fn pump(ctx: &egui::Context, fb_rect: Rect, ps2: &Ps2Controller, state: &mut
ctx.input(|i| {
if !state.captured {
- // Not captured: the only thing we care about is a primary click
- // inside the framebuffer, which grabs input. Everything else is
- // left to egui (menus, config side panel, …).
- if i.pointer.button_pressed(PointerButton::Primary) {
- if let Some(p) = i.pointer.interact_pos().or_else(|| i.pointer.latest_pos()) {
- if fb_rect.contains(p) { want_enter = true; }
- }
- }
+ // Not captured: capture only when the framebuffer Image widget
+ // itself was clicked. egui routes clicks on menus/popups/panels to
+ // those widgets first, so this never fires for menu navigation that
+ // happens to overlap the display. Everything else stays with egui.
+ if fb_clicked { want_enter = true; }
return;
}
@@ -250,6 +249,11 @@ fn map_key(k: Key) -> Option {
Key::OpenBracket => KeyCode::BracketLeft,
Key::CloseBracket => KeyCode::BracketRight,
Key::Backtick => KeyCode::Backquote,
+ // egui reports the *shifted* symbol as its own Key; these two share a
+ // physical key with Backslash/Slash (Shift is sent separately, so the
+ // guest forms '|' and '?'). Without them those keys send nothing.
+ Key::Pipe => KeyCode::Backslash,
+ Key::Questionmark => KeyCode::Slash,
// F-keys (egui has no F5; iris likely doesn't need F13+ either)
Key::F1 => KeyCode::F1, Key::F2 => KeyCode::F2, Key::F3 => KeyCode::F3,
Key::F4 => KeyCode::F4, Key::F6 => KeyCode::F6, Key::F7 => KeyCode::F7,
diff --git a/iris-gui/src/main.rs b/iris-gui/src/main.rs
index 7b2ef48..0524748 100644
--- a/iris-gui/src/main.rs
+++ b/iris-gui/src/main.rs
@@ -1,5 +1,6 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+mod camera_test;
mod config_ui;
mod dialogs;
mod framebuffer;
@@ -8,6 +9,7 @@ mod input;
mod macos_sandbox;
mod safe_stop;
mod scsi_menu;
+mod serial_console;
mod settings;
mod single_instance;
@@ -19,7 +21,7 @@ use egui::{Color32, RichText, ViewportCommand};
use handle::{Cmd, EmulatorHandle, Evt};
use iris::config::MachineConfig;
use safe_stop::{evaluate, reason_lines};
-use settings::{GuiSettings, UI_SCALE_MAX, UI_SCALE_MIN};
+use settings::{GuiSettings, UI_SCALE_MAX, UI_SCALE_MIN, WINDOW_DEFAULT_SIZE};
use std::path::PathBuf;
/// Decode the bundled window/taskbar icon (256×256 RGBA PNG, generated by
@@ -40,6 +42,38 @@ fn load_icon() -> egui::IconData {
}
}
+/// Largest aspect-preserving size (egui points) that fits `avail` for a
+/// framebuffer whose native pixel dimensions are `px`.
+fn fb_fit_size(avail: egui::Vec2, px: egui::Vec2) -> egui::Vec2 {
+ let fb_aspect = px.x / px.y;
+ if avail.x / avail.y > fb_aspect {
+ egui::vec2(avail.y * fb_aspect, avail.y)
+ } else {
+ egui::vec2(avail.x, avail.x / fb_aspect)
+ }
+}
+
+/// Resolve a config path to an absolute string for display — a relative path is
+/// joined to the process working directory (where the emulator actually looks
+/// for it), so the user never sees a bare `scsi3.raw` with no idea where it is.
+fn abs_path(p: &str) -> String {
+ let path = std::path::Path::new(p);
+ if path.is_absolute() || p.is_empty() {
+ return p.to_string();
+ }
+ std::env::current_dir()
+ .map(|d| d.join(path).to_string_lossy().into_owned())
+ .unwrap_or_else(|_| p.to_string())
+}
+
+/// True when `scale` (device pixels per emulated pixel) is close enough to a
+/// positive integer that nearest-neighbour sampling stays pixel-perfect. Off
+/// an integer, bilinear filtering avoids uneven pixel doubling.
+fn is_integer_scale(scale: f32) -> bool {
+ let rounded = scale.round();
+ rounded >= 1.0 && (scale - rounded).abs() <= 0.01
+}
+
fn main() -> eframe::Result<()> {
env_logger::init();
// Prevent the iris lib from calling process::exit on guest soft-power-off
@@ -73,17 +107,25 @@ fn main() -> eframe::Result<()> {
// once, before any worker thread (CPU / REX3) can read it.
#[cfg(feature = "appstore")]
std::env::set_var("IRIS_NO_JIT", "1");
- let mut viewport = egui::ViewportBuilder::default()
+ let viewport = egui::ViewportBuilder::default()
.with_title("iris — SGI Indy emulator")
// app_id sets the X11 WM_CLASS / Wayland app_id so the compositor can
// match an installed .desktop/icon (icons regenerated by
// scripts/generate-icon.sh from iris-gui/assets/icon-original.png).
.with_app_id("iris-gui")
.with_icon(load_icon())
- .with_inner_size(prefs.window_size.unwrap_or([1100.0, 720.0]));
- if prefs.fullscreen {
- viewport = viewport.with_fullscreen(true);
- }
+ // Open large enough for the 1280×1024 display + chrome so it looks right
+ // immediately; clamp to the monitor so it can't overflow a smaller
+ // screen. Persisted size (once saved) takes precedence over the default.
+ .with_inner_size(prefs.window_size.unwrap_or(WINDOW_DEFAULT_SIZE))
+ .with_clamp_size_to_monitor_size(true)
+ // Start hidden so the first frame can fit the window to the monitor
+ // (see the reveal logic in `update`) before it's shown — the window
+ // then appears already at the right size instead of opening at the
+ // default and visibly resizing.
+ .with_visible(false);
+ // Intentionally do NOT restore fullscreen on launch — the app always opens
+ // windowed; fullscreen is only ever entered when the user asks (F11).
let opts = eframe::NativeOptions {
viewport,
..Default::default()
@@ -130,9 +172,56 @@ struct App {
/// Sequence number of the last frame we uploaded; used to skip the
/// upload when the renderer hasn't produced a new frame.
last_fb_seq: u64,
+ /// Filter the framebuffer texture is currently uploaded with: `true` =
+ /// NEAREST (crisp; used at integer device-pixel scales), `false` = LINEAR
+ /// (smooths the uneven pixel doubling at fractional scales). Tracked so we
+ /// only re-upload when the integer/fractional status actually flips.
+ fb_nearest: bool,
+ /// Current on-screen magnification of the emulated display: logical points
+ /// per emulated pixel (1.0 = native, i.e. the picture at its true size; <1
+ /// shrunk to fit; >1 enlarged). 0.0 until the first frame is drawn. Shown in
+ /// the status footer next to MIPS. Crispness (NEAREST vs LINEAR) tracks the
+ /// *device-pixel* scale via `fb_nearest`, which this can differ from on HiDPI.
+ fb_scale: f32,
+ /// Set on a VM-scale slider or UI-zoom change; consumed on the next real
+ /// REX3 frame to resize the window so the display lands at the chosen VM
+ /// scale (clamped + ½×-snapped to fit the monitor; see `framebuffer_panel`).
+ /// Not set on Start — the window size is latched at app load, so launching
+ /// the VM never resizes the window.
+ pending_fb_snap: bool,
+ /// True on a first-ever launch (no persisted window size). Consumed on the
+ /// first frame that knows the monitor size, to fit the window to a 1280×1024
+ /// display at the chosen VM scale so it opens at a sensible, windowed size
+ /// before the first Start. Returning users just reopen at their saved size.
+ pending_launcher_fit: bool,
+ /// The window starts hidden (`with_visible(false)`) so the first frame can
+ /// fit it to the monitor before it's shown. Set true once we've revealed it.
+ revealed: bool,
+ /// Frames rendered since launch; gates the reveal so the startup fit's
+ /// resize is applied before the window appears (and as a hard fallback so a
+ /// missing monitor size can't leave the window hidden).
+ startup_frame: u32,
/// Per-frame state for the egui→PS2 input pump (modifier diff,
/// mouse button mask, last cursor position).
input_state: input::InputState,
+ /// Previous frame's `cpu_halted` status, so we can edge-detect the guest
+ /// becoming "safe to stop" and auto-release the captured mouse/keyboard
+ /// exactly once on that transition. Reset to true on Start so the initial
+ /// idle-at-PROM state doesn't count as a halt.
+ prev_cpu_halted: bool,
+ /// Active "Test Camera" preview (None when the window is closed). Opening it
+ /// starts host-camera capture; dropping it releases the device.
+ camera_test: Option,
+ /// egui texture for the camera-test preview + the last frame seq uploaded.
+ camera_test_tex: Option,
+ camera_test_seq: u64,
+ /// Active in-app IRIX serial-console viewer (None when closed). Connects to
+ /// the loopback serial server; dropping it closes the connection.
+ serial_console: Option,
+ /// Pending line typed into the serial console input field.
+ serial_input: String,
+ /// Whether the "How camera & networking work" Help window is open.
+ show_help_info: bool,
}
struct StopModal {
@@ -215,9 +304,18 @@ impl App {
opened_new_machine = true;
}
let _ = opened_new_machine; // (kept for future telemetry)
+ // Anchor the live config's NVRAM to the stable data dir too — covers the
+ // legacy-TOML import path above, which doesn't go through load()'s
+ // per-machine migration.
+ GuiSettings::migrate_nvram_path(&mut cfg.nvram);
Self {
- fullscreen: prefs.fullscreen,
+ fullscreen: false,
+ // First-ever launch (no saved size) → fit the window to the monitor
+ // on the first frame instead of using the static default verbatim.
+ pending_launcher_fit: prefs.window_size.is_none(),
+ revealed: false,
+ startup_frame: 0,
prefs,
cfg,
cfg_path,
@@ -237,7 +335,17 @@ impl App {
restore_state_name: "snap1".into(),
fb_tex: None,
last_fb_seq: 0,
+ fb_nearest: true,
+ fb_scale: 0.0,
+ pending_fb_snap: false,
input_state: input::InputState::default(),
+ prev_cpu_halted: true,
+ camera_test: None,
+ camera_test_tex: None,
+ camera_test_seq: 0,
+ serial_console: None,
+ serial_input: String::new(),
+ show_help_info: false,
}
}
@@ -336,8 +444,44 @@ impl App {
}
self.jit.export();
self.emu.send(Cmd::Start(Box::new(self.cfg.clone())));
+ // Don't resize the window when the VM launches — its size is latched at
+ // app load (the saved window size, or the first-launch fit to vm_scale)
+ // and the guest display is letterboxed into it. Only the VM-scale slider
+ // and UI zoom re-snap the window after that.
+ // Drop the previous run's cached texture so we never flash its last
+ // frame before the new run renders (the shared FrameSink is reset
+ // worker-side on Start; this clears the GUI's mirror of it).
+ self.fb_tex = None;
+ self.last_fb_seq = 0;
+ // Assume halted at boot (idle at the PROM) so the auto-release only
+ // fires on a later running→halted transition, not at startup.
+ self.prev_cpu_halted = true;
+ // If the NVRAM has no Ethernet MAC, IRIX won't attach ec0 — networking,
+ // System Manager, and Disk Manager all fail. Offer to set one up, and
+ // hold the machine at the PROM by interrupting autoboot (see the Esc
+ // guard in `update`) so the user sets the MAC before IRIX boots — one
+ // boot instead of boot-then-reboot.
+ // Seed a default NVRAM if there's none yet (a fresh install / bundled
+ // app has nothing in the working dir to migrate), so the machine boots
+ // with proper PROM env instead of a blank one.
+ if settings::ensure_nvram_seeded(&self.cfg.nvram) {
+ self.toast("seeded a default NVRAM");
+ }
+ // Networking needs an Ethernet MAC in NVRAM (6 raw bytes at a fixed
+ // offset). If there's none, write a generated one *now*, before boot —
+ // so IRIX attaches ec0 on the first boot, no PROM monitor / reboot.
+ if !settings::nvram_has_mac(&self.cfg.nvram) {
+ let seed = self.prefs.active_machine.as_deref().unwrap_or("indy");
+ let mac = settings::generate_mac_bytes(seed);
+ match settings::write_nvram_mac(&self.cfg.nvram, mac) {
+ Ok(true) => self.toast(format!("no Ethernet MAC in NVRAM — wrote {}", settings::mac_to_string(mac))),
+ Ok(false) => self.toast("no Ethernet MAC, and no NVRAM file yet to write into"),
+ Err(e) => self.toast(format!("couldn't write MAC to NVRAM: {e}")),
+ }
+ }
}
+
/// Walk the configured SCSI devices and report any whose image file
/// is missing. Scratch volumes are skipped (iris auto-creates those).
/// For CD-ROMs the device is "present" if either the primary path or
@@ -397,9 +541,11 @@ impl App {
ctx.request_repaint_after(std::time::Duration::from_millis(next));
}
- fn menu_bar(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
- egui::menu::bar(ui, |ui| {
- ui.menu_button("File", |ui| {
+ /// The File/Machine/Memory/SCSI/View/Help menus, stacked vertically for the
+ /// left control column. Each is a full-width drop-down button.
+ fn menu_list(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
+ ui.vertical(|ui| {
+ ui.menu_button("File ▶", |ui| {
ui.set_min_width(220.0);
if ui.button("New machine…").clicked() {
self.new_machine.open();
@@ -491,7 +637,7 @@ impl App {
ctx.send_viewport_cmd(ViewportCommand::Close);
}
});
- ui.menu_button("Machine", |ui| {
+ ui.menu_button("Machine ▶", |ui| {
let running = self.emu.is_running();
if ui.add_enabled(!running, egui::Button::new("Start")).clicked() {
self.start_emulator();
@@ -506,6 +652,23 @@ impl App {
self.start_emulator();
ui.close_menu();
}
+ if ui.add_enabled(!running, egui::Button::new("Reset NVRAM (fresh PRAM)"))
+ .on_hover_text(format!(
+ "Restore this machine's NVRAM to defaults and assign a fresh Ethernet MAC.\n{}",
+ abs_path(&self.cfg.nvram)))
+ .clicked()
+ {
+ match settings::reset_nvram(&self.cfg.nvram) {
+ Ok(()) => {
+ let seed = self.prefs.active_machine.as_deref().unwrap_or("indy");
+ let mac = settings::generate_mac_bytes(seed);
+ let _ = settings::write_nvram_mac(&self.cfg.nvram, mac);
+ self.toast(format!("NVRAM reset — new MAC {}", settings::mac_to_string(mac)));
+ }
+ Err(e) => self.toast(format!("NVRAM reset failed: {e}")),
+ }
+ ui.close_menu();
+ }
ui.separator();
ui.horizontal(|ui| {
ui.label("Save state:");
@@ -528,8 +691,15 @@ impl App {
}
ui.close_menu();
}
+ if ui.add_enabled(running, egui::Button::new("Serial console…"))
+ .on_hover_text("View the IRIX serial console (ttyd1) over the loopback serial server")
+ .clicked()
+ {
+ self.open_serial_console();
+ ui.close_menu();
+ }
});
- ui.menu_button("Memory", |ui| {
+ ui.menu_button("Memory ▶", |ui| {
ui.set_min_width(220.0);
let total: u32 = self.cfg.banks.iter().sum();
ui.label(RichText::new(format!("Total: {total} MB")).strong());
@@ -557,7 +727,7 @@ impl App {
});
}
});
- ui.menu_button("SCSI", |ui| {
+ ui.menu_button("SCSI ▶", |ui| {
let action = scsi_menu::draw(ui, &self.cfg);
match action {
scsi_menu::ScsiAction::None => {}
@@ -572,7 +742,7 @@ impl App {
}
}
});
- ui.menu_button("View", |ui| {
+ ui.menu_button("View ▶", |ui| {
if ui.button(if self.fullscreen { "Exit fullscreen (F11)" } else { "Fullscreen (F11)" }).clicked() {
self.fullscreen = !self.fullscreen;
ctx.send_viewport_cmd(ViewportCommand::Fullscreen(self.fullscreen));
@@ -587,14 +757,54 @@ impl App {
ui.add(egui::Slider::new(&mut self.prefs.ui_scale, UI_SCALE_MIN..=UI_SCALE_MAX));
if ui.button("Apply").clicked() {
ctx.set_zoom_factor(self.prefs.ui_scale);
+ // Re-fit the window so the bigger/smaller controls grow
+ // the window rather than squeezing the picture.
+ self.pending_fb_snap = true;
}
});
ui.label(RichText::new("Ctrl+= / Ctrl+- / Ctrl+0 to zoom").weak().small());
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("VM screen");
+ // Sets the emulated-display magnification directly (1× =
+ // native), independent of UI scale. The window resizes to
+ // hold the picture at the chosen size on the next frame.
+ let changed = ui.add(
+ egui::Slider::new(&mut self.prefs.vm_scale, settings::VM_SCALE_MIN..=settings::VM_SCALE_MAX)
+ .step_by(settings::VM_SCALE_STEP)
+ .suffix("×"),
+ ).changed();
+ if changed { self.pending_fb_snap = true; }
+ });
+ ui.label(RichText::new("1× = native pixels; ¼× steps (½-integers crispest on Retina)").weak().small());
});
- ui.menu_button("Help", |ui| {
+ ui.menu_button("Help ▶", |ui| {
ui.label(RichText::new("IRIS — SGI Indy (MIPS R4400) Emulator").strong());
ui.label(format!("Version {}", env!("APP_VERSION")));
ui.separator();
+ ui.label(RichText::new("Diagnostics").strong());
+ let running = self.emu.is_running();
+ if ui.add_enabled(running, egui::Button::new("📷 Test Camera…"))
+ .on_hover_text("Preview the host camera used for the emulated IndyCam")
+ .on_disabled_hover_text("Start a machine first")
+ .clicked()
+ {
+ self.open_camera_test();
+ ui.close_menu();
+ }
+ if ui.add_enabled(running, egui::Button::new("🌐 Network test (serial console)…"))
+ .on_hover_text("Connect to the emulator's loopback serial server (127.0.0.1:8881)")
+ .on_disabled_hover_text("Start a machine first")
+ .clicked()
+ {
+ self.open_serial_console();
+ ui.close_menu();
+ }
+ if ui.button("ℹ How camera & networking work…").clicked() {
+ self.show_help_info = true;
+ ui.close_menu();
+ }
+ ui.separator();
ui.label(RichText::new("Authors").strong());
ui.label("Original: techomancer");
ui.label("iris-gui fork: Dani Sarfati (danifunker)");
@@ -619,33 +829,42 @@ impl App {
});
}
- fn toolbar(&mut self, ui: &mut egui::Ui) {
- ui.horizontal(|ui| {
- let running = self.emu.is_running();
- if !running {
- if ui.add(egui::Button::new(RichText::new("▶ Start").size(16.0))
- .fill(Color32::from_rgb(40, 110, 40))).clicked()
- {
- self.start_emulator();
- }
- } else if ui.add(egui::Button::new(RichText::new("■ Stop").size(16.0))
- .fill(Color32::from_rgb(160, 60, 60))).clicked()
+ /// Start/Stop + save-state controls, stacked full-width for the left column.
+ fn machine_controls(&mut self, ui: &mut egui::Ui) {
+ let running = self.emu.is_running();
+ let full = egui::vec2(ui.available_width(), 0.0);
+ if !running {
+ if ui.add_sized(full, egui::Button::new(RichText::new("▶ Start").size(16.0))
+ .fill(Color32::from_rgb(40, 110, 40))).clicked()
{
- self.request_stop();
- }
- ui.separator();
- if ui.add_enabled(running, egui::Button::new("💾 Save state")).clicked() {
- self.emu.send(Cmd::SaveState(self.save_state_name.clone()));
- }
- if ui.add_enabled(running, egui::Button::new("Restore state")).clicked() {
- self.emu.send(Cmd::RestoreState(self.restore_state_name.clone()));
- }
- ui.separator();
- let edit_label = if self.show_config_editor { "Hide config editor" } else { "Edit config…" };
- if ui.button(edit_label).clicked() {
- self.show_config_editor = !self.show_config_editor;
+ self.start_emulator();
}
- if self.show_config_editor {
+ } else if ui.add_sized(full, egui::Button::new(RichText::new("■ Stop").size(16.0))
+ .fill(Color32::from_rgb(160, 60, 60))).clicked()
+ {
+ self.request_stop();
+ }
+ if ui.add_enabled_ui(running, |ui| {
+ ui.add_sized(egui::vec2(ui.available_width(), 0.0), egui::Button::new("💾 Save state")).clicked()
+ }).inner {
+ self.emu.send(Cmd::SaveState(self.save_state_name.clone()));
+ }
+ if ui.add_enabled_ui(running, |ui| {
+ ui.add_sized(egui::vec2(ui.available_width(), 0.0), egui::Button::new("Restore state")).clicked()
+ }).inner {
+ self.emu.send(Cmd::RestoreState(self.restore_state_name.clone()));
+ }
+ }
+
+ /// "Edit config" toggle plus the quick-jump tab buttons (shown only while
+ /// the config editor is open). Stacked for the left column.
+ fn config_quick_buttons(&mut self, ui: &mut egui::Ui) {
+ let edit_label = if self.show_config_editor { "Hide config editor" } else { "Edit config…" };
+ if ui.add_sized(egui::vec2(ui.available_width(), 0.0), egui::Button::new(edit_label)).clicked() {
+ self.show_config_editor = !self.show_config_editor;
+ }
+ if self.show_config_editor {
+ ui.indent("quick_tabs", |ui| {
if ui.button("Network").clicked() { self.tab = Tab::Network; }
if ui.button("Video-In").clicked() { self.tab = Tab::VideoIn; }
// Debug/JIT is compiled out of lightning builds; CI is hidden
@@ -657,24 +876,96 @@ impl App {
if !cfg!(feature = "appstore") && ui.button("CI").clicked() {
self.tab = Tab::Ci;
}
- }
-
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- let status = if self.emu.status.power_off_seen {
- RichText::new("halted").color(Color32::LIGHT_GRAY)
- } else if self.emu.status.in_prom {
- RichText::new("PROM").color(Color32::LIGHT_BLUE)
- } else if running {
- RichText::new("IRIX running").color(Color32::LIGHT_GREEN)
- } else {
- RichText::new("stopped").color(Color32::GRAY)
- };
- ui.label(status);
- if running {
- ui.label(format!("{:.0} MIPS", self.emu.status.mips));
- }
});
- });
+ }
+ }
+
+ /// Run-state line (IRIX running / PROM / halted / stopped + MIPS). Used in
+ /// the control column's status footer.
+ fn run_state_label(&self, ui: &mut egui::Ui) {
+ let running = self.emu.is_running();
+ let halted = running && self.emu.status.cpu_halted;
+ let status = if halted {
+ RichText::new("halted — safe to stop").color(Color32::LIGHT_GRAY)
+ } else if self.emu.status.in_prom {
+ RichText::new("PROM").color(Color32::LIGHT_BLUE)
+ } else if running {
+ RichText::new("IRIX running").color(Color32::LIGHT_GREEN)
+ } else {
+ RichText::new("stopped").color(Color32::GRAY)
+ };
+ ui.label(status);
+ if running && !halted {
+ ui.label(format!("{:.0} MIPS", self.emu.status.mips));
+ }
+ if running && self.fb_scale > 0.0 {
+ // How magnified the emulated display currently is (1× = native).
+ // Round-snap the readout so a whole-number scale reads cleanly.
+ let mag = self.fb_scale;
+ let whole = (mag - mag.round()).abs() <= 0.01;
+ let num = if whole { format!("{:.0}×", mag.round()) } else { format!("{mag:.2}×") };
+ let label = if self.fb_nearest {
+ RichText::new(format!("{num} scale")).color(Color32::LIGHT_GRAY)
+ } else {
+ RichText::new(format!("{num} scale · filtered")).color(Color32::from_rgb(200, 175, 90))
+ };
+ ui.label(label).on_hover_text(
+ "On-screen size of the emulated display: logical points per emulated \
+ pixel (1× = native). \"filtered\" means the current size isn't a whole \
+ device-pixel multiple, so the image is smoothed rather than pixel-crisp.",
+ );
+ }
+ }
+
+ /// Resize the window so the central panel exactly holds the emulated
+ /// display at native scale — 1 framebuffer pixel = 1 logical point, which
+ /// is an integer device-pixel scale on both standard (1×) and HiDPI (2×)
+ /// screens, so the picture stays crisp and fills the window without
+ /// letterbox bars. Shrinks below native only if that wouldn't fit the
+ /// monitor work area. `central_avail` is the framebuffer panel's free space;
+ /// `screen_rect − central_avail` is the surrounding chrome (the left control
+ /// column, plus the config editor when open) we must keep room for. The math
+ /// is orientation-agnostic, so it works whether chrome is a side column or
+ /// the older top/bottom bars.
+ /// Resizes the window so the display lands at `vm_scale` (clamped to fit the
+ /// monitor). Does NOT write the clamped value back to `prefs.vm_scale` — the
+ /// slider stays the user's requested scale so it can always be dragged; the
+ /// footer readout reports the scale actually achieved.
+ fn snap_window_to_fb(ctx: &egui::Context, fb_px: egui::Vec2, central_avail: egui::Vec2, vm_scale: f32) {
+ if fb_px.x < 1.0 || fb_px.y < 1.0 { return; }
+ // egui-winit reports screen_rect / available_size / monitor_size *and*
+ // interprets ViewportCommand::InnerSize all in the same (zoom-scaled)
+ // point space, so chrome math stays in egui points.
+ let screen = ctx.screen_rect().size();
+ let chrome_w = (screen.x - central_avail.x).max(0.0);
+ let chrome_h = (screen.y - central_avail.y).max(0.0);
+ let zoom = ctx.zoom_factor().max(0.1);
+ // Target points-per-pixel for the requested VM scale (vm_scale device
+ // pixels per emulated pixel at native backing). Dividing by zoom keeps
+ // the picture decoupled from the UI scale, so scaling the controls
+ // widens the window instead of shrinking the display.
+ let target = (vm_scale / zoom).max(0.01);
+ // Always shrink to fit the work area, leaving a clear margin so the
+ // window stays obviously windowed (not edge-to-edge). Fall back to a
+ // conservative cap if the monitor size isn't reported, so a high VM
+ // scale can never blow the window up off-screen and push the controls
+ // out of view.
+ const MARGIN: f32 = 0.85;
+ let (avail_w, avail_h) = match ctx.input(|i| i.viewport().monitor_size) {
+ Some(m) => (m.x * MARGIN - chrome_w, m.y * MARGIN - chrome_h),
+ None => (1400.0 - chrome_w, 900.0 - chrome_h),
+ };
+ // Use the requested scale, or the largest that fits when the monitor is
+ // the binding constraint. The slider already restricts requests to clean
+ // ¼× steps, so we don't snap here — when we must clamp to the monitor we
+ // use the full fitting size (the footer readout reports the actual scale
+ // and tags non-crisp ones) rather than dropping a whole step.
+ let scale = target
+ .min((avail_w.max(64.0)) / fb_px.x)
+ .min((avail_h.max(64.0)) / fb_px.y)
+ .clamp(0.05, target);
+ let inner = egui::vec2(fb_px.x * scale + chrome_w, fb_px.y * scale + chrome_h);
+ ctx.send_viewport_cmd(ViewportCommand::InnerSize(inner));
}
/// Draw the live REX3 framebuffer as an egui image, scaled to fit
@@ -693,32 +984,70 @@ impl App {
return;
}
- if self.fb_tex.is_none() || seq != self.last_fb_seq {
+ let avail = ui.available_size();
+
+ // Pick the texture filter from the *device-pixel* scale at which the
+ // framebuffer will actually be drawn. At an integer scale (native 1×,
+ // 2×, 3×, …) NEAREST keeps every emulated pixel crisp and square. At a
+ // fractional scale — which is what most users hit once they set a
+ // non-100% UI scale or resize the window freely — NEAREST has to double
+ // some source pixels and not others, so e.g. the strokes of a "T" come
+ // out uneven; LINEAR (bilinear) spreads the error and looks right. We
+ // need the native size to compute this, so on the very first frame
+ // (no texture yet) we default to NEAREST and correct on the next frame.
+ let zoom = ui.ctx().zoom_factor();
+ let want_nearest = match self.fb_tex.as_ref().map(|t| t.size_vec2()) {
+ Some(px) if px.x >= 1.0 && px.y >= 1.0 => {
+ let size = fb_fit_size(avail, px);
+ let scale = size.y * ui.ctx().pixels_per_point() / px.y;
+ is_integer_scale(scale)
+ }
+ _ => true,
+ };
+
+ if self.fb_tex.is_none() || seq != self.last_fb_seq || want_nearest != self.fb_nearest {
let frame = self.emu.frame_sink.snapshot();
if frame.width == 0 || frame.height == 0 { return; }
let img = egui::ColorImage::from_rgba_unmultiplied(
[frame.width, frame.height], &frame.rgba);
+ let opts = if want_nearest {
+ egui::TextureOptions::NEAREST
+ } else {
+ egui::TextureOptions::LINEAR
+ };
match &mut self.fb_tex {
- Some(t) => t.set(img, egui::TextureOptions::NEAREST),
+ Some(t) => t.set(img, opts),
None => {
- self.fb_tex = Some(ui.ctx().load_texture(
- "rex3_fb", img, egui::TextureOptions::NEAREST));
+ self.fb_tex = Some(ui.ctx().load_texture("rex3_fb", img, opts));
}
}
self.last_fb_seq = frame.seq;
+ self.fb_nearest = want_nearest;
}
+ // Consume the snap request before the immutable borrow of self.fb_tex.
+ let do_snap = std::mem::take(&mut self.pending_fb_snap);
+
let mut fb_rect = egui::Rect::NOTHING;
+ let mut fb_clicked = false;
+ let mut new_fb_scale = 0.0;
if let Some(tex) = &self.fb_tex {
- let avail = ui.available_size();
let tex_size = tex.size_vec2();
- let fb_aspect = tex_size.x / tex_size.y;
- let avail_aspect = avail.x / avail.y;
- let size = if avail_aspect > fb_aspect {
- egui::vec2(avail.y * fb_aspect, avail.y)
- } else {
- egui::vec2(avail.x, avail.x / fb_aspect)
- };
+ // First frame after Start (or after a VM/UI scale change): size the
+ // window so the picture lands at the requested VM scale.
+ if do_snap {
+ Self::snap_window_to_fb(ui.ctx(), tex_size, avail, self.prefs.vm_scale);
+ }
+ // Fill the available area (aspect-preserved). The window — not the
+ // image — carries the chosen scale (set by the snap above), so the
+ // steady-state draw is stable: no per-frame resize, no jitter.
+ let size = fb_fit_size(avail, tex_size);
+ // Reported VM scale: device pixels per emulated pixel relative to
+ // native backing (1.0 = native). `size` is in zoom-scaled points, so
+ // multiply by zoom to recover the zoom-independent figure.
+ if tex_size.y >= 1.0 {
+ new_fb_scale = size.y * zoom / tex_size.y;
+ }
ui.centered_and_justified(|ui| {
let response = ui.add(
egui::Image::new((tex.id(), size)).fit_to_exact_size(size).sense(egui::Sense::click())
@@ -727,16 +1056,30 @@ impl App {
// Take keyboard focus so that egui delivers Key events
// to us instead of routing them to other widgets when
// the user clicks into the FB.
- if response.clicked() { response.request_focus(); }
+ if response.clicked() { response.request_focus(); fb_clicked = true; }
});
}
+ self.fb_scale = new_fb_scale;
+
+ // When the guest becomes "safe to stop" (CPU halted — a clean IRIX
+ // shutdown / `halt`), auto-release the captured mouse & keyboard so the
+ // user gets their cursor back without pressing Ctrl+Alt+Esc. Edge-
+ // triggered on the running→halted transition (prev is reset to true at
+ // Start, so idling at the PROM during boot doesn't count), and they can
+ // still click the display to re-capture.
+ let halted = self.emu.status.cpu_halted;
+ if halted && !self.prev_cpu_halted && self.input_state.captured {
+ input::force_release(ui.ctx(), &mut self.input_state);
+ self.toast("guest halted — mouse released (click display to re-capture)");
+ }
+ self.prev_cpu_halted = halted;
// Pump egui input → PS/2 controller. Mouse/keyboard only reach the
// guest while captured (click the framebuffer to capture, Ctrl+Alt+Esc
// to release), so menu clicks and config typing don't leak in.
let ps2 = self.emu.ps2.lock().clone();
if let Some(ps2) = ps2 {
- input::pump(ui.ctx(), fb_rect, &ps2, &mut self.input_state, self.cfg.mouse_scroll_pixels_per_line);
+ input::pump(ui.ctx(), fb_clicked, &ps2, &mut self.input_state, self.cfg.mouse_scroll_pixels_per_line);
}
// Capture hint, drawn over the framebuffer.
@@ -765,10 +1108,248 @@ impl App {
ui.separator();
match show_tab(ui, self.tab, &mut self.cfg, &mut self.jit) {
ConfigAction::RequestEmbeddedProm => self.confirm_embedded_prom = true,
+ ConfigAction::TestCamera => self.open_camera_test(),
ConfigAction::None => {}
}
}
+ /// Open (or restart) the live host-camera preview using the current
+ /// `[vino]` standard and camera index. Releases any previous test first.
+ fn open_camera_test(&mut self) {
+ use iris::video_source::VideoStandard;
+ let standard = match self.cfg.vino.standard {
+ iris::config::VinoStandard::Ntsc => VideoStandard::Ntsc,
+ iris::config::VinoStandard::Pal => VideoStandard::Pal,
+ };
+ // Drop the previous instance first so the camera is fully released
+ // before re-opening (its Drop joins the capture thread).
+ self.camera_test = None;
+ self.camera_test_tex = None;
+ self.camera_test_seq = 0;
+ self.camera_test = Some(camera_test::CameraTest::start(standard, self.cfg.vino.camera_index));
+ }
+
+ /// Draw the live host-camera preview window (no-op when closed). Closing it
+ /// (or pressing Stop) drops the `CameraTest`, releasing the camera.
+ fn camera_test_window(&mut self, ctx: &egui::Context) {
+ let Some(test) = &self.camera_test else { return };
+
+ // Pull the latest frame and upload it to the preview texture.
+ if let Some((w, h, rgba)) = test.take_new_frame(&mut self.camera_test_seq) {
+ let image = egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &rgba);
+ match &mut self.camera_test_tex {
+ Some(tex) => tex.set(image, egui::TextureOptions::LINEAR),
+ None => {
+ self.camera_test_tex =
+ Some(ctx.load_texture("camera-test", image, egui::TextureOptions::LINEAR));
+ }
+ }
+ }
+ let status = test.status();
+ let error = test.error();
+
+ let mut open = true;
+ let mut close_now = false;
+ egui::Window::new("Test Camera")
+ .open(&mut open)
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ if let Some(e) = &error {
+ ui.colored_label(Color32::from_rgb(200, 80, 80),
+ format!("Camera unavailable: {e}"));
+ ui.label(RichText::new(
+ "Check that a camera is connected and that IRIS has camera \
+ permission (System Settings → Privacy & Security → Camera).")
+ .weak());
+ } else if let Some(tex) = &self.camera_test_tex {
+ // The capture field is half-height (interlaced), so present
+ // it at ~4:3 by drawing into a fixed-size rect.
+ ui.add(egui::Image::new(&*tex)
+ .fit_to_exact_size(egui::vec2(480.0, 360.0))
+ .rounding(4.0));
+ } else {
+ ui.add_space(110.0);
+ ui.label("Starting capture…");
+ ui.label(RichText::new(
+ "If no image appears, grant camera access in System \
+ Settings → Privacy & Security → Camera, then reopen.")
+ .weak().small());
+ }
+ ui.add_space(6.0);
+ ui.label(RichText::new(&status).weak().small());
+ ui.add_space(6.0);
+ if ui.button("Close").clicked() {
+ close_now = true;
+ }
+ });
+
+ if !open || close_now {
+ // Drop releases the camera (CameraTest::Drop joins the worker).
+ self.camera_test = None;
+ self.camera_test_tex = None;
+ self.camera_test_seq = 0;
+ } else {
+ // Keep the preview animating even when egui is otherwise idle.
+ ctx.request_repaint_after(std::time::Duration::from_millis(33));
+ }
+ }
+
+ /// Open (or reconnect) the in-app IRIX serial-console viewer. Connects to
+ /// the loopback serial server the running emulator exposes.
+ fn open_serial_console(&mut self) {
+ self.serial_console = Some(serial_console::SerialConsole::connect());
+ }
+
+ /// Draw the in-app serial-console window (no-op when closed). Demonstrates
+ /// the loopback serial server: the emulator listens on 127.0.0.1:8881 and
+ /// this viewer connects to it.
+ fn serial_console_window(&mut self, ctx: &egui::Context) {
+ let Some(console) = &self.serial_console else { return };
+ let (text, connected, error, _seq) = console.snapshot();
+
+ let mut open = true;
+ let mut close_now = false;
+ let mut clear_now = false;
+ let mut to_send: Option = None;
+ egui::Window::new("IRIX Serial Console (ttyd1)")
+ .open(&mut open)
+ .default_width(620.0)
+ .default_height(420.0)
+ .resizable(true)
+ .show(ctx, |ui| {
+ ui.horizontal(|ui| {
+ if let Some(e) = &error {
+ ui.colored_label(Color32::from_rgb(200, 80, 80), e);
+ } else if connected {
+ ui.colored_label(Color32::from_rgb(90, 170, 90),
+ format!("● connected to {}", serial_console::SERIAL_ADDR));
+ } else {
+ ui.label("disconnected");
+ }
+ });
+ ui.separator();
+
+ egui::ScrollArea::vertical()
+ .stick_to_bottom(true)
+ .auto_shrink([false, false])
+ .max_height(320.0)
+ .show(ui, |ui| {
+ ui.add(
+ egui::Label::new(
+ RichText::new(&text).monospace().size(12.0),
+ )
+ .wrap(),
+ );
+ });
+
+ ui.separator();
+ ui.horizontal(|ui| {
+ let resp = ui.add(
+ egui::TextEdit::singleline(&mut self.serial_input)
+ .hint_text("type a command, press Enter")
+ .desired_width(420.0),
+ );
+ let entered = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
+ if (ui.button("Send").clicked() || entered) && connected {
+ to_send = Some(std::mem::take(&mut self.serial_input));
+ resp.request_focus();
+ }
+ if ui.button("Clear").clicked() {
+ clear_now = true;
+ }
+ if ui.button("Close").clicked() {
+ close_now = true;
+ }
+ });
+ });
+
+ if let Some(line) = to_send {
+ let mut bytes = line.into_bytes();
+ bytes.push(b'\n');
+ console.send(&bytes);
+ }
+ if clear_now {
+ console.clear();
+ }
+ if !open || close_now {
+ self.serial_console = None;
+ } else if connected {
+ // Poll for new console output even when egui is otherwise idle.
+ ctx.request_repaint_after(std::time::Duration::from_millis(80));
+ }
+ }
+
+ /// Explains the camera (IndyCam) and networking features — what they do and
+ /// how to use them (for end users), and what host capabilities they use and
+ /// why (for App Review). Opened from Help → "How camera & networking work".
+ fn help_info_window(&mut self, ctx: &egui::Context) {
+ if !self.show_help_info {
+ return;
+ }
+ let mut open = true;
+ egui::Window::new("How camera & networking work")
+ .open(&mut open)
+ .default_width(560.0)
+ .default_height(480.0)
+ .collapsible(false)
+ .resizable(true)
+ .show(ctx, |ui| {
+ egui::ScrollArea::vertical().max_height(420.0).auto_shrink([false, false]).show(ui, |ui| {
+ ui.heading("📷 Camera — the IndyCam");
+ ui.label(
+ "IRIS emulates the SGI Indy's IndyCam video-input hardware (the VINO device). \
+ When you pick your Mac's camera as the video source, IRIS captures live frames \
+ from it and feeds them to the emulated video input — just as a real IndyCam fed \
+ a real Indy.",
+ );
+ ui.add_space(6.0);
+ ui.label(RichText::new("How to use it").strong());
+ ui.label("• Help → Diagnostics → Test Camera shows a live preview (start a machine first).");
+ ui.label("• Or set Video-In → Source = camera, boot IRIX, and run an IndyCam app like vino/cam.");
+ ui.label("• On first use macOS asks for camera permission. Closing the preview releases the camera.");
+ ui.add_space(6.0);
+ ui.label(RichText::new("Privacy / for App Review").strong());
+ ui.label(
+ "Camera frames are used only as the emulated video input — IRIS never records, \
+ stores, or transmits them. It uses the public AVFoundation API with the \
+ com.apple.security.device.camera entitlement and the NSCameraUsageDescription \
+ purpose string.",
+ );
+
+ ui.separator();
+ ui.heading("🌐 Networking");
+ ui.label(
+ "The emulated Indy reaches the internet through a built-in user-mode NAT, like a \
+ home router: outbound connections from IRIX are translated onto the host. No \
+ system network settings or elevated privileges are touched.",
+ );
+ ui.add_space(6.0);
+ ui.label(RichText::new("How to use it").strong());
+ ui.label("• The guest serial console (ttyd1) and PROM monitor are exposed on loopback");
+ ui.label(" TCP (127.0.0.1:8881 / 8888) so you can attach a terminal.");
+ ui.label("• Help → Diagnostics → Network test opens an in-app viewer of that console.");
+ ui.label("• Optional inbound port-forwards (Networking tab) let you reach guest services.");
+ ui.add_space(6.0);
+ ui.label(RichText::new("Privacy / for App Review").strong());
+ ui.label(
+ "Outbound guest traffic uses com.apple.security.network.client. The loopback \
+ serial/monitor servers and any inbound port-forwards use \
+ com.apple.security.network.server. Every socket is on loopback or user-initiated; \
+ IRIS opens no network connections on its own.",
+ );
+ });
+ ui.separator();
+ if ui.button("Close").clicked() {
+ self.show_help_info = false;
+ }
+ });
+ if !open {
+ self.show_help_info = false;
+ }
+ }
+
fn welcome_panel(&mut self, ui: &mut egui::Ui) {
ui.add_space(8.0);
ui.heading("iris — SGI Indy emulator");
@@ -786,13 +1367,13 @@ impl App {
egui::Grid::new("summary_grid").num_columns(2).striped(true).show(ui, |ui| {
ui.label("PROM");
ui.label(if std::path::Path::new(&self.cfg.prom).exists() {
- self.cfg.prom.clone()
+ abs_path(&self.cfg.prom)
} else {
format!("{} (missing -> embedded fallback)", self.cfg.prom)
});
ui.end_row();
ui.label("NVRAM");
- ui.label(&self.cfg.nvram);
+ ui.label(abs_path(&self.cfg.nvram));
ui.end_row();
ui.label("RAM");
ui.label(format!("{total_ram} MB ({:?})", self.cfg.banks));
@@ -807,7 +1388,7 @@ impl App {
for id in ids {
let d = &self.cfg.scsi[&id];
let kind = if d.cdrom { "CD" } else { "HDD" };
- ui.label(format!("scsi{id} {kind}: {}", d.path));
+ ui.label(format!("scsi{id} {kind}: {}", abs_path(&d.path)));
}
ui.label(RichText::new("Use the SCSI menu to attach / detach / replace.").weak().small());
});
@@ -829,21 +1410,41 @@ impl App {
}
}
- fn status_bar(&mut self, ui: &mut egui::Ui) {
- ui.horizontal(|ui| {
- let name = self.prefs.active_machine.as_deref().unwrap_or("(unsaved)");
- ui.label(format!("Machine: {name}{}", if self.cfg_dirty { " *" } else { "" }));
- ui.separator();
- ui.label(format!("Dirty COW: {}", self.emu.status.dirty_cow));
- if let Some((msg, when)) = self.toast.clone() {
- if when.elapsed().as_secs() < 5 {
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- ui.label(RichText::new(msg).color(Color32::YELLOW));
- });
- } else {
- self.toast = None;
- }
+ /// Status footer for the left control column: run-state, machine name,
+ /// dirty-COW count, and the transient toast. Laid out vertically.
+ fn status_block(&mut self, ui: &mut egui::Ui) {
+ ui.add_space(4.0);
+ self.run_state_label(ui);
+ ui.separator();
+ let name = self.prefs.active_machine.as_deref().unwrap_or("(unsaved)");
+ ui.label(format!("Machine: {name}{}", if self.cfg_dirty { " *" } else { "" }));
+ ui.label(format!("Dirty COW: {}", self.emu.status.dirty_cow));
+ if let Some((msg, when)) = self.toast.clone() {
+ if when.elapsed().as_secs() < 5 {
+ ui.add_space(2.0);
+ ui.label(RichText::new(msg).color(Color32::YELLOW));
+ } else {
+ self.toast = None;
}
+ }
+ ui.add_space(2.0);
+ }
+
+ /// The full left control column: machine controls, menus, and config
+ /// quick-buttons stacked vertically, with the status block pinned to the
+ /// bottom. This replaces the old top menu bar + toolbar + bottom status bar,
+ /// freeing vertical space for the (tall, 5:4) emulated display.
+ fn control_panel(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
+ egui::TopBottomPanel::bottom("ctl_status")
+ .show_inside(ui, |ui| self.status_block(ui));
+
+ egui::ScrollArea::vertical().show(ui, |ui| {
+ ui.add_space(4.0);
+ self.machine_controls(ui);
+ ui.separator();
+ self.menu_list(ui, ctx);
+ ui.separator();
+ self.config_quick_buttons(ui);
});
}
}
@@ -853,6 +1454,17 @@ impl eframe::App for App {
self.handle_events(ctx);
self.maybe_autosave();
+ // Remember the current window size so the next launch reopens at it.
+ // inner_rect is in logical points — the same unit ViewportBuilder's
+ // with_inner_size() takes — so this round-trips regardless of UI zoom.
+ // Stored in-memory here; on_exit() (and other save() calls) persist it.
+ if let Some(r) = ctx.input(|i| i.viewport().inner_rect) {
+ let sz = r.size();
+ if sz.x.is_finite() && sz.y.is_finite() && sz.x >= 480.0 && sz.y >= 360.0 {
+ self.prefs.window_size = Some([sz.x.round(), sz.y.round()]);
+ }
+ }
+
// F11 toggles fullscreen.
if ctx.input(|i| i.key_pressed(egui::Key::F11)) {
self.fullscreen = !self.fullscreen;
@@ -869,18 +1481,16 @@ impl eframe::App for App {
if zoom_in { self.prefs.ui_scale = (self.prefs.ui_scale + 0.1).min(UI_SCALE_MAX); ctx.set_zoom_factor(self.prefs.ui_scale); }
if zoom_out { self.prefs.ui_scale = (self.prefs.ui_scale - 0.1).max(UI_SCALE_MIN); ctx.set_zoom_factor(self.prefs.ui_scale); }
if zoom_reset { self.prefs.ui_scale = settings::UI_SCALE_DEFAULT; ctx.set_zoom_factor(self.prefs.ui_scale); }
+ // Any UI-zoom change re-fits the window so the controls grow it instead
+ // of squeezing the (decoupled) VM screen.
+ if zoom_in || zoom_out || zoom_reset { self.pending_fb_snap = true; }
- // In fullscreen, only reveal menu/toolbar when the cursor is near the top.
- let pointer_y = ctx.input(|i| i.pointer.latest_pos().map(|p| p.y).unwrap_or(f32::MAX));
- let chrome_visible = !self.fullscreen || pointer_y < 36.0;
-
- if chrome_visible {
- egui::TopBottomPanel::top("menu_bar").show(ctx, |ui| self.menu_bar(ui, ctx));
- egui::TopBottomPanel::top("toolbar").show(ctx, |ui| self.toolbar(ui));
- }
- if !self.fullscreen {
- egui::TopBottomPanel::bottom("status_bar").show(ctx, |ui| self.status_bar(ui));
- }
+ // The control column lives on the left, always visible (even in
+ // fullscreen) — the VM screen sits to its right and never hides it.
+ egui::SidePanel::left("control_panel")
+ .resizable(false)
+ .exact_width(186.0)
+ .show(ctx, |ui| self.control_panel(ui, ctx));
// Config editor lives in a collapsible side panel so the emulator
// screen (central panel) is never hidden by it. The toolbar's
@@ -902,7 +1512,13 @@ impl eframe::App for App {
egui::ScrollArea::vertical().show(ui, |ui| self.central_tabs(ui));
});
- egui::CentralPanel::default().show(ctx, |ui| {
+ // Zero the central panel's inner margin so the emulated display reaches
+ // the window edges — every reclaimed pixel makes the (tall, 5:4) picture
+ // a little bigger. Keep the dark panel fill so the aspect-ratio
+ // letterbox bars stay black.
+ let central_frame = egui::Frame::central_panel(&ctx.style())
+ .inner_margin(egui::Margin::ZERO);
+ egui::CentralPanel::default().frame(central_frame).show(ctx, |ui| {
// The central panel always shows the emulator screen when the
// machine is running (the REX3 framebuffer), falling back to the
// welcome / status summary when idle. The config editor no longer
@@ -910,6 +1526,16 @@ impl eframe::App for App {
if self.emu.is_running() {
self.framebuffer_panel(ui);
} else {
+ // First-ever launch: size the window to the monitor for the
+ // standard 1280×1024 display before the user sees it (the
+ // on-Start snap later re-fits to the actual guest resolution).
+ // Wait for the monitor size to be known before consuming the flag.
+ if self.pending_launcher_fit
+ && ui.ctx().input(|i| i.viewport().monitor_size).is_some()
+ {
+ Self::snap_window_to_fb(ui.ctx(), egui::vec2(1280.0, 1024.0), ui.available_size(), self.prefs.vm_scale);
+ self.pending_launcher_fit = false;
+ }
// Emulator not running: make sure a leftover mouse capture is
// released so the host cursor isn't stuck hidden/locked.
input::force_release(ui.ctx(), &mut self.input_state);
@@ -941,6 +1567,15 @@ impl eframe::App for App {
self.toast(format!("created {path_str} and attached at scsi{}", result.scsi_id));
}
+ // Live host-camera test window.
+ self.camera_test_window(ctx);
+
+ // In-app IRIX serial-console viewer.
+ self.serial_console_window(ctx);
+
+ // Help → "How camera & networking work" explainer.
+ self.help_info_window(ctx);
+
// Safe-stop confirmation modal.
let mut close_modal = false;
let mut do_force = false;
@@ -968,25 +1603,16 @@ impl eframe::App for App {
if close_modal { self.stop_modal = None; }
if do_force { self.emu.send(Cmd::Stop); }
if do_halt {
- // iris always opens 127.0.0.1:8881 as the ttyd1 (IRIX serial
- // console) TCP listener in non-CI mode. Connect to it,
- // write "halt\n", disconnect. IRIX takes a few seconds to
- // shut down cleanly; the user can hit Stop again once the
- // PROM "halted" message appears.
- use std::io::Write as _;
- match std::net::TcpStream::connect_timeout(
- &"127.0.0.1:8881".parse().unwrap(),
- std::time::Duration::from_millis(500),
- ) {
- Ok(mut s) => {
- let _ = s.write_all(b"halt\n");
- self.toast("sent 'halt' to IRIX — wait for shutdown, then Stop");
- }
- Err(e) => {
- self.toast(format!("halt failed: {e} — falling back to Force stop"));
- self.emu.send(Cmd::Stop);
- }
- }
+ // Type "halt\n" at the IRIX serial console in-process (see
+ // EmulatorHandle / Machine::inject_serial_console). This used to
+ // open a loopback TCP client to 127.0.0.1:8881; doing it in-process
+ // means clean shutdown no longer depends on the serial server
+ // socket (which the macOS App Sandbox would otherwise gate behind
+ // the network.server entitlement). IRIX takes a few seconds to shut
+ // down cleanly; the user can hit Stop once the PROM "halted"
+ // message appears.
+ self.emu.send(Cmd::HaltIrix);
+ self.toast("sent 'halt' to IRIX — wait for shutdown, then Stop");
}
// Confirm switching from a custom PROM back to the built-in image.
@@ -1074,6 +1700,23 @@ impl eframe::App for App {
self.detach_and_start(&ids);
}
}
+
+ // The window starts hidden so the first frame(s) can fit it to the
+ // monitor (the launcher fit, when not running) before it's shown —
+ // avoiding a visible open-then-resize. Reveal one frame after the fit
+ // settles so its resize has applied, or unconditionally after a short
+ // grace period so a missing monitor size can't leave the window hidden.
+ if !self.revealed {
+ self.startup_frame = self.startup_frame.saturating_add(1);
+ let fit_settled = !self.pending_launcher_fit;
+ if (fit_settled && self.startup_frame >= 2) || self.startup_frame >= 10 {
+ ctx.send_viewport_cmd(ViewportCommand::Visible(true));
+ self.revealed = true;
+ } else {
+ // Keep frames coming while hidden so we reach the reveal.
+ ctx.request_repaint();
+ }
+ }
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
diff --git a/iris-gui/src/safe_stop.rs b/iris-gui/src/safe_stop.rs
index 9504450..a231ede 100644
--- a/iris-gui/src/safe_stop.rs
+++ b/iris-gui/src/safe_stop.rs
@@ -18,8 +18,12 @@ impl UnsafeReasons {
/// Evaluate whether stopping the emulator right now is safe.
///
-/// The core does not expose live dirty-sector state, so we decide purely from
-/// config: an abrupt power-off only risks the on-disk image when some attached
+/// If the CPU has halted (clean shutdown / soft power-off, or idle at the PROM),
+/// nothing is writing and stopping is always safe — see the `cpu_halted`
+/// short-circuit below.
+///
+/// Otherwise the core does not expose live dirty-sector state, so we decide
+/// purely from config: an abrupt power-off only risks the on-disk image when some attached
/// device persists guest writes straight into its **base image** — i.e. a
/// plain read-write hard disk. Everything else leaves the base image untouched
/// and is safe to power off without warning:
@@ -34,7 +38,14 @@ impl UnsafeReasons {
///
/// So when no attached device writes through to its base image, powering off
/// will NOT damage the hard disk and we skip the confirmation dialog entirely.
-pub fn evaluate(_status: &Status, cfg: &MachineConfig) -> UnsafeReasons {
+pub fn evaluate(status: &Status, cfg: &MachineConfig) -> UnsafeReasons {
+ // If the CPU has halted — a clean IRIX shutdown / soft power-off, or sitting
+ // idle at the PROM (0 MIPS) — nothing is writing to any disk, so stopping
+ // now cannot corrupt a filesystem. Skip the warning regardless of config.
+ if status.cpu_halted {
+ return UnsafeReasons::default();
+ }
+
let mut r = UnsafeReasons::default();
for (id, dev) in &cfg.scsi {
let persists_to_base = !dev.cdrom
@@ -61,3 +72,29 @@ pub fn reason_lines(r: &UnsafeReasons) -> Vec {
})
.collect()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // MachineConfig::default() attaches scsi1 as a plain read-write disk image,
+ // so it is the "unsafe while running" case.
+ fn running(halted: bool) -> Status {
+ Status { running: true, cpu_halted: halted, ..Status::default() }
+ }
+
+ #[test]
+ fn writable_disk_is_unsafe_while_cpu_runs() {
+ let r = evaluate(&running(false), &MachineConfig::default());
+ assert!(!r.is_empty(), "a live rw disk should warn before force-stop");
+ assert!(r.writable_disks.contains(&1));
+ }
+
+ #[test]
+ fn halted_cpu_is_always_safe() {
+ // After IRIX shuts down (0 MIPS / power-off) stopping can't corrupt a
+ // disk, so the same config must now evaluate as safe.
+ let r = evaluate(&running(true), &MachineConfig::default());
+ assert!(r.is_empty(), "a halted CPU must be safe to stop");
+ }
+}
diff --git a/iris-gui/src/serial_console.rs b/iris-gui/src/serial_console.rs
new file mode 100644
index 0000000..e65c31f
--- /dev/null
+++ b/iris-gui/src/serial_console.rs
@@ -0,0 +1,192 @@
+//! In-app IRIX serial-console viewer.
+//!
+//! The emulated SGI Indy exposes its serial console (ttyd1) as a loopback TCP
+//! server on `127.0.0.1:8881` (see `iris::z85c30`). This viewer connects to it
+//! as a client and shows the live console stream, and lets the user type back
+//! into it — so the serial console works inside the app without an external
+//! terminal. It is also the visible demonstration of the app's network
+//! entitlements: the emulator *listens* (network.server) and this viewer
+//! *connects* (network.client), both on loopback.
+//!
+//! A background thread owns the socket, strips inbound telnet negotiation via
+//! `iris::telnet::TelnetFilter`, and parks decoded text in a shared buffer.
+
+use std::io::{Read, Write};
+use std::net::{Shutdown, SocketAddr, TcpStream};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::thread::JoinHandle;
+use std::time::Duration;
+
+use parking_lot::Mutex;
+
+use iris::telnet::{self, TelnetFilter};
+
+/// The loopback address the emulator binds for ttyd1 (IRIX serial console).
+pub const SERIAL_ADDR: &str = "127.0.0.1:8881";
+/// Cap on retained scrollback so a long boot doesn't grow the buffer forever.
+const MAX_TEXT: usize = 128 * 1024;
+
+#[derive(Default)]
+struct Shared {
+ /// Decoded console text (telnet stripped, bare CR dropped).
+ text: String,
+ /// True once the TCP connection is established.
+ connected: bool,
+ /// Set if the connection could not be made / was lost.
+ error: Option,
+ /// Bumped on every change so the GUI can decide whether to re-scroll.
+ seq: u64,
+}
+
+pub struct SerialConsole {
+ shared: Arc>,
+ running: Arc,
+ /// Write half (a clone of the socket) for sending typed input.
+ write: Arc>>,
+ worker: Option>,
+}
+
+impl SerialConsole {
+ /// Connect to the loopback serial console and start streaming.
+ pub fn connect() -> Self {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let running = Arc::new(AtomicBool::new(true));
+ let write = Arc::new(Mutex::new(None));
+ let (s2, r2, w2) = (shared.clone(), running.clone(), write.clone());
+ let worker = std::thread::Builder::new()
+ .name("iris-gui-serial".into())
+ .spawn(move || run(s2, r2, w2))
+ .expect("spawn serial-console worker");
+ Self { shared, running, write, worker: Some(worker) }
+ }
+
+ /// (text, connected, error, seq) snapshot for rendering.
+ pub fn snapshot(&self) -> (String, bool, Option, u64) {
+ let g = self.shared.lock();
+ (g.text.clone(), g.connected, g.error.clone(), g.seq)
+ }
+
+ pub fn clear(&self) {
+ let mut g = self.shared.lock();
+ g.text.clear();
+ g.seq = g.seq.wrapping_add(1);
+ }
+
+ /// Send raw bytes to the guest console (telnet-escaping 0xFF).
+ pub fn send(&self, bytes: &[u8]) {
+ let mut esc = Vec::with_capacity(bytes.len());
+ for &b in bytes {
+ telnet::escape_byte(b, &mut esc);
+ }
+ if let Some(s) = self.write.lock().as_mut() {
+ let _ = s.write_all(&esc);
+ let _ = s.flush();
+ }
+ }
+}
+
+impl Drop for SerialConsole {
+ fn drop(&mut self) {
+ self.running.store(false, Ordering::Relaxed);
+ // Shutting the socket down unblocks the reader's blocking read so the
+ // worker exits promptly.
+ if let Some(s) = self.write.lock().take() {
+ let _ = s.shutdown(Shutdown::Both);
+ }
+ if let Some(w) = self.worker.take() {
+ let _ = w.join();
+ }
+ }
+}
+
+fn run(shared: Arc>, running: Arc, write: Arc>>) {
+ let addr: SocketAddr = SERIAL_ADDR.parse().expect("valid loopback addr");
+ let stream = match TcpStream::connect_timeout(&addr, Duration::from_millis(800)) {
+ Ok(s) => s,
+ Err(e) => {
+ shared.lock().error = Some(format!(
+ "could not connect to {SERIAL_ADDR}: {e}\nStart the emulator first, then reopen."
+ ));
+ return;
+ }
+ };
+ let wclone = match stream.try_clone() {
+ Ok(c) => c,
+ Err(e) => {
+ shared.lock().error = Some(format!("socket clone failed: {e}"));
+ return;
+ }
+ };
+ *write.lock() = Some(wclone);
+ // Short read timeout so the loop can observe `running` for shutdown.
+ let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
+ {
+ let mut g = shared.lock();
+ g.connected = true;
+ g.error = None;
+ g.seq = g.seq.wrapping_add(1);
+ }
+
+ // Client-side telnet handling: decline negotiation, strip IAC. The guest's
+ // tty echoes typed characters, so no telnet-layer echo is needed.
+ let mut filter = TelnetFilter::new_passive();
+ let mut buf = [0u8; 2048];
+ let mut rstream = stream;
+
+ while running.load(Ordering::Relaxed) {
+ match rstream.read(&mut buf) {
+ Ok(0) => break, // EOF — server closed
+ Ok(n) => {
+ let mut replies = Vec::new();
+ let mut data = Vec::with_capacity(n);
+ for &b in &buf[..n] {
+ if let Some(d) = filter.feed(b, &mut replies) {
+ data.push(d);
+ }
+ }
+ if !replies.is_empty() {
+ if let Some(s) = write.lock().as_mut() {
+ let _ = s.write_all(&replies);
+ let _ = s.flush();
+ }
+ }
+ if !data.is_empty() {
+ append_text(&shared, &data);
+ }
+ }
+ Err(ref e)
+ if e.kind() == std::io::ErrorKind::WouldBlock
+ || e.kind() == std::io::ErrorKind::TimedOut =>
+ {
+ continue;
+ }
+ Err(_) => break,
+ }
+ }
+
+ *write.lock() = None;
+ let mut g = shared.lock();
+ g.connected = false;
+ g.seq = g.seq.wrapping_add(1);
+}
+
+fn append_text(shared: &Arc>, data: &[u8]) {
+ let chunk = String::from_utf8_lossy(data);
+ let mut g = shared.lock();
+ for ch in chunk.chars() {
+ // Drop bare CR; egui handles \n line breaks.
+ if ch != '\r' {
+ g.text.push(ch);
+ }
+ }
+ if g.text.len() > MAX_TEXT {
+ let cut = g.text.len() - MAX_TEXT;
+ let mut idx = cut;
+ while !g.text.is_char_boundary(idx) {
+ idx += 1;
+ }
+ g.text.drain(..idx);
+ }
+ g.seq = g.seq.wrapping_add(1);
+}
diff --git a/iris-gui/src/settings.rs b/iris-gui/src/settings.rs
index 4f6378d..1b92e6e 100644
--- a/iris-gui/src/settings.rs
+++ b/iris-gui/src/settings.rs
@@ -1,7 +1,7 @@
use iris::config::MachineConfig;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
/// GUI-only persisted state. Lives at `~/.config/iris/gui.json`.
///
@@ -16,6 +16,12 @@ pub struct GuiSettings {
/// egui UI scale (1.0 = default).
#[serde(default = "default_ui_scale")]
pub ui_scale: f32,
+ /// Emulated-display (VM screen) magnification: 1.0 = native (1 emulated
+ /// pixel : 1 logical point). Driven by the View-menu slider (0.5×–3× in 0.5
+ /// steps), **independent of `ui_scale`** — scaling the controls doesn't
+ /// resize the picture, and vice-versa.
+ #[serde(default = "default_vm_scale")]
+ pub vm_scale: f32,
/// Was the app left in fullscreen mode at last close?
#[serde(default)]
pub fullscreen: bool,
@@ -47,6 +53,89 @@ pub struct GuiSettings {
pub bookmarks: BTreeMap>,
}
+/// Byte offset of the Indy's 6-byte Ethernet MAC inside the NVRAM. The PROM
+/// reads the MAC from these *raw bytes* — it is NOT the colon-separated ASCII
+/// you type at `setenv` (that's just the human entry form). Reverse-engineered
+/// from firmware-written NVRAMs (the SGI OUI 08:00:69 lands exactly here, with
+/// zero bytes around it and no adjacent checksum). Like the `console` byte the
+/// headless path patches, this is a fixed, PROM-specific offset.
+pub const NVRAM_MAC_OFFSET: usize = 0x13a;
+
+/// The 6 raw MAC bytes from an NVRAM file, if it holds a non-blank one.
+pub fn nvram_mac(path: &str) -> Option<[u8; 6]> {
+ let b = std::fs::read(path).ok()?;
+ let m: [u8; 6] = b.get(NVRAM_MAC_OFFSET..NVRAM_MAC_OFFSET + 6)?.try_into().ok()?;
+ let blank = m.iter().all(|&x| x == 0x00) || m.iter().all(|&x| x == 0xff);
+ (!blank).then_some(m)
+}
+
+/// Whether the NVRAM already has an Ethernet MAC (so IRIX can attach `ec0`).
+pub fn nvram_has_mac(path: &str) -> bool {
+ nvram_mac(path).is_some()
+}
+
+/// Deterministic SGI-OUI MAC bytes (`08:00:69:xx:xx:xx`) from `seed` (machine
+/// name) — stable per machine. Uniqueness across instances doesn't matter; each
+/// runs on its own isolated NAT.
+pub fn generate_mac_bytes(seed: &str) -> [u8; 6] {
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ seed.hash(&mut h);
+ let v = h.finish();
+ [0x08, 0x00, 0x69, (v >> 16) as u8, (v >> 8) as u8, v as u8]
+}
+
+/// Human form `08:00:69:xx:xx:xx` for display/logging.
+pub fn mac_to_string(m: [u8; 6]) -> String {
+ m.iter().map(|b| format!("{b:02x}")).collect::>().join(":")
+}
+
+/// Write 6 MAC bytes into an existing NVRAM file at [`NVRAM_MAC_OFFSET`],
+/// touching only those 6 bytes so the boot env is preserved. Backs the file up
+/// to `.bak` first. Returns Ok(false) if there's no NVRAM file yet (a
+/// bare MAC with no DS1386 structure would be useless) or it's too small.
+pub fn write_nvram_mac(path: &str, mac: [u8; 6]) -> std::io::Result {
+ let Ok(mut bytes) = std::fs::read(path) else { return Ok(false); };
+ if bytes.len() < NVRAM_MAC_OFFSET + 6 {
+ return Ok(false);
+ }
+ let _ = std::fs::copy(path, format!("{path}.bak")); // best-effort backup
+ bytes[NVRAM_MAC_OFFSET..NVRAM_MAC_OFFSET + 6].copy_from_slice(&mac);
+ std::fs::write(path, &bytes)?;
+ Ok(true)
+}
+
+/// Default NVRAM image baked into the binary: the repo's known-good NVRAM (boot
+/// env present) with the MAC zeroed. Lets a fresh install — especially the
+/// bundled `.app`, which has nothing in its working dir to migrate — boot with
+/// proper PROM env, while the auto-write fills in a per-machine MAC.
+pub const DEFAULT_NVRAM: &[u8] = include_bytes!("../assets/nvram-default.bin");
+
+/// Write the embedded default NVRAM to `path` if there's no (non-empty) file
+/// there yet. Returns true if it seeded one. Creates the parent dir as needed.
+pub fn ensure_nvram_seeded(path: &str) -> bool {
+ if std::fs::metadata(path).map(|m| m.len() > 0).unwrap_or(false) {
+ return false;
+ }
+ if let Some(parent) = Path::new(path).parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ std::fs::write(path, DEFAULT_NVRAM).is_ok()
+}
+
+/// Overwrite the NVRAM at `path` with the embedded default (boot env, blank
+/// MAC) — backs the current file up to `.bak` first. Used by the
+/// "Reset NVRAM / fresh PRAM" menu action.
+pub fn reset_nvram(path: &str) -> std::io::Result<()> {
+ if std::fs::metadata(path).map(|m| m.len() > 0).unwrap_or(false) {
+ let _ = std::fs::copy(path, format!("{path}.bak"));
+ }
+ if let Some(parent) = Path::new(path).parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ std::fs::write(path, DEFAULT_NVRAM)
+}
+
/// Allowed UI-scale range, shared by the View-menu slider, the Ctrl +/-/0
/// keyboard zoom, and the load-time clamp so a stale persisted value can never
/// put the UI into a state the slider can't represent (which egui would then
@@ -55,11 +144,89 @@ pub const UI_SCALE_MIN: f32 = 1.0;
pub const UI_SCALE_MAX: f32 = 3.0;
pub const UI_SCALE_DEFAULT: f32 = 1.25;
+/// Allowed VM-screen scale range and step for the View-menu slider. ¼× steps
+/// (0.5, 0.75, 1.0, 1.25, …) give finer control; on a HiDPI (2×) display the
+/// half-integer steps (0.5, 1.0, 1.5, …) are pixel-crisp and the ¼ steps in
+/// between are bilinear-smoothed — the footer readout tags which is which.
+pub const VM_SCALE_MIN: f32 = 0.5;
+pub const VM_SCALE_MAX: f32 = 3.0;
+pub const VM_SCALE_STEP: f64 = 0.25;
+pub const VM_SCALE_DEFAULT: f32 = 1.0;
+
+/// First-launch window size in logical points. Sized to match the *running*
+/// window for the standard 1280×1024 display so the picture doesn't visibly
+/// jump when you press Start: with the left control column (~186 pt) and no
+/// top/bottom chrome, the running size at the default UI scale is ≈ the native
+/// 1280×1024 display plus the column width. The launcher fit (see `main`) and
+/// the on-Start snap still refine this — clamping to the monitor on smaller
+/// screens — so it's only the initial size and the fallback when the monitor
+/// size is unknown. Once a real size is persisted to `gui.json`, that's used.
+pub const WINDOW_DEFAULT_SIZE: [f32; 2] = [1512.0, 1024.0];
+
fn default_ui_scale() -> f32 { UI_SCALE_DEFAULT }
+fn default_vm_scale() -> f32 { VM_SCALE_DEFAULT }
impl GuiSettings {
pub fn config_path() -> Option {
- dirs::config_dir().map(|d| d.join("iris").join("gui.json"))
+ Self::data_dir().map(|d| d.join("gui.json"))
+ }
+
+ /// Stable per-user directory for GUI state (gui.json, nvram.bin, …). The OS
+ /// maps this into the sandbox container automatically on the App Store
+ /// build, so the *same* code resolves the right place for `cargo run` and
+ /// the bundled app alike.
+ pub fn data_dir() -> Option {
+ dirs::config_dir().map(|d| d.join("iris"))
+ }
+
+ /// Default absolute NVRAM path: `/nvram.bin`. Absolute on purpose
+ /// — a relative `nvram.bin` resolves against the process's working
+ /// directory, which differs between `cargo run` (repo root) and a bundled
+ /// `.app`, silently loading different (often blank, MAC-less) NVRAMs. Anchor
+ /// it once and every launch shares one NVRAM.
+ pub fn default_nvram_path() -> String {
+ Self::data_dir()
+ .map(|d| d.join("nvram.bin").to_string_lossy().into_owned())
+ .unwrap_or_else(|| "nvram.bin".to_string())
+ }
+
+ /// Managed directory for newly-created disk images: `/disks`.
+ /// Absolute and writable in every launch context — the OS maps it into the
+ /// sandbox container on the App Store build, so creating a disk here needs
+ /// no permission prompt. Users can still pick another location.
+ pub fn disks_dir() -> Option {
+ Self::data_dir().map(|d| d.join("disks"))
+ }
+
+ /// Default absolute path for a new SCSI disk image: `/scsiN.raw`.
+ pub fn default_disk_path(scsi_id: u8) -> String {
+ Self::disks_dir()
+ .map(|d| d.join(format!("scsi{scsi_id}.raw")).to_string_lossy().into_owned())
+ .unwrap_or_else(|| format!("scsi{scsi_id}.raw"))
+ }
+
+ /// Anchor a machine's NVRAM path to [`data_dir`] if it's relative (the
+ /// legacy default was a bare `"nvram.bin"`). Best-effort: if the anchored
+ /// file doesn't exist yet but the old cwd-relative one does, copy it over so
+ /// the PROM env (boot settings, any MAC) carries forward instead of starting
+ /// blank. Idempotent — absolute paths are left untouched.
+ pub fn migrate_nvram_path(nvram: &mut String) {
+ if !nvram.is_empty() && Path::new(&nvram).is_absolute() {
+ return;
+ }
+ let Some(dir) = Self::data_dir() else { return; };
+ let _ = std::fs::create_dir_all(&dir);
+ let leaf = Path::new(nvram.as_str())
+ .file_name()
+ .and_then(|s| s.to_str())
+ .filter(|s| !s.is_empty())
+ .unwrap_or("nvram.bin");
+ let dst = dir.join(leaf);
+ let src = PathBuf::from(nvram.as_str()); // relative to cwd
+ if !dst.exists() && !nvram.is_empty() && src.exists() {
+ let _ = std::fs::copy(&src, &dst);
+ }
+ *nvram = dst.to_string_lossy().into_owned();
}
pub fn load() -> Self {
@@ -76,6 +243,17 @@ impl GuiSettings {
} else {
s.ui_scale.min(UI_SCALE_MAX)
};
+ s.vm_scale = if !s.vm_scale.is_finite() || s.vm_scale < VM_SCALE_MIN {
+ VM_SCALE_DEFAULT
+ } else {
+ s.vm_scale.min(VM_SCALE_MAX)
+ };
+ // Anchor every machine's NVRAM to the stable data dir so all launch
+ // methods share one file (the persisted path becomes absolute on the
+ // next save).
+ for m in s.machines.values_mut() {
+ Self::migrate_nvram_path(&mut m.nvram);
+ }
s
}
diff --git a/rules/gui/gui_mouse_integration.md b/rules/gui/gui_mouse_integration.md
index b84a2be..16e4669 100644
--- a/rules/gui/gui_mouse_integration.md
+++ b/rules/gui/gui_mouse_integration.md
@@ -1,9 +1,9 @@
-# GUI mouse integration — current approach, and the Snow absolute-mouse pattern
+# GUI mouse integration — current approach, and the classic-Mac absolute-mouse pattern
Status: reference / design analysis. Captures why iris-gui uses pointer
**capture** for the framebuffer, and why the seamless absolute-mouse trick used
-by the `snow` Macintosh emulator does **not** port to IRIX without significant
-new machinery. Read this before proposing "make the mouse seamless like snow."
+by some classic Macintosh emulators does **not** port to IRIX without
+significant new machinery. Read this before proposing "make the mouse seamless."
## Current iris-gui approach: capture (grab + hide)
@@ -36,25 +36,22 @@ host cursor can't get stuck hidden.
> warp-to-center + relative deltas (`src/ui.rs:532`), *not* absolute
> positioning. There is no hidden absolute backend to tap.
-## What `snow` does (the absolute pattern)
+## The absolute pattern (classic Mac OS)
-`snow` (sibling repo `../snow`, a classic Macintosh emulator) gets seamless,
-capture-free, 1:1 mouse alignment via an **absolute** mode that bypasses the
-emulated mouse hardware entirely:
+Some classic Macintosh emulators get seamless, capture-free, 1:1 mouse
+alignment via an **absolute** mode that bypasses the emulated mouse hardware
+entirely. It works because **classic Mac OS exposes a stable, documented,
+memory-mapped cursor position you may overwrite, and cooperatively re-reads
+it**:
-- `mouse_update_abs(x, y)` writes the host cursor position directly into classic
- Mac OS **low-memory globals**: `MTemp` (MouseTemp) and `RawMouse`, then sets
- the `CrsrNew` flag. See `core/src/mac/compact/bus.rs:476` (and the Mac II
- variant in `core/src/mac/macii/bus.rs`).
+- The host cursor position is written directly into classic Mac OS **low-memory
+ globals** — `MTemp` (MouseTemp) and `RawMouse` — and the `CrsrNew` flag is
+ set.
- Mac OS polls those globals every tick and "jumps" its cursor to the new
- position. The ADB mouse (`core/src/mac/adb/mouse.rs`) stays relative but is
- sidestepped in absolute mode.
+ position. The emulated ADB mouse stays relative but is sidestepped in
+ absolute mode.
- The frontend exposes a `MouseMode { Absolute, RelativeHw, Disabled }` seam and
- calls `update_mouse(abs_p, rel_p)` (`frontend_egui/src/emulator.rs:434`),
- dispatching `MouseUpdateAbsolute { x, y }` vs `MouseUpdateRelative { .. }`.
-
-It works because **classic Mac OS exposes a stable, documented, memory-mapped
-cursor position you may overwrite, and cooperatively re-reads it.**
+ dispatches an absolute vs. relative update per event.
## Why it does not port to IRIS/IRIX cheaply
@@ -70,7 +67,7 @@ IRIX has no equivalent of that mechanism:
paths are the input protocol (absolute valuators / XInput) or
`XWarpPointer`/XTEST — none of which the emulated SGI PS/2-style mouse exposes.
-## What a Snow-like absolute mode would actually require here
+## What an absolute mode would actually require here
One of:
@@ -88,8 +85,9 @@ None of these is a small port.
## Recommendation
Capture is the correct, standard approach for an X11 guest — it is what
-SGI/Unix emulators do, and what snow itself falls back to (`RelativeHw`). The
-one piece genuinely worth borrowing from snow is its clean frontend seam: a
-`MouseMode` enum + `update_mouse(abs, rel)`. Adopting that abstraction now
-(even with only relative/capture wired up) would make options 1 or 2 drop-in
-later, without committing to the absolute backend today.
+SGI/Unix emulators do, and what the classic-Mac absolute approach itself falls
+back to (a relative-hardware mode) when absolute isn't available. The one piece
+genuinely worth borrowing is the clean frontend seam: a `MouseMode` enum +
+`update_mouse(abs, rel)`. Adopting that abstraction now (even with only
+relative/capture wired up) would make options 1 or 2 drop-in later, without
+committing to the absolute backend today.
diff --git a/rules/macos/appstore-private-api.md b/rules/macos/appstore-private-api.md
new file mode 100644
index 0000000..eb92367
--- /dev/null
+++ b/rules/macos/appstore-private-api.md
@@ -0,0 +1,64 @@
+# Mac App Store rejects winit's private SkyLight blur API (`CGSSetWindowBackgroundBlurRadius`)
+
+**Symptom.** App Store review rejects the `iris-gui` binary under **Guideline
+2.5.1 (Performance — Software Requirements)**:
+
+> The app uses or references the following non-public or deprecated APIs:
+> Contents/MacOS/iris-gui — Symbols: `_CGSSetWindowBackgroundBlurRadius`
+
+**Root cause.** `eframe 0.29` pulls in `winit 0.30` for window creation. winit's
+macOS backend (`platform_impl/macos/window_delegate.rs::set_blur`) calls the
+private SkyLight APIs `CGSSetWindowBackgroundBlurRadius` /
+`CGSMainConnectionID`, declared in `platform_impl/macos/ffi.rs`. The call site
+is reached unconditionally during window init (`set_blur(attrs.blur)`), so the
+import lands in the linked binary **even though iris-gui never requests blur**
+(`egui::ViewportBuilder` leaves `blur = false`). Apple's static binary scan
+flags the imported symbol regardless of whether it's called at runtime.
+
+Confirm with:
+
+```
+nm -u target/release/iris-gui | grep -i CGSSetWindowBackgroundBlurRadius
+```
+
+`U _CGSSetWindowBackgroundBlurRadius` = present (rejected). No output = clean.
+(`_CGShieldingWindowLevel` also shows up but is a **public** CoreGraphics API —
+Apple does not flag it.)
+
+**Fix.** Vendor a patched winit and override it via `[patch.crates-io]`:
+
+- `third_party/winit-0.30.13/` — copy of the crate with:
+ - `set_blur` stubbed to a no-op (no `ffi::CGS…` calls),
+ - the two private `extern` declarations removed from `ffi.rs` (and the
+ now-unused `NSInteger` / `AnyObject` imports dropped).
+- Root `Cargo.toml`: `[patch.crates-io] winit = { path = "third_party/winit-0.30.13" }`.
+
+Only the `0.30.x` requirement (eframe → egui-winit → glutin-winit) matches the
+patch. `iris`'s own `winit 0.29` dependency is the keyboard `KeyCode` type only
+and creates no window inside `iris-gui`, so its `set_blur` is dead-stripped —
+patching just the 0.30 copy removes the symbol entirely (verified with `nm -u`).
+
+**Two-version gotcha.** Cargo allows only one `[patch.crates-io]` entry per
+crate name, so you cannot patch both 0.29.15 and 0.30.13. That's fine here —
+only the eframe (0.30) window code reaches `set_blur`. If a future change makes
+`iris` create a winit-0.29 window inside the GUI process, re-check `nm -u`;
+you'd then have to unify on a single winit version before patching.
+
+**When bumping eframe/winit:** re-vendor the matching winit version, re-apply
+the two-edit patch, and re-run the `nm -u` check before submitting.
+
+## Upstream status (don't file a new bug — already tracked)
+
+- winit issue **#4205** "_CGSSetWindowBackgroundBlurRadius non-public or
+ deprecated API" — open, milestone **winit 0.31.0**.
+- winit PR **#4541** "macOS: Feature-gate `CGSSetWindowBackgroundBlurRadius`" —
+ open/in-progress. Puts the call behind a `private-apple-apis` Cargo feature
+ (off by default → symbol absent unless opted in). Resolves #4205.
+- #4574 (dup App Store rejection report) closed as duplicate; #4538 (remove it
+ outright) abandoned.
+
+**Migration:** once IRIS moves to a winit (≥0.31) that ships the feature gate —
+which only happens after eframe bumps to a winit-0.31 release and we bump eframe
+— delete `third_party/winit-0.30.13/` and the `[patch.crates-io]`, and just make
+sure the `private-apple-apis` feature stays disabled (and that eframe doesn't
+enable it). Re-run the `nm -u` check to confirm.
diff --git a/src/camera.rs b/src/camera.rs
index d2c1caf..dd58697 100644
--- a/src/camera.rs
+++ b/src/camera.rs
@@ -15,6 +15,7 @@
//! returns a solid black field so VINO DMA still gets coherent bytes.
use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Instant;
@@ -47,7 +48,11 @@ pub(crate) struct Shared {
pub struct CameraSource {
standard: VideoStandard,
shared: Arc>,
- _worker: thread::JoinHandle<()>,
+ /// Cleared on drop to stop the capture loop so the host camera is released
+ /// (its indicator light turns off) rather than the worker running until the
+ /// process exits. The backend polls this between frames.
+ running: Arc,
+ worker: Option>,
}
impl CameraSource {
@@ -69,13 +74,27 @@ impl CameraSource {
capture_res: None,
}));
let s2 = shared.clone();
+ let running = Arc::new(AtomicBool::new(true));
+ let r2 = running.clone();
let worker = thread::Builder::new()
.name("iris-camera".into())
- .spawn(move || backend::capture_loop(s2, frame_w, frame_h, camera_index))
+ .spawn(move || backend::capture_loop(s2, frame_w, frame_h, camera_index, r2))
.map_err(|e| format!("camera worker spawn failed: {}", e))?;
- Ok(Self { standard, shared, _worker: worker })
+ Ok(Self { standard, shared, running, worker: Some(worker) })
+ }
+}
+
+impl Drop for CameraSource {
+ fn drop(&mut self) {
+ self.running.store(false, Ordering::Relaxed);
+ if let Some(w) = self.worker.take() {
+ // The backend exits within one frame interval of seeing `running`
+ // clear, then closes the camera stream. Join so the device is fully
+ // released before we return (e.g. before a re-open).
+ let _ = w.join();
+ }
}
}
diff --git a/src/camera_nokhwa.rs b/src/camera_nokhwa.rs
index 6fa2731..a36fd09 100644
--- a/src/camera_nokhwa.rs
+++ b/src/camera_nokhwa.rs
@@ -1,6 +1,7 @@
//! nokhwa-based capture loop (macOS AVFoundation, Windows MediaFoundation).
use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
@@ -9,7 +10,7 @@ use parking_lot::Mutex;
use super::{Shared, downscale_yuyv_to_uyvy, split_fields};
pub(super) fn capture_loop(shared: Arc>, frame_w: u32, frame_h: u32,
- camera_index: u32) {
+ camera_index: u32, running: Arc) {
use nokhwa::pixel_format::YuyvFormat;
use nokhwa::utils::{
CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution,
@@ -49,7 +50,7 @@ pub(super) fn capture_loop(shared: Arc>, frame_w: u32, frame_h: u3
eprintln!("camera: streaming at {}×{} → downscale to {}×{}", sw, sh, frame_w, frame_h);
shared.lock().capture_res = Some((sw, sh));
- loop {
+ while running.load(Ordering::Relaxed) {
let buf = match cam.frame() {
Ok(b) => b,
Err(e) => {
diff --git a/src/camera_v4l.rs b/src/camera_v4l.rs
index 1494752..38b460a 100644
--- a/src/camera_v4l.rs
+++ b/src/camera_v4l.rs
@@ -13,6 +13,7 @@
//! start an mmap stream, and pull frames directly.
use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
@@ -81,12 +82,13 @@ fn best_yuyv_resolution(dev: &Device) -> Option<(u32, u32)> {
}
pub(super) fn capture_loop(shared: Arc>, frame_w: u32, frame_h: u32,
- camera_index: u32) {
+ camera_index: u32, running: Arc) {
// Outer retry loop: reopens the device from scratch after stream loss or
// hot-plug. Re-resolves the device index each time so a swap (e.g. Logitech
// → Huddly GO) picks up the new camera's node without restarting iris.
let mut open_attempts = 0u32;
'outer: loop {
+ if !running.load(Ordering::Relaxed) { return; }
let cur_idx = match resolve_device_index(camera_index) {
Some(i) => i,
None => {
@@ -150,6 +152,7 @@ pub(super) fn capture_loop(shared: Arc>, frame_w: u32, frame_h: u3
open_attempts = 0;
loop {
+ if !running.load(Ordering::Relaxed) { return; }
let (data, _meta) = match stream.next() {
Ok(f) => f,
Err(e) => {
diff --git a/src/config.rs b/src/config.rs
index 6383173..85564dc 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -269,6 +269,13 @@ pub struct MachineConfig {
#[serde(default = "default_scroll_pixels_per_line")]
pub mouse_scroll_pixels_per_line: f64,
+ /// Lock the window's aspect ratio to the emulated display (picture +
+ /// status bar) while resizing, so it fills the window without letterbox
+ /// bars. Set to false if you have a non-standard monitor and prefer free
+ /// resizing — the display is then letterboxed to fit. Default: true.
+ #[serde(default = "default_lock_aspect_ratio")]
+ pub lock_aspect_ratio: bool,
+
/// Optional file path that will receive every byte emitted on ttyd1
/// (the IRIX serial console) in `--ci` mode. Append-only. Useful for
/// keeping a continuously-updated transcript of the install or test run.
@@ -296,6 +303,7 @@ pub struct MachineConfig {
fn default_ci_socket() -> String { "/tmp/iris.sock".to_string() }
fn default_scroll_pixels_per_line() -> f64 { 40.0 }
+fn default_lock_aspect_ratio() -> bool { true }
fn default_prom() -> String {
"prom.bin".to_string()
@@ -352,6 +360,7 @@ impl Default for MachineConfig {
serial_log: None,
vino: VinoConfig::default(),
mouse_scroll_pixels_per_line: default_scroll_pixels_per_line(),
+ lock_aspect_ratio: default_lock_aspect_ratio(),
}
}
}
diff --git a/src/jit/compiler.rs b/src/jit/compiler.rs
index 90fd898..400ecac 100644
--- a/src/jit/compiler.rs
+++ b/src/jit/compiler.rs
@@ -275,7 +275,6 @@ impl BlockCompiler {
let old_gpr = gpr;
let old_hi = hi;
let old_lo = lo;
- let old_modified = modified_gprs;
let (_, delay_d) = &instrs[idx];
let delay_pc = block_pc.wrapping_add(idx as u64 * 4);
let delay_result = emit_instruction(
@@ -297,7 +296,9 @@ impl BlockCompiler {
gpr = old_gpr;
hi = old_hi;
lo = old_lo;
- modified_gprs = old_modified;
+ // modified_gprs intentionally not restored: the
+ // post-loop flush stores every GPR (all_modified
+ // = 0xFFFFFFFE), so its value is dead past here.
compiled_count -= 1;
break;
}
diff --git a/src/machine.rs b/src/machine.rs
index df1eaa0..a00fbad 100644
--- a/src/machine.rs
+++ b/src/machine.rs
@@ -694,6 +694,13 @@ impl Machine {
self.ci_serial.clone()
}
+ /// Type bytes at the IRIX serial console (tty1) in-process, without any
+ /// loopback TCP client. Used by the GUI to send `halt\n` for a clean
+ /// shutdown so the feature doesn't depend on the serial server socket.
+ pub fn inject_serial_console(&self, bytes: &[u8]) {
+ self.hpc3.ioc().scc().inject_b(bytes);
+ }
+
/// CPU thread, started explicitly by the CI `start` command or by
/// `ci_restore`. In `--ci` mode the CPU is not autostarted in `start()`
/// — the harness drives startup via `restore`.
@@ -701,6 +708,14 @@ impl Machine {
self.cpu.start();
}
+ /// Whether the CPU thread is currently executing. Goes false when the CPU
+ /// is stopped — including the soft power-off path (a guest `poweroff` makes
+ /// the machine-events thread call `stop()`), so an embedder can tell the
+ /// guest has shut down without subscribing to machine events.
+ pub fn cpu_is_running(&self) -> bool {
+ self.cpu.is_running()
+ }
+
/// Step the CPU `n` instructions in-line on the calling thread, with all
/// peripheral threads stopped so the CPU sees no external interrupts.
/// Used by Phase 3.3 snapshot determinism validator.
diff --git a/src/main.rs b/src/main.rs
index 8bcc31b..7c41153 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -6,6 +6,7 @@ fn main() {
let (mut cfg, scale) = load_config();
let scroll_pixels_per_line = cfg.mouse_scroll_pixels_per_line;
+ let lock_aspect_ratio = cfg.lock_aspect_ratio;
let headless = cfg.headless;
let gdb_port = cfg.gdb_port;
let ci_enabled = cfg.ci;
@@ -104,7 +105,7 @@ fn main() {
use winit::event_loop::EventLoop;
let event_loop = EventLoop::new().unwrap();
let rex3 = machine.get_rex3().expect("rex3 must be present in non-headless mode");
- let ui = Ui::new(machine.get_ps2(), rex3, machine.get_timer_manager(), &event_loop, scale, scroll_pixels_per_line);
+ let ui = Ui::new(machine.get_ps2(), rex3, machine.get_timer_manager(), &event_loop, scale, scroll_pixels_per_line, lock_aspect_ratio);
ui.run(event_loop);
}
diff --git a/src/ui.rs b/src/ui.rs
index 3359754..2ef35fb 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -55,6 +55,9 @@ struct GlRenderer {
gl_config: glutin::config::Config,
window_size: Arc>>,
scale_snap: Arc>>,
+ // Current emulated display resolution (width, height), published for the
+ // event thread so it can lock the window to the right aspect ratio.
+ display_res: Arc>,
state: Option,
compositor: Box,
use_gl_compositor: bool,
@@ -402,6 +405,8 @@ impl Renderer for GlRenderer {
self.current_h = height;
self.current_win_w = win_w;
self.current_win_h = win_h;
+ // Publish the display resolution for the event thread's aspect lock.
+ *self.display_res.lock() = (width as u32, height as u32);
// UV coords into 2048×1024 texture
let max_u = width as f32 / 2048.0;
let max_v_main = height as f32 / 1024.0;
@@ -481,6 +486,10 @@ impl Renderer for GlRenderer {
}
fn resize(&mut self, width: usize, height: usize) {
+ // Publish the new resolution *before* the snap below, so the event
+ // thread's aspect lock sees it when it handles the resulting Resized
+ // event (otherwise it would re-fit the window to the stale aspect).
+ *self.display_res.lock() = (width as u32, height as u32);
// On display resolution change, snap window to 1x of the new resolution.
let _ = self.window.request_inner_size(winit::dpi::PhysicalSize::new(
width as u32,
@@ -535,15 +544,20 @@ pub struct Ui {
window: Arc,
window_size: Arc>>,
scale_snap: Arc>>,
+ display_res: Arc>,
timer_manager: Arc,
initial_scale: u32,
scroll_pixels_per_line: f64,
+ lock_aspect_ratio: bool,
}
impl Ui {
- pub fn new(ps2: Arc, rex3: Arc, timer_manager: Arc, event_loop: &EventLoop<()>, scale: u32, scroll_pixels_per_line: f64) -> Self {
- let w = 1024 * scale;
- let h = (768 + STATUS_BAR_HEIGHT as u32) * scale;
+ pub fn new(ps2: Arc, rex3: Arc, timer_manager: Arc, event_loop: &EventLoop<()>, scale: u32, scroll_pixels_per_line: f64, lock_aspect_ratio: bool) -> Self {
+ // The Indy's default video mode is 1280×1024; open the window at that
+ // size (plus the status bar). The renderer snaps to the real resolution
+ // via resize() once the PROM/IRIX programs its actual mode.
+ let w = 1280 * scale;
+ let h = (1024 + STATUS_BAR_HEIGHT as u32) * scale;
let window_builder = WindowBuilder::new()
.with_title(crate::machine::emulator_name())
.with_resizable(true)
@@ -568,12 +582,16 @@ impl Ui {
let window = Arc::new(window.unwrap());
let window_size = Arc::new(Mutex::new(None));
let scale_snap = Arc::new(Mutex::new(None));
+ // Seed with the Indy's default 1280×1024; the render thread republishes
+ // the real resolution on the first frame and on any mode change.
+ let display_res = Arc::new(Mutex::new((1280u32, 1024u32)));
let renderer = GlRenderer {
window: window.clone(),
gl_config,
window_size: window_size.clone(),
scale_snap: scale_snap.clone(),
+ display_res: display_res.clone(),
state: None,
compositor: Box::new(GlCompositor::new()),
use_gl_compositor: true,
@@ -585,16 +603,22 @@ impl Ui {
*rex3.renderer.lock() = Some(Box::new(renderer));
- Self { ps2, rex3, window, window_size, scale_snap, timer_manager, initial_scale: scale, scroll_pixels_per_line }
+ Self { ps2, rex3, window, window_size, scale_snap, display_res, timer_manager, initial_scale: scale, scroll_pixels_per_line, lock_aspect_ratio }
}
/// Run the UI event loop (blocks the current thread)
pub fn run(self, event_loop: EventLoop<()>) {
- let Ui { ps2, rex3, window, window_size, scale_snap, timer_manager, initial_scale, scroll_pixels_per_line } = self;
+ let Ui { ps2, rex3, window, window_size, scale_snap, display_res, timer_manager, initial_scale, scroll_pixels_per_line, lock_aspect_ratio } = self;
let scale = initial_scale;
let mut mouse_grabbed = false;
let mut rctrl_held = false;
+ // Last window size we accepted, used to tell which edge the user is
+ // dragging when locking the aspect ratio.
+ let mut last_win_size = {
+ let s = window.inner_size();
+ (s.width, s.height)
+ };
let mouse_delta = Arc::new(Mutex::new(MouseDelta { accum: (0.0, 0.0), wheel: 0.0, buttons: 0 }));
{
@@ -618,7 +642,31 @@ impl Ui {
WindowEvent::CloseRequested => { elwt.exit() },
WindowEvent::Resized(size) => {
if size.width != 0 && size.height != 0 {
- *window_size.lock() = Some((size.width, size.height));
+ let mut new_size = (size.width, size.height);
+ // Lock the window to the display's aspect ratio so the
+ // picture fills it without letterbox bars. Skipped when
+ // fullscreen or maximized (aspect can't be honoured there)
+ // and when disabled by config.
+ if lock_aspect_ratio
+ && window.fullscreen().is_none()
+ && !window.is_maximized()
+ {
+ let (dw, dh) = *display_res.lock();
+ if let Some(fixed) = Self::aspect_fit(
+ size.width, size.height, last_win_size, dw, dh)
+ {
+ new_size = match window.request_inner_size(
+ winit::dpi::PhysicalSize::new(fixed.0, fixed.1))
+ {
+ // Some => applied synchronously, no further
+ // Resized event; use the actual granted size.
+ Some(actual) => (actual.width, actual.height),
+ None => fixed,
+ };
+ }
+ }
+ last_win_size = new_size;
+ *window_size.lock() = Some(new_size);
}
}
WindowEvent::KeyboardInput { event, .. } => {
@@ -695,6 +743,33 @@ impl Ui {
ps2.push_mouse_input(buttons, dx, dy, dz);
}
+ /// Adjust an incoming window size to match the emulated display's aspect
+ /// ratio (display width : display height + status bar). Whichever axis the
+ /// user is actively dragging — the one that moved most from `prev` — is
+ /// kept, and the other is derived from it. Returns `None` when the size is
+ /// already within 1 px of the target (no correction needed), which keeps
+ /// the follow-up resize from oscillating.
+ fn aspect_fit(win_w: u32, win_h: u32, prev: (u32, u32), disp_w: u32, disp_h: u32)
+ -> Option<(u32, u32)>
+ {
+ if disp_w == 0 || disp_h == 0 { return None; }
+ let content_h = disp_h + STATUS_BAR_HEIGHT as u32;
+ // round(a * b / c) in u64 to avoid overflow/bias.
+ let muldiv = |a: u32, b: u32, c: u32| -> u32 {
+ ((a as u64 * b as u64 + c as u64 / 2) / c as u64) as u32
+ };
+ let (pw, ph) = prev;
+ if win_w.abs_diff(pw) >= win_h.abs_diff(ph) {
+ // Width is the driven axis: derive height from it.
+ let target_h = muldiv(win_w, content_h, disp_w).max(1);
+ if target_h.abs_diff(win_h) <= 1 { None } else { Some((win_w, target_h)) }
+ } else {
+ // Height is the driven axis: derive width from it.
+ let target_w = muldiv(win_h, disp_w, content_h).max(1);
+ if target_w.abs_diff(win_w) <= 1 { None } else { Some((target_w, win_h)) }
+ }
+ }
+
fn handle_keyboard(ps2: &Ps2Controller, rex3: &Rex3, scale_snap: &Mutex>,
input: KeyEvent, grabbed: &mut bool, rctrl_held: &mut bool, window: &Window)
{
@@ -744,3 +819,49 @@ impl Ui {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // Indy default mode. Content aspect = 1280 : (1024 + 16) = 1280 : 1040.
+ const DW: u32 = 1280;
+ const DH: u32 = 1024;
+
+ #[test]
+ fn dragging_width_derives_height() {
+ // Width grows from 1280 to 2560; height untouched. Expect height locked
+ // to the content ratio: 2560 * 1040 / 1280 = 2080.
+ let fixed = Ui::aspect_fit(2560, 1040, (1280, 1040), DW, DH);
+ assert_eq!(fixed, Some((2560, 2080)));
+ }
+
+ #[test]
+ fn dragging_height_derives_width() {
+ // Height grows from 1040 to 2080; width untouched. Expect width locked:
+ // 2080 * 1280 / 1040 = 2560.
+ let fixed = Ui::aspect_fit(1280, 2080, (1280, 1040), DW, DH);
+ assert_eq!(fixed, Some((2560, 2080)));
+ }
+
+ #[test]
+ fn already_locked_is_noop() {
+ // A size already on-ratio needs no correction (prevents oscillation on
+ // the follow-up Resized event after we apply a fix).
+ assert_eq!(Ui::aspect_fit(2560, 2080, (2560, 2080), DW, DH), None);
+ assert_eq!(Ui::aspect_fit(1280, 1040, (1280, 1040), DW, DH), None);
+ }
+
+ #[test]
+ fn within_one_pixel_tolerance() {
+ // 1 px off the exact ratio is accepted as-is (no visible letterbox).
+ assert_eq!(Ui::aspect_fit(2560, 2079, (2560, 2079), DW, DH), None);
+ assert_eq!(Ui::aspect_fit(2560, 2081, (2560, 2081), DW, DH), None);
+ }
+
+ #[test]
+ fn zero_resolution_is_noop() {
+ // Guard against a divide-by-zero before the first frame publishes a res.
+ assert_eq!(Ui::aspect_fit(800, 600, (800, 600), 0, 0), None);
+ }
+}
diff --git a/src/z85c30.rs b/src/z85c30.rs
index ef4c0d4..0032100 100644
--- a/src/z85c30.rs
+++ b/src/z85c30.rs
@@ -584,6 +584,12 @@ pub struct Z85c30 {
// so `Z85c30` stays `Clone` and the swap is thread-safe.
backend_a: Arc>>,
backend_b: Arc>>,
+ // In-process injection queue for channel B (tty1, the IRIX serial console).
+ // Bytes queued via `inject_b` are delivered to the guest by the channel-B
+ // RX thread ahead of any socket input, so a host action (e.g. the GUI's
+ // "Send IRIX halt") can type at the console without opening a loopback TCP
+ // client. Independent of whichever backend is installed.
+ inject_b: Arc>>,
running: Arc,
threads: Arc>>>,
}
@@ -628,6 +634,7 @@ impl Z85c30 {
channel_b: Arc::new((Mutex::new(Channel::new("B", ip_b, ip_a, callback)), Condvar::new())),
backend_a: Arc::new(Mutex::new(backend_a)),
backend_b: Arc::new(Mutex::new(backend_b)),
+ inject_b: Arc::new(Mutex::new(VecDeque::new())),
running: Arc::new(AtomicBool::new(false)),
threads: Arc::new(Mutex::new(Vec::new())),
}
@@ -654,6 +661,16 @@ impl Z85c30 {
self.backend_b.lock().clone()
}
+ /// Queue host bytes to be delivered to channel B (tty1, the IRIX serial
+ /// console) as if typed at the console — entirely in-process, with no
+ /// loopback TCP client. The bytes ride the same RX path as socket input
+ /// (FIFO backpressure + baud pacing), so the guest sees them identically.
+ /// Used by the GUI's "Send IRIX halt" for a clean shutdown that doesn't
+ /// depend on the serial server socket.
+ pub fn inject_b(&self, data: &[u8]) {
+ self.inject_b.lock().extend(data.iter().copied());
+ }
+
pub fn read_a_control(&self) -> u8 {
let mut a = self.channel_a.0.lock();
if a.reg_ptr == 2 {
@@ -871,6 +888,9 @@ impl Device for Z85c30 {
let rx_channel = channel_arc.clone();
let rx_backend = backend.clone();
let running = self.running.clone();
+ // Only channel B (the IRIX serial console) accepts in-process
+ // injection; channel A has no queue.
+ let rx_inject = if i == 1 { Some(self.inject_b.clone()) } else { None };
threads.push(thread::Builder::new().name(format!("SCC-RX-{}", ch_name)).spawn(move || {
let mut last_rx_time = Instant::now();
@@ -886,12 +906,18 @@ impl Device for Z85c30 {
while running.load(Ordering::Relaxed) {
let mut byte = match pending.take() {
Some(b) => b,
- None => match rx_backend.recv_byte() {
- Ok(b) => b,
- Err(_) => {
- thread::sleep(Duration::from_millis(10));
- continue;
- }
+ // In-process injection (channel B) takes priority over
+ // socket input, so a queued "halt\n" is delivered even
+ // when no TCP client is attached.
+ None => match rx_inject.as_ref().and_then(|q| q.lock().pop_front()) {
+ Some(b) => b,
+ None => match rx_backend.recv_byte() {
+ Ok(b) => b,
+ Err(_) => {
+ thread::sleep(Duration::from_millis(10));
+ continue;
+ }
+ },
},
};
if byte == 0x05 {
diff --git a/third_party/winit-0.30.13/.cargo-ok b/third_party/winit-0.30.13/.cargo-ok
new file mode 100644
index 0000000..5f8b795
--- /dev/null
+++ b/third_party/winit-0.30.13/.cargo-ok
@@ -0,0 +1 @@
+{"v":1}
\ No newline at end of file
diff --git a/third_party/winit-0.30.13/.cargo_vcs_info.json b/third_party/winit-0.30.13/.cargo_vcs_info.json
new file mode 100644
index 0000000..6a63283
--- /dev/null
+++ b/third_party/winit-0.30.13/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "e9809ef54b18499bb4f2cac945719ecc2a61061b"
+ },
+ "path_in_vcs": ""
+}
\ No newline at end of file
diff --git a/third_party/winit-0.30.13/Cargo.toml b/third_party/winit-0.30.13/Cargo.toml
new file mode 100644
index 0000000..4bfded8
--- /dev/null
+++ b/third_party/winit-0.30.13/Cargo.toml
@@ -0,0 +1,553 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.70.0"
+name = "winit"
+version = "0.30.13"
+authors = [
+ "The winit contributors",
+ "Pierre Krieger ",
+]
+build = "build.rs"
+include = [
+ "/build.rs",
+ "/docs",
+ "/examples",
+ "/FEATURES.md",
+ "/LICENSE",
+ "/src",
+ "!/src/platform_impl/web/script",
+ "/src/platform_impl/web/script/**/*.min.js",
+ "/tests",
+]
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "Cross-platform window creation library."
+documentation = "https://docs.rs/winit"
+readme = "README.md"
+keywords = ["windowing"]
+categories = ["gui"]
+license = "Apache-2.0"
+repository = "https://github.com/rust-windowing/winit"
+
+[package.metadata.docs.rs]
+features = [
+ "rwh_04",
+ "rwh_05",
+ "rwh_06",
+ "serde",
+ "mint",
+ "android-native-activity",
+]
+targets = [
+ "i686-pc-windows-msvc",
+ "x86_64-pc-windows-msvc",
+ "x86_64-apple-darwin",
+ "i686-unknown-linux-gnu",
+ "x86_64-unknown-linux-gnu",
+ "x86_64-apple-ios",
+ "aarch64-linux-android",
+ "wasm32-unknown-unknown",
+]
+rustdoc-args = [
+ "--cfg",
+ "docsrs",
+]
+
+[features]
+android-game-activity = ["android-activity/game-activity"]
+android-native-activity = ["android-activity/native-activity"]
+default = [
+ "rwh_06",
+ "x11",
+ "wayland",
+ "wayland-dlopen",
+ "wayland-csd-adwaita",
+]
+mint = ["dpi/mint"]
+rwh_04 = [
+ "dep:rwh_04",
+ "ndk/rwh_04",
+]
+rwh_05 = [
+ "dep:rwh_05",
+ "ndk/rwh_05",
+]
+rwh_06 = [
+ "dep:rwh_06",
+ "ndk/rwh_06",
+]
+serde = [
+ "dep:serde",
+ "cursor-icon/serde",
+ "smol_str/serde",
+ "dpi/serde",
+]
+wayland = [
+ "wayland-client",
+ "wayland-backend",
+ "wayland-protocols",
+ "wayland-protocols-plasma",
+ "sctk",
+ "ahash",
+ "memmap2",
+]
+wayland-csd-adwaita = [
+ "sctk-adwaita",
+ "sctk-adwaita/ab_glyph",
+]
+wayland-csd-adwaita-crossfont = [
+ "sctk-adwaita",
+ "sctk-adwaita/crossfont",
+]
+wayland-csd-adwaita-notitle = ["sctk-adwaita"]
+wayland-dlopen = ["wayland-backend/dlopen"]
+x11 = [
+ "x11-dl",
+ "bytemuck",
+ "percent-encoding",
+ "xkbcommon-dl/x11",
+ "x11rb",
+]
+
+[lib]
+name = "winit"
+path = "src/lib.rs"
+
+[[example]]
+name = "child_window"
+path = "examples/child_window.rs"
+
+[[example]]
+name = "control_flow"
+path = "examples/control_flow.rs"
+
+[[example]]
+name = "pump_events"
+path = "examples/pump_events.rs"
+
+[[example]]
+name = "run_on_demand"
+path = "examples/run_on_demand.rs"
+
+[[example]]
+name = "window"
+path = "examples/window.rs"
+doc-scrape-examples = true
+
+[[example]]
+name = "x11_embed"
+path = "examples/x11_embed.rs"
+
+[[test]]
+name = "send_objects"
+path = "tests/send_objects.rs"
+
+[[test]]
+name = "serde_objects"
+path = "tests/serde_objects.rs"
+
+[[test]]
+name = "sync_object"
+path = "tests/sync_object.rs"
+
+[dependencies.bitflags]
+version = "2"
+
+[dependencies.cursor-icon]
+version = "1.1.0"
+
+[dependencies.dpi]
+version = "0.1.1"
+
+[dependencies.rwh_04]
+version = "0.4"
+optional = true
+package = "raw-window-handle"
+
+[dependencies.rwh_05]
+version = "0.5.2"
+features = ["std"]
+optional = true
+package = "raw-window-handle"
+
+[dependencies.rwh_06]
+version = "0.6"
+features = ["std"]
+optional = true
+package = "raw-window-handle"
+
+[dependencies.serde]
+version = "1"
+features = ["serde_derive"]
+optional = true
+
+[dependencies.smol_str]
+version = "0.2.0"
+
+[dependencies.tracing]
+version = "0.1.40"
+default-features = false
+
+[dev-dependencies.image]
+version = "0.25.0"
+features = ["png"]
+default-features = false
+
+[dev-dependencies.tracing]
+version = "0.1.40"
+features = ["log"]
+default-features = false
+
+[dev-dependencies.tracing-subscriber]
+version = "0.3.18"
+features = ["env-filter"]
+
+[build-dependencies.cfg_aliases]
+version = "0.2.1"
+
+[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies.atomic-waker]
+version = "1"
+
+[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies.concurrent-queue]
+version = "2"
+default-features = false
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.ahash]
+version = "0.8.7"
+features = ["no-rng"]
+optional = true
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.bytemuck]
+version = "1.13.1"
+optional = true
+default-features = false
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.calloop]
+version = "0.13.0"
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.libc]
+version = "0.2.64"
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.memmap2]
+version = "0.9.0"
+optional = true
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.percent-encoding]
+version = "2.0"
+optional = true
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.rustix]
+version = "0.38.4"
+features = [
+ "std",
+ "system",
+ "thread",
+ "process",
+]
+default-features = false
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.sctk]
+version = "0.19.2"
+features = ["calloop"]
+optional = true
+default-features = false
+package = "smithay-client-toolkit"
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.sctk-adwaita]
+version = "0.10.1"
+optional = true
+default-features = false
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.wayland-backend]
+version = "0.3.10"
+features = ["client_system"]
+optional = true
+default-features = false
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.wayland-client]
+version = "0.31.10"
+optional = true
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.wayland-protocols]
+version = "0.32.8"
+features = ["staging"]
+optional = true
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.wayland-protocols-plasma]
+version = "0.3.8"
+features = ["client"]
+optional = true
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.x11-dl]
+version = "2.19.1"
+optional = true
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.x11rb]
+version = "0.13.0"
+features = [
+ "allow-unsafe-code",
+ "dl-libxcb",
+ "randr",
+ "resource_manager",
+ "xinput",
+ "xkb",
+]
+optional = true
+default-features = false
+
+[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.xkbcommon-dl]
+version = "0.4.2"
+
+[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies.block2]
+version = "0.5.1"
+
+[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies.core-foundation]
+version = "0.9.3"
+
+[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies.objc2]
+version = "0.5.2"
+features = ["relax-sign-encoding"]
+
+[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies.softbuffer]
+version = "0.4.0"
+features = [
+ "x11",
+ "x11-dlopen",
+ "wayland",
+ "wayland-dlopen",
+]
+default-features = false
+
+[target.'cfg(target_family = "wasm")'.dependencies.js-sys]
+version = "0.3.70"
+
+[target.'cfg(target_family = "wasm")'.dependencies.pin-project]
+version = "1"
+
+[target.'cfg(target_family = "wasm")'.dependencies.wasm-bindgen]
+version = "0.2.93"
+
+[target.'cfg(target_family = "wasm")'.dependencies.wasm-bindgen-futures]
+version = "0.4.43"
+
+[target.'cfg(target_family = "wasm")'.dependencies.web-time]
+version = "1"
+
+[target.'cfg(target_family = "wasm")'.dependencies.web_sys]
+version = "0.3.70"
+features = [
+ "AbortController",
+ "AbortSignal",
+ "Blob",
+ "BlobPropertyBag",
+ "console",
+ "CssStyleDeclaration",
+ "Document",
+ "DomException",
+ "DomRect",
+ "DomRectReadOnly",
+ "Element",
+ "Event",
+ "EventTarget",
+ "FocusEvent",
+ "HtmlCanvasElement",
+ "HtmlElement",
+ "HtmlImageElement",
+ "ImageBitmap",
+ "ImageBitmapOptions",
+ "ImageBitmapRenderingContext",
+ "ImageData",
+ "IntersectionObserver",
+ "IntersectionObserverEntry",
+ "KeyboardEvent",
+ "MediaQueryList",
+ "MessageChannel",
+ "MessagePort",
+ "Navigator",
+ "Node",
+ "OrientationLockType",
+ "OrientationType",
+ "PageTransitionEvent",
+ "Permissions",
+ "PermissionState",
+ "PermissionStatus",
+ "PointerEvent",
+ "PremultiplyAlpha",
+ "ResizeObserver",
+ "ResizeObserverBoxOptions",
+ "ResizeObserverEntry",
+ "ResizeObserverOptions",
+ "ResizeObserverSize",
+ "Screen",
+ "ScreenOrientation",
+ "Url",
+ "VisibilityState",
+ "WheelEvent",
+ "Window",
+ "Worker",
+]
+package = "web-sys"
+
+[target.'cfg(target_family = "wasm")'.dev-dependencies.console_error_panic_hook]
+version = "0.1"
+
+[target.'cfg(target_family = "wasm")'.dev-dependencies.tracing-web]
+version = "0.1"
+
+[target.'cfg(target_os = "android")'.dependencies.android-activity]
+version = "0.6.0"
+
+[target.'cfg(target_os = "android")'.dependencies.ndk]
+version = "0.9.0"
+default-features = false
+
+[target.'cfg(target_os = "ios")'.dependencies.objc2-foundation]
+version = "0.2.2"
+features = [
+ "block2",
+ "dispatch",
+ "NSArray",
+ "NSEnumerator",
+ "NSGeometry",
+ "NSObjCRuntime",
+ "NSOperation",
+ "NSString",
+ "NSProcessInfo",
+ "NSThread",
+ "NSSet",
+]
+
+[target.'cfg(target_os = "ios")'.dependencies.objc2-ui-kit]
+version = "0.2.2"
+features = [
+ "UIApplication",
+ "UIDevice",
+ "UIEvent",
+ "UIGeometry",
+ "UIGestureRecognizer",
+ "UITextInput",
+ "UITextInputTraits",
+ "UIOrientation",
+ "UIPanGestureRecognizer",
+ "UIPinchGestureRecognizer",
+ "UIResponder",
+ "UIRotationGestureRecognizer",
+ "UIScreen",
+ "UIScreenMode",
+ "UITapGestureRecognizer",
+ "UITouch",
+ "UITraitCollection",
+ "UIView",
+ "UIViewController",
+ "UIWindow",
+]
+
+[target.'cfg(target_os = "macos")'.dependencies.core-graphics]
+version = "0.23.1"
+
+[target.'cfg(target_os = "macos")'.dependencies.objc2-app-kit]
+version = "0.2.2"
+features = [
+ "NSAppearance",
+ "NSApplication",
+ "NSBitmapImageRep",
+ "NSButton",
+ "NSColor",
+ "NSControl",
+ "NSCursor",
+ "NSDragging",
+ "NSEvent",
+ "NSGraphics",
+ "NSGraphicsContext",
+ "NSImage",
+ "NSImageRep",
+ "NSMenu",
+ "NSMenuItem",
+ "NSOpenGLView",
+ "NSPasteboard",
+ "NSResponder",
+ "NSRunningApplication",
+ "NSScreen",
+ "NSTextInputClient",
+ "NSTextInputContext",
+ "NSView",
+ "NSWindow",
+ "NSWindowScripting",
+ "NSWindowTabGroup",
+]
+
+[target.'cfg(target_os = "macos")'.dependencies.objc2-foundation]
+version = "0.2.2"
+features = [
+ "block2",
+ "dispatch",
+ "NSArray",
+ "NSAttributedString",
+ "NSData",
+ "NSDictionary",
+ "NSDistributedNotificationCenter",
+ "NSEnumerator",
+ "NSKeyValueObserving",
+ "NSNotification",
+ "NSObjCRuntime",
+ "NSPathUtilities",
+ "NSProcessInfo",
+ "NSRunLoop",
+ "NSString",
+ "NSThread",
+ "NSValue",
+]
+
+[target.'cfg(target_os = "redox")'.dependencies.orbclient]
+version = "0.3.47"
+default-features = false
+
+[target.'cfg(target_os = "redox")'.dependencies.redox_syscall]
+version = "0.4.1"
+
+[target.'cfg(target_os = "windows")'.dependencies.unicode-segmentation]
+version = "1.7.1"
+
+[target.'cfg(target_os = "windows")'.dependencies.windows-sys]
+version = "0.52.0"
+features = [
+ "Win32_Devices_HumanInterfaceDevice",
+ "Win32_Foundation",
+ "Win32_Globalization",
+ "Win32_Graphics_Dwm",
+ "Win32_Graphics_Gdi",
+ "Win32_Media",
+ "Win32_System_Com_StructuredStorage",
+ "Win32_System_Com",
+ "Win32_System_LibraryLoader",
+ "Win32_System_Ole",
+ "Win32_Security",
+ "Win32_System_SystemInformation",
+ "Win32_System_SystemServices",
+ "Win32_System_Threading",
+ "Win32_System_WindowsProgramming",
+ "Win32_UI_Accessibility",
+ "Win32_UI_Controls",
+ "Win32_UI_HiDpi",
+ "Win32_UI_Input_Ime",
+ "Win32_UI_Input_KeyboardAndMouse",
+ "Win32_UI_Input_Pointer",
+ "Win32_UI_Input_Touch",
+ "Win32_UI_Shell",
+ "Win32_UI_TextServices",
+ "Win32_UI_WindowsAndMessaging",
+]
diff --git a/third_party/winit-0.30.13/FEATURES.md b/third_party/winit-0.30.13/FEATURES.md
new file mode 100644
index 0000000..2ae9477
--- /dev/null
+++ b/third_party/winit-0.30.13/FEATURES.md
@@ -0,0 +1,248 @@
+# Winit Scope
+
+Winit aims to expose an interface that abstracts over window creation and input handling and can
+be used to create both games and applications. It supports the following main graphical platforms:
+- Desktop
+ - Windows
+ - macOS
+ - Unix
+ - via X11
+ - via Wayland
+ - Redox OS, via Orbital
+- Mobile
+ - iOS
+ - Android
+- Web
+
+Most platforms expose capabilities that cannot be meaningfully transposed onto others. Winit does not
+aim to support every single feature of every platform, but rather to abstract over the common features
+available everywhere. In this context, APIs exposed in winit can be split into different "support tiers":
+
+- **Core:** Features that are essential to providing a well-formed abstraction over each platform's
+ windowing and input APIs.
+- **Platform:** Platform-specific features that can't be meaningfully exposed through a common API and
+ cannot be implemented outside of Winit without exposing a significant amount of Winit's internals
+ or interfering with Winit's abstractions.
+- **Usability:** Features that are not strictly essential to Winit's functionality, but provide meaningful
+ usability improvements and cannot be reasonably implemented in an external crate. These are
+ generally optional and exposed through Cargo features.
+
+Core features are taken care of by the core Winit maintainers. Platform features are not.
+When a platform feature is submitted, the submitter is considered the expert in the
+feature and may be asked to support the feature should it break in the future.
+
+Winit ***does not*** directly expose functionality for drawing inside windows or creating native
+menus, but ***does*** commit to providing APIs that higher-level crates can use to implement that
+functionality.
+
+## `1.0` and stability
+
+When all core features are implemented to the satisfaction of the Winit maintainers, Winit 1.0 will
+be released and the library will enter maintenance mode. For the most part, new core features will not
+be added past this point. New platform features may be accepted and exposed through point releases.
+
+### Tier upgrades
+Some platform features could, in theory, be exposed across multiple platforms, but have not gone
+through the implementation work necessary to function on all platforms. When one of these features
+gets implemented across all platforms, a PR can be opened to upgrade the feature to a core feature.
+If that gets accepted, the platform-specific functions get deprecated and become permanently
+exposed through the core, cross-platform API.
+
+# Features
+
+## Extending this section
+
+If your PR makes notable changes to Winit's features, please update this section as follows:
+
+- If your PR adds a new feature, add a brief description to the relevant section. If the feature is a core
+ feature, add a row to the feature matrix and describe what platforms the feature has been implemented on.
+
+- If your PR begins a new API rework, add a row to the `Pending API Reworks` table. If the PR implements the
+ API rework on all relevant platforms, please move it to the `Completed API Reworks` table.
+
+- If your PR implements an already-existing feature on a new platform, either mark the feature as *completed*,
+ or mark it as *mostly completed* and link to an issue describing the problems with the implementation.
+
+## Core
+
+### Windowing
+- **Window initialization**: Winit allows the creation of a window
+- **Providing pointer to init OpenGL**: Winit provides the necessary pointers to initialize a working opengl context
+- **Providing pointer to init Vulkan**: Same as OpenGL but for Vulkan
+- **Window decorations**: The windows created by winit are properly decorated, and the decorations can
+ be deactivated
+- **Window decorations toggle**: Decorations can be turned on or off after window creation
+- **Window resizing**: The windows created by winit can be resized and generate the appropriate events
+ when they are. The application can precisely control its window size if desired.
+- **Window resize increments**: When the window gets resized, the application can choose to snap the window's
+ size to specific values.
+- **Window transparency**: Winit allows the creation of windows with a transparent background.
+- **Window maximization**: The windows created by winit can be maximized upon creation.
+- **Window maximization toggle**: The windows created by winit can be maximized and unmaximized after
+ creation.
+- **Window minimization**: The windows created by winit can be minimized after creation.
+- **Fullscreen**: The windows created by winit can be put into fullscreen mode.
+- **Fullscreen toggle**: The windows created by winit can be switched to and from fullscreen after
+ creation.
+- **Exclusive fullscreen**: Winit allows changing the video mode of the monitor
+ for fullscreen windows and, if applicable, captures the monitor for exclusive
+ use by this application.
+- **HiDPI support**: Winit assists developers in appropriately scaling HiDPI content.
+- **Popup / modal windows**: Windows can be created relative to the client area of other windows, and parent
+ windows can be disabled in favor of popup windows. This feature also guarantees that popup windows
+ get drawn above their owner.
+
+
+### System Information
+- **Monitor list**: Retrieve the list of monitors and their metadata, including which one is primary.
+- **Video mode query**: Monitors can be queried for their supported fullscreen video modes (consisting of resolution, refresh rate, and bit depth).
+
+### Input Handling
+- **Mouse events**: Generating mouse events associated with pointer motion, click, and scrolling events.
+- **Mouse set location**: Forcibly changing the location of the pointer.
+- **Cursor locking**: Locking the cursor inside the window so it cannot move.
+- **Cursor confining**: Confining the cursor to the window bounds so it cannot leave them.
+- **Cursor icon**: Changing the cursor icon or hiding the cursor.
+- **Cursor image**: Changing the cursor to your own image.
+- **Cursor hittest**: Handle or ignore mouse events for a window.
+- **Touch events**: Single-touch events.
+- **Touch pressure**: Touch events contain information about the amount of force being applied.
+- **Multitouch**: Multi-touch events, including cancellation of a gesture.
+- **Keyboard events**: Properly processing keyboard events using the user-specified keymap and
+ translating keypresses into UTF-8 characters, handling dead keys and IMEs.
+- **Drag & Drop**: Dragging content into winit, detecting when content enters, drops, or if the drop is cancelled.
+- **Raw Device Events**: Capturing input from input devices without any OS filtering.
+- **Gamepad/Joystick events**: Capturing input from gamepads and joysticks.
+- **Device movement events**: Capturing input from the device gyroscope and accelerometer.
+
+## Platform
+### Windows
+* Setting the name of the internal window class
+* Setting the taskbar icon
+* Setting the parent window
+* Setting a menu bar
+* `WS_EX_NOREDIRECTIONBITMAP` support
+* Theme the title bar according to Windows 10 Dark Mode setting or set a preferred theme
+* Changing a system-drawn backdrop
+* Setting the window border color
+* Setting the title bar background color
+* Setting the title color
+* Setting the corner rounding preference
+
+### macOS
+* Window activation policy
+* Window movable by background
+* Transparent titlebar
+* Hidden titlebar
+* Hidden titlebar buttons
+* Full-size content view
+* Accepts first mouse
+* Set a preferred theme and get current theme.
+
+### Unix
+* Window urgency
+* X11 Window Class
+* X11 Override Redirect Flag
+* GTK Theme Variant
+* Base window size
+* Setting the X11 parent window
+
+### iOS
+* Get the `UIScreen` object pointer
+* Setting the `UIView` hidpi factor
+* Valid orientations
+* Home indicator visibility
+* Status bar visibility and style
+* Deferring system gestures
+* Getting the device idiom
+* Getting the preferred video mode
+
+### Web
+* Get if the systems preferred color scheme is "dark"
+
+## Compatibility Matrix
+
+Legend:
+
+- ✔️: Works as intended
+- ▢: Mostly works, but some bugs are known
+- ❌: Missing feature or large bugs making it unusable
+- **N/A**: Not applicable for this platform
+- ❓: Unknown status
+
+### Windowing
+|Feature |Windows|MacOS |Linux x11 |Linux Wayland |Android|iOS |Web |Redox OS|
+|-------------------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
+|Window initialization |✔️ |✔️ |▢[#5] |✔️ |▢[#33]|▢[#33] |✔️ |✔️ |
+|Providing pointer to init OpenGL |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |
+|Providing pointer to init Vulkan |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |**N/A**|**N/A** |
+|Window decorations |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|✔️ |
+|Window decorations toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
+|Window resizing |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
+|Window resize increments |✔️ |✔️ |✔️ |❌ |**N/A**|**N/A**|**N/A**|**N/A** |
+|Window transparency |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|N/A |✔️ |
+|Window blur |❌ |❌ |❌ |✔️ |**N/A**|**N/A**|N/A |❌ |
+|Window maximization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
+|Window maximization toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
+|Window minimization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
+|Fullscreen |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** |
+|Fullscreen toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** |
+|Exclusive fullscreen |✔️ |✔️ |✔️ |**N/A** |❌ |✔️ |**N/A**|**N/A** |
+|HiDPI support |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |
+|Popup windows |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**|**N/A** |
+
+### System information
+|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
+|---------------- | ----- | ---- | ------- | ----------- | ----- | ------- | -------- | ------ |
+|Monitor list |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
+|Video mode query |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
+
+### Input handling
+|Feature |Windows |MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
+|----------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
+|Mouse events |✔️ |▢[#63] |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
+|Mouse set location |✔️ |✔️ |✔️ |✔️(when locked) |**N/A**|**N/A**|**N/A**|**N/A** |
+|Cursor locking |❌ |✔️ |❌ |✔️ |**N/A**|**N/A**|✔️ |❌ |
+|Cursor confining |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
+|Cursor icon |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
+|Cursor image |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
+|Cursor hittest |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
+|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A** |
+|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |✔️ |**N/A** |
+|Multitouch |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |❌ |**N/A** |
+|Keyboard events |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
+|Drag & Drop |▢[#720] |▢[#720] |▢[#720] |▢[#720] |**N/A**|**N/A**|❓ |**N/A** |
+|Raw Device Events |▢[#750] |▢[#750] |▢[#750] |❌ |❌ |❌ |❓ |**N/A** |
+|Gamepad/Joystick events |❌[#804] |❌ |❌ |❌ |❌ |❌ |❓ |**N/A** |
+|Device movement events |❓ |❓ |❓ |❓ |❌ |❌ |❓ |**N/A** |
+|Drag window with cursor |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** |
+|Resize with cursor |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** |
+
+### Pending API Reworks
+Changes in the API that have been agreed upon but aren't implemented across all platforms.
+
+|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
+|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
+|New API for HiDPI ([#315] [#319]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |❓ |
+|Event Loop 2.0 ([#459]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |✔️ |
+|Keyboard Input 2.0 ([#753]) |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
+
+### Completed API Reworks
+|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
+|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
+
+[#165]: https://github.com/rust-windowing/winit/issues/165
+[#219]: https://github.com/rust-windowing/winit/issues/219
+[#242]: https://github.com/rust-windowing/winit/issues/242
+[#306]: https://github.com/rust-windowing/winit/issues/306
+[#315]: https://github.com/rust-windowing/winit/issues/315
+[#319]: https://github.com/rust-windowing/winit/issues/319
+[#33]: https://github.com/rust-windowing/winit/issues/33
+[#459]: https://github.com/rust-windowing/winit/issues/459
+[#5]: https://github.com/rust-windowing/winit/issues/5
+[#63]: https://github.com/rust-windowing/winit/issues/63
+[#720]: https://github.com/rust-windowing/winit/issues/720
+[#721]: https://github.com/rust-windowing/winit/issues/721
+[#750]: https://github.com/rust-windowing/winit/issues/750
+[#753]: https://github.com/rust-windowing/winit/issues/753
+[#804]: https://github.com/rust-windowing/winit/issues/804
diff --git a/third_party/winit-0.30.13/LICENSE b/third_party/winit-0.30.13/LICENSE
new file mode 100644
index 0000000..ad410e1
--- /dev/null
+++ b/third_party/winit-0.30.13/LICENSE
@@ -0,0 +1,201 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/third_party/winit-0.30.13/README.md b/third_party/winit-0.30.13/README.md
new file mode 100644
index 0000000..ab95887
--- /dev/null
+++ b/third_party/winit-0.30.13/README.md
@@ -0,0 +1,70 @@
+# winit - Cross-platform window creation and management in Rust
+
+[](https://crates.io/crates/winit)
+[](https://docs.rs/winit)
+[](https://rust-windowing.github.io/winit/winit/index.html)
+[](https://github.com/rust-windowing/winit/actions)
+
+```toml
+[dependencies]
+winit = "0.30.13"
+```
+
+## [Documentation](https://docs.rs/winit)
+
+For features _within_ the scope of winit, see [FEATURES.md](FEATURES.md).
+
+For features _outside_ the scope of winit, see [Are we GUI Yet?](https://areweguiyet.com/) and [Are we game yet?](https://arewegameyet.rs/), depending on what kind of project you're looking to do.
+
+## Contact Us
+
+Join us in our [](https://matrix.to/#/#rust-windowing:matrix.org) room.
+
+The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings).
+
+## Usage
+
+Winit is a window creation and management library. It can create windows and lets you handle
+events (for example: the window being resized, a key being pressed, a mouse movement, etc.)
+produced by the window.
+
+Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to
+show something on the window you need to use the platform-specific getters provided by winit, or
+another library.
+
+## CONTRIBUTING
+
+For contributing guidelines see [CONTRIBUTING.md](./CONTRIBUTING.md).
+
+## MSRV Policy
+
+This crate's Minimum Supported Rust Version (MSRV) is **1.70**. Changes to
+the MSRV will be accompanied by a minor version bump.
+
+As a **tentative** policy, the upper bound of the MSRV is given by the following
+formula:
+
+```
+min(sid, stable - 3)
+```
+
+Where `sid` is the current version of `rustc` provided by [Debian Sid], and
+`stable` is the latest stable version of Rust. This bound may be broken in case of a major ecosystem shift or a security vulnerability.
+
+[Debian Sid]: https://packages.debian.org/sid/rustc
+
+The exception is for the Android platform, where a higher Rust version
+must be used for certain Android features. In this case, the MSRV will be
+capped at the latest stable version of Rust minus three. This inconsistency is
+not reflected in Cargo metadata, as it is not powerful enough to expose this
+restriction.
+
+All crates in the [`rust-windowing`] organizations have the
+same MSRV policy.
+
+[`rust-windowing`]: https://github.com/rust-windowing
+
+### Platform-specific usage
+
+Check out the [`winit::platform`](https://rust-windowing.github.io/winit/winit/platform/index.html) module for platform-specific usage.
diff --git a/third_party/winit-0.30.13/build.rs b/third_party/winit-0.30.13/build.rs
new file mode 100644
index 0000000..6a4528b
--- /dev/null
+++ b/third_party/winit-0.30.13/build.rs
@@ -0,0 +1,27 @@
+use cfg_aliases::cfg_aliases;
+
+fn main() {
+ // The script doesn't depend on our code.
+ println!("cargo:rerun-if-changed=build.rs");
+
+ // Setup cfg aliases.
+ cfg_aliases! {
+ // Systems.
+ android_platform: { target_os = "android" },
+ web_platform: { all(target_family = "wasm", target_os = "unknown") },
+ macos_platform: { target_os = "macos" },
+ ios_platform: { target_os = "ios" },
+ windows_platform: { target_os = "windows" },
+ apple: { any(target_os = "ios", target_os = "macos") },
+ free_unix: { all(unix, not(apple), not(android_platform), not(target_os = "emscripten")) },
+ redox: { target_os = "redox" },
+
+ // Native displays.
+ x11_platform: { all(feature = "x11", free_unix, not(redox)) },
+ wayland_platform: { all(feature = "wayland", free_unix, not(redox)) },
+ orbital_platform: { redox },
+ }
+
+ // Winit defined cfgs.
+ println!("cargo:rustc-check-cfg=cfg(unreleased_changelogs)");
+}
diff --git a/third_party/winit-0.30.13/docs/res/ATTRIBUTION.md b/third_party/winit-0.30.13/docs/res/ATTRIBUTION.md
new file mode 100644
index 0000000..268316f
--- /dev/null
+++ b/third_party/winit-0.30.13/docs/res/ATTRIBUTION.md
@@ -0,0 +1,11 @@
+# Image Attribution
+
+These images are used in the documentation of `winit`.
+
+## keyboard_*.svg
+
+These files are a modified version of "[ANSI US QWERTY (Windows)](https://commons.wikimedia.org/wiki/File:ANSI_US_QWERTY_(Windows).svg)"
+by [Tomiĉo] (https://commons.wikimedia.org/wiki/User:Tomi%C4%89o). It was
+originally released under the [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.en)
+License. Minor modifications have been made by [John Nunley](https://github.com/notgull),
+which have been released under the same license as a derivative work.
diff --git a/third_party/winit-0.30.13/docs/res/keyboard_left_shift_key.svg b/third_party/winit-0.30.13/docs/res/keyboard_left_shift_key.svg
new file mode 100644
index 0000000..bae6f9a
--- /dev/null
+++ b/third_party/winit-0.30.13/docs/res/keyboard_left_shift_key.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/third_party/winit-0.30.13/docs/res/keyboard_numpad_1_key.svg b/third_party/winit-0.30.13/docs/res/keyboard_numpad_1_key.svg
new file mode 100644
index 0000000..d595758
--- /dev/null
+++ b/third_party/winit-0.30.13/docs/res/keyboard_numpad_1_key.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/third_party/winit-0.30.13/docs/res/keyboard_right_shift_key.svg b/third_party/winit-0.30.13/docs/res/keyboard_right_shift_key.svg
new file mode 100644
index 0000000..dc016f0
--- /dev/null
+++ b/third_party/winit-0.30.13/docs/res/keyboard_right_shift_key.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/third_party/winit-0.30.13/docs/res/keyboard_standard_1_key.svg b/third_party/winit-0.30.13/docs/res/keyboard_standard_1_key.svg
new file mode 100644
index 0000000..3520d55
--- /dev/null
+++ b/third_party/winit-0.30.13/docs/res/keyboard_standard_1_key.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/third_party/winit-0.30.13/examples/child_window.rs b/third_party/winit-0.30.13/examples/child_window.rs
new file mode 100644
index 0000000..715996e
--- /dev/null
+++ b/third_party/winit-0.30.13/examples/child_window.rs
@@ -0,0 +1,88 @@
+#[cfg(all(feature = "rwh_06", any(x11_platform, macos_platform, windows_platform)))]
+#[allow(deprecated)]
+fn main() -> Result<(), impl std::error::Error> {
+ use std::collections::HashMap;
+
+ use winit::dpi::{LogicalPosition, LogicalSize, Position};
+ use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
+ use winit::event_loop::{ActiveEventLoop, EventLoop};
+ use winit::raw_window_handle::HasRawWindowHandle;
+ use winit::window::Window;
+
+ #[path = "util/fill.rs"]
+ mod fill;
+
+ fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
+ let parent = parent.raw_window_handle().unwrap();
+ let mut window_attributes = Window::default_attributes()
+ .with_title("child window")
+ .with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
+ .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
+ .with_visible(true);
+ // `with_parent_window` is unsafe. Parent window must be a valid window.
+ window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
+
+ event_loop.create_window(window_attributes).unwrap()
+ }
+
+ let mut windows = HashMap::new();
+
+ let event_loop: EventLoop<()> = EventLoop::new().unwrap();
+ let mut parent_window_id = None;
+
+ event_loop.run(move |event: Event<()>, event_loop| {
+ match event {
+ Event::Resumed => {
+ let attributes = Window::default_attributes()
+ .with_title("parent window")
+ .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
+ .with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
+ let window = event_loop.create_window(attributes).unwrap();
+
+ parent_window_id = Some(window.id());
+
+ println!("Parent window id: {parent_window_id:?})");
+ windows.insert(window.id(), window);
+ },
+ Event::WindowEvent { window_id, event } => match event {
+ WindowEvent::CloseRequested => {
+ windows.clear();
+ event_loop.exit();
+ },
+ WindowEvent::CursorEntered { device_id: _ } => {
+ // On x11, println when the cursor entered in a window even if the child window
+ // is created by some key inputs.
+ // the child windows are always placed at (0, 0) with size (200, 200) in the
+ // parent window, so we also can see this log when we move
+ // the cursor around (200, 200) in parent window.
+ println!("cursor entered in the window {window_id:?}");
+ },
+ WindowEvent::KeyboardInput {
+ event: KeyEvent { state: ElementState::Pressed, .. },
+ ..
+ } => {
+ let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
+ let child_window = spawn_child_window(parent_window, event_loop);
+ let child_id = child_window.id();
+ println!("Child window created with id: {child_id:?}");
+ windows.insert(child_id, child_window);
+ },
+ WindowEvent::RedrawRequested => {
+ if let Some(window) = windows.get(&window_id) {
+ fill::fill_window(window);
+ }
+ },
+ _ => (),
+ },
+ _ => (),
+ }
+ })
+}
+
+#[cfg(all(feature = "rwh_06", not(any(x11_platform, macos_platform, windows_platform))))]
+fn main() {
+ panic!(
+ "This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature \
+ enabled."
+ );
+}
diff --git a/third_party/winit-0.30.13/examples/control_flow.rs b/third_party/winit-0.30.13/examples/control_flow.rs
new file mode 100644
index 0000000..13cc947
--- /dev/null
+++ b/third_party/winit-0.30.13/examples/control_flow.rs
@@ -0,0 +1,148 @@
+#![allow(clippy::single_match)]
+
+use std::thread;
+#[cfg(not(web_platform))]
+use std::time;
+
+use ::tracing::{info, warn};
+#[cfg(web_platform)]
+use web_time as time;
+
+use winit::application::ApplicationHandler;
+use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent};
+use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
+use winit::keyboard::{Key, NamedKey};
+use winit::window::{Window, WindowId};
+
+#[path = "util/fill.rs"]
+mod fill;
+#[path = "util/tracing.rs"]
+mod tracing;
+
+const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
+const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
+
+#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
+enum Mode {
+ #[default]
+ Wait,
+ WaitUntil,
+ Poll,
+}
+
+fn main() -> Result<(), impl std::error::Error> {
+ #[cfg(web_platform)]
+ console_error_panic_hook::set_once();
+
+ tracing::init();
+
+ info!("Press '1' to switch to Wait mode.");
+ info!("Press '2' to switch to WaitUntil mode.");
+ info!("Press '3' to switch to Poll mode.");
+ info!("Press 'R' to toggle request_redraw() calls.");
+ info!("Press 'Esc' to close the window.");
+
+ let event_loop = EventLoop::new().unwrap();
+
+ let mut app = ControlFlowDemo::default();
+ event_loop.run_app(&mut app)
+}
+
+#[derive(Default)]
+struct ControlFlowDemo {
+ mode: Mode,
+ request_redraw: bool,
+ wait_cancelled: bool,
+ close_requested: bool,
+ window: Option,
+}
+
+impl ApplicationHandler for ControlFlowDemo {
+ fn new_events(&mut self, _event_loop: &ActiveEventLoop, cause: StartCause) {
+ info!("new_events: {cause:?}");
+
+ self.wait_cancelled = match cause {
+ StartCause::WaitCancelled { .. } => self.mode == Mode::WaitUntil,
+ _ => false,
+ }
+ }
+
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ let window_attributes = Window::default_attributes().with_title(
+ "Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
+ );
+ self.window = Some(event_loop.create_window(window_attributes).unwrap());
+ }
+
+ fn window_event(
+ &mut self,
+ _event_loop: &ActiveEventLoop,
+ _window_id: WindowId,
+ event: WindowEvent,
+ ) {
+ info!("{event:?}");
+
+ match event {
+ WindowEvent::CloseRequested => {
+ self.close_requested = true;
+ },
+ WindowEvent::KeyboardInput {
+ event: KeyEvent { logical_key: key, state: ElementState::Pressed, .. },
+ ..
+ } => match key.as_ref() {
+ // WARNING: Consider using `key_without_modifiers()` if available on your platform.
+ // See the `key_binding` example
+ Key::Character("1") => {
+ self.mode = Mode::Wait;
+ warn!("mode: {:?}", self.mode);
+ },
+ Key::Character("2") => {
+ self.mode = Mode::WaitUntil;
+ warn!("mode: {:?}", self.mode);
+ },
+ Key::Character("3") => {
+ self.mode = Mode::Poll;
+ warn!("mode: {:?}", self.mode);
+ },
+ Key::Character("r") => {
+ self.request_redraw = !self.request_redraw;
+ warn!("request_redraw: {}", self.request_redraw);
+ },
+ Key::Named(NamedKey::Escape) => {
+ self.close_requested = true;
+ },
+ _ => (),
+ },
+ WindowEvent::RedrawRequested => {
+ let window = self.window.as_ref().unwrap();
+ window.pre_present_notify();
+ fill::fill_window(window);
+ },
+ _ => (),
+ }
+ }
+
+ fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ if self.request_redraw && !self.wait_cancelled && !self.close_requested {
+ self.window.as_ref().unwrap().request_redraw();
+ }
+
+ match self.mode {
+ Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
+ Mode::WaitUntil => {
+ if !self.wait_cancelled {
+ event_loop
+ .set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
+ }
+ },
+ Mode::Poll => {
+ thread::sleep(POLL_SLEEP_TIME);
+ event_loop.set_control_flow(ControlFlow::Poll);
+ },
+ };
+
+ if self.close_requested {
+ event_loop.exit();
+ }
+ }
+}
diff --git a/third_party/winit-0.30.13/examples/data/cross.png b/third_party/winit-0.30.13/examples/data/cross.png
new file mode 100644
index 0000000..9bfdf36
Binary files /dev/null and b/third_party/winit-0.30.13/examples/data/cross.png differ
diff --git a/third_party/winit-0.30.13/examples/data/cross2.png b/third_party/winit-0.30.13/examples/data/cross2.png
new file mode 100644
index 0000000..b9f7a48
Binary files /dev/null and b/third_party/winit-0.30.13/examples/data/cross2.png differ
diff --git a/third_party/winit-0.30.13/examples/data/gradient.png b/third_party/winit-0.30.13/examples/data/gradient.png
new file mode 100644
index 0000000..41ce610
Binary files /dev/null and b/third_party/winit-0.30.13/examples/data/gradient.png differ
diff --git a/third_party/winit-0.30.13/examples/data/icon.png b/third_party/winit-0.30.13/examples/data/icon.png
new file mode 100644
index 0000000..aa3fbf3
Binary files /dev/null and b/third_party/winit-0.30.13/examples/data/icon.png differ
diff --git a/third_party/winit-0.30.13/examples/pump_events.rs b/third_party/winit-0.30.13/examples/pump_events.rs
new file mode 100644
index 0000000..ad198cf
--- /dev/null
+++ b/third_party/winit-0.30.13/examples/pump_events.rs
@@ -0,0 +1,80 @@
+#![allow(clippy::single_match)]
+
+// Limit this example to only compatible platforms.
+#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, android_platform,))]
+fn main() -> std::process::ExitCode {
+ use std::process::ExitCode;
+ use std::thread::sleep;
+ use std::time::Duration;
+
+ use winit::application::ApplicationHandler;
+ use winit::event::WindowEvent;
+ use winit::event_loop::{ActiveEventLoop, EventLoop};
+ use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
+ use winit::window::{Window, WindowId};
+
+ #[path = "util/fill.rs"]
+ mod fill;
+
+ #[derive(Default)]
+ struct PumpDemo {
+ window: Option,
+ }
+
+ impl ApplicationHandler for PumpDemo {
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ let window_attributes = Window::default_attributes().with_title("A fantastic window!");
+ self.window = Some(event_loop.create_window(window_attributes).unwrap());
+ }
+
+ fn window_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ _window_id: WindowId,
+ event: WindowEvent,
+ ) {
+ println!("{event:?}");
+
+ let window = match self.window.as_ref() {
+ Some(window) => window,
+ None => return,
+ };
+
+ match event {
+ WindowEvent::CloseRequested => event_loop.exit(),
+ WindowEvent::RedrawRequested => {
+ fill::fill_window(window);
+ window.request_redraw();
+ },
+ _ => (),
+ }
+ }
+ }
+
+ let mut event_loop = EventLoop::new().unwrap();
+
+ tracing_subscriber::fmt::init();
+
+ let mut app = PumpDemo::default();
+
+ loop {
+ let timeout = Some(Duration::ZERO);
+ let status = event_loop.pump_app_events(timeout, &mut app);
+
+ if let PumpStatus::Exit(exit_code) = status {
+ break ExitCode::from(exit_code as u8);
+ }
+
+ // Sleep for 1/60 second to simulate application work
+ //
+ // Since `pump_events` doesn't block it will be important to
+ // throttle the loop in the app somehow.
+ println!("Update()");
+ sleep(Duration::from_millis(16));
+ }
+}
+
+#[cfg(any(ios_platform, web_platform, orbital_platform))]
+fn main() {
+ println!("This platform doesn't support pump_events.");
+}
diff --git a/third_party/winit-0.30.13/examples/run_on_demand.rs b/third_party/winit-0.30.13/examples/run_on_demand.rs
new file mode 100644
index 0000000..5a277de
--- /dev/null
+++ b/third_party/winit-0.30.13/examples/run_on_demand.rs
@@ -0,0 +1,99 @@
+#![allow(clippy::single_match)]
+
+// Limit this example to only compatible platforms.
+#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform,))]
+fn main() -> Result<(), Box> {
+ use std::time::Duration;
+
+ use winit::application::ApplicationHandler;
+ use winit::event::WindowEvent;
+ use winit::event_loop::{ActiveEventLoop, EventLoop};
+ use winit::platform::run_on_demand::EventLoopExtRunOnDemand;
+ use winit::window::{Window, WindowId};
+
+ #[path = "util/fill.rs"]
+ mod fill;
+
+ #[derive(Default)]
+ struct App {
+ idx: usize,
+ window_id: Option,
+ window: Option,
+ }
+
+ impl ApplicationHandler for App {
+ fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
+ if let Some(window) = self.window.as_ref() {
+ window.request_redraw();
+ }
+ }
+
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ let window_attributes = Window::default_attributes()
+ .with_title("Fantastic window number one!")
+ .with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0));
+ let window = event_loop.create_window(window_attributes).unwrap();
+ self.window_id = Some(window.id());
+ self.window = Some(window);
+ }
+
+ fn window_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ window_id: WindowId,
+ event: WindowEvent,
+ ) {
+ if event == WindowEvent::Destroyed && self.window_id == Some(window_id) {
+ println!(
+ "--------------------------------------------------------- Window {} Destroyed",
+ self.idx
+ );
+ self.window_id = None;
+ event_loop.exit();
+ return;
+ }
+
+ let window = match self.window.as_mut() {
+ Some(window) => window,
+ None => return,
+ };
+
+ match event {
+ WindowEvent::CloseRequested => {
+ println!(
+ "--------------------------------------------------------- Window {} \
+ CloseRequested",
+ self.idx
+ );
+ fill::cleanup_window(window);
+ self.window = None;
+ },
+ WindowEvent::RedrawRequested => {
+ fill::fill_window(window);
+ },
+ _ => (),
+ }
+ }
+ }
+
+ tracing_subscriber::fmt::init();
+
+ let mut event_loop = EventLoop::new().unwrap();
+
+ let mut app = App { idx: 1, ..Default::default() };
+ event_loop.run_app_on_demand(&mut app)?;
+
+ println!("--------------------------------------------------------- Finished first loop");
+ println!("--------------------------------------------------------- Waiting 5 seconds");
+ std::thread::sleep(Duration::from_secs(5));
+
+ app.idx += 1;
+ event_loop.run_app_on_demand(&mut app)?;
+ println!("--------------------------------------------------------- Finished second loop");
+ Ok(())
+}
+
+#[cfg(not(any(windows_platform, macos_platform, x11_platform, wayland_platform,)))]
+fn main() {
+ println!("This example is not supported on this platform");
+}
diff --git a/third_party/winit-0.30.13/examples/util/fill.rs b/third_party/winit-0.30.13/examples/util/fill.rs
new file mode 100644
index 0000000..31540c0
--- /dev/null
+++ b/third_party/winit-0.30.13/examples/util/fill.rs
@@ -0,0 +1,117 @@
+//! Fill the window buffer with a solid color.
+//!
+//! Launching a window without drawing to it has unpredictable results varying from platform to
+//! platform. In order to have well-defined examples, this module provides an easy way to
+//! fill the window buffer with a solid color.
+//!
+//! The `softbuffer` crate is used, largely because of its ease of use. `glutin` or `wgpu` could
+//! also be used to fill the window buffer, but they are more complicated to use.
+
+#[allow(unused_imports)]
+pub use platform::cleanup_window;
+pub use platform::fill_window;
+
+#[cfg(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios"))))]
+mod platform {
+ use std::cell::RefCell;
+ use std::collections::HashMap;
+ use std::mem;
+ use std::mem::ManuallyDrop;
+ use std::num::NonZeroU32;
+
+ use softbuffer::{Context, Surface};
+ use winit::window::{Window, WindowId};
+
+ thread_local! {
+ // NOTE: You should never do things like that, create context and drop it before
+ // you drop the event loop. We do this for brevity to not blow up examples. We use
+ // ManuallyDrop to prevent destructors from running.
+ //
+ // A static, thread-local map of graphics contexts to open windows.
+ static GC: ManuallyDrop>> = const { ManuallyDrop::new(RefCell::new(None)) };
+ }
+
+ /// The graphics context used to draw to a window.
+ struct GraphicsContext {
+ /// The global softbuffer context.
+ context: RefCell>,
+
+ /// The hash map of window IDs to surfaces.
+ surfaces: HashMap>,
+ }
+
+ impl GraphicsContext {
+ fn new(w: &Window) -> Self {
+ Self {
+ context: RefCell::new(
+ Context::new(unsafe { mem::transmute::<&'_ Window, &'static Window>(w) })
+ .expect("Failed to create a softbuffer context"),
+ ),
+ surfaces: HashMap::new(),
+ }
+ }
+
+ fn create_surface(
+ &mut self,
+ window: &Window,
+ ) -> &mut Surface<&'static Window, &'static Window> {
+ self.surfaces.entry(window.id()).or_insert_with(|| {
+ Surface::new(&self.context.borrow(), unsafe {
+ mem::transmute::<&'_ Window, &'static Window>(window)
+ })
+ .expect("Failed to create a softbuffer surface")
+ })
+ }
+
+ fn destroy_surface(&mut self, window: &Window) {
+ self.surfaces.remove(&window.id());
+ }
+ }
+
+ pub fn fill_window(window: &Window) {
+ GC.with(|gc| {
+ let size = window.inner_size();
+ let (Some(width), Some(height)) =
+ (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
+ else {
+ return;
+ };
+
+ // Either get the last context used or create a new one.
+ let mut gc = gc.borrow_mut();
+ let surface =
+ gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window);
+
+ // Fill a buffer with a solid color.
+ const DARK_GRAY: u32 = 0xff181818;
+
+ surface.resize(width, height).expect("Failed to resize the softbuffer surface");
+
+ let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer");
+ buffer.fill(DARK_GRAY);
+ buffer.present().expect("Failed to present the softbuffer buffer");
+ })
+ }
+
+ #[allow(dead_code)]
+ pub fn cleanup_window(window: &Window) {
+ GC.with(|gc| {
+ let mut gc = gc.borrow_mut();
+ if let Some(context) = gc.as_mut() {
+ context.destroy_surface(window);
+ }
+ });
+ }
+}
+
+#[cfg(not(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios")))))]
+mod platform {
+ pub fn fill_window(_window: &winit::window::Window) {
+ // No-op on mobile platforms.
+ }
+
+ #[allow(dead_code)]
+ pub fn cleanup_window(_window: &winit::window::Window) {
+ // No-op on mobile platforms.
+ }
+}
diff --git a/third_party/winit-0.30.13/examples/util/tracing.rs b/third_party/winit-0.30.13/examples/util/tracing.rs
new file mode 100644
index 0000000..bab7ced
--- /dev/null
+++ b/third_party/winit-0.30.13/examples/util/tracing.rs
@@ -0,0 +1,25 @@
+#[cfg(not(web_platform))]
+pub fn init() {
+ use tracing_subscriber::filter::{EnvFilter, LevelFilter};
+
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ EnvFilter::builder().with_default_directive(LevelFilter::INFO.into()).from_env_lossy(),
+ )
+ .init();
+}
+
+#[cfg(web_platform)]
+pub fn init() {
+ use tracing_subscriber::layer::SubscriberExt;
+ use tracing_subscriber::util::SubscriberInitExt;
+
+ tracing_subscriber::registry()
+ .with(
+ tracing_subscriber::fmt::layer()
+ .with_ansi(false)
+ .without_time()
+ .with_writer(tracing_web::MakeWebConsoleWriter::new()),
+ )
+ .init();
+}
diff --git a/third_party/winit-0.30.13/examples/window.rs b/third_party/winit-0.30.13/examples/window.rs
new file mode 100644
index 0000000..48afadf
--- /dev/null
+++ b/third_party/winit-0.30.13/examples/window.rs
@@ -0,0 +1,1110 @@
+//! Simple winit application.
+
+use std::collections::HashMap;
+use std::error::Error;
+use std::fmt::Debug;
+#[cfg(not(any(android_platform, ios_platform)))]
+use std::num::NonZeroU32;
+use std::sync::Arc;
+use std::{fmt, mem};
+
+use ::tracing::{error, info};
+use cursor_icon::CursorIcon;
+#[cfg(not(any(android_platform, ios_platform)))]
+use rwh_06::{DisplayHandle, HasDisplayHandle};
+#[cfg(not(any(android_platform, ios_platform)))]
+use softbuffer::{Context, Surface};
+
+use winit::application::ApplicationHandler;
+use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
+use winit::event::{DeviceEvent, DeviceId, Ime, MouseButton, MouseScrollDelta, WindowEvent};
+use winit::event_loop::{ActiveEventLoop, EventLoop};
+use winit::keyboard::{Key, ModifiersState};
+use winit::window::{
+ Cursor, CursorGrabMode, CustomCursor, CustomCursorSource, Fullscreen, Icon, ResizeDirection,
+ Theme, Window, WindowId,
+};
+
+#[cfg(macos_platform)]
+use winit::platform::macos::{OptionAsAlt, WindowAttributesExtMacOS, WindowExtMacOS};
+#[cfg(any(x11_platform, wayland_platform))]
+use winit::platform::startup_notify::{
+ self, EventLoopExtStartupNotify, WindowAttributesExtStartupNotify, WindowExtStartupNotify,
+};
+#[cfg(x11_platform)]
+use winit::platform::x11::WindowAttributesExtX11;
+
+#[path = "util/tracing.rs"]
+mod tracing;
+
+/// The amount of points to around the window for drag resize direction calculations.
+const BORDER_SIZE: f64 = 20.;
+
+fn main() -> Result<(), Box> {
+ #[cfg(web_platform)]
+ console_error_panic_hook::set_once();
+
+ tracing::init();
+
+ let event_loop = EventLoop::::with_user_event().build()?;
+ let _event_loop_proxy = event_loop.create_proxy();
+
+ // Wire the user event from another thread.
+ #[cfg(not(web_platform))]
+ std::thread::spawn(move || {
+ // Wake up the `event_loop` once every second and dispatch a custom event
+ // from a different thread.
+ info!("Starting to send user event every second");
+ loop {
+ let _ = _event_loop_proxy.send_event(UserEvent::WakeUp);
+ std::thread::sleep(std::time::Duration::from_secs(1));
+ }
+ });
+
+ let mut state = Application::new(&event_loop);
+
+ event_loop.run_app(&mut state).map_err(Into::into)
+}
+
+#[allow(dead_code)]
+#[derive(Debug, Clone, Copy)]
+enum UserEvent {
+ WakeUp,
+}
+
+/// Application state and event handling.
+struct Application {
+ /// Custom cursors assets.
+ custom_cursors: Vec,
+ /// Application icon.
+ icon: Icon,
+ windows: HashMap,
+ /// Drawing context.
+ ///
+ /// With OpenGL it could be EGLDisplay.
+ #[cfg(not(any(android_platform, ios_platform)))]
+ context: Option>>,
+}
+
+impl Application {
+ fn new(event_loop: &EventLoop) -> Self {
+ // SAFETY: we drop the context right before the event loop is stopped, thus making it safe.
+ #[cfg(not(any(android_platform, ios_platform)))]
+ let context = Some(
+ Context::new(unsafe {
+ std::mem::transmute::, DisplayHandle<'static>>(
+ event_loop.display_handle().unwrap(),
+ )
+ })
+ .unwrap(),
+ );
+
+ // You'll have to choose an icon size at your own discretion. On X11, the desired size
+ // varies by WM, and on Windows, you still have to account for screen scaling. Here
+ // we use 32px, since it seems to work well enough in most cases. Be careful about
+ // going too high, or you'll be bitten by the low-quality downscaling built into the
+ // WM.
+ let icon = load_icon(include_bytes!("data/icon.png"));
+
+ info!("Loading cursor assets");
+ let custom_cursors = vec![
+ event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross.png"))),
+ event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross2.png"))),
+ event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/gradient.png"))),
+ ];
+
+ Self {
+ #[cfg(not(any(android_platform, ios_platform)))]
+ context,
+ custom_cursors,
+ icon,
+ windows: Default::default(),
+ }
+ }
+
+ fn create_window(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ _tab_id: Option,
+ ) -> Result> {
+ // TODO read-out activation token.
+
+ #[allow(unused_mut)]
+ let mut window_attributes = Window::default_attributes()
+ .with_title("Winit window")
+ .with_transparent(true)
+ .with_window_icon(Some(self.icon.clone()));
+
+ #[cfg(any(x11_platform, wayland_platform))]
+ if let Some(token) = event_loop.read_token_from_env() {
+ startup_notify::reset_activation_token_env();
+ info!("Using token {:?} to activate a window", token);
+ window_attributes = window_attributes.with_activation_token(token);
+ }
+
+ #[cfg(x11_platform)]
+ match std::env::var("X11_VISUAL_ID") {
+ Ok(visual_id_str) => {
+ info!("Using X11 visual id {visual_id_str}");
+ let visual_id = visual_id_str.parse()?;
+ window_attributes = window_attributes.with_x11_visual(visual_id);
+ },
+ Err(_) => info!("Set the X11_VISUAL_ID env variable to request specific X11 visual"),
+ }
+
+ #[cfg(x11_platform)]
+ match std::env::var("X11_SCREEN_ID") {
+ Ok(screen_id_str) => {
+ info!("Placing the window on X11 screen {screen_id_str}");
+ let screen_id = screen_id_str.parse()?;
+ window_attributes = window_attributes.with_x11_screen(screen_id);
+ },
+ Err(_) => info!(
+ "Set the X11_SCREEN_ID env variable to place the window on non-default screen"
+ ),
+ }
+
+ #[cfg(macos_platform)]
+ if let Some(tab_id) = _tab_id {
+ window_attributes = window_attributes.with_tabbing_identifier(&tab_id);
+ }
+
+ #[cfg(web_platform)]
+ {
+ use winit::platform::web::WindowAttributesExtWebSys;
+ window_attributes = window_attributes.with_append(true);
+ }
+
+ let window = event_loop.create_window(window_attributes)?;
+
+ #[cfg(ios_platform)]
+ {
+ use winit::platform::ios::WindowExtIOS;
+ window.recognize_doubletap_gesture(true);
+ window.recognize_pinch_gesture(true);
+ window.recognize_rotation_gesture(true);
+ window.recognize_pan_gesture(true, 2, 2);
+ }
+
+ let window_state = WindowState::new(self, window)?;
+ let window_id = window_state.window.id();
+ info!("Created new window with id={window_id:?}");
+ self.windows.insert(window_id, window_state);
+ Ok(window_id)
+ }
+
+ fn handle_action(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, action: Action) {
+ // let cursor_position = self.cursor_position;
+ let window = self.windows.get_mut(&window_id).unwrap();
+ info!("Executing action: {action:?}");
+ match action {
+ Action::CloseWindow => {
+ let _ = self.windows.remove(&window_id);
+ },
+ Action::CreateNewWindow => {
+ #[cfg(any(x11_platform, wayland_platform))]
+ if let Err(err) = window.window.request_activation_token() {
+ info!("Failed to get activation token: {err}");
+ } else {
+ return;
+ }
+
+ if let Err(err) = self.create_window(event_loop, None) {
+ error!("Error creating new window: {err}");
+ }
+ },
+ Action::ToggleResizeIncrements => window.toggle_resize_increments(),
+ Action::ToggleCursorVisibility => window.toggle_cursor_visibility(),
+ Action::ToggleResizable => window.toggle_resizable(),
+ Action::ToggleDecorations => window.toggle_decorations(),
+ Action::ToggleFullscreen => window.toggle_fullscreen(),
+ Action::ToggleMaximize => window.toggle_maximize(),
+ Action::ToggleImeInput => window.toggle_ime(),
+ Action::Minimize => window.minimize(),
+ Action::NextCursor => window.next_cursor(),
+ Action::NextCustomCursor => window.next_custom_cursor(&self.custom_cursors),
+ #[cfg(web_platform)]
+ Action::UrlCustomCursor => window.url_custom_cursor(event_loop),
+ #[cfg(web_platform)]
+ Action::AnimationCustomCursor => {
+ window.animation_custom_cursor(event_loop, &self.custom_cursors)
+ },
+ Action::CycleCursorGrab => window.cycle_cursor_grab(),
+ Action::DragWindow => window.drag_window(),
+ Action::DragResizeWindow => window.drag_resize_window(),
+ Action::ShowWindowMenu => window.show_menu(),
+ Action::PrintHelp => self.print_help(),
+ #[cfg(macos_platform)]
+ Action::CycleOptionAsAlt => window.cycle_option_as_alt(),
+ Action::SetTheme(theme) => {
+ window.window.set_theme(theme);
+ // Get the resulting current theme to draw with
+ let actual_theme = theme.or_else(|| window.window.theme()).unwrap_or(Theme::Dark);
+ window.set_draw_theme(actual_theme);
+ },
+ #[cfg(macos_platform)]
+ Action::CreateNewTab => {
+ let tab_id = window.window.tabbing_identifier();
+ if let Err(err) = self.create_window(event_loop, Some(tab_id)) {
+ error!("Error creating new window: {err}");
+ }
+ },
+ Action::RequestResize => window.swap_dimensions(),
+ }
+ }
+
+ fn dump_monitors(&self, event_loop: &ActiveEventLoop) {
+ info!("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() {
+ info!("{intro}: {name}");
+ } else {
+ info!("{intro}: [no name]");
+ }
+
+ let PhysicalSize { width, height } = monitor.size();
+ info!(
+ " Current mode: {width}x{height}{}",
+ if let Some(m_hz) = monitor.refresh_rate_millihertz() {
+ format!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000)
+ } else {
+ String::new()
+ }
+ );
+
+ let PhysicalPosition { x, y } = monitor.position();
+ info!(" Position: {x},{y}");
+
+ info!(" Scale factor: {}", monitor.scale_factor());
+
+ info!(" Available modes (width x height x bit-depth):");
+ for mode in monitor.video_modes() {
+ let PhysicalSize { width, height } = mode.size();
+ let bits = mode.bit_depth();
+ let m_hz = mode.refresh_rate_millihertz();
+ info!(" {width}x{height}x{bits} @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
+ }
+ }
+ }
+
+ /// Process the key binding.
+ fn process_key_binding(key: &str, mods: &ModifiersState) -> Option {
+ KEY_BINDINGS
+ .iter()
+ .find_map(|binding| binding.is_triggered_by(&key, mods).then_some(binding.action))
+ }
+
+ /// Process mouse binding.
+ fn process_mouse_binding(button: MouseButton, mods: &ModifiersState) -> Option {
+ MOUSE_BINDINGS
+ .iter()
+ .find_map(|binding| binding.is_triggered_by(&button, mods).then_some(binding.action))
+ }
+
+ fn print_help(&self) {
+ info!("Keyboard bindings:");
+ for binding in KEY_BINDINGS {
+ info!(
+ "{}{:<10} - {} ({})",
+ modifiers_to_string(binding.mods),
+ binding.trigger,
+ binding.action,
+ binding.action.help(),
+ );
+ }
+ info!("Mouse bindings:");
+ for binding in MOUSE_BINDINGS {
+ info!(
+ "{}{:<10} - {} ({})",
+ modifiers_to_string(binding.mods),
+ mouse_button_to_string(binding.trigger),
+ binding.action,
+ binding.action.help(),
+ );
+ }
+ }
+}
+
+impl ApplicationHandler for Application {
+ fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: UserEvent) {
+ info!("User event: {event:?}");
+ }
+
+ fn window_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ window_id: WindowId,
+ event: WindowEvent,
+ ) {
+ let window = match self.windows.get_mut(&window_id) {
+ Some(window) => window,
+ None => return,
+ };
+
+ match event {
+ WindowEvent::Resized(size) => {
+ window.resize(size);
+ },
+ WindowEvent::Focused(focused) => {
+ if focused {
+ info!("Window={window_id:?} focused");
+ } else {
+ info!("Window={window_id:?} unfocused");
+ }
+ },
+ WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
+ info!("Window={window_id:?} changed scale to {scale_factor}");
+ },
+ WindowEvent::ThemeChanged(theme) => {
+ info!("Theme changed to {theme:?}");
+ window.set_draw_theme(theme);
+ },
+ WindowEvent::RedrawRequested => {
+ if let Err(err) = window.draw() {
+ error!("Error drawing window: {err}");
+ }
+ },
+ WindowEvent::Occluded(occluded) => {
+ window.set_occluded(occluded);
+ },
+ WindowEvent::CloseRequested => {
+ info!("Closing Window={window_id:?}");
+ self.windows.remove(&window_id);
+ },
+ WindowEvent::ModifiersChanged(modifiers) => {
+ window.modifiers = modifiers.state();
+ info!("Modifiers changed to {:?}", window.modifiers);
+ },
+ WindowEvent::MouseWheel { delta, .. } => match delta {
+ MouseScrollDelta::LineDelta(x, y) => {
+ info!("Mouse wheel Line Delta: ({x},{y})");
+ },
+ MouseScrollDelta::PixelDelta(px) => {
+ info!("Mouse wheel Pixel Delta: ({},{})", px.x, px.y);
+ },
+ },
+ WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => {
+ let mods = window.modifiers;
+
+ // Dispatch actions only on press.
+ if event.state.is_pressed() {
+ let action = if let Key::Character(ch) = event.logical_key.as_ref() {
+ Self::process_key_binding(&ch.to_uppercase(), &mods)
+ } else {
+ None
+ };
+
+ if let Some(action) = action {
+ self.handle_action(event_loop, window_id, action);
+ }
+ }
+ },
+ WindowEvent::MouseInput { button, state, .. } => {
+ let mods = window.modifiers;
+ if let Some(action) =
+ state.is_pressed().then(|| Self::process_mouse_binding(button, &mods)).flatten()
+ {
+ self.handle_action(event_loop, window_id, action);
+ }
+ },
+ WindowEvent::CursorLeft { .. } => {
+ info!("Cursor left Window={window_id:?}");
+ window.cursor_left();
+ },
+ WindowEvent::CursorMoved { position, .. } => {
+ info!("Moved cursor to {position:?}");
+ window.cursor_moved(position);
+ },
+ WindowEvent::ActivationTokenDone { token: _token, .. } => {
+ #[cfg(any(x11_platform, wayland_platform))]
+ {
+ startup_notify::set_activation_token_env(_token);
+ if let Err(err) = self.create_window(event_loop, None) {
+ error!("Error creating new window: {err}");
+ }
+ }
+ },
+ WindowEvent::Ime(event) => match event {
+ Ime::Enabled => info!("IME enabled for Window={window_id:?}"),
+ Ime::Preedit(text, caret_pos) => {
+ info!("Preedit: {}, with caret at {:?}", text, caret_pos);
+ },
+ Ime::Commit(text) => {
+ info!("Committed: {}", text);
+ },
+ Ime::Disabled => info!("IME disabled for Window={window_id:?}"),
+ },
+ WindowEvent::PinchGesture { delta, .. } => {
+ window.zoom += delta;
+ let zoom = window.zoom;
+ if delta > 0.0 {
+ info!("Zoomed in {delta:.5} (now: {zoom:.5})");
+ } else {
+ info!("Zoomed out {delta:.5} (now: {zoom:.5})");
+ }
+ },
+ WindowEvent::RotationGesture { delta, .. } => {
+ window.rotated += delta;
+ let rotated = window.rotated;
+ if delta > 0.0 {
+ info!("Rotated counterclockwise {delta:.5} (now: {rotated:.5})");
+ } else {
+ info!("Rotated clockwise {delta:.5} (now: {rotated:.5})");
+ }
+ },
+ WindowEvent::PanGesture { delta, phase, .. } => {
+ window.panned.x += delta.x;
+ window.panned.y += delta.y;
+ info!("Panned ({delta:?})) (now: {:?}), {phase:?}", window.panned);
+ },
+ WindowEvent::DoubleTapGesture { .. } => {
+ info!("Smart zoom");
+ },
+ WindowEvent::TouchpadPressure { .. }
+ | WindowEvent::HoveredFileCancelled
+ | WindowEvent::KeyboardInput { .. }
+ | WindowEvent::CursorEntered { .. }
+ | WindowEvent::AxisMotion { .. }
+ | WindowEvent::DroppedFile(_)
+ | WindowEvent::HoveredFile(_)
+ | WindowEvent::Destroyed
+ | WindowEvent::Touch(_)
+ | WindowEvent::Moved(_) => (),
+ }
+ }
+
+ fn device_event(
+ &mut self,
+ _event_loop: &ActiveEventLoop,
+ device_id: DeviceId,
+ event: DeviceEvent,
+ ) {
+ info!("Device {device_id:?} event: {event:?}");
+ }
+
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ info!("Resumed the event loop");
+ self.dump_monitors(event_loop);
+
+ // Create initial window.
+ self.create_window(event_loop, None).expect("failed to create initial window");
+
+ self.print_help();
+ }
+
+ fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ if self.windows.is_empty() {
+ info!("No windows left, exiting...");
+ event_loop.exit();
+ }
+ }
+
+ #[cfg(not(any(android_platform, ios_platform)))]
+ fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
+ // We must drop the context here.
+ self.context = None;
+ }
+}
+
+/// State of the window.
+struct WindowState {
+ /// IME input.
+ ime: bool,
+ /// Render surface.
+ ///
+ /// NOTE: This surface must be dropped before the `Window`.
+ #[cfg(not(any(android_platform, ios_platform)))]
+ surface: Surface, Arc>,
+ /// The actual winit Window.
+ window: Arc,
+ /// The window theme we're drawing with.
+ theme: Theme,
+ /// Cursor position over the window.
+ cursor_position: Option>,
+ /// Window modifiers state.
+ modifiers: ModifiersState,
+ /// Occlusion state of the window.
+ occluded: bool,
+ /// Current cursor grab mode.
+ cursor_grab: CursorGrabMode,
+ /// The amount of zoom into window.
+ zoom: f64,
+ /// The amount of rotation of the window.
+ rotated: f32,
+ /// The amount of pan of the window.
+ panned: PhysicalPosition,
+
+ #[cfg(macos_platform)]
+ option_as_alt: OptionAsAlt,
+
+ // Cursor states.
+ named_idx: usize,
+ custom_idx: usize,
+ cursor_hidden: bool,
+}
+
+impl WindowState {
+ fn new(app: &Application, window: Window) -> Result> {
+ let window = Arc::new(window);
+
+ // SAFETY: the surface is dropped before the `window` which provided it with handle, thus
+ // it doesn't outlive it.
+ #[cfg(not(any(android_platform, ios_platform)))]
+ let surface = Surface::new(app.context.as_ref().unwrap(), Arc::clone(&window))?;
+
+ let theme = window.theme().unwrap_or(Theme::Dark);
+ info!("Theme: {theme:?}");
+ let named_idx = 0;
+ window.set_cursor(CURSORS[named_idx]);
+
+ // Allow IME out of the box.
+ let ime = true;
+ window.set_ime_allowed(ime);
+
+ let size = window.inner_size();
+ let mut state = Self {
+ #[cfg(macos_platform)]
+ option_as_alt: window.option_as_alt(),
+ custom_idx: app.custom_cursors.len() - 1,
+ cursor_grab: CursorGrabMode::None,
+ named_idx,
+ #[cfg(not(any(android_platform, ios_platform)))]
+ surface,
+ window,
+ theme,
+ ime,
+ cursor_position: Default::default(),
+ cursor_hidden: Default::default(),
+ modifiers: Default::default(),
+ occluded: Default::default(),
+ rotated: Default::default(),
+ panned: Default::default(),
+ zoom: Default::default(),
+ };
+
+ state.resize(size);
+ Ok(state)
+ }
+
+ pub fn toggle_ime(&mut self) {
+ self.ime = !self.ime;
+ self.window.set_ime_allowed(self.ime);
+ if let Some(position) = self.ime.then_some(self.cursor_position).flatten() {
+ self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
+ }
+ }
+
+ pub fn minimize(&mut self) {
+ self.window.set_minimized(true);
+ }
+
+ pub fn cursor_moved(&mut self, position: PhysicalPosition) {
+ self.cursor_position = Some(position);
+ if self.ime {
+ self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
+ }
+ }
+
+ pub fn cursor_left(&mut self) {
+ self.cursor_position = None;
+ }
+
+ /// Toggle maximized.
+ fn toggle_maximize(&self) {
+ let maximized = self.window.is_maximized();
+ self.window.set_maximized(!maximized);
+ }
+
+ /// Toggle window decorations.
+ fn toggle_decorations(&self) {
+ let decorated = self.window.is_decorated();
+ self.window.set_decorations(!decorated);
+ }
+
+ /// Toggle window resizable state.
+ fn toggle_resizable(&self) {
+ let resizable = self.window.is_resizable();
+ self.window.set_resizable(!resizable);
+ }
+
+ /// Toggle cursor visibility
+ fn toggle_cursor_visibility(&mut self) {
+ self.cursor_hidden = !self.cursor_hidden;
+ self.window.set_cursor_visible(!self.cursor_hidden);
+ }
+
+ /// Toggle resize increments on a window.
+ fn toggle_resize_increments(&mut self) {
+ let new_increments = match self.window.resize_increments() {
+ Some(_) => None,
+ None => Some(LogicalSize::new(25.0, 25.0)),
+ };
+ info!("Had increments: {}", new_increments.is_none());
+ self.window.set_resize_increments(new_increments);
+ }
+
+ /// Toggle fullscreen.
+ fn toggle_fullscreen(&self) {
+ let fullscreen = if self.window.fullscreen().is_some() {
+ None
+ } else {
+ Some(Fullscreen::Borderless(None))
+ };
+
+ self.window.set_fullscreen(fullscreen);
+ }
+
+ /// Cycle through the grab modes ignoring errors.
+ fn cycle_cursor_grab(&mut self) {
+ self.cursor_grab = match self.cursor_grab {
+ CursorGrabMode::None => CursorGrabMode::Confined,
+ CursorGrabMode::Confined => CursorGrabMode::Locked,
+ CursorGrabMode::Locked => CursorGrabMode::None,
+ };
+ info!("Changing cursor grab mode to {:?}", self.cursor_grab);
+ if let Err(err) = self.window.set_cursor_grab(self.cursor_grab) {
+ error!("Error setting cursor grab: {err}");
+ }
+ }
+
+ #[cfg(macos_platform)]
+ fn cycle_option_as_alt(&mut self) {
+ self.option_as_alt = match self.option_as_alt {
+ OptionAsAlt::None => OptionAsAlt::OnlyLeft,
+ OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
+ OptionAsAlt::OnlyRight => OptionAsAlt::Both,
+ OptionAsAlt::Both => OptionAsAlt::None,
+ };
+ info!("Setting option as alt {:?}", self.option_as_alt);
+ self.window.set_option_as_alt(self.option_as_alt);
+ }
+
+ /// Swap the window dimensions with `request_inner_size`.
+ fn swap_dimensions(&mut self) {
+ let old_inner_size = self.window.inner_size();
+ let mut inner_size = old_inner_size;
+
+ mem::swap(&mut inner_size.width, &mut inner_size.height);
+ info!("Requesting resize from {old_inner_size:?} to {inner_size:?}");
+
+ if let Some(new_inner_size) = self.window.request_inner_size(inner_size) {
+ if old_inner_size == new_inner_size {
+ info!("Inner size change got ignored");
+ } else {
+ self.resize(new_inner_size);
+ }
+ } else {
+ info!("Request inner size is asynchronous");
+ }
+ }
+
+ /// Pick the next cursor.
+ fn next_cursor(&mut self) {
+ self.named_idx = (self.named_idx + 1) % CURSORS.len();
+ info!("Setting cursor to \"{:?}\"", CURSORS[self.named_idx]);
+ self.window.set_cursor(Cursor::Icon(CURSORS[self.named_idx]));
+ }
+
+ /// Pick the next custom cursor.
+ fn next_custom_cursor(&mut self, custom_cursors: &[CustomCursor]) {
+ self.custom_idx = (self.custom_idx + 1) % custom_cursors.len();
+ let cursor = Cursor::Custom(custom_cursors[self.custom_idx].clone());
+ self.window.set_cursor(cursor);
+ }
+
+ /// Custom cursor from an URL.
+ #[cfg(web_platform)]
+ fn url_custom_cursor(&mut self, event_loop: &ActiveEventLoop) {
+ let cursor = event_loop.create_custom_cursor(url_custom_cursor());
+
+ self.window.set_cursor(cursor);
+ }
+
+ /// Custom cursor from a URL.
+ #[cfg(web_platform)]
+ fn animation_custom_cursor(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ custom_cursors: &[CustomCursor],
+ ) {
+ use std::time::Duration;
+ use winit::platform::web::CustomCursorExtWebSys;
+
+ let cursors = vec![
+ custom_cursors[0].clone(),
+ custom_cursors[1].clone(),
+ event_loop.create_custom_cursor(url_custom_cursor()),
+ ];
+ let cursor = CustomCursor::from_animation(Duration::from_secs(3), cursors).unwrap();
+ let cursor = event_loop.create_custom_cursor(cursor);
+
+ self.window.set_cursor(cursor);
+ }
+
+ /// Resize the window to the new size.
+ fn resize(&mut self, size: PhysicalSize) {
+ info!("Resized to {size:?}");
+ #[cfg(not(any(android_platform, ios_platform)))]
+ {
+ let (width, height) = match (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
+ {
+ (Some(width), Some(height)) => (width, height),
+ _ => return,
+ };
+ self.surface.resize(width, height).expect("failed to resize inner buffer");
+ }
+ self.window.request_redraw();
+ }
+
+ /// Change the theme that things are drawn in.
+ fn set_draw_theme(&mut self, theme: Theme) {
+ self.theme = theme;
+ self.window.request_redraw();
+ }
+
+ /// Show window menu.
+ fn show_menu(&self) {
+ if let Some(position) = self.cursor_position {
+ self.window.show_window_menu(position);
+ }
+ }
+
+ /// Drag the window.
+ fn drag_window(&self) {
+ if let Err(err) = self.window.drag_window() {
+ info!("Error starting window drag: {err}");
+ } else {
+ info!("Dragging window Window={:?}", self.window.id());
+ }
+ }
+
+ /// Drag-resize the window.
+ fn drag_resize_window(&self) {
+ let position = match self.cursor_position {
+ Some(position) => position,
+ None => {
+ info!("Drag-resize requires cursor to be inside the window");
+ return;
+ },
+ };
+
+ let win_size = self.window.inner_size();
+ let border_size = BORDER_SIZE * self.window.scale_factor();
+
+ let x_direction = if position.x < border_size {
+ ResizeDirection::West
+ } else if position.x > (win_size.width as f64 - border_size) {
+ ResizeDirection::East
+ } else {
+ // Use arbitrary direction instead of None for simplicity.
+ ResizeDirection::SouthEast
+ };
+
+ let y_direction = if position.y < border_size {
+ ResizeDirection::North
+ } else if position.y > (win_size.height as f64 - border_size) {
+ ResizeDirection::South
+ } else {
+ // Use arbitrary direction instead of None for simplicity.
+ ResizeDirection::SouthEast
+ };
+
+ let direction = match (x_direction, y_direction) {
+ (ResizeDirection::West, ResizeDirection::North) => ResizeDirection::NorthWest,
+ (ResizeDirection::West, ResizeDirection::South) => ResizeDirection::SouthWest,
+ (ResizeDirection::West, _) => ResizeDirection::West,
+ (ResizeDirection::East, ResizeDirection::North) => ResizeDirection::NorthEast,
+ (ResizeDirection::East, ResizeDirection::South) => ResizeDirection::SouthEast,
+ (ResizeDirection::East, _) => ResizeDirection::East,
+ (_, ResizeDirection::South) => ResizeDirection::South,
+ (_, ResizeDirection::North) => ResizeDirection::North,
+ _ => return,
+ };
+
+ if let Err(err) = self.window.drag_resize_window(direction) {
+ info!("Error starting window drag-resize: {err}");
+ } else {
+ info!("Drag-resizing window Window={:?}", self.window.id());
+ }
+ }
+
+ /// Change window occlusion state.
+ fn set_occluded(&mut self, occluded: bool) {
+ self.occluded = occluded;
+ if !occluded {
+ self.window.request_redraw();
+ }
+ }
+
+ /// Draw the window contents.
+ #[cfg(not(any(android_platform, ios_platform)))]
+ fn draw(&mut self) -> Result<(), Box> {
+ if self.occluded {
+ info!("Skipping drawing occluded window={:?}", self.window.id());
+ return Ok(());
+ }
+
+ const WHITE: u32 = 0xffffffff;
+ const DARK_GRAY: u32 = 0xff181818;
+
+ let color = match self.theme {
+ Theme::Light => WHITE,
+ Theme::Dark => DARK_GRAY,
+ };
+
+ let mut buffer = self.surface.buffer_mut()?;
+ buffer.fill(color);
+ self.window.pre_present_notify();
+ buffer.present()?;
+ Ok(())
+ }
+
+ #[cfg(any(android_platform, ios_platform))]
+ fn draw(&mut self) -> Result<(), Box> {
+ info!("Drawing but without rendering...");
+ Ok(())
+ }
+}
+
+struct Binding {
+ trigger: T,
+ mods: ModifiersState,
+ action: Action,
+}
+
+impl Binding {
+ const fn new(trigger: T, mods: ModifiersState, action: Action) -> Self {
+ Self { trigger, mods, action }
+ }
+
+ fn is_triggered_by(&self, trigger: &T, mods: &ModifiersState) -> bool {
+ &self.trigger == trigger && &self.mods == mods
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Action {
+ CloseWindow,
+ ToggleCursorVisibility,
+ CreateNewWindow,
+ ToggleResizeIncrements,
+ ToggleImeInput,
+ ToggleDecorations,
+ ToggleResizable,
+ ToggleFullscreen,
+ ToggleMaximize,
+ Minimize,
+ NextCursor,
+ NextCustomCursor,
+ #[cfg(web_platform)]
+ UrlCustomCursor,
+ #[cfg(web_platform)]
+ AnimationCustomCursor,
+ CycleCursorGrab,
+ PrintHelp,
+ DragWindow,
+ DragResizeWindow,
+ ShowWindowMenu,
+ #[cfg(macos_platform)]
+ CycleOptionAsAlt,
+ SetTheme(Option),
+ #[cfg(macos_platform)]
+ CreateNewTab,
+ RequestResize,
+}
+
+impl Action {
+ fn help(&self) -> &'static str {
+ match self {
+ Action::CloseWindow => "Close window",
+ Action::ToggleCursorVisibility => "Hide cursor",
+ Action::CreateNewWindow => "Create new window",
+ Action::ToggleImeInput => "Toggle IME input",
+ Action::ToggleDecorations => "Toggle decorations",
+ Action::ToggleResizable => "Toggle window resizable state",
+ Action::ToggleFullscreen => "Toggle fullscreen",
+ Action::ToggleMaximize => "Maximize",
+ Action::Minimize => "Minimize",
+ Action::ToggleResizeIncrements => "Use resize increments when resizing window",
+ Action::NextCursor => "Advance the cursor to the next value",
+ Action::NextCustomCursor => "Advance custom cursor to the next value",
+ #[cfg(web_platform)]
+ Action::UrlCustomCursor => "Custom cursor from an URL",
+ #[cfg(web_platform)]
+ Action::AnimationCustomCursor => "Custom cursor from an animation",
+ Action::CycleCursorGrab => "Cycle through cursor grab mode",
+ Action::PrintHelp => "Print help",
+ Action::DragWindow => "Start window drag",
+ Action::DragResizeWindow => "Start window drag-resize",
+ Action::ShowWindowMenu => "Show window menu",
+ #[cfg(macos_platform)]
+ Action::CycleOptionAsAlt => "Cycle option as alt mode",
+ Action::SetTheme(None) => "Change to the system theme",
+ Action::SetTheme(Some(Theme::Light)) => "Change to a light theme",
+ Action::SetTheme(Some(Theme::Dark)) => "Change to a dark theme",
+ #[cfg(macos_platform)]
+ Action::CreateNewTab => "Create new tab",
+ Action::RequestResize => "Request a resize",
+ }
+ }
+}
+
+impl fmt::Display for Action {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ Debug::fmt(&self, f)
+ }
+}
+
+fn decode_cursor(bytes: &[u8]) -> CustomCursorSource {
+ let img = image::load_from_memory(bytes).unwrap().to_rgba8();
+ let samples = img.into_flat_samples();
+ let (_, w, h) = samples.extents();
+ let (w, h) = (w as u16, h as u16);
+ CustomCursor::from_rgba(samples.samples, w, h, w / 2, h / 2).unwrap()
+}
+
+#[cfg(web_platform)]
+fn url_custom_cursor() -> CustomCursorSource {
+ use std::sync::atomic::{AtomicU64, Ordering};
+
+ use winit::platform::web::CustomCursorExtWebSys;
+
+ static URL_COUNTER: AtomicU64 = AtomicU64::new(0);
+
+ CustomCursor::from_url(
+ format!("https://picsum.photos/128?random={}", URL_COUNTER.fetch_add(1, Ordering::Relaxed)),
+ 64,
+ 64,
+ )
+}
+
+fn load_icon(bytes: &[u8]) -> Icon {
+ let (icon_rgba, icon_width, icon_height) = {
+ let image = image::load_from_memory(bytes).unwrap().into_rgba8();
+ let (width, height) = image.dimensions();
+ let rgba = image.into_raw();
+ (rgba, width, height)
+ };
+ Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon")
+}
+
+fn modifiers_to_string(mods: ModifiersState) -> String {
+ let mut mods_line = String::new();
+ // Always add + since it's printed as a part of the bindings.
+ for (modifier, desc) in [
+ (ModifiersState::SUPER, "Super+"),
+ (ModifiersState::ALT, "Alt+"),
+ (ModifiersState::CONTROL, "Ctrl+"),
+ (ModifiersState::SHIFT, "Shift+"),
+ ] {
+ if !mods.contains(modifier) {
+ continue;
+ }
+
+ mods_line.push_str(desc);
+ }
+ mods_line
+}
+
+fn mouse_button_to_string(button: MouseButton) -> &'static str {
+ match button {
+ MouseButton::Left => "LMB",
+ MouseButton::Right => "RMB",
+ MouseButton::Middle => "MMB",
+ MouseButton::Back => "Back",
+ MouseButton::Forward => "Forward",
+ MouseButton::Other(_) => "",
+ }
+}
+
+/// Cursor list to cycle through.
+const CURSORS: &[CursorIcon] = &[
+ CursorIcon::Default,
+ CursorIcon::Crosshair,
+ CursorIcon::Pointer,
+ CursorIcon::Move,
+ CursorIcon::Text,
+ CursorIcon::Wait,
+ CursorIcon::Help,
+ CursorIcon::Progress,
+ CursorIcon::NotAllowed,
+ CursorIcon::ContextMenu,
+ CursorIcon::Cell,
+ CursorIcon::VerticalText,
+ CursorIcon::Alias,
+ CursorIcon::Copy,
+ CursorIcon::NoDrop,
+ CursorIcon::Grab,
+ CursorIcon::Grabbing,
+ CursorIcon::AllScroll,
+ CursorIcon::ZoomIn,
+ CursorIcon::ZoomOut,
+ CursorIcon::EResize,
+ CursorIcon::NResize,
+ CursorIcon::NeResize,
+ CursorIcon::NwResize,
+ CursorIcon::SResize,
+ CursorIcon::SeResize,
+ CursorIcon::SwResize,
+ CursorIcon::WResize,
+ CursorIcon::EwResize,
+ CursorIcon::NsResize,
+ CursorIcon::NeswResize,
+ CursorIcon::NwseResize,
+ CursorIcon::ColResize,
+ CursorIcon::RowResize,
+];
+
+const KEY_BINDINGS: &[Binding<&'static str>] = &[
+ Binding::new("Q", ModifiersState::CONTROL, Action::CloseWindow),
+ Binding::new("H", ModifiersState::CONTROL, Action::PrintHelp),
+ Binding::new("F", ModifiersState::CONTROL, Action::ToggleFullscreen),
+ Binding::new("D", ModifiersState::CONTROL, Action::ToggleDecorations),
+ Binding::new("I", ModifiersState::CONTROL, Action::ToggleImeInput),
+ Binding::new("L", ModifiersState::CONTROL, Action::CycleCursorGrab),
+ Binding::new("P", ModifiersState::CONTROL, Action::ToggleResizeIncrements),
+ Binding::new("R", ModifiersState::CONTROL, Action::ToggleResizable),
+ Binding::new("R", ModifiersState::ALT, Action::RequestResize),
+ // M.
+ Binding::new("M", ModifiersState::CONTROL, Action::ToggleMaximize),
+ Binding::new("M", ModifiersState::ALT, Action::Minimize),
+ // N.
+ Binding::new("N", ModifiersState::CONTROL, Action::CreateNewWindow),
+ // C.
+ Binding::new("C", ModifiersState::CONTROL, Action::NextCursor),
+ Binding::new("C", ModifiersState::ALT, Action::NextCustomCursor),
+ #[cfg(web_platform)]
+ Binding::new(
+ "C",
+ ModifiersState::CONTROL.union(ModifiersState::SHIFT),
+ Action::UrlCustomCursor,
+ ),
+ #[cfg(web_platform)]
+ Binding::new(
+ "C",
+ ModifiersState::ALT.union(ModifiersState::SHIFT),
+ Action::AnimationCustomCursor,
+ ),
+ Binding::new("Z", ModifiersState::CONTROL, Action::ToggleCursorVisibility),
+ // K.
+ Binding::new("K", ModifiersState::empty(), Action::SetTheme(None)),
+ Binding::new("K", ModifiersState::SUPER, Action::SetTheme(Some(Theme::Light))),
+ Binding::new("K", ModifiersState::CONTROL, Action::SetTheme(Some(Theme::Dark))),
+ #[cfg(macos_platform)]
+ Binding::new("T", ModifiersState::SUPER, Action::CreateNewTab),
+ #[cfg(macos_platform)]
+ Binding::new("O", ModifiersState::CONTROL, Action::CycleOptionAsAlt),
+];
+
+const MOUSE_BINDINGS: &[Binding] = &[
+ Binding::new(MouseButton::Left, ModifiersState::ALT, Action::DragResizeWindow),
+ Binding::new(MouseButton::Left, ModifiersState::CONTROL, Action::DragWindow),
+ Binding::new(MouseButton::Right, ModifiersState::CONTROL, Action::ShowWindowMenu),
+];
diff --git a/third_party/winit-0.30.13/examples/x11_embed.rs b/third_party/winit-0.30.13/examples/x11_embed.rs
new file mode 100644
index 0000000..9db55e5
--- /dev/null
+++ b/third_party/winit-0.30.13/examples/x11_embed.rs
@@ -0,0 +1,69 @@
+//! A demonstration of embedding a winit window in an existing X11 application.
+use std::error::Error;
+
+#[cfg(x11_platform)]
+fn main() -> Result<(), Box> {
+ use winit::application::ApplicationHandler;
+ use winit::event::WindowEvent;
+ use winit::event_loop::{ActiveEventLoop, EventLoop};
+ use winit::platform::x11::WindowAttributesExtX11;
+ use winit::window::{Window, WindowId};
+
+ #[path = "util/fill.rs"]
+ mod fill;
+
+ pub struct XEmbedDemo {
+ parent_window_id: u32,
+ window: Option,
+ }
+
+ impl ApplicationHandler for XEmbedDemo {
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ let window_attributes = Window::default_attributes()
+ .with_title("An embedded window!")
+ .with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
+ .with_embed_parent_window(self.parent_window_id);
+
+ self.window = Some(event_loop.create_window(window_attributes).unwrap());
+ }
+
+ fn window_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ _window_id: WindowId,
+ event: WindowEvent,
+ ) {
+ let window = self.window.as_ref().unwrap();
+ match event {
+ WindowEvent::CloseRequested => event_loop.exit(),
+ WindowEvent::RedrawRequested => {
+ window.pre_present_notify();
+ fill::fill_window(window);
+ },
+ _ => (),
+ }
+ }
+
+ fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
+ self.window.as_ref().unwrap().request_redraw();
+ }
+ }
+
+ // First argument should be a 32-bit X11 window ID.
+ let parent_window_id = std::env::args()
+ .nth(1)
+ .ok_or("Expected a 32-bit X11 window ID as the first argument.")?
+ .parse::()?;
+
+ tracing_subscriber::fmt::init();
+ let event_loop = EventLoop::new()?;
+
+ let mut app = XEmbedDemo { parent_window_id, window: None };
+ event_loop.run_app(&mut app).map_err(Into::into)
+}
+
+#[cfg(not(x11_platform))]
+fn main() -> Result<(), Box> {
+ println!("This example is only supported on X11 platforms.");
+ Ok(())
+}
diff --git a/third_party/winit-0.30.13/src/application.rs b/third_party/winit-0.30.13/src/application.rs
new file mode 100644
index 0000000..977a7c7
--- /dev/null
+++ b/third_party/winit-0.30.13/src/application.rs
@@ -0,0 +1,339 @@
+//! End user application handling.
+
+use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent};
+use crate::event_loop::ActiveEventLoop;
+use crate::window::WindowId;
+
+/// The handler of the application events.
+pub trait ApplicationHandler {
+ /// Emitted when new events arrive from the OS to be processed.
+ ///
+ /// This is a useful place to put code that should be done before you start processing
+ /// events, such as updating frame timing information for benchmarking or checking the
+ /// [`StartCause`] to see if a timer set by
+ /// [`ControlFlow::WaitUntil`][crate::event_loop::ControlFlow::WaitUntil] has elapsed.
+ fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
+ let _ = (event_loop, cause);
+ }
+
+ /// Emitted when the application has been resumed.
+ ///
+ /// For consistency, all platforms emit a `Resumed` event even if they don't themselves have a
+ /// formal suspend/resume lifecycle. For systems without a formal suspend/resume lifecycle
+ /// the `Resumed` event is always emitted after the
+ /// [`NewEvents(StartCause::Init)`][StartCause::Init] event.
+ ///
+ /// # Portability
+ ///
+ /// It's recommended that applications should only initialize their graphics context and create
+ /// a window after they have received their first `Resumed` event. Some systems
+ /// (specifically Android) won't allow applications to create a render surface until they are
+ /// resumed.
+ ///
+ /// Considering that the implementation of [`Suspended`] and `Resumed` events may be internally
+ /// driven by multiple platform-specific events, and that there may be subtle differences across
+ /// platforms with how these internal events are delivered, it's recommended that applications
+ /// be able to gracefully handle redundant (i.e. back-to-back) [`Suspended`] or `Resumed`
+ /// events.
+ ///
+ /// Also see [`Suspended`] notes.
+ ///
+ /// ## Android
+ ///
+ /// On Android, the `Resumed` event is sent when a new [`SurfaceView`] has been created. This is
+ /// expected to closely correlate with the [`onResume`] lifecycle event but there may
+ /// technically be a discrepancy.
+ ///
+ /// [`onResume`]: https://developer.android.com/reference/android/app/Activity#onResume()
+ ///
+ /// Applications that need to run on Android must wait until they have been `Resumed`
+ /// before they will be able to create a render surface (such as an `EGLSurface`,
+ /// [`VkSurfaceKHR`] or [`wgpu::Surface`]) which depend on having a
+ /// [`SurfaceView`]. Applications must also assume that if they are [`Suspended`], then their
+ /// render surfaces are invalid and should be dropped.
+ ///
+ /// Also see [`Suspended`] notes.
+ ///
+ /// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
+ /// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
+ /// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
+ /// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
+ ///
+ /// ## iOS
+ ///
+ /// On iOS, the `Resumed` event is emitted in response to an [`applicationDidBecomeActive`]
+ /// callback which means the application is "active" (according to the
+ /// [iOS application lifecycle]).
+ ///
+ /// [`applicationDidBecomeActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive
+ /// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
+ ///
+ /// ## Web
+ ///
+ /// On Web, the `Resumed` event is emitted in response to a [`pageshow`] event
+ /// with the property [`persisted`] being true, which means that the page is being
+ /// restored from the [`bfcache`] (back/forward cache) - an in-memory cache that
+ /// stores a complete snapshot of a page (including the JavaScript heap) as the
+ /// user is navigating away.
+ ///
+ /// [`pageshow`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event
+ /// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
+ /// [`bfcache`]: https://web.dev/bfcache/
+ /// [`Suspended`]: Self::suspended
+ fn resumed(&mut self, event_loop: &ActiveEventLoop);
+
+ /// Emitted when an event is sent from [`EventLoopProxy::send_event`].
+ ///
+ /// [`EventLoopProxy::send_event`]: crate::event_loop::EventLoopProxy::send_event
+ fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) {
+ let _ = (event_loop, event);
+ }
+
+ /// Emitted when the OS sends an event to a winit window.
+ fn window_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ window_id: WindowId,
+ event: WindowEvent,
+ );
+
+ /// Emitted when the OS sends an event to a device.
+ fn device_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ device_id: DeviceId,
+ event: DeviceEvent,
+ ) {
+ let _ = (event_loop, device_id, event);
+ }
+
+ /// Emitted when the event loop is about to block and wait for new events.
+ ///
+ /// Most applications shouldn't need to hook into this event since there is no real relationship
+ /// between how often the event loop needs to wake up and the dispatching of any specific
+ /// events.
+ ///
+ /// High frequency event sources, such as input devices could potentially lead to lots of wake
+ /// ups and also lots of corresponding `AboutToWait` events.
+ ///
+ /// This is not an ideal event to drive application rendering from and instead applications
+ /// should render in response to [`WindowEvent::RedrawRequested`] events.
+ fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ let _ = event_loop;
+ }
+
+ /// Emitted when the application has been suspended.
+ ///
+ /// # Portability
+ ///
+ /// Not all platforms support the notion of suspending applications, and there may be no
+ /// technical way to guarantee being able to emit a `Suspended` event if the OS has
+ /// no formal application lifecycle (currently only Android, iOS, and Web do). For this reason,
+ /// Winit does not currently try to emit pseudo `Suspended` events before the application
+ /// quits on platforms without an application lifecycle.
+ ///
+ /// Considering that the implementation of `Suspended` and [`Resumed`] events may be internally
+ /// driven by multiple platform-specific events, and that there may be subtle differences across
+ /// platforms with how these internal events are delivered, it's recommended that applications
+ /// be able to gracefully handle redundant (i.e. back-to-back) `Suspended` or [`Resumed`]
+ /// events.
+ ///
+ /// Also see [`Resumed`] notes.
+ ///
+ /// ## Android
+ ///
+ /// On Android, the `Suspended` event is only sent when the application's associated
+ /// [`SurfaceView`] is destroyed. This is expected to closely correlate with the [`onPause`]
+ /// lifecycle event but there may technically be a discrepancy.
+ ///
+ /// [`onPause`]: https://developer.android.com/reference/android/app/Activity#onPause()
+ ///
+ /// Applications that need to run on Android should assume their [`SurfaceView`] has been
+ /// destroyed, which indirectly invalidates any existing render surfaces that may have been
+ /// created outside of Winit (such as an `EGLSurface`, [`VkSurfaceKHR`] or [`wgpu::Surface`]).
+ ///
+ /// After being `Suspended` on Android applications must drop all render surfaces before
+ /// the event callback completes, which may be re-created when the application is next
+ /// [`Resumed`].
+ ///
+ /// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
+ /// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
+ /// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
+ /// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
+ ///
+ /// ## iOS
+ ///
+ /// On iOS, the `Suspended` event is currently emitted in response to an
+ /// [`applicationWillResignActive`] callback which means that the application is
+ /// about to transition from the active to inactive state (according to the
+ /// [iOS application lifecycle]).
+ ///
+ /// [`applicationWillResignActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622950-applicationwillresignactive
+ /// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
+ ///
+ /// ## Web
+ ///
+ /// On Web, the `Suspended` event is emitted in response to a [`pagehide`] event
+ /// with the property [`persisted`] being true, which means that the page is being
+ /// put in the [`bfcache`] (back/forward cache) - an in-memory cache that stores a
+ /// complete snapshot of a page (including the JavaScript heap) as the user is
+ /// navigating away.
+ ///
+ /// [`pagehide`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
+ /// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
+ /// [`bfcache`]: https://web.dev/bfcache/
+ /// [`Resumed`]: Self::resumed
+ fn suspended(&mut self, event_loop: &ActiveEventLoop) {
+ let _ = event_loop;
+ }
+
+ /// Emitted when the event loop is being shut down.
+ ///
+ /// This is irreversible - if this method is called, it is guaranteed that the event loop
+ /// will exit right after.
+ fn exiting(&mut self, event_loop: &ActiveEventLoop) {
+ let _ = event_loop;
+ }
+
+ /// Emitted when the application has received a memory warning.
+ ///
+ /// ## Platform-specific
+ ///
+ /// ### Android
+ ///
+ /// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The
+ /// application must [release memory] or risk being killed.
+ ///
+ /// [`onLowMemory`]: https://developer.android.com/reference/android/app/Application.html#onLowMemory()
+ /// [release memory]: https://developer.android.com/topic/performance/memory#release
+ ///
+ /// ### iOS
+ ///
+ /// On iOS, the `MemoryWarning` event is emitted in response to an
+ /// [`applicationDidReceiveMemoryWarning`] callback. The application must free as much
+ /// memory as possible or risk being terminated, see [how to respond to memory warnings].
+ ///
+ /// [`applicationDidReceiveMemoryWarning`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623063-applicationdidreceivememorywarni
+ /// [how to respond to memory warnings]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle/responding_to_memory_warnings
+ ///
+ /// ### Others
+ ///
+ /// - **macOS / Orbital / Wayland / Web / Windows:** Unsupported.
+ fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
+ let _ = event_loop;
+ }
+}
+
+impl, T: 'static> ApplicationHandler for &mut A {
+ #[inline]
+ fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
+ (**self).new_events(event_loop, cause);
+ }
+
+ #[inline]
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).resumed(event_loop);
+ }
+
+ #[inline]
+ fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) {
+ (**self).user_event(event_loop, event);
+ }
+
+ #[inline]
+ fn window_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ window_id: WindowId,
+ event: WindowEvent,
+ ) {
+ (**self).window_event(event_loop, window_id, event);
+ }
+
+ #[inline]
+ fn device_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ device_id: DeviceId,
+ event: DeviceEvent,
+ ) {
+ (**self).device_event(event_loop, device_id, event);
+ }
+
+ #[inline]
+ fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).about_to_wait(event_loop);
+ }
+
+ #[inline]
+ fn suspended(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).suspended(event_loop);
+ }
+
+ #[inline]
+ fn exiting(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).exiting(event_loop);
+ }
+
+ #[inline]
+ fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).memory_warning(event_loop);
+ }
+}
+
+impl, T: 'static> ApplicationHandler for Box {
+ #[inline]
+ fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
+ (**self).new_events(event_loop, cause);
+ }
+
+ #[inline]
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).resumed(event_loop);
+ }
+
+ #[inline]
+ fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) {
+ (**self).user_event(event_loop, event);
+ }
+
+ #[inline]
+ fn window_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ window_id: WindowId,
+ event: WindowEvent,
+ ) {
+ (**self).window_event(event_loop, window_id, event);
+ }
+
+ #[inline]
+ fn device_event(
+ &mut self,
+ event_loop: &ActiveEventLoop,
+ device_id: DeviceId,
+ event: DeviceEvent,
+ ) {
+ (**self).device_event(event_loop, device_id, event);
+ }
+
+ #[inline]
+ fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).about_to_wait(event_loop);
+ }
+
+ #[inline]
+ fn suspended(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).suspended(event_loop);
+ }
+
+ #[inline]
+ fn exiting(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).exiting(event_loop);
+ }
+
+ #[inline]
+ fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
+ (**self).memory_warning(event_loop);
+ }
+}
diff --git a/third_party/winit-0.30.13/src/changelog/mod.rs b/third_party/winit-0.30.13/src/changelog/mod.rs
new file mode 100644
index 0000000..a05ea9c
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/mod.rs
@@ -0,0 +1,77 @@
+//! # Changelog and migrations
+//!
+//! All notable changes to this project will be documented in this module,
+//! along with migration instructions for larger changes.
+// Put the current entry at the top of this page, for discoverability.
+// See `.cargo/config.toml` for details about `unreleased_changelogs`.
+#![cfg_attr(unreleased_changelogs, doc = include_str!("unreleased.md"))]
+#![cfg_attr(not(unreleased_changelogs), doc = include_str!("v0.30.md"))]
+
+#[doc = include_str!("v0.30.md")]
+pub mod v0_30 {}
+
+#[doc = include_str!("v0.29.md")]
+pub mod v0_29 {}
+
+#[doc = include_str!("v0.28.md")]
+pub mod v0_28 {}
+
+#[doc = include_str!("v0.27.md")]
+pub mod v0_27 {}
+
+#[doc = include_str!("v0.26.md")]
+pub mod v0_26 {}
+
+#[doc = include_str!("v0.25.md")]
+pub mod v0_25 {}
+
+#[doc = include_str!("v0.24.md")]
+pub mod v0_24 {}
+
+#[doc = include_str!("v0.23.md")]
+pub mod v0_23 {}
+
+#[doc = include_str!("v0.22.md")]
+pub mod v0_22 {}
+
+#[doc = include_str!("v0.21.md")]
+pub mod v0_21 {}
+
+#[doc = include_str!("v0.20.md")]
+pub mod v0_20 {}
+
+#[doc = include_str!("v0.19.md")]
+pub mod v0_19 {}
+
+#[doc = include_str!("v0.18.md")]
+pub mod v0_18 {}
+
+#[doc = include_str!("v0.17.md")]
+pub mod v0_17 {}
+
+#[doc = include_str!("v0.16.md")]
+pub mod v0_16 {}
+
+#[doc = include_str!("v0.15.md")]
+pub mod v0_15 {}
+
+#[doc = include_str!("v0.14.md")]
+pub mod v0_14 {}
+
+#[doc = include_str!("v0.13.md")]
+pub mod v0_13 {}
+
+#[doc = include_str!("v0.12.md")]
+pub mod v0_12 {}
+
+#[doc = include_str!("v0.11.md")]
+pub mod v0_11 {}
+
+#[doc = include_str!("v0.10.md")]
+pub mod v0_10 {}
+
+#[doc = include_str!("v0.9.md")]
+pub mod v0_9 {}
+
+#[doc = include_str!("v0.8.md")]
+pub mod v0_8 {}
diff --git a/third_party/winit-0.30.13/src/changelog/unreleased.md b/third_party/winit-0.30.13/src/changelog/unreleased.md
new file mode 100644
index 0000000..f3a0f6d
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/unreleased.md
@@ -0,0 +1,41 @@
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
+
+The sections should follow the order `Added`, `Changed`, `Deprecated`,
+`Removed`, and `Fixed`.
+
+Platform specific changed should be added to the end of the section and grouped
+by platform name. Common API additions should have `, implemented` at the end
+for platforms where the API was initially implemented. See the following example
+on how to add them:
+
+```md
+### Added
+
+- Add `Window::turbo()`, implemented on X11, Wayland, and Web.
+- On X11, add `Window::some_rare_api`.
+- On X11, add `Window::even_more_rare_api`.
+- On Wayland, add `Window::common_api`.
+- On Windows, add `Window::some_rare_api`.
+```
+
+When the change requires non-trivial amount of work for users to comply
+with it, the migration guide should be added below the entry, like:
+
+```md
+- Deprecate `Window` creation outside of `EventLoop::run`
+
+ This was done to simply migration in the future. Consider the
+ following code:
+
+ // Code snippet.
+
+ To migrate it we should do X, Y, and then Z, for example:
+
+ // Code snippet.
+
+```
+
+The migration guide could reference other migration examples in the current
+changelog entry.
+
+## Unreleased
diff --git a/third_party/winit-0.30.13/src/changelog/v0.10.md b/third_party/winit-0.30.13/src/changelog/v0.10.md
new file mode 100644
index 0000000..9e47c0b
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.10.md
@@ -0,0 +1,13 @@
+## 0.10.1
+
+_Yanked_
+
+## 0.10.0
+
+- Add support for `Touch` for emscripten backend.
+- Added support for `DroppedFile`, `HoveredFile`, and `HoveredFileCancelled` to X11 backend.
+- **Breaking:** `unix::WindowExt` no longer returns pointers for things that aren't actually pointers; `get_xlib_window` now returns `Option` and `get_xlib_screen_id` returns `Option`. Additionally, methods that previously returned `libc::c_void` have been changed to return `std::os::raw::c_void`, which are not interchangeable types, so users wanting the former will need to explicitly cast.
+- Added `set_decorations` method to `Window` to allow decorations to be toggled after the window is built. Presently only implemented on X11.
+- Raised the minimum supported version of Rust to 1.20 on MacOS due to usage of associated constants in new versions of cocoa and core-graphics.
+- Added `modifiers` field to `MouseInput`, `MouseWheel`, and `CursorMoved` events to track the modifiers state (`ModifiersState`).
+- Fixed the emscripten backend to return the size of the canvas instead of the size of the window.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.11.md b/third_party/winit-0.30.13/src/changelog/v0.11.md
new file mode 100644
index 0000000..31fb1d3
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.11.md
@@ -0,0 +1,27 @@
+## 0.11.3
+
+- Added `set_min_dimensions` and `set_max_dimensions` methods to `Window`, and implemented on Windows, X11, Wayland, and OSX.
+- On X11, dropping a `Window` actually closes it now, and clicking the window's × button (or otherwise having the WM signal to close it) will result in the window closing.
+- Added `WindowBuilderExt` methods for macos: `with_titlebar_transparent`,
+ `with_title_hidden`, `with_titlebar_buttons_hidden`,
+ `with_fullsize_content_view`.
+- Mapped X11 numpad keycodes (arrows, Home, End, PageUp, PageDown, Insert and Delete) to corresponding virtual keycodes
+
+## 0.11.2
+
+- Impl `Hash`, `PartialEq`, and `Eq` for `events::ModifiersState`.
+- Implement `MonitorId::get_hidpi_factor` for MacOS.
+- Added method `os::macos::MonitorIdExt::get_nsscreen() -> *mut c_void` that gets a `NSScreen` object matching the monitor ID.
+- Send `Awakened` event on Android when event loop is woken up.
+
+## 0.11.1
+
+- Fixed windows not receiving mouse events when click-dragging the mouse outside the client area of a window, on Windows platforms.
+- Added method `os::android::EventsLoopExt:set_suspend_callback(Option ()>>)` that allows glutin to register a callback when a suspend event happens
+
+## 0.11.0
+
+- Implement `MonitorId::get_dimensions` for Android.
+- Added method `os::macos::WindowBuilderExt::with_movable_by_window_background(bool)` that allows to move a window without a titlebar - `with_decorations(false)`
+- Implement `Window::set_fullscreen`, `Window::set_maximized` and `Window::set_decorations` for Wayland.
+- Added `Caret` as VirtualKeyCode and support OSX ^-Key with german input.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.12.md b/third_party/winit-0.30.13/src/changelog/v0.12.md
new file mode 100644
index 0000000..3f9c83d
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.12.md
@@ -0,0 +1,8 @@
+## 0.12.0
+
+- Added subclass to macos windows so they can be made resizable even with no decorations.
+- Dead keys now work properly on X11, no longer resulting in a panic.
+- On X11, input method creation first tries to use the value from the user's `XMODIFIERS` environment variable, so application developers should no longer need to manually call `XSetLocaleModifiers`. If that fails, fallbacks are tried, which should prevent input method initialization from ever outright failing.
+- Fixed thread safety issues with input methods on X11.
+- Add support for `Touch` for win32 backend.
+- Fixed `Window::get_inner_size` and friends to return the size in pixels instead of points when using HIDPI displays on OSX.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.13.md b/third_party/winit-0.30.13/src/changelog/v0.13.md
new file mode 100644
index 0000000..fd45665
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.13.md
@@ -0,0 +1,20 @@
+## 0.13.1
+
+- Ensure necessary `x11-dl` version is used.
+
+## 0.13.0
+
+- Implement `WindowBuilder::with_maximized`, `Window::set_fullscreen`, `Window::set_maximized` and `Window::set_decorations` for MacOS.
+- Implement `WindowBuilder::with_maximized`, `Window::set_fullscreen`, `Window::set_maximized` and `Window::set_decorations` for Windows.
+- On Windows, `WindowBuilder::with_fullscreen` no longer changing monitor display resolution.
+- Overhauled X11 window geometry calculations. `get_position` and `set_position` are more universally accurate across different window managers, and `get_outer_size` actually works now.
+- Fixed SIGSEGV/SIGILL crashes on macOS caused by stabilization of the `!` (never) type.
+- Implement `WindowEvent::HiDPIFactorChanged` for macOS
+- On X11, input methods now work completely out of the box, no longer requiring application developers to manually call `setlocale`. Additionally, when input methods are started, stopped, or restarted on the server end, it's correctly handled.
+- Implemented `Refresh` event on Windows.
+- Properly calculate the minimum and maximum window size on Windows, including window decorations.
+- Map more `MouseCursor` variants to cursor icons on Windows.
+- Corrected `get_position` on macOS to return outer frame position, not content area position.
+- Corrected `set_position` on macOS to set outer frame position, not content area position.
+- Added `get_inner_position` method to `Window`, which gets the position of the window's client area. This is implemented on all applicable platforms (all desktop platforms other than Wayland, where this isn't possible).
+- **Breaking:** the `Closed` event has been replaced by `CloseRequested` and `Destroyed`. To migrate, you typically just need to replace all usages of `Closed` with `CloseRequested`; see example programs for more info. The exception is iOS, where `Closed` must be replaced by `Destroyed`.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.14.md b/third_party/winit-0.30.13/src/changelog/v0.14.md
new file mode 100644
index 0000000..822ae20
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.14.md
@@ -0,0 +1,21 @@
+## 0.14.0
+
+- Created the `Copy`, `Paste` and `Cut` `VirtualKeyCode`s and added support for them on X11 and Wayland
+- Fix `.with_decorations(false)` in macOS
+- On Mac, `NSWindow` and supporting objects might be alive long after they were `closed` which resulted in apps consuming more heap then needed. Mainly it was affecting multi window applications. Not expecting any user visible change of behaviour after the fix.
+- Fix regression of Window platform extensions for macOS where `NSFullSizeContentViewWindowMask` was not being correctly applied to `.fullsize_content_view`.
+- Corrected `get_position` on Windows to be relative to the screen rather than to the taskbar.
+- Corrected `Moved` event on Windows to use position values equivalent to those returned by `get_position`. It previously supplied client area positions instead of window positions, and would additionally interpret negative values as being very large (around `u16::MAX`).
+- Implemented `Moved` event on macOS.
+- On X11, the `Moved` event correctly use window positions rather than client area positions. Additionally, a stray `Moved` that unconditionally accompanied `Resized` with the client area position relative to the parent has been eliminated; `Moved` is still received alongside `Resized`, but now only once and always correctly.
+- On Windows, implemented all variants of `DeviceEvent` other than `Text`. Mouse `DeviceEvent`s are now received even if the window isn't in the foreground.
+- `DeviceId` on Windows is no longer a unit struct, and now contains a `u32`. For `WindowEvent`s, this will always be 0, but on `DeviceEvent`s it will be the handle to that device. `DeviceIdExt::get_persistent_identifier` can be used to acquire a unique identifier for that device that persists across replugs/reboots/etc.
+- Corrected `run_forever` on X11 to stop discarding `Awakened` events.
+- Various safety and correctness improvements to the X11 backend internals.
+- Fixed memory leak on X11 every time the mouse entered the window.
+- On X11, drag and drop now works reliably in release mode.
+- Added `WindowBuilderExt::with_resize_increments` and `WindowBuilderExt::with_base_size` to X11, allowing for more optional hints to be set.
+- Rework of the wayland backend, migrating it to use [Smithay's Client Toolkit](https://github.com/Smithay/client-toolkit).
+- Added `WindowBuilder::with_window_icon` and `Window::set_window_icon`, finally making it possible to set the window icon on Windows and X11. The `icon_loading` feature can be enabled to allow for icons to be easily loaded; see example program `window_icon.rs` for usage.
+- Windows additionally has `WindowBuilderExt::with_taskbar_icon` and `WindowExt::set_taskbar_icon`.
+- On Windows, fix panic when trying to call `set_fullscreen(None)` on a window that has not been fullscreened prior.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.15.md b/third_party/winit-0.30.13/src/changelog/v0.15.md
new file mode 100644
index 0000000..f5fc485
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.15.md
@@ -0,0 +1,42 @@
+## 0.15.1
+
+- On X11, the `Moved` event is no longer sent when the window is resized without changing position.
+- `MouseCursor` and `CursorState` now implement `Default`.
+- `WindowBuilder::with_resizable` implemented for Windows, X11, Wayland, and macOS.
+- `Window::set_resizable` implemented for Windows, X11, Wayland, and macOS.
+- On X11, if the monitor's width or height in millimeters is reported as 0, the DPI is now 1.0 instead of +inf.
+- On X11, the environment variable `WINIT_HIDPI_FACTOR` has been added for overriding DPI factor.
+- On X11, enabling transparency no longer causes the window contents to flicker when resizing.
+- On X11, `with_override_redirect` now actually enables override redirect.
+- macOS now generates `VirtualKeyCode::LAlt` and `VirtualKeyCode::RAlt` instead of `None` for both.
+- On macOS, `VirtualKeyCode::RWin` and `VirtualKeyCode::LWin` are no longer switched.
+- On macOS, windows without decorations can once again be resized.
+- Fixed race conditions when creating an `EventsLoop` on X11, most commonly manifesting as `"[xcb] Unknown sequence number while processing queue"`.
+- On macOS, `CursorMoved` and `MouseInput` events are only generated if they occurs within the window's client area.
+- On macOS, resizing the window no longer generates a spurious `MouseInput` event.
+
+## 0.15.0
+
+- `Icon::to_cardinals` is no longer public, since it was never supposed to be.
+- Wayland: improve diagnostics if initialization fails
+- Fix some system event key doesn't work when focused, do not block keyevent forward to system on macOS
+- On X11, the scroll wheel position is now correctly reset on i3 and other WMs that have the same quirk.
+- On X11, `Window::get_current_monitor` now reliably returns the correct monitor.
+- On X11, `Window::hidpi_factor` returns values from XRandR rather than the inaccurate values previously queried from the core protocol.
+- On X11, the primary monitor is detected correctly even when using versions of XRandR less than 1.5.
+- `MonitorId` now implements `Debug`.
+- Fixed bug on macOS where using `with_decorations(false)` would cause `set_decorations(true)` to produce a transparent titlebar with no title.
+- Implemented `MonitorId::get_position` on macOS.
+- On macOS, `Window::get_current_monitor` now returns accurate values.
+- Added `WindowBuilderExt::with_resize_increments` to macOS.
+- **Breaking:** On X11, `WindowBuilderExt::with_resize_increments` and `WindowBuilderExt::with_base_size` now take `u32` values rather than `i32`.
+- macOS keyboard handling has been overhauled, allowing for the use of dead keys, IME, etc. Right modifier keys are also no longer reported as being left.
+- Added the `Window::set_ime_spot(x: i32, y: i32)` method, which is implemented on X11 and macOS.
+- **Breaking**: `os::unix::WindowExt::send_xim_spot(x: i16, y: i16)` no longer exists. Switch to the new `Window::set_ime_spot(x: i32, y: i32)`, which has equivalent functionality.
+- Fixed detection of `Pause` and `Scroll` keys on Windows.
+- On Windows, alt-tabbing while the cursor is grabbed no longer makes it impossible to re-grab the cursor.
+- On Windows, using `CursorState::Hide` when the cursor is grabbed now ungrabs the cursor first.
+- Implemented `MouseCursor::NoneCursor` on Windows.
+- Added `WindowBuilder::with_always_on_top` and `Window::set_always_on_top`. Implemented on Windows, macOS, and X11.
+- On X11, `WindowBuilderExt` now has `with_class`, `with_override_redirect`, and `with_x11_window_type` to allow for more control over window creation. `WindowExt` additionally has `set_urgent`.
+- More hints are set by default on X11, including `_NET_WM_PID` and `WM_CLIENT_MACHINE`. Note that prior to this, the `WM_CLASS` hint was automatically set to whatever value was passed to `with_title`. It's now set to the executable name to better conform to expectations and the specification; if this is undesirable, you must explicitly use `WindowBuilderExt::with_class`.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.16.md b/third_party/winit-0.30.13/src/changelog/v0.16.md
new file mode 100644
index 0000000..126ad9f
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.16.md
@@ -0,0 +1,32 @@
+## 0.16.2
+
+- On Windows, non-resizable windows now have the maximization button disabled. This is consistent with behavior on macOS and popular X11 WMs.
+- Corrected incorrect `unreachable!` usage when guessing the DPI factor with no detected monitors.
+
+## 0.16.1
+
+- Added logging through `log`. Logging will become more extensive over time.
+- On X11 and Windows, the window's DPI factor is guessed before creating the window. This _greatly_ cuts back on unsightly auto-resizing that would occur immediately after window creation.
+- Fixed X11 backend compilation for environments where `c_char` is unsigned.
+
+## 0.16.0
+
+- Windows additionally has `WindowBuilderExt::with_no_redirection_bitmap`.
+- **Breaking:** Removed `VirtualKeyCode::LMenu` and `VirtualKeyCode::RMenu`; Windows now generates `VirtualKeyCode::LAlt` and `VirtualKeyCode::RAlt` instead.
+- On X11, exiting fullscreen no longer leaves the window in the monitor's top left corner.
+- **Breaking:** `Window::hidpi_factor` has been renamed to `Window::get_hidpi_factor` for better consistency. `WindowEvent::HiDPIFactorChanged` has been renamed to `WindowEvent::HiDpiFactorChanged`. DPI factors are always represented as `f64` instead of `f32` now.
+- The Windows backend is now DPI aware. `WindowEvent::HiDpiFactorChanged` is implemented, and `MonitorId::get_hidpi_factor` and `Window::hidpi_factor` return accurate values.
+- Implemented `WindowEvent::HiDpiFactorChanged` on X11.
+- On macOS, `Window::set_cursor_position` is now relative to the client area.
+- On macOS, setting the maximum and minimum dimensions now applies to the client area dimensions rather than to the window dimensions.
+- On iOS, `MonitorId::get_dimensions` has been implemented and both `MonitorId::get_hidpi_factor` and `Window::get_hidpi_factor` return accurate values.
+- On Emscripten, `MonitorId::get_hidpi_factor` now returns the same value as `Window::get_hidpi_factor` (it previously would always return 1.0).
+- **Breaking:** The entire API for sizes, positions, etc. has changed. In the majority of cases, winit produces and consumes positions and sizes as `LogicalPosition` and `LogicalSize`, respectively. The notable exception is `MonitorId` methods, which deal in `PhysicalPosition` and `PhysicalSize`. See the documentation for specifics and explanations of the types. Additionally, winit automatically conserves logical size when the DPI factor changes.
+- **Breaking:** All deprecated methods have been removed. For `Window::platform_display` and `Window::platform_window`, switch to the appropriate platform-specific `WindowExt` methods. For `Window::get_inner_size_points` and `Window::get_inner_size_pixels`, use the `LogicalSize` returned by `Window::get_inner_size` and convert as needed.
+- HiDPI support for Wayland.
+- `EventsLoop::get_available_monitors` and `EventsLoop::get_primary_monitor` now have identical counterparts on `Window`, so this information can be acquired without an `EventsLoop` borrow.
+- `AvailableMonitorsIter` now implements `Debug`.
+- Fixed quirk on macOS where certain keys would generate characters at twice the normal rate when held down.
+- On X11, all event loops now share the same `XConnection`.
+- **Breaking:** `Window::set_cursor_state` and `CursorState` enum removed in favor of the more composable `Window::grab_cursor` and `Window::hide_cursor`. As a result, grabbing the cursor no longer automatically hides it; you must call both methods to retain the old behavior on Windows and macOS. `Cursor::NoneCursor` has been removed, as it's no longer useful.
+- **Breaking:** `Window::set_cursor_position` now returns `Result<(), String>`, thus allowing for `Box` conversion via `?`.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.17.md b/third_party/winit-0.30.13/src/changelog/v0.17.md
new file mode 100644
index 0000000..0a1abc8
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.17.md
@@ -0,0 +1,23 @@
+## 0.17.2
+
+- On macOS, fix `` so applications receive the event.
+- On macOS, fix `` so applications receive the event.
+- On Wayland, key press events will now be repeated.
+
+## 0.17.1
+
+- On X11, prevent a compilation failure in release mode for versions of Rust greater than or equal to 1.30.
+- Fixed deadlock that broke fullscreen mode on Windows.
+
+## 0.17.0
+
+- Cocoa and core-graphics updates.
+- Fixed thread-safety issues in several `Window` functions on Windows.
+- On MacOS, the key state for modifiers key events is now properly set.
+- On iOS, the view is now set correctly. This makes it possible to render things (instead of being stuck on a black screen), and touch events work again.
+- Added NetBSD support.
+- **Breaking:** On iOS, `UIView` is now the default root view. `WindowBuilderExt::with_root_view_class` can be used to set the root view objective-c class to `GLKView` (OpenGLES) or `MTKView` (Metal/MoltenVK).
+- On iOS, the `UIApplication` is not started until `Window::new` is called.
+- Fixed thread unsafety with cursor hiding on macOS.
+- On iOS, fixed the size of the `JmpBuf` type used for `setjmp`/`longjmp` calls. Previously this was a buffer overflow on most architectures.
+- On Windows, use cached window DPI instead of repeatedly querying the system. This fixes sporadic crashes on Windows 7.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.18.md b/third_party/winit-0.30.13/src/changelog/v0.18.md
new file mode 100644
index 0000000..e98df5b
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.18.md
@@ -0,0 +1,52 @@
+## 0.18.1
+
+- On macOS, fix `Yen` (JIS) so applications receive the event.
+- On X11 with a tiling WM, fixed high CPU usage when moving windows across monitors.
+- On X11, fixed panic caused by dropping the window before running the event loop.
+- on macOS, added `WindowExt::set_simple_fullscreen` which does not require a separate space
+- Introduce `WindowBuilderExt::with_app_id` to allow setting the application ID on Wayland.
+- On Windows, catch panics in event loop child thread and forward them to the parent thread. This prevents an invocation of undefined behavior due to unwinding into foreign code.
+- On Windows, fix issue where resizing or moving window combined with grabbing the cursor would freeze program.
+- On Windows, fix issue where resizing or moving window would eat `Awakened` events.
+- On Windows, exiting fullscreen after entering fullscreen with disabled decorations no longer shrinks window.
+- On X11, fixed a segfault when using virtual monitors with XRandR.
+- Derive `Ord` and `PartialOrd` for `VirtualKeyCode` enum.
+- On Windows, fix issue where hovering or dropping a non file item would create a panic.
+- On Wayland, fix resizing and DPI calculation when a `wl_output` is removed without sending a `leave` event to the `wl_surface`, such as disconnecting a monitor from a laptop.
+- On Wayland, DPI calculation is handled by smithay-client-toolkit.
+- On X11, `WindowBuilder::with_min_dimensions` and `WindowBuilder::with_max_dimensions` now correctly account for DPI.
+- Added support for generating dummy `DeviceId`s and `WindowId`s to better support unit testing.
+- On macOS, fixed unsoundness in drag-and-drop that could result in drops being rejected.
+- On macOS, implemented `WindowEvent::Refresh`.
+- On macOS, all `MouseCursor` variants are now implemented and the cursor will no longer reset after unfocusing.
+- Removed minimum supported Rust version guarantee.
+
+## 0.18.0
+
+- **Breaking:** `image` crate upgraded to 0.20. This is exposed as part of the `icon_loading` API.
+- On Wayland, pointer events will now provide the current modifiers state.
+- On Wayland, titles will now be displayed in the window header decoration.
+- On Wayland, key repetition is now ended when keyboard loses focus.
+- On Wayland, windows will now use more stylish and modern client side decorations.
+- On Wayland, windows will use server-side decorations when available.
+- **Breaking:** Added support for F16-F24 keys (variants were added to the `VirtualKeyCode` enum).
+- Fixed graphical glitches when resizing on Wayland.
+- On Windows, fix freezes when performing certain actions after a window resize has been triggered. Reintroduces some visual artifacts when resizing.
+- Updated window manager hints under X11 to v1.5 of [Extended Window Manager Hints](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html#idm140200472629520).
+- Added `WindowBuilderExt::with_gtk_theme_variant` to X11-specific `WindowBuilder` functions.
+- Fixed UTF8 handling bug in X11 `set_title` function.
+- On Windows, `Window::set_cursor` now applies immediately instead of requiring specific events to occur first.
+- On Windows, the `HoveredFile` and `HoveredFileCancelled` events are now implemented.
+- On Windows, fix `Window::set_maximized`.
+- On Windows 10, fix transparency (#260).
+- On macOS, fix modifiers during key repeat.
+- Implemented the `Debug` trait for `Window`, `EventsLoop`, `EventsLoopProxy` and `WindowBuilder`.
+- On X11, now a `Resized` event will always be generated after a DPI change to ensure the window's logical size is consistent with the new DPI.
+- Added further clarifications to the DPI docs.
+- On Linux, if neither X11 nor Wayland manage to initialize, the corresponding panic now consists of a single line only.
+- Add optional `serde` feature with implementations of `Serialize`/`Deserialize` for DPI types and various event types.
+- Add `PartialEq`, `Eq`, and `Hash` implementations on public types that could have them but were missing them.
+- On X11, drag-and-drop receiving an unsupported drop type can no longer cause the WM to freeze.
+- Fix issue whereby the OpenGL context would not appear at startup on macOS Mojave (#1069).
+- **Breaking:** Removed `From` impl from `ActivationPolicy` on macOS.
+- On macOS, the application can request the user's attention with `WindowExt::request_user_attention`.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.19.md b/third_party/winit-0.30.13/src/changelog/v0.19.md
new file mode 100644
index 0000000..65aefef
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.19.md
@@ -0,0 +1,27 @@
+## 0.19.1
+
+- On Wayland, added a `get_wayland_display` function to `EventsLoopExt`.
+- On Windows, fix `CursorMoved(0, 0)` getting dispatched on window focus.
+- On macOS, fix command key event left and right reverse.
+- On FreeBSD, NetBSD, and OpenBSD, fix build of X11 backend.
+- On Linux, the numpad's add, subtract and divide keys are now mapped to the `Add`, `Subtract` and `Divide` virtual key codes
+- On macOS, the numpad's subtract key has been added to the `Subtract` mapping
+- On Wayland, the numpad's home, end, page up and page down keys are now mapped to the `Home`, `End`, `PageUp` and `PageDown` virtual key codes
+- On Windows, fix icon not showing up in corner of window.
+- On X11, change DPI scaling factor behavior. First, winit tries to read it from "Xft.dpi" XResource, and uses DPI calculation from xrandr dimensions as fallback behavior.
+
+## 0.19.0
+
+- On X11, we will use the faster `XRRGetScreenResourcesCurrent` function instead of `XRRGetScreenResources` when available.
+- On macOS, fix keycodes being incorrect when using a non-US keyboard layout.
+- On Wayland, fix `with_title()` not setting the windows title
+- On Wayland, add `set_wayland_theme()` to control client decoration color theme
+- Added serde serialization to `os::unix::XWindowType`.
+- **Breaking:** Remove the `icon_loading` feature and the associated `image` dependency.
+- On X11, make event loop thread safe by replacing XNextEvent with select(2) and XCheckIfEvent
+- On Windows, fix malformed function pointer typecast that could invoke undefined behavior.
+- Refactored Windows state/flag-setting code.
+- On Windows, hiding the cursor no longer hides the cursor for all Winit windows - just the one `hide_cursor` was called on.
+- On Windows, cursor grabs used to get perpetually canceled when the grabbing window lost focus. Now, cursor grabs automatically get re-initialized when the window regains focus and the mouse moves over the client area.
+- On Windows, only vertical mouse wheel events were handled. Now, horizontal mouse wheel events are also handled.
+- On Windows, ignore the AltGr key when populating the `ModifiersState` type.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.20.md b/third_party/winit-0.30.13/src/changelog/v0.20.md
new file mode 100644
index 0000000..eb4ba6a
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.20.md
@@ -0,0 +1,200 @@
+## 0.20.0
+
+- On X11, fix `ModifiersChanged` emitting incorrect modifier change events
+- **Breaking**: Overhaul how Winit handles DPI:
+ - Window functions and events now return `PhysicalSize` instead of `LogicalSize`.
+ - Functions that take `Size` or `Position` types can now take either `Logical` or `Physical` types.
+ - `hidpi_factor` has been renamed to `scale_factor`.
+ - `HiDpiFactorChanged` has been renamed to `ScaleFactorChanged`, and lets you control how the OS
+ resizes the window in response to the change.
+ - On X11, deprecate `WINIT_HIDPI_FACTOR` environment variable in favor of `WINIT_X11_SCALE_FACTOR`.
+ - `Size` and `Position` types are now generic over their exact pixel type.
+
+## 0.20.0-alpha6
+
+- On macOS, fix `set_cursor_visible` hides cursor outside of window.
+- On macOS, fix `CursorEntered` and `CursorLeft` events fired at old window size.
+- On macOS, fix error when `set_fullscreen` is called during fullscreen transition.
+- On all platforms except mobile and WASM, implement `Window::set_minimized`.
+- On X11, fix `CursorEntered` event being generated for non-winit windows.
+- On macOS, fix crash when starting maximized without decorations.
+- On macOS, fix application not terminating on `run_return`.
+- On Wayland, fix cursor icon updates on window borders when using CSD.
+- On Wayland, under mutter(GNOME Wayland), fix CSD being behind the status bar, when starting window in maximized mode.
+- On Windows, theme the title bar according to whether the system theme is "Light" or "Dark".
+- Added `WindowEvent::ThemeChanged` variant to handle changes to the system theme. Currently only implemented on Windows.
+- **Breaking**: Changes to the `RedrawRequested` event (#1041):
+ - `RedrawRequested` has been moved from `WindowEvent` to `Event`.
+ - `EventsCleared` has been renamed to `MainEventsCleared`.
+ - `RedrawRequested` is now issued only after `MainEventsCleared`.
+ - `RedrawEventsCleared` is issued after each set of `RedrawRequested` events.
+- Implement synthetic window focus key events on Windows.
+- **Breaking**: Change `ModifiersState` to a `bitflags` struct.
+- On Windows, implement `VirtualKeyCode` translation for `LWin` and `RWin`.
+- On Windows, fix closing the last opened window causing `DeviceEvent`s to stop getting emitted.
+- On Windows, fix `Window::set_visible` not setting internal flags correctly. This resulted in some weird behavior.
+- Add `DeviceEvent::ModifiersChanged`.
+ - Deprecate `modifiers` fields in other events in favor of `ModifiersChanged`.
+- On X11, `WINIT_HIDPI_FACTOR` now dominates `Xft.dpi` when picking DPI factor for output.
+- On X11, add special value `randr` for `WINIT_HIDPI_FACTOR` to make winit use self computed DPI factor instead of the one from `Xft.dpi`.
+
+## 0.20.0-alpha5
+
+- On macOS, fix application termination on `ControlFlow::Exit`
+- On Windows, fix missing `ReceivedCharacter` events when Alt is held.
+- On macOS, stop emitting private corporate characters in `ReceivedCharacter` events.
+- On X11, fix misreporting DPI factor at startup.
+- On X11, fix events not being reported when using `run_return`.
+- On X11, fix key modifiers being incorrectly reported.
+- On X11, fix window creation hanging when another window is fullscreen.
+- On Windows, fix focusing unfocused windows when switching from fullscreen to windowed.
+- On X11, fix reporting incorrect DPI factor when waking from suspend.
+- Change `EventLoopClosed` to contain the original event.
+- **Breaking**: Add `is_synthetic` field to `WindowEvent` variant `KeyboardInput`,
+ indicating that the event is generated by winit.
+- On X11, generate synthetic key events for keys held when a window gains or loses focus.
+- On X11, issue a `CursorMoved` event when a `Touch` event occurs,
+ as X11 implicitly moves the cursor for such events.
+
+## 0.20.0-alpha4
+
+- Add web support via the 'stdweb' or 'web-sys' features
+- On Windows, implemented function to get HINSTANCE
+- On macOS, implement `run_return`.
+- On iOS, fix inverted parameter in `set_prefers_home_indicator_hidden`.
+- On X11, performance is improved when rapidly calling `Window::set_cursor_icon`.
+- On iOS, fix improper `msg_send` usage that was UB and/or would break if `!` is stabilized.
+- On Windows, unset `maximized` when manually changing the window's position or size.
+- On Windows, add touch pressure information for touch events.
+- On macOS, differentiate between `CursorIcon::Grab` and `CursorIcon::Grabbing`.
+- On Wayland, fix event processing sometimes stalling when using OpenGL with vsync.
+- Officially remove the Emscripten backend.
+- On Windows, fix handling of surrogate pairs when dispatching `ReceivedCharacter`.
+- On macOS 10.15, fix freeze upon exiting exclusive fullscreen mode.
+- On iOS, fix panic upon closing the app.
+- On X11, allow setting multiple `XWindowType`s.
+- On iOS, fix null window on initial `HiDpiFactorChanged` event.
+- On Windows, fix fullscreen window shrinking upon getting restored to a normal window.
+- On macOS, fix events not being emitted during modal loops, such as when windows are being resized
+ by the user.
+- On Windows, fix hovering the mouse over the active window creating an endless stream of CursorMoved events.
+- Always dispatch a `RedrawRequested` event after creating a new window.
+- On X11, return dummy monitor data to avoid panicking when no monitors exist.
+- On X11, prevent stealing input focus when creating a new window.
+ Only steal input focus when entering fullscreen mode.
+- On Wayland, fixed DeviceEvents for relative mouse movement is not always produced
+- On Wayland, add support for set_cursor_visible and set_cursor_grab.
+- On Wayland, fixed DeviceEvents for relative mouse movement is not always produced.
+- Removed `derivative` crate dependency.
+- On Wayland, add support for set_cursor_icon.
+- Use `impl Iterator- ` instead of `AvailableMonitorsIter` consistently.
+- On macOS, fix fullscreen state being updated after entering fullscreen instead of before,
+ resulting in `Window::fullscreen` returning the old state in `Resized` events instead of
+ reflecting the new fullscreen state
+- On X11, fix use-after-free during window creation
+- On Windows, disable monitor change keyboard shortcut while in exclusive fullscreen.
+- On Windows, ensure that changing a borderless fullscreen window's monitor via keyboard shortcuts keeps the window fullscreen on the new monitor.
+- Prevent `EventLoop::new` and `EventLoop::with_user_event` from getting called outside the main thread.
+ - This is because some platforms cannot run the event loop outside the main thread. Preventing this
+ reduces the potential for cross-platform compatibility gotchyas.
+- On Windows and Linux X11/Wayland, add platform-specific functions for creating an `EventLoop` outside the main thread.
+- On Wayland, drop resize events identical to the current window size.
+- On Windows, fix window rectangle not getting set correctly on high-DPI systems.
+
+## 0.20.0-alpha3
+
+- On macOS, drop the run closure on exit.
+- On Windows, location of `WindowEvent::Touch` are window client coordinates instead of screen coordinates.
+- On X11, fix delayed events after window redraw.
+- On macOS, add `WindowBuilderExt::with_disallow_hidpi` to have the option to turn off best resolution openGL surface.
+- On Windows, screen saver won't start if the window is in fullscreen mode.
+- Change all occurrences of the `new_user_event` method to `with_user_event`.
+- On macOS, the dock and the menu bar are now hidden in fullscreen mode.
+- `Window::set_fullscreen` now takes `Option
` where `Fullscreen`
+ consists of `Fullscreen::Exclusive(VideoMode)` and
+ `Fullscreen::Borderless(MonitorHandle)` variants.
+ - Adds support for exclusive fullscreen mode.
+- On iOS, add support for hiding the home indicator.
+- On iOS, add support for deferring system gestures.
+- On iOS, fix a crash that occurred while acquiring a monitor's name.
+- On iOS, fix armv7-apple-ios compile target.
+- Removed the `T: Clone` requirement from the `Clone` impl of `EventLoopProxy`.
+- On iOS, disable overscan compensation for external displays (removes black
+ bars surrounding the image).
+- On Linux, the functions `is_wayland`, `is_x11`, `xlib_xconnection` and `wayland_display` have been moved to a new `EventLoopWindowTargetExtUnix` trait.
+- On iOS, add `set_prefers_status_bar_hidden` extension function instead of
+ hijacking `set_decorations` for this purpose.
+- On macOS and iOS, corrected the auto trait impls of `EventLoopProxy`.
+- On iOS, add touch pressure information for touch events.
+- Implement `raw_window_handle::HasRawWindowHandle` for `Window` type on all supported platforms.
+- On macOS, fix the signature of `-[NSView drawRect:]`.
+- On iOS, fix the behavior of `ControlFlow::Poll`. It wasn't polling if that was the only mode ever used by the application.
+- On iOS, fix DPI sent out by views on creation was `0.0` - now it gives a reasonable number.
+- On iOS, RedrawRequested now works for gl/metal backed views.
+- On iOS, RedrawRequested is generally ordered after EventsCleared.
+
+## 0.20.0-alpha2
+
+- On X11, non-resizable windows now have maximize explicitly disabled.
+- On Windows, support paths longer than MAX_PATH (260 characters) in `WindowEvent::DroppedFile`
+ and `WindowEvent::HoveredFile`.
+- On Mac, implement `DeviceEvent::Button`.
+- Change `Event::Suspended(true / false)` to `Event::Suspended` and `Event::Resumed`.
+- On X11, fix sanity check which checks that a monitor's reported width and height (in millimeters) are non-zero when calculating the DPI factor.
+- Revert the use of invisible surfaces in Wayland, which introduced graphical glitches with OpenGL (#835)
+- On X11, implement `_NET_WM_PING` to allow desktop environment to kill unresponsive programs.
+- On Windows, when a window is initially invisible, it won't take focus from the existing visible windows.
+- On Windows, fix multiple calls to `request_redraw` during `EventsCleared` sending multiple `RedrawRequested events.`
+- On Windows, fix edge case where `RedrawRequested` could be dispatched before input events in event loop iteration.
+- On Windows, fix timing issue that could cause events to be improperly dispatched after `RedrawRequested` but before `EventsCleared`.
+- On macOS, drop unused Metal dependency.
+- On Windows, fix the trail effect happening on transparent decorated windows. Borderless (or un-decorated) windows were not affected.
+- On Windows, fix `with_maximized` not properly setting window size to entire window.
+- On macOS, change `WindowExtMacOS::request_user_attention()` to take an `enum` instead of a `bool`.
+
+## 0.20.0-alpha1
+
+- Changes below are considered **breaking**.
+- Change all occurrences of `EventsLoop` to `EventLoop`.
+- Previously flat API is now exposed through `event`, `event_loop`, `monitor`, and `window` modules.
+- `os` module changes:
+ - Renamed to `platform`.
+ - All traits now have platform-specific suffixes.
+ - Exposes new `desktop` module on Windows, Mac, and Linux.
+- Changes to event loop types:
+ - `EventLoopProxy::wakeup` has been removed in favor of `send_event`.
+ - **Major:** New `run` method drives winit event loop.
+ - Returns `!` to ensure API behaves identically across all supported platforms.
+ - This allows `emscripten` implementation to work without lying about the API.
+ - `ControlFlow`'s variants have been replaced with `Wait`, `WaitUntil(Instant)`, `Poll`, and `Exit`.
+ - Is read after `EventsCleared` is processed.
+ - `Wait` waits until new events are available.
+ - `WaitUntil` waits until either new events are available or the provided time has been reached.
+ - `Poll` instantly resumes the event loop.
+ - `Exit` aborts the event loop.
+ - Takes a closure that implements `'static + FnMut(Event, &EventLoop, &mut ControlFlow)`.
+ - `&EventLoop` is provided to allow new `Window`s to be created.
+ - **Major:** `platform::desktop` module exposes `EventLoopExtDesktop` trait with `run_return` method.
+ - Behaves identically to `run`, but returns control flow to the calling context and can take non-`'static` closures.
+ - `EventLoop`'s `poll_events` and `run_forever` methods have been removed in favor of `run` and `run_return`.
+- Changes to events:
+ - Remove `Event::Awakened` in favor of `Event::UserEvent(T)`.
+ - Can be sent with `EventLoopProxy::send_event`.
+ - Rename `WindowEvent::Refresh` to `WindowEvent::RedrawRequested`.
+ - `RedrawRequested` can be sent by the user with the `Window::request_redraw` method.
+ - `EventLoop`, `EventLoopProxy`, and `Event` are now generic over `T`, for use in `UserEvent`.
+ - **Major:** Add `NewEvents(StartCause)`, `EventsCleared`, and `LoopDestroyed` variants to `Event`.
+ - `NewEvents` is emitted when new events are ready to be processed by event loop.
+ - `StartCause` describes why new events are available, with `ResumeTimeReached`, `Poll`, `WaitCancelled`, and `Init` (sent once at start of loop).
+ - `EventsCleared` is emitted when all available events have been processed.
+ - Can be used to perform logic that depends on all events being processed (e.g. an iteration of a game loop).
+ - `LoopDestroyed` is emitted when the `run` or `run_return` method is about to exit.
+- Rename `MonitorId` to `MonitorHandle`.
+- Removed `serde` implementations from `ControlFlow`.
+- Rename several functions to improve both internal consistency and compliance with Rust API guidelines.
+- Remove `WindowBuilder::multitouch` field, since it was only implemented on a few platforms. Multitouch is always enabled now.
+- **Breaking:** On macOS, change `ns` identifiers to use snake_case for consistency with iOS's `ui` identifiers.
+- Add `MonitorHandle::video_modes` method for retrieving supported video modes for the given monitor.
+- On Wayland, the window now exists even if nothing has been drawn.
+- On Windows, fix initial dimensions of a fullscreen window.
+- On Windows, Fix transparent borderless windows rendering wrong.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.21.md b/third_party/winit-0.30.13/src/changelog/v0.21.md
new file mode 100644
index 0000000..48f3d35
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.21.md
@@ -0,0 +1,16 @@
+## 0.21.0
+
+- On Windows, fixed "error: linking with `link.exe` failed: exit code: 1120" error on older versions of windows.
+- On macOS, fix set_minimized(true) works only with decorations.
+- On macOS, add `hide_application` to `EventLoopWindowTarget` via a new `EventLoopWindowTargetExtMacOS` trait. `hide_application` will hide the entire application by calling `-[NSApplication hide: nil]`.
+- On macOS, fix not sending ReceivedCharacter event for specific keys combinations.
+- On macOS, fix `CursorMoved` event reporting the cursor position using logical coordinates.
+- On macOS, fix issue where unbundled applications would sometimes open without being focused.
+- On macOS, fix `run_return` does not return unless it receives a message.
+- On Windows, fix bug where `RedrawRequested` would only get emitted every other iteration of the event loop.
+- On X11, fix deadlock on window state when handling certain window events.
+- `WindowBuilder` now implements `Default`.
+- **Breaking:** `WindowEvent::CursorMoved` changed to `f64` units, preserving high-precision data supplied by most backends
+- On Wayland, fix coordinates in mouse events when scale factor isn't 1
+- On Web, add the ability to provide a custom canvas
+- **Breaking:** On Wayland, the `WaylandTheme` struct has been replaced with a `Theme` trait, allowing for extra configuration
diff --git a/third_party/winit-0.30.13/src/changelog/v0.22.md b/third_party/winit-0.30.13/src/changelog/v0.22.md
new file mode 100644
index 0000000..07bc1ef
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.22.md
@@ -0,0 +1,37 @@
+## 0.22.2
+
+- Added Clone implementation for 'static events.
+- On Windows, fix window intermittently hanging when `ControlFlow` was set to `Poll`.
+- On Windows, fix `WindowBuilder::with_maximized` being ignored.
+- On Android, minimal platform support.
+- On iOS, touch positions are now properly converted to physical pixels.
+- On macOS, updated core-* dependencies and cocoa
+
+## 0.22.1
+
+- On X11, fix `ResumeTimeReached` being fired too early.
+- On Web, replaced zero timeout for `ControlFlow::Poll` with `requestAnimationFrame`
+- On Web, fix a possible panic during event handling
+- On macOS, fix `EventLoopProxy` leaking memory for every instance.
+
+## 0.22.0
+
+- On Windows, fix minor timing issue in wait_until_time_or_msg
+- On Windows, rework handling of request_redraw() to address panics.
+- On macOS, fix `set_simple_screen` to remember frame excluding title bar.
+- On Wayland, fix coordinates in touch events when scale factor isn't 1.
+- On Wayland, fix color from `close_button_icon_color` not applying.
+- Ignore locale if unsupported by X11 backend
+- On Wayland, Add HiDPI cursor support
+- On Web, add the ability to query "Light" or "Dark" system theme send `ThemeChanged` on change.
+- Fix `Event::to_static` returning `None` for user events.
+- On Wayland, Hide CSD for fullscreen windows.
+- On Windows, ignore spurious mouse move messages.
+- **Breaking:** Move `ModifiersChanged` variant from `DeviceEvent` to `WindowEvent`.
+- On Windows, add `IconExtWindows` trait which exposes creating an `Icon` from an external file or embedded resource
+- Add `BadIcon::OsError` variant for when OS icon functionality fails
+- On Windows, fix crash at startup on systems that do not properly support Windows' Dark Mode
+- Revert On macOS, fix not sending ReceivedCharacter event for specific keys combinations.
+- on macOS, fix incorrect ReceivedCharacter events for some key combinations.
+- **Breaking:** Use `i32` instead of `u32` for position type in `WindowEvent::Moved`.
+- On macOS, a mouse motion event is now generated before every mouse click.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.23.md b/third_party/winit-0.30.13/src/changelog/v0.23.md
new file mode 100644
index 0000000..33ea2ab
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.23.md
@@ -0,0 +1,65 @@
+## 0.23.0
+
+- On iOS, fixed support for the "Debug View Hierarchy" feature in Xcode.
+- On all platforms, `available_monitors` and `primary_monitor` are now on `EventLoopWindowTarget` rather than `EventLoop` to list monitors event in the event loop.
+- On Unix, X11 and Wayland are now optional features (enabled by default)
+- On X11, fix deadlock when calling `set_fullscreen_inner`.
+- On Web, prevent the webpage from scrolling when the user is focused on a winit canvas
+- On Web, calling `window.set_cursor_icon` no longer breaks HiDPI scaling
+- On Windows, drag and drop is now optional (enabled by default) and can be disabled with `WindowBuilderExtWindows::with_drag_and_drop(false)`.
+- On Wayland, fix deadlock when calling to `set_inner_size` from a callback.
+- On macOS, add `hide__other_applications` to `EventLoopWindowTarget` via existing `EventLoopWindowTargetExtMacOS` trait. `hide_other_applications` will hide other applications by calling `-[NSApplication hideOtherApplications: nil]`.
+- On android added support for `run_return`.
+- On MacOS, Fixed fullscreen and dialog support for `run_return`.
+- On Windows, fix bug where we'd try to emit `MainEventsCleared` events during nested win32 event loops.
+- On Web, use mouse events if pointer events aren't supported. This affects Safari.
+- On Windows, `set_ime_position` is now a no-op instead of a runtime crash.
+- On Android, `set_fullscreen` is now a no-op instead of a runtime crash.
+- On iOS and Android, `set_inner_size` is now a no-op instead of a runtime crash.
+- On Android, fix `ControlFlow::Poll` not polling the Android event queue.
+- On macOS, add `NSWindow.hasShadow` support.
+- On Web, fix vertical mouse wheel scrolling being inverted.
+- On Web, implement mouse capturing for click-dragging out of the canvas.
+- On Web, fix `ControlFlow::Exit` not properly handled.
+- On Web (web-sys only), send `WindowEvent::ScaleFactorChanged` event when `window.devicePixelRatio` is changed.
+- **Breaking:** On Web, `set_cursor_position` and `set_cursor_grab` will now always return an error.
+- **Breaking:** `PixelDelta` scroll events now return a `PhysicalPosition`.
+- On NetBSD, fixed crash due to incorrect detection of the main thread.
+- **Breaking:** On X11, `-` key is mapped to the `Minus` virtual key code, instead of `Subtract`.
+- On macOS, fix inverted horizontal scroll.
+- **Breaking:** `current_monitor` now returns `Option`.
+- **Breaking:** `primary_monitor` now returns `Option`.
+- On macOS, updated core-* dependencies and cocoa.
+- Bump `parking_lot` to 0.11
+- On Android, bump `ndk`, `ndk-sys` and `ndk-glue` to 0.2. Checkout the new ndk-glue main proc attribute.
+- On iOS, fixed starting the app in landscape where the view still had portrait dimensions.
+- Deprecate the stdweb backend, to be removed in a future release
+- **Breaking:** Prefixed virtual key codes `Add`, `Multiply`, `Divide`, `Decimal`, and `Subtract` with `Numpad`.
+- Added `Asterisk` and `Plus` virtual key codes.
+- On Web (web-sys only), the `Event::LoopDestroyed` event is correctly emitted when leaving the page.
+- On Web, the `WindowEvent::Destroyed` event now gets emitted when a `Window` is dropped.
+- On Web (web-sys only), the event listeners are now removed when a `Window` is dropped or when the event loop is destroyed.
+- On Web, the event handler closure passed to `EventLoop::run` now gets dropped after the event loop is destroyed.
+- **Breaking:** On Web, the canvas element associated to a `Window` is no longer removed from the DOM when the `Window` is dropped.
+- On Web, `WindowEvent::Resized` is now emitted when `Window::set_inner_size` is called.
+- **Breaking:** `Fullscreen` enum now uses `Borderless(Option)` instead of `Borderless(MonitorHandle)` to allow picking the current monitor.
+- On MacOS, fix `WindowEvent::Moved` ignoring the scale factor.
+- On Wayland, add missing virtual keycodes.
+- On Wayland, implement proper `set_cursor_grab`.
+- On Wayland, the cursor will use similar icons if the requested one isn't available.
+- On Wayland, right clicking on client side decorations will request application menu.
+- On Wayland, fix tracking of window size after state changes.
+- On Wayland, fix client side decorations not being hidden properly in fullscreen.
+- On Wayland, fix incorrect size event when entering fullscreen with client side decorations.
+- On Wayland, fix `resizable` attribute not being applied properly on startup.
+- On Wayland, fix disabled repeat rate not being handled.
+- On Wayland, fix decoration buttons not working after tty switch.
+- On Wayland, fix scaling not being applied on output re-enable.
+- On Wayland, fix crash when `XCURSOR_SIZE` is `0`.
+- On Wayland, fix pointer getting created in some cases without pointer capability.
+- On Wayland, on kwin, fix space between window and decorations on startup.
+- **Breaking:** On Wayland, `Theme` trait was reworked.
+- On Wayland, disable maximize button for non-resizable window.
+- On Wayland, added support for `set_ime_position`.
+- On Wayland, fix crash on startup since GNOME 3.37.90.
+- On X11, fix incorrect modifiers state on startup.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.24.md b/third_party/winit-0.30.13/src/changelog/v0.24.md
new file mode 100644
index 0000000..fa0a27b
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.24.md
@@ -0,0 +1,28 @@
+## 0.24.0
+
+- On Windows, fix applications not exiting gracefully due to thread_event_target_callback accessing corrupted memory.
+- On Windows, implement `Window::set_ime_position`.
+- **Breaking:** On Windows, Renamed `WindowBuilderExtWindows`'s `is_dark_mode` to `theme`.
+- **Breaking:** On Windows, renamed `WindowBuilderExtWindows::is_dark_mode` to `theme`.
+- On Windows, add `WindowBuilderExtWindows::with_theme` to set a preferred theme.
+- On Windows, fix bug causing message boxes to appear delayed.
+- On Android, calling `WindowEvent::Focused` now works properly instead of always returning false.
+- On Windows, fix Alt-Tab behaviour by removing borderless fullscreen "always on top" flag.
+- On Windows, fix bug preventing windows with transparency enabled from having fully-opaque regions.
+- **Breaking:** On Windows, include prefix byte in scancodes.
+- On Wayland, fix window not being resizeable when using `WindowBuilder::with_min_inner_size`.
+- On Unix, fix cross-compiling to wasm32 without enabling X11 or Wayland.
+- On Windows, fix use-after-free crash during window destruction.
+- On Web, fix `WindowEvent::ReceivedCharacter` never being sent on key input.
+- On macOS, fix compilation when targeting aarch64.
+- On X11, fix `Window::request_redraw` not waking the event loop.
+- On Wayland, the keypad arrow keys are now recognized.
+- **Breaking** Rename `desktop::EventLoopExtDesktop` to `run_return::EventLoopExtRunReturn`.
+- Added `request_user_attention` method to `Window`.
+- **Breaking:** On macOS, removed `WindowExt::request_user_attention`, use `Window::request_user_attention`.
+- **Breaking:** On X11, removed `WindowExt::set_urgent`, use `Window::request_user_attention`.
+- On Wayland, default font size in CSD increased from 11 to 17.
+- On Windows, fix bug causing message boxes to appear delayed.
+- On Android, support multi-touch.
+- On Wayland, extra mouse buttons are not dropped anymore.
+- **Breaking**: `MouseButton::Other` now uses `u16`.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.25.md b/third_party/winit-0.30.13/src/changelog/v0.25.md
new file mode 100644
index 0000000..00451c0
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.25.md
@@ -0,0 +1,31 @@
+## 0.25.0
+
+- **Breaking:** On macOS, replace `WindowBuilderExtMacOS::with_activation_policy` with `EventLoopExtMacOS::set_activation_policy`
+- On macOS, wait with activating the application until the application has initialized.
+- On macOS, fix creating new windows when the application has a main menu.
+- On Windows, fix fractional deltas for mouse wheel device events.
+- On macOS, fix segmentation fault after dropping the main window.
+- On Android, `InputEvent::KeyEvent` is partially implemented providing the key scancode.
+- Added `is_maximized` method to `Window`.
+- On Windows, fix bug where clicking the decoration bar would make the cursor blink.
+- On Windows, fix bug causing newly created windows to erroneously display the "wait" (spinning) cursor.
+- On macOS, wake up the event loop immediately when a redraw is requested.
+- On Windows, change the default window size (1024x768) to match the default on other desktop platforms (800x600).
+- On Windows, fix bug causing mouse capture to not be released.
+- On Windows, fix fullscreen not preserving minimized/maximized state.
+- On Android, unimplemented events are marked as unhandled on the native event loop.
+- On Windows, added `WindowBuilderExtWindows::with_menu` to set a custom menu at window creation time.
+- On Android, bump `ndk` and `ndk-glue` to 0.3: use predefined constants for event `ident`.
+- On macOS, fix objects captured by the event loop closure not being dropped on panic.
+- On Windows, fixed `WindowEvent::ThemeChanged` not properly firing and fixed `Window::theme` returning the wrong theme.
+- On Web, added support for `DeviceEvent::MouseMotion` to listen for relative mouse movements.
+- Added `WindowBuilder::with_position` to allow setting the position of a `Window` on creation. Supported on Windows, macOS and X11.
+- Added `Window::drag_window`. Implemented on Windows, macOS, X11 and Wayland.
+- On X11, bump `mio` to 0.7.
+- On Windows, added `WindowBuilderExtWindows::with_owner_window` to allow creating popup windows.
+- On Windows, added `WindowExtWindows::set_enable` to allow creating modal popup windows.
+- On macOS, emit `RedrawRequested` events immediately while the window is being resized.
+- Implement `Default`, `Hash`, and `Eq` for `LogicalPosition`, `PhysicalPosition`, `LogicalSize`, and `PhysicalSize`.
+- On macOS, initialize the Menu Bar with minimal defaults. (Can be prevented using `enable_default_menu_creation`)
+- On macOS, change the default behavior for first click when the window was unfocused. Now the window becomes focused and then emits a `MouseInput` event on a "first mouse click".
+- Implement mint (math interoperability standard types) conversions (under feature flag `mint`).
diff --git a/third_party/winit-0.30.13/src/changelog/v0.26.md b/third_party/winit-0.30.13/src/changelog/v0.26.md
new file mode 100644
index 0000000..d33d4a3
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.26.md
@@ -0,0 +1,36 @@
+## 0.26.1
+
+- Fix linking to the `ColorSync` framework on macOS 10.7, and in newer Rust versions.
+- On Web, implement cursor grabbing through the pointer lock API.
+- On X11, add mappings for numpad comma, numpad enter, numlock and pause.
+- On macOS, fix Pinyin IME input by reverting a change that intended to improve IME.
+- On Windows, fix a crash with transparent windows on Windows 11.
+
+## 0.26.0
+
+- Update `raw-window-handle` to `v0.4`. This is _not_ a breaking change, we still implement `HasRawWindowHandle` from `v0.3`, see [rust-windowing/raw-window-handle#74](https://github.com/rust-windowing/raw-window-handle/pull/74). Note that you might have to run `cargo update -p raw-window-handle` after upgrading.
+- On X11, bump `mio` to 0.8.
+- On Android, fixed `WindowExtAndroid::config` initially returning an empty `Configuration`.
+- On Android, fixed `Window::scale_factor` and `MonitorHandle::scale_factor` initially always returning 1.0.
+- On X11, select an appropriate visual for transparency if is requested
+- On Wayland and X11, fix diagonal window resize cursor orientation.
+- On macOS, drop the event callback before exiting.
+- On Android, implement `Window::request_redraw`
+- **Breaking:** On Web, remove the `stdweb` backend.
+- Added `Window::focus_window`to bring the window to the front and set input focus.
+- On Wayland and X11, implement `is_maximized` method on `Window`.
+- On Windows, prevent ghost window from showing up in the taskbar after either several hours of use or restarting `explorer.exe`.
+- On macOS, fix issue where `ReceivedCharacter` was not being emitted during some key repeat events.
+- On Wayland, load cursor icons `hand2` and `hand1` for `CursorIcon::Hand`.
+- **Breaking:** On Wayland, Theme trait and its support types are dropped.
+- On Wayland, bump `smithay-client-toolkit` to 0.15.1.
+- On Wayland, implement `request_user_attention` with `xdg_activation_v1`.
+- On X11, emit missing `WindowEvent::ScaleFactorChanged` when the only monitor gets reconnected.
+- On X11, if RANDR based scale factor is higher than 20 reset it to 1
+- On Wayland, add an enabled-by-default feature called `wayland-dlopen` so users can opt out of using `dlopen` to load system libraries.
+- **Breaking:** On Android, bump `ndk` and `ndk-glue` to 0.5.
+- On Windows, increase wait timer resolution for more accurate timing when using `WaitUntil`.
+- On macOS, fix native file dialogs hanging the event loop.
+- On Wayland, implement a workaround for wrong configure size when using `xdg_decoration` in `kwin_wayland`
+- On macOS, fix an issue that prevented the menu bar from showing in borderless fullscreen mode.
+- On X11, EINTR while polling for events no longer causes a panic. Instead it will be treated as a spurious wakeup.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.27.md b/third_party/winit-0.30.13/src/changelog/v0.27.md
new file mode 100644
index 0000000..5f067f5
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.27.md
@@ -0,0 +1,107 @@
+## 0.27.5
+
+- On Wayland, fix byte offset in `Ime::Preedit` pointing to invalid bytes.
+
+## 0.27.4
+
+- On Windows, emit `ReceivedCharacter` events on system keybindings.
+- On Windows, fixed focus event emission on minimize.
+- On X11, fixed IME crashing during reload.
+
+## 0.27.3
+
+- On Windows, added `WindowExtWindows::set_undecorated_shadow` and `WindowBuilderExtWindows::with_undecorated_shadow` to draw the drop shadow behind a borderless window.
+- On Windows, fixed default window features (ie snap, animations, shake, etc.) when decorations are disabled.
+- On Windows, fixed ALT+Space shortcut to open window menu.
+- On Wayland, fixed `Ime::Preedit` not being sent on IME reset.
+- Fixed unbound version specified for `raw-window-handle` leading to compilation failures.
+- Empty `Ime::Preedit` event will be sent before `Ime::Commit` to help clearing preedit.
+- On X11, fixed IME context picking by querying for supported styles beforehand.
+
+## 0.27.2
+
+- On macOS, fixed touch phase reporting when scrolling.
+- On X11, fix min, max and resize increment hints not persisting for resizable windows (e.g. on DPI change).
+- On Windows, respect min/max inner sizes when creating the window.
+- For backwards compatibility, `Window` now (additionally) implements the old version (`0.4`) of the `HasRawWindowHandle` trait
+- On Windows, added support for `EventLoopWindowTarget::set_device_event_filter`.
+- On Wayland, fix user requested `WindowEvent::RedrawRequested` being delayed by a frame.
+
+## 0.27.1
+
+- The minimum supported Rust version was lowered to `1.57.0` and now explicitly tested.
+- On X11, fix crash on start due to inability to create an IME context without any preedit.
+
+## 0.27.0
+
+- On Windows, fix hiding a maximized window.
+- On Android, `ndk-glue`'s `NativeWindow` lock is now held between `Event::Resumed` and `Event::Suspended`.
+- On Web, added `EventLoopExtWebSys` with a `spawn` method to start the event loop without throwing an exception.
+- Added `WindowEvent::Occluded(bool)`, currently implemented on macOS and X11.
+- On X11, fix events for caps lock key not being sent
+- Build docs on `docs.rs` for iOS and Android as well.
+- **Breaking:** Removed the `WindowAttributes` struct, since all its functionality is accessible from `WindowBuilder`.
+- Added `WindowBuilder::transparent` getter to check if the user set `transparent` attribute.
+- On macOS, Fix emitting `Event::LoopDestroyed` on CMD+Q.
+- On macOS, fixed an issue where having multiple windows would prevent run_return from ever returning.
+- On Wayland, fix bug where the cursor wouldn't hide in GNOME.
+- On macOS, Windows, and Wayland, add `set_cursor_hittest` to let the window ignore mouse events.
+- On Windows, added `WindowExtWindows::set_skip_taskbar` and `WindowBuilderExtWindows::with_skip_taskbar`.
+- On Windows, added `EventLoopBuilderExtWindows::with_msg_hook`.
+- On Windows, remove internally unique DC per window.
+- On macOS, remove the need to call `set_ime_position` after moving the window.
+- Added `Window::is_visible`.
+- Added `Window::is_resizable`.
+- Added `Window::is_decorated`.
+- On X11, fix for repeated event loop iteration when `ControlFlow` was `Wait`
+- On X11, fix scale factor calculation when the only monitor is reconnected
+- On Wayland, report unaccelerated mouse deltas in `DeviceEvent::MouseMotion`.
+- On Web, a focused event is manually generated when a click occurs to emulate behaviour of other backends.
+- **Breaking:** Bump `ndk` version to 0.6, ndk-sys to `v0.3`, `ndk-glue` to `0.6`.
+- Remove no longer needed `WINIT_LINK_COLORSYNC` environment variable.
+- **Breaking:** Rename the `Exit` variant of `ControlFlow` to `ExitWithCode`, which holds a value to control the exit code after running. Add an `Exit` constant which aliases to `ExitWithCode(0)` instead to avoid major breakage. This shouldn't affect most existing programs.
+- Add `EventLoopBuilder`, which allows you to create and tweak the settings of an event loop before creating it.
+- Deprecated `EventLoop::with_user_event`; use `EventLoopBuilder::with_user_event` instead.
+- **Breaking:** Replaced `EventLoopExtMacOS` with `EventLoopBuilderExtMacOS` (which also has renamed methods).
+- **Breaking:** Replaced `EventLoopExtWindows` with `EventLoopBuilderExtWindows` (which also has renamed methods).
+- **Breaking:** Replaced `EventLoopExtUnix` with `EventLoopBuilderExtUnix` (which also has renamed methods).
+- **Breaking:** The platform specific extensions for Windows `winit::platform::windows` have changed. All `HANDLE`-like types e.g. `HWND` and `HMENU` were converted from winapi types or `*mut c_void` to `isize`. This was done to be consistent with the type definitions in windows-sys and to not expose internal dependencies.
+- The internal bindings to the [Windows API](https://docs.microsoft.com/en-us/windows/) were changed from the unofficial [winapi](https://github.com/retep998/winapi-rs) bindings to the official Microsoft [windows-sys](https://github.com/microsoft/windows-rs) bindings.
+- On Wayland, fix polling during consecutive `EventLoop::run_return` invocations.
+- On Windows, fix race issue creating fullscreen windows with `WindowBuilder::with_fullscreen`
+- On Android, `virtual_keycode` for `KeyboardInput` events is now filled in where a suitable match is found.
+- Added helper methods on `ControlFlow` to set its value.
+- On Wayland, fix `TouchPhase::Ended` always reporting the location of the first touch down, unless the compositor
+ sent a cancel or frame event.
+- On iOS, send `RedrawEventsCleared` even if there are no redraw events, consistent with other platforms.
+- **Breaking:** Replaced `Window::with_app_id` and `Window::with_class` with `Window::with_name` on `WindowBuilderExtUnix`.
+- On Wayland, fallback CSD was replaced with proper one:
+ - `WindowBuilderExtUnix::with_wayland_csd_theme` to set color theme in builder.
+ - `WindowExtUnix::wayland_set_csd_theme` to set color theme when creating a window.
+ - `WINIT_WAYLAND_CSD_THEME` env variable was added, it can be used to set "dark"/"light" theme in apps that don't expose theme setting.
+ - `wayland-csd-adwaita` feature that enables proper CSD with title rendering using FreeType system library.
+ - `wayland-csd-adwaita-notitle` feature that enables CSD but without title rendering.
+- On Wayland and X11, fix window not resizing with `Window::set_inner_size` after calling `Window:set_resizable(false)`.
+- On Windows, fix wrong fullscreen monitors being recognized when handling WM_WINDOWPOSCHANGING messages
+- **Breaking:** Added new `WindowEvent::Ime` supported on desktop platforms.
+- Added `Window::set_ime_allowed` supported on desktop platforms.
+- **Breaking:** IME input on desktop platforms won't be received unless it's explicitly allowed via `Window::set_ime_allowed` and new `WindowEvent::Ime` events are handled.
+- On macOS, `WindowEvent::Resized` is now emitted in `frameDidChange` instead of `windowDidResize`.
+- **Breaking:** On X11, device events are now ignored for unfocused windows by default, use `EventLoopWindowTarget::set_device_event_filter` to set the filter level.
+- Implemented `Default` on `EventLoop<()>`.
+- Implemented `Eq` for `Fullscreen`, `Theme`, and `UserAttentionType`.
+- **Breaking:** `Window::set_cursor_grab` now accepts `CursorGrabMode` to control grabbing behavior.
+- On Wayland, add support for `Window::set_cursor_position`.
+- Fix on macOS `WindowBuilder::with_disallow_hidpi`, setting true or false by the user no matter the SO default value.
+- `EventLoopBuilder::build` will now panic when the `EventLoop` is being created more than once.
+- Added `From` for `WindowId` and `From` for `u64`.
+- Added `MonitorHandle::refresh_rate_millihertz` to get monitor's refresh rate.
+- **Breaking**, Replaced `VideoMode::refresh_rate` with `VideoMode::refresh_rate_millihertz` providing better precision.
+- On Web, add `with_prevent_default` and `with_focusable` to `WindowBuilderExtWebSys` to control whether events should be propagated.
+- On Windows, fix focus events being sent to inactive windows.
+- **Breaking**, update `raw-window-handle` to `v0.5` and implement `HasRawDisplayHandle` for `Window` and `EventLoopWindowTarget`.
+- On X11, add function `register_xlib_error_hook` into `winit::platform::unix` to subscribe for errors coming from Xlib.
+- On Android, upgrade `ndk` and `ndk-glue` dependencies to the recently released `0.7.0`.
+- All platforms can now be relied on to emit a `Resumed` event. Applications are recommended to lazily initialize graphics state and windows on first resume for portability.
+- **Breaking:**: Reverse horizontal scrolling sign in `MouseScrollDelta` to match the direction of vertical scrolling. A positive X value now means moving the content to the right. The meaning of vertical scrolling stays the same: a positive Y value means moving the content down.
+- On MacOS, fix deadlock when calling `set_maximized` from event loop.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.28.md b/third_party/winit-0.30.13/src/changelog/v0.28.md
new file mode 100644
index 0000000..a8b3262
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.28.md
@@ -0,0 +1,100 @@
+## 0.28.7
+
+- Fix window size sometimes being invalid when resizing on macOS 14 Sonoma.
+
+## 0.28.6
+
+- On macOS, fixed memory leak when getting monitor handle.
+- On macOS, fix `Backspace` being emitted when clearing preedit with it.
+
+## 0.28.5
+
+- On macOS, fix `key_up` being ignored when `Ime` is disabled.
+
+## 0.28.4
+
+- On macOS, fix empty marked text blocking regular input.
+- On macOS, fix potential panic when getting refresh rate.
+- On macOS, fix crash when calling `Window::set_ime_position` from another thread.
+
+## 0.28.3
+
+- Fix macOS memory leaks.
+
+## 0.28.2
+
+- Implement `HasRawDisplayHandle` for `EventLoop`.
+- On macOS, set resize increments only for live resizes.
+- On Wayland, fix rare crash on DPI change
+- Web: Added support for `Window::theme`.
+- On Wayland, fix rounding issues when doing resize.
+- On macOS, fix wrong focused state on startup.
+- On Windows, fix crash on setting taskbar when using Visual Studio debugger.
+- On macOS, resize simple fullscreen windows on windowDidChangeScreen events.
+
+## 0.28.1
+
+- On Wayland, fix crash when dropping a window in multi-window setup.
+
+## 0.28.0
+
+- On macOS, fixed `Ime::Commit` persisting for all input after interacting with `Ime`.
+- On macOS, added `WindowExtMacOS::option_as_alt` and `WindowExtMacOS::set_option_as_alt`.
+- On Windows, fix window size for maximized, undecorated windows.
+- On Windows and macOS, add `WindowBuilder::with_active`.
+- Add `Window::is_minimized`.
+- On X11, fix errors handled during `register_xlib_error_hook` invocation bleeding into winit.
+- Add `Window::has_focus`.
+- On Windows, fix `Window::set_minimized(false)` not working for windows minimized by `Win + D` hotkey.
+- **Breaking:** On Web, touch input no longer fires `WindowEvent::Cursor*`, `WindowEvent::MouseInput`, or `DeviceEvent::MouseMotion` like other platforms, but instead it fires `WindowEvent::Touch`.
+- **Breaking:** Removed platform specific `WindowBuilder::with_parent` API in favor of `WindowBuilder::with_parent_window`.
+- On Windows, retain `WS_MAXIMIZE` window style when un-minimizing a maximized window.
+- On Windows, fix left mouse button release event not being sent after `Window::drag_window`.
+- On macOS, run most actions on the main thread, which is strictly more correct, but might make multithreaded applications block slightly more.
+- On macOS, fix panic when getting current monitor without any monitor attached.
+- On Windows and MacOS, add API to enable/disable window buttons (close, minimize, ...etc).
+- On Windows, macOS, X11 and Wayland, add `Window::set_theme`.
+- **Breaking:** Remove `WindowExtWayland::wayland_set_csd_theme` and `WindowBuilderExtX11::with_gtk_theme_variant`.
+- On Windows, revert window background to an empty brush to avoid white flashes when changing scaling.
+- **Breaking:** Removed `Window::set_always_on_top` and related APIs in favor of `Window::set_window_level`.
+- On Windows, MacOS and X11, add always on bottom APIs.
+- On Windows, fix the value in `MouseButton::Other`.
+- On macOS, add `WindowExtMacOS::is_document_edited` and `WindowExtMacOS::set_document_edited` APIs.
+- **Breaking:** Removed `WindowBuilderExtIOS::with_root_view_class`; instead, you should use `[[view layer] addSublayer: ...]` to add an instance of the desired layer class (e.g. `CAEAGLLayer` or `CAMetalLayer`). See `vulkano-win` or `wgpu` for examples of this.
+- On MacOS and Windows, add `Window::set_content_protected`.
+- On MacOS, add `EventLoopBuilderExtMacOS::with_activate_ignoring_other_apps`.
+- On Windows, fix icons specified on `WindowBuilder` not taking effect for windows created after the first one.
+- On Windows and macOS, add `Window::title` to query the current window title.
+- On Windows, fix focusing menubar when pressing `Alt`.
+- On MacOS, made `accepts_first_mouse` configurable.
+- Migrated `WindowBuilderExtUnix::with_resize_increments` to `WindowBuilder`.
+- Added `Window::resize_increments`/`Window::set_resize_increments` to update resize increments at runtime for X11/macOS.
+- macOS/iOS: Use `objc2` instead of `objc` internally.
+- **Breaking:** Bump MSRV from `1.57` to `1.60`.
+- **Breaking:** Split the `platform::unix` module into `platform::x11` and `platform::wayland`. The extension types are similarly renamed.
+- **Breaking:**: Removed deprecated method `platform::unix::WindowExtUnix::is_ready`.
+- Removed `parking_lot` dependency.
+- **Breaking:** On macOS, add support for two-finger touchpad magnification and rotation gestures with new events `WindowEvent::TouchpadMagnify` and `WindowEvent::TouchpadRotate`. Also add support for touchpad smart-magnification gesture with a new event `WindowEvent::SmartMagnify`.
+- **Breaking:** On web, the `WindowBuilderExtWebSys::with_prevent_default` setting (enabled by default), now additionally prevents scrolling of the webpage in mobile browsers, previously it only disabled scrolling on desktop.
+- On Wayland, `wayland-csd-adwaita` now uses `ab_glyph` instead of `crossfont` to render the title for decorations.
+- On Wayland, a new `wayland-csd-adwaita-crossfont` feature was added to use `crossfont` instead of `ab_glyph` for decorations.
+- On Wayland, if not otherwise specified use upstream automatic CSD theme selection.
+- On X11, added `WindowExtX11::with_parent` to create child windows.
+- Added support for `WindowBuilder::with_theme` and `Window::theme` to support per-window dark/light/system theme configuration on macos, windows and wayland.
+- On macOS, added support for `WindowEvent::ThemeChanged`.
+- **Breaking:** Removed `WindowBuilderExtWindows::with_theme` and `WindowBuilderExtWayland::with_wayland_csd_theme` in favour of `WindowBuilder::with_theme`.
+- **Breaking:** Removed `WindowExtWindows::theme` in favour of `Window::theme`.
+- Enabled `doc_auto_cfg` when generating docs on docs.rs for feature labels.
+- **Breaking:** On Android, switched to using [`android-activity`](https://github.com/rib/android-activity) crate as a glue layer instead of [`ndk-glue`](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue). See [README.md#Android](https://github.com/rust-windowing/winit#Android) for more details. ([#2444](https://github.com/rust-windowing/winit/pull/2444))
+- **Breaking:** Removed support for `raw-window-handle` version `0.4`
+- On Wayland, `RedrawRequested` not emitted during resize.
+- Add a `set_wait_timeout` function to `ControlFlow` to allow waiting for a `Duration`.
+- **Breaking:** Remove the unstable `xlib_xconnection()` function from the private interface.
+- Added Orbital support for Redox OS
+- On X11, added `drag_resize_window` method.
+- Added `Window::set_transparent` to provide a hint about transparency of the window on Wayland and macOS.
+- On macOS, fix the mouse buttons other than left/right/middle being reported as middle.
+- On Wayland, support fractional scaling via the wp-fractional-scale protocol.
+- On web, fix removal of mouse event listeners from the global object upon window destruction.
+- Add WindowAttributes getter to WindowBuilder to allow introspection of default values.
+- Added `Window::set_ime_purpose` for setting the IME purpose, currently implemented on Wayland only.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.29.md b/third_party/winit-0.30.13/src/changelog/v0.29.md
new file mode 100644
index 0000000..fc17f17
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.29.md
@@ -0,0 +1,289 @@
+## 0.29.15
+
+- On X11, fix crash due to xsettings query on systems with incomplete xsettings.
+
+## 0.29.14
+
+- On X11/Wayland, fix `text` and `text_with_all_modifiers` not being `None` during compose.
+- On Wayland, don't reapply cursor grab when unchanged.
+- On X11, fix a bug where some mouse events would be unexpectedly filtered out.
+
+## 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
+
+- Fix compatibility with 32-bit platforms without 64-bit atomics.
+- On macOS, fix incorrect IME cursor rect origin.
+- On Windows, fixed a race condition when sending an event through the loop proxy.
+- On X11, fix swapped instance and general class names.
+- On X11, don't require XIM to run.
+- On X11, fix xkb state not being updated correctly sometimes leading to wrong input.
+- On X11, reload dpi on `_XSETTINGS_SETTINGS` update.
+- On X11, fix deadlock when adjusting DPI and resizing at the same time.
+- On Wayland, disable `Occluded` event handling.
+- On Wayland, fix DeviceEvent::Motion not being sent
+- On Wayland, fix `Focused(false)` being send when other seats still have window focused.
+- On Wayland, fix `Window::set_{min,max}_inner_size` not always applied.
+- On Wayland, fix title in CSD not updated from `AboutToWait`.
+- On Windows, fix inconsistent resizing behavior with multi-monitor setups when repositioning outside the event loop.
+- On Wayland, fix `WAYLAND_SOCKET` not used when detecting platform.
+- On Orbital, fix `logical_key` and `text` not reported in `KeyEvent`.
+- On Orbital, implement `KeyEventExtModifierSupplement`.
+- On Orbital, map keys to `NamedKey` when possible.
+- On Orbital, implement `set_cursor_grab`.
+- On Orbital, implement `set_cursor_visible`.
+- On Orbital, implement `drag_window`.
+- On Orbital, implement `drag_resize_window`.
+- On Orbital, implement `set_transparent`.
+- On Orbital, implement `set_visible`.
+- On Orbital, implement `is_visible`.
+- On Orbital, implement `set_resizable`.
+- On Orbital, implement `is_resizable`.
+- On Orbital, implement `set_maximized`.
+- On Orbital, implement `is_maximized`.
+- On Orbital, implement `set_decorations`.
+- On Orbital, implement `is_decorated`.
+- On Orbital, implement `set_window_level`.
+- On Orbital, emit `DeviceEvent::MouseMotion`.
+
+## 0.29.10
+
+- On Web, account for canvas being focused already before event loop starts.
+- On Web, increase cursor position accuracy.
+
+## 0.29.9
+
+- On X11, fix `NotSupported` error not propagated when creating event loop.
+- On Wayland, fix resize not issued when scale changes
+- On X11 and Wayland, fix arrow up on keypad reported as `ArrowLeft`.
+- On macOS, report correct logical key when Ctrl or Cmd is pressed.
+
+## 0.29.8
+
+- On X11, fix IME input lagging behind.
+- On X11, fix `ModifiersChanged` not sent from xdotool-like input
+- On X11, fix keymap not updated from xmodmap.
+- On X11, reduce the amount of time spent fetching screen resources.
+- On Wayland, fix `Window::request_inner_size` being overwritten by resize.
+- On Wayland, fix `Window::inner_size` not using the correct rounding.
+
+## 0.29.7
+
+- On X11, fix `Xft.dpi` reload during runtime.
+- On X11, fix window minimize.
+
+## 0.29.6
+
+- On Web, fix context menu not being disabled by `with_prevent_default(true)`.
+- On Wayland, fix `WindowEvent::Destroyed` not being delivered after destroying window.
+- Fix `EventLoopExtRunOnDemand::run_on_demand` not working for consequent invocation
+
+## 0.29.5
+
+- On macOS, remove spurious error logging when handling `Fn`.
+- On X11, fix an issue where floating point data from the server is
+ misinterpreted during a drag and drop operation.
+- On X11, fix a bug where focusing the window would panic.
+- On macOS, fix `refresh_rate_millihertz`.
+- On Wayland, disable Client Side Decorations when `wl_subcompositor` is not supported.
+- On X11, fix `Xft.dpi` detection from Xresources.
+- On Windows, fix consecutive calls to `window.set_fullscreen(Some(Fullscreen::Borderless(None)))` resulting in losing previous window state when eventually exiting fullscreen using `window.set_fullscreen(None)`.
+- On Wayland, fix resize being sent on focus change.
+- On Windows, fix `set_ime_cursor_area`.
+
+## 0.29.4
+
+- Fix crash when running iOS app on macOS.
+- On X11, check common alternative cursor names when loading cursor.
+- On X11, reload the DPI after a property change event.
+- On Windows, fix so `drag_window` and `drag_resize_window` can be called from another thread.
+- On Windows, fix `set_control_flow` in `AboutToWait` not being taken in account.
+- On macOS, send a `Resized` event after each `ScaleFactorChanged` event.
+- On Wayland, fix `wl_surface` being destroyed before associated objects.
+- On macOS, fix assertion when pressing `Fn` key.
+- On Windows, add `WindowBuilderExtWindows::with_clip_children` to control `WS_CLIPCHILDREN` style.
+
+## 0.29.3
+
+- On Wayland, apply correct scale to `PhysicalSize` passed in `WindowBuilder::with_inner_size` when possible.
+- On Wayland, fix `RedrawRequested` being always sent without decorations and `sctk-adwaita` feature.
+- On Wayland, ignore resize requests when the window is fully tiled.
+- On Wayland, use `configure_bounds` to constrain `with_inner_size` when compositor wants users to pick size.
+- On Windows, fix deadlock when accessing the state during `Cursor{Enter,Leave}`.
+- On Windows, add support for `Window::set_transparent`.
+- On macOS, fix deadlock when entering a nested event loop from an event handler.
+- On macOS, add support for `Window::set_blur`.
+
+## 0.29.2
+
+- **Breaking:** Bump MSRV from `1.60` to `1.65`.
+- **Breaking:** Add `Event::MemoryWarning`; implemented on iOS/Android.
+- **Breaking:** Bump `ndk` version to `0.8.0`, ndk-sys to `0.5.0`, `android-activity` to `0.5.0`.
+- **Breaking:** Change default `ControlFlow` from `Poll` to `Wait`.
+- **Breaking:** Move `Event::RedrawRequested` to `WindowEvent::RedrawRequested`.
+- **Breaking:** Moved `ControlFlow::Exit` to `EventLoopWindowTarget::exit()` and `EventLoopWindowTarget::exiting()` and removed `ControlFlow::ExitWithCode(_)` entirely.
+- **Breaking:** Moved `ControlFlow` to `EventLoopWindowTarget::set_control_flow()` and `EventLoopWindowTarget::control_flow()`.
+- **Breaking:** `EventLoop::new` and `EventLoopBuilder::build` now return `Result`
+- **Breaking:** `WINIT_UNIX_BACKEND` was removed in favor of standard `WAYLAND_DISPLAY` and `DISPLAY` variables.
+- **Breaking:** on Wayland, dispatching user created Wayland queue won't wake up the loop unless winit has event to send back.
+- **Breaking:** remove `DeviceEvent::Text`.
+- **Breaking:** Remove lifetime parameter from `Event` and `WindowEvent`.
+- **Breaking:** Rename `Window::set_inner_size` to `Window::request_inner_size` and indicate if the size was applied immediately.
+- **Breaking:** `ActivationTokenDone` event which could be requested with the new `startup_notify` module, see its docs for more.
+- **Breaking:** `ScaleFactorChanged` now contains a writer instead of a reference to update inner size.
+- **Breaking** `run() -> !` has been replaced by `run() -> Result<(), EventLoopError>` for returning errors without calling `std::process::exit()` ([#2767](https://github.com/rust-windowing/winit/pull/2767))
+- **Breaking** Removed `EventLoopExtRunReturn` / `run_return` in favor of `EventLoopExtPumpEvents` / `pump_events` and `EventLoopExtRunOnDemand` / `run_on_demand` ([#2767](https://github.com/rust-windowing/winit/pull/2767))
+- `RedrawRequested` is no longer guaranteed to be emitted after `MainEventsCleared`, it is now platform-specific when the event is emitted after being requested via `redraw_request()`.
+ - On Windows, `RedrawRequested` is now driven by `WM_PAINT` messages which are requested via `redraw_request()`
+- **Breaking** `LoopDestroyed` renamed to `LoopExiting` ([#2900](https://github.com/rust-windowing/winit/issues/2900))
+- **Breaking** `RedrawEventsCleared` removed ([#2900](https://github.com/rust-windowing/winit/issues/2900))
+- **Breaking** `MainEventsCleared` removed ([#2900](https://github.com/rust-windowing/winit/issues/2900))
+- **Breaking:** Remove all deprecated `modifiers` fields.
+- **Breaking:** Rename `DeviceEventFilter` to `DeviceEvents` reversing the behavior of variants.
+- **Breaking** Add `AboutToWait` event which is emitted when the event loop is about to block and wait for new events ([#2900](https://github.com/rust-windowing/winit/issues/2900))
+- **Breaking:** Rename `EventLoopWindowTarget::set_device_event_filter` to `listen_device_events`.
+- **Breaking:** Rename `Window::set_ime_position` to `Window::set_ime_cursor_area` adding a way to set exclusive zone.
+- **Breaking:** `with_x11_visual` now takes the visual ID instead of the bare pointer.
+- **Breaking** `MouseButton` now supports `Back` and `Forward` variants, emitted from mouse events on Wayland, X11, Windows, macOS and Web.
+- **Breaking:** On Web, `instant` is now replaced by `web_time`.
+- **Breaking:** On Web, dropped support for Safari versions below 13.1.
+- **Breaking:** On Web, the canvas output bitmap size is no longer adjusted.
+- **Breaking:** On Web, the canvas size is not controlled by Winit anymore and external changes to the canvas size will be reported through `WindowEvent::Resized`.
+- **Breaking:** Updated `bitflags` crate version to `2`, which changes the API on exposed types.
+- **Breaking:** `CursorIcon::Arrow` was removed.
+- **Breaking:** `CursorIcon::Hand` is now named `CursorIcon::Pointer`.
+- **Breaking:** `CursorIcon` is now used from the `cursor-icon` crate.
+- **Breaking:** `WindowExtWebSys::canvas()` now returns an `Option`.
+- **Breaking:** Overhaul keyboard input handling.
+ - Replace `KeyboardInput` with `KeyEvent` and `RawKeyEvent`.
+ - Change `WindowEvent::KeyboardInput` to contain a `KeyEvent`.
+ - Change `Event::Key` to contain a `RawKeyEvent`.
+ - Remove `Event::ReceivedCharacter`. In its place, you should use
+ `KeyEvent.text` in combination with `WindowEvent::Ime`.
+ - Replace `VirtualKeyCode` with the `Key` enum.
+ - Replace `ScanCode` with the `KeyCode` enum.
+ - Rename `ModifiersState::LOGO` to `SUPER` and `ModifiersState::CTRL` to `CONTROL`.
+ - Add `PhysicalKey` wrapping `KeyCode` and `NativeKeyCode`.
+ - Add `KeyCode` to refer to keys (roughly) by their physical location.
+ - Add `NativeKeyCode` to represent raw `KeyCode`s which Winit doesn't
+ understand.
+ - Add `Key` to represent the keys after they've been interpreted by the
+ active (software) keyboard layout.
+ - Add `NamedKey` to represent the categorized keys.
+ - Add `NativeKey` to represent raw `Key`s which Winit doesn't understand.
+ - Add `KeyLocation` to tell apart `Key`s which usually "mean" the same thing,
+ but can appear simultaneously in different spots on the same keyboard
+ layout.
+ - Add `Window::reset_dead_keys` to enable application-controlled cancellation
+ of dead key sequences.
+ - Add `KeyEventExtModifierSupplement` to expose additional (and less
+ portable) interpretations of a given key-press.
+ - Add `PhysicalKeyExtScancode`, which lets you convert between scancodes and
+ `PhysicalKey`.
+ - `ModifiersChanged` now uses dedicated `Modifiers` struct.
+- Removed platform-specific extensions that should be retrieved through `raw-window-handle` trait implementations instead:
+ - `platform::windows::HINSTANCE`.
+ - `WindowExtWindows::hinstance`.
+ - `WindowExtWindows::hwnd`.
+ - `WindowExtIOS::ui_window`.
+ - `WindowExtIOS::ui_view_controller`.
+ - `WindowExtIOS::ui_view`.
+ - `WindowExtMacOS::ns_window`.
+ - `WindowExtMacOS::ns_view`.
+ - `EventLoopWindowTargetExtWayland::wayland_display`.
+ - `WindowExtWayland::wayland_surface`.
+ - `WindowExtWayland::wayland_display`.
+ - `WindowExtX11::xlib_window`.
+ - `WindowExtX11::xlib_display`.
+ - `WindowExtX11::xlib_screen_id`.
+ - `WindowExtX11::xcb_connection`.
+- Reexport `raw-window-handle` in `window` module.
+- Add `ElementState::is_pressed`.
+- Add `Window::pre_present_notify` to notify winit before presenting to the windowing system.
+- Add `Window::set_blur` to request a blur behind the window; implemented on Wayland for now.
+- Add `Window::show_window_menu` to request a titlebar/system menu; implemented on Wayland/Windows for now.
+- Implement `AsFd`/`AsRawFd` for `EventLoop` on X11 and Wayland.
+- Implement `PartialOrd` and `Ord` for `MouseButton`.
+- Implement `PartialOrd` and `Ord` on types in the `dpi` module.
+- Make `WindowBuilder` `Send + Sync`.
+- Make iOS `MonitorHandle` and `VideoMode` usable from other threads.
+- Make iOS windows usable from other threads.
+- On Android, add force data to touch events.
+- On Android, added `EventLoopBuilderExtAndroid::handle_volume_keys` to indicate that the application will handle the volume keys manually.
+- On Android, fix `DeviceId` to contain device id's.
+- On Orbital, fix `ModifiersChanged` not being sent.
+- On Wayland, `Window::outer_size` now accounts for **client side** decorations.
+- On Wayland, add `Window::drag_resize_window` method.
+- On Wayland, remove `WINIT_WAYLAND_CSD_THEME` variable.
+- On Wayland, fix `TouchPhase::Canceled` being sent for moved events.
+- On Wayland, fix forward compatibility issues.
+- On Wayland, fix initial window size not restored for maximized/fullscreened on startup window.
+- On Wayland, fix maximized startup not taking full size on GNOME.
+- On Wayland, fix maximized window creation and window geometry handling.
+- On Wayland, fix window not checking that it actually got initial configure event.
+- On Wayland, make double clicking and moving the CSD frame more reliable.
+- On Wayland, support `Occluded` event with xdg-shell v6
+- On Wayland, use frame callbacks to throttle `RedrawRequested` events so redraws will align with compositor.
+- On Web, `ControlFlow::WaitUntil` now uses the Prioritized Task Scheduling API. `setTimeout()`, with a trick to circumvent throttling to 4ms, is used as a fallback.
+- On Web, `EventLoopProxy` now implements `Send`.
+- On Web, `Window` now implements `Send` and `Sync`.
+- On Web, account for CSS `padding`, `border`, and `margin` when getting or setting the canvas position.
+- On Web, add Fullscreen API compatibility for Safari.
+- On Web, add `DeviceEvent::Motion`, `DeviceEvent::MouseWheel`, `DeviceEvent::Button` and `DeviceEvent::Key` support.
+- On Web, add `EventLoopWindowTargetExtWebSys` and `PollStrategy`, which allows to set different strategies for `ControlFlow::Poll`. By default the Prioritized Task Scheduling API is used, but an option to use `Window.requestIdleCallback` is available as well. Both use `setTimeout()`, with a trick to circumvent throttling to 4ms, as a fallback.
+- On Web, add `WindowBuilderExtWebSys::with_append()` to append the canvas element to the web page on creation.
+- On Web, allow event loops to be recreated with `spawn`.
+- On Web, enable event propagation.
+- On Web, fix `ControlFlow::WaitUntil` to never wake up **before** the given time.
+- On Web, fix `DeviceEvent::MouseMotion` only being emitted for each canvas instead of the whole window.
+- On Web, fix `Window:::set_fullscreen` doing nothing when called outside the event loop but during transient activation.
+- On Web, fix pen treated as mouse input.
+- On Web, fix pointer button events not being processed when a buttons is already pressed.
+- On Web, fix scale factor resize suggestion always overwriting the canvas size.
+- On Web, fix some `WindowBuilder` methods doing nothing.
+- On Web, fix some `Window` methods using incorrect HTML attributes instead of CSS properties.
+- On Web, fix the bfcache by not using the `beforeunload` event and map bfcache loading/unloading to `Suspended`/`Resumed` events.
+- On Web, fix touch input not gaining or losing focus.
+- On Web, fix touch location to be as accurate as mouse position.
+- On Web, handle coalesced pointer events, which increases the resolution of pointer inputs.
+- On Web, implement `Window::focus_window()`.
+- On Web, implement `Window::set_(min|max)_inner_size()`.
+- On Web, implement `WindowEvent::Occluded`.
+- On Web, never return a `MonitorHandle`.
+- On Web, prevent clicks on the canvas to select text.
+- On Web, remove any fullscreen requests from the queue when an external fullscreen activation was detected.
+- On Web, remove unnecessary `Window::is_dark_mode()`, which was replaced with `Window::theme()`.
+- On Web, respect `EventLoopWindowTarget::listen_device_events()` settings.
+- On Web, scale factor and dark mode detection are now more robust.
+- On Web, send mouse position on button release as well.
+- On Web, take all transient activations on the canvas and window into account to queue a fullscreen request.
+- On Web, use `Window.requestAnimationFrame()` to throttle `RedrawRequested` events.
+- On Web, use the correct canvas size when calculating the new size during scale factor change, instead of using the output bitmap size.
+- On Web: fix `Window::request_redraw` not waking the event loop when called from outside the loop.
+- On Web: fix position of touch events to be relative to the canvas.
+- On Windows, add `drag_resize_window` method support.
+- On Windows, add horizontal MouseWheel `DeviceEvent`.
+- On Windows, added `WindowBuilderExtWindows::with_class_name` to customize the internal class name.
+- On Windows, fix IME APIs not working when from non event loop thread.
+- On Windows, fix `CursorEnter/Left` not being sent when grabbing the mouse.
+- On Windows, fix `RedrawRequested` not being delivered when calling `Window::request_redraw` from `RedrawRequested`.
+- On Windows, port to `windows-sys` version 0.48.0.
+- On X11, add a `with_embedded_parent_window` function to the window builder to allow embedding a window into another window.
+- On X11, fix event loop not waking up on `ControlFlow::Poll` and `ControlFlow::WaitUntil`.
+- On X11, fix false positive flagging of key repeats when pressing different keys with no release between presses.
+- On X11, set `visual_id` in returned `raw-window-handle`.
+- On iOS, add ability to change the status bar style.
+- On iOS, add force data to touch events when using the Apple Pencil.
+- On iOS, always wake the event loop when transitioning from `ControlFlow::Poll` to `ControlFlow::Poll`.
+- On iOS, send events `WindowEvent::Occluded(false)`, `WindowEvent::Occluded(true)` when application enters/leaves foreground.
+- On macOS, add tabbing APIs on `WindowExtMacOS` and `EventLoopWindowTargetExtMacOS`.
+- On macOS, fix assertion when pressing `Globe` key.
+- On macOS, fix crash in `window.set_minimized(false)`.
+- On macOS, fix crash when dropping `Window`.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.30.md b/third_party/winit-0.30.13/src/changelog/v0.30.md
new file mode 100644
index 0000000..6b0b47d
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.30.md
@@ -0,0 +1,413 @@
+## 0.30.13
+
+### Added
+
+- On Wayland, add `Window::set_resize_increments`.
+
+### Fixed
+
+- On macOS, fixed crash when dragging non-file content onto window.
+- On X11, fix `set_hittest` not working on some window managers.
+- On X11, fix debug mode overflow panic in `set_timestamp`.
+- On macOS, fix crash in `set_marked_text` when native Pinyin IME sends out-of-bounds `selected_range`.
+- On Windows, fix `WM_IME_SETCONTEXT` IME UI flag masking on `lParam`.
+- On Android, populate `KeyEvent::text` and `KeyEvent::text_with_all_modifiers` via `Key::to_text()`.
+
+## 0.30.12
+
+### Fixed
+
+- On macOS, fix crash on macOS 26 by using objc2's `relax-sign-encoding` feature.
+
+## 0.30.11
+
+### Fixed
+
+- On Windows, fixed crash in should_apps_use_dark_mode() for Windows versions < 17763.
+- On Wayland, fixed `pump_events` driven loop deadlocking when loop was not drained before exit.
+
+## 0.30.10
+
+### Added
+
+- On Windows, add `IconExtWindows::from_resource_name`.
+- On Windows, add `CursorGrabMode::Locked`.
+- On Wayland, add `WindowExtWayland::xdg_toplevel`.
+
+### Changed
+
+- On macOS, no longer need control of the main `NSApplication` class (which means you can now override it yourself).
+- On iOS, remove custom application delegates. You are now allowed to override the
+ application delegate yourself.
+- On iOS, no longer act as-if the application successfully open all URLs. Override
+ `application:didFinishLaunchingWithOptions:` and provide the desired behaviour yourself.
+
+### Fixed
+
+- On Windows, fixed ~500 ms pause when clicking the title bar during continuous redraw.
+- On macOS, `WindowExtMacOS::set_simple_fullscreen` now honors `WindowExtMacOS::set_borderless_game`
+- On X11 and Wayland, fixed pump_events with `Some(Duration::Zero)` blocking with `Wait` polling mode
+- On Wayland, fixed a crash when consequently calling `set_cursor_grab` without pointer focus.
+- On Wayland, ensure that external event loop is woken-up when using pump_events and integrating via `FD`.
+- On Wayland, apply fractional scaling to custom cursors.
+- On macOS, fixed `run_app_on_demand` returning without closing open windows.
+- On macOS, fixed `VideoMode::refresh_rate_millihertz` for fractional refresh rates.
+- On macOS, store monitor handle to avoid panics after going in/out of sleep.
+- On macOS, allow certain invalid monitor handles and return `None` instead of panicking.
+- On Windows, fixed `Ime::Preedit` cursor offset calculation.
+
+## 0.30.9
+
+### Changed
+
+- On Wayland, no longer send an explicit clearing `Ime::Preedit` just prior to a new `Ime::Preedit`.
+
+### Fixed
+
+- On X11, fix crash with uim.
+- On X11, fix modifiers for keys that were sent by the same X11 request.
+- On iOS, fix high CPU usage even when using `ControlFlow::Wait`.
+
+## 0.30.8
+
+### Added
+
+- `ActivationToken::from_raw` and `ActivationToken::into_raw`.
+- On X11, add a workaround for disabling IME on GNOME.
+
+### Fixed
+
+- On Windows, fixed the event loop not waking on accessibility requests.
+- On X11, fixed cursor grab mode state tracking on error.
+
+## 0.30.7
+
+### Fixed
+
+- On X11, fixed KeyboardInput delivered twice when IME enabled.
+
+## 0.30.6
+
+### Added
+
+- On macOS, add `WindowExtMacOS::set_borderless_game` and `WindowAttributesExtMacOS::with_borderless_game`
+ to fully disable the menu bar and dock in Borderless Fullscreen as commonly done in games.
+- On X11, the `window` example now understands the `X11_VISUAL_ID` and `X11_SCREEN_ID` env
+ variables to test the respective modifiers of window creation.
+- On Android, the soft keyboard can now be shown using `Window::set_ime_allowed`.
+- Add basic iOS IME support. The soft keyboard can now be shown using `Window::set_ime_allowed`.
+
+### Fixed
+
+- On macOS, fix `WindowEvent::Moved` sometimes being triggered unnecessarily on resize.
+- On macOS, package manifest definitions of `LSUIElement` will no longer be overridden with the
+ default activation policy, unless explicitly provided during initialization.
+- On macOS, fix crash when calling `drag_window()` without a left click present.
+- On X11, key events forward to IME anyway, even when it's disabled.
+- On Windows, make `ControlFlow::WaitUntil` work more precisely using `CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`.
+- On X11, creating windows on screen that is not the first one (e.g. `DISPLAY=:0.1`) works again.
+- On X11, creating windows while passing `with_x11_screen(non_default_screen)` works again.
+- On X11, fix XInput handling that prevented a new window from getting the focus in some cases.
+- On macOS, fix crash when pressing Caps Lock in certain configurations.
+- On iOS, fixed `MonitorHandle`'s `PartialEq` and `Hash` implementations.
+- On macOS, fixed undocumented cursors (e.g. zoom, resize, help) always appearing to be invalid and falling back to the default cursor.
+
+## 0.30.5
+
+### Added
+
+- Add `ActiveEventLoop::system_theme()`, returning the current system theme.
+- On Web, implement `Error` for `platform::web::CustomCursorError`.
+- On Android, add `{Active,}EventLoopExtAndroid::android_app()` to access the app used to create the loop.
+
+### Fixed
+
+- On MacOS, fix building with `feature = "rwh_04"`.
+- On Web, pen events are now routed through to `WindowEvent::Cursor*`.
+- On macOS, fix panic when releasing not available monitor.
+- On MacOS, return the system theme in `Window::theme()` if no theme override is set.
+
+## 0.30.4
+
+### Changed
+
+- `DeviceId::dummy()` and `WindowId::dummy()` are no longer marked `unsafe`.
+
+### Fixed
+
+- On Wayland, avoid crashing when compositor is misbehaving.
+- On Web, fix `WindowEvent::Resized` not using `requestAnimationFrame` when sending
+ `WindowEvent::RedrawRequested` and also potentially causing `WindowEvent::RedrawRequested`
+ to not be de-duplicated.
+- Account for different browser engine implementations of pointer movement coordinate space.
+
+## 0.30.3
+
+### Added
+
+- On Web, add `EventLoopExtWebSys::(set_)poll_strategy()` to allow setting
+ control flow strategies before starting the event loop.
+- On Web, add `WaitUntilStrategy`, which allows to set different strategies for
+ `ControlFlow::WaitUntil`. By default the Prioritized Task Scheduling API is
+ used, with a fallback to `setTimeout()` with a trick to circumvent throttling
+ to 4ms. But an option to use a Web worker to schedule the timer is available
+ as well, which commonly prevents any throttling when the window is not focused.
+
+### Changed
+
+- On macOS, set the window theme on the `NSWindow` instead of application-wide.
+
+### Fixed
+
+- On X11, build on arm platforms.
+- On macOS, fixed `WindowBuilder::with_theme` not having any effect on the window.
+
+## 0.30.2
+
+### Fixed
+
+- On Web, fix `EventLoopProxy::send_event()` triggering event loop immediately
+ when not called from inside the event loop. Now queues a microtask instead.
+- On Web, stop overwriting default cursor with `CursorIcon::Default`.
+- On Web, prevent crash when using `InnerSizeWriter::request_inner_size()`.
+- On macOS, fix not working opacity for entire window.
+
+## 0.30.1
+
+### Added
+
+- Reexport `raw-window-handle` versions 0.4 and 0.5 as `raw_window_handle_04` and `raw_window_handle_05`.
+- Implement `ApplicationHandler` for `&mut` references and heap allocations to something that implements `ApplicationHandler`.
+
+### Fixed
+
+- On macOS, fix panic on exit when dropping windows outside the event loop.
+- On macOS, fix window dragging glitches when dragging across a monitor boundary with different scale factor.
+- On macOS, fix the range in `Ime::Preedit`.
+- On macOS, use the system's internal mechanisms for queuing events.
+- On macOS, handle events directly instead of queuing when possible.
+
+## 0.30.0
+
+### Added
+
+- Add `OwnedDisplayHandle` type for allowing safe display handle usage outside of
+ trivial cases.
+- Add `ApplicationHandler` trait which mimics `Event`.
+- Add `WindowBuilder::with_cursor` and `Window::set_cursor` which takes a
+ `CursorIcon` or `CustomCursor`.
+- Add `Sync` implementation for `EventLoopProxy`.
+- Add `Window::default_attributes` to get default `WindowAttributes`.
+- Add `EventLoop::builder` to get `EventLoopBuilder` without export.
+- Add `CustomCursor::from_rgba` to allow creating cursor images from RGBA data.
+- Add `CustomCursorExtWebSys::from_url` to allow loading cursor images from URLs.
+- Add `CustomCursorExtWebSys::from_animation` to allow creating animated
+ cursors from other `CustomCursor`s.
+- Add `{Active,}EventLoop::create_custom_cursor` to load custom cursor image sources.
+- Add `ActiveEventLoop::create_window` and `EventLoop::create_window`.
+- Add `CustomCursor` which could be set via `Window::set_cursor`, implemented on
+ Windows, macOS, X11, Wayland, and Web.
+- On Web, add to toggle calling `Event.preventDefault()` on `Window`.
+- On iOS, add `PinchGesture`, `DoubleTapGesture`, `PanGesture` and `RotationGesture`.
+- on iOS, use `UIGestureRecognizerDelegate` for fine grained control of gesture recognizers.
+- On macOS, add services menu.
+- On Windows, add `with_title_text_color`, and `with_corner_preference` on
+ `WindowAttributesExtWindows`.
+- On Windows, implement resize increments.
+- On Windows, add `AnyThread` API to access window handle off the main thread.
+
+### Changed
+
+- Bump MSRV from `1.65` to `1.70`.
+- On Wayland, bump `sctk-adwaita` to `0.9.0`, which changed system library
+ crates. This change is a **cascading breaking change**, you must do breaking
+ change as well, even if you don't expose winit.
+- Rename `TouchpadMagnify` to `PinchGesture`.
+- Rename `SmartMagnify` to `DoubleTapGesture`.
+- Rename `TouchpadRotate` to `RotationGesture`.
+- Rename `EventLoopWindowTarget` to `ActiveEventLoop`.
+- Rename `platform::x11::XWindowType` to `platform::x11::WindowType`.
+- Rename `VideoMode` to `VideoModeHandle` to represent that it doesn't hold
+ static data.
+- Make `Debug` formatting of `WindowId` more concise.
+- Move `dpi` types to its own crate, and re-export it from the root crate.
+- Replace `log` with `tracing`, use `log` feature on `tracing` to restore old
+ behavior.
+- `EventLoop::with_user_event` now returns `EventLoopBuilder`.
+- On Web, return `HandleError::Unavailable` when a window handle is not available.
+- On Web, return `RawWindowHandle::WebCanvas` instead of `RawWindowHandle::Web`.
+- On Web, remove queuing fullscreen request in absence of transient activation.
+- On iOS, return `HandleError::Unavailable` when a window handle is not available.
+- On macOS, return `HandleError::Unavailable` when a window handle is not available.
+- On Windows, remove `WS_CAPTION`, `WS_BORDER`, and `WS_EX_WINDOWEDGE` styles
+ for child windows without decorations.
+- On Android, bump `ndk` to `0.9.0` and `android-activity` to `0.6.0`,
+ and remove unused direct dependency on `ndk-sys`.
+
+### Deprecated
+
+- Deprecate `EventLoop::run`, use `EventLoop::run_app`.
+- Deprecate `EventLoopExtRunOnDemand::run_on_demand`, use `EventLoop::run_app_on_demand`.
+- Deprecate `EventLoopExtPumpEvents::pump_events`, use `EventLoopExtPumpEvents::pump_app_events`.
+
+ The new `app` APIs accept a newly added `ApplicationHandler` instead of
+ `Fn`. The semantics are mostly the same, given that the capture list of the
+ closure is your new `State`. Consider the following code:
+
+ ```rust,no_run
+ use winit::event::Event;
+ use winit::event_loop::EventLoop;
+ use winit::window::Window;
+
+ struct MyUserEvent;
+
+ let event_loop = EventLoop::::with_user_event().build().unwrap();
+ let window = event_loop.create_window(Window::default_attributes()).unwrap();
+ let mut counter = 0;
+
+ let _ = event_loop.run(move |event, event_loop| {
+ match event {
+ Event::AboutToWait => {
+ window.request_redraw();
+ counter += 1;
+ }
+ Event::WindowEvent { window_id, event } => {
+ // Handle window event.
+ }
+ Event::UserEvent(event) => {
+ // Handle user event.
+ }
+ Event::DeviceEvent { device_id, event } => {
+ // Handle device event.
+ }
+ _ => (),
+ }
+ });
+ ```
+
+ To migrate this code, you should move all the captured values into some
+ newtype `State` and implement `ApplicationHandler` for this type. Finally,
+ we move particular `match event` arms into methods on `ApplicationHandler`,
+ for example:
+
+ ```rust,no_run
+ use winit::application::ApplicationHandler;
+ use winit::event::{Event, WindowEvent, DeviceEvent, DeviceId};
+ use winit::event_loop::{EventLoop, ActiveEventLoop};
+ use winit::window::{Window, WindowId};
+
+ struct MyUserEvent;
+
+ struct State {
+ window: Window,
+ counter: i32,
+ }
+
+ impl ApplicationHandler for State {
+ fn user_event(&mut self, event_loop: &ActiveEventLoop, user_event: MyUserEvent) {
+ // Handle user event.
+ }
+
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ // Your application got resumed.
+ }
+
+ fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) {
+ // Handle window event.
+ }
+
+ fn device_event(&mut self, event_loop: &ActiveEventLoop, device_id: DeviceId, event: DeviceEvent) {
+ // Handle device event.
+ }
+
+ fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ self.window.request_redraw();
+ self.counter += 1;
+ }
+ }
+
+ let event_loop = EventLoop::::with_user_event().build().unwrap();
+ #[allow(deprecated)]
+ let window = event_loop.create_window(Window::default_attributes()).unwrap();
+ let mut state = State { window, counter: 0 };
+
+ let _ = event_loop.run_app(&mut state);
+ ```
+
+ Please submit your feedback after migrating in [this issue](https://github.com/rust-windowing/winit/issues/3626).
+
+- Deprecate `Window::set_cursor_icon`, use `Window::set_cursor`.
+
+### Removed
+
+- Remove `Window::new`, use `ActiveEventLoop::create_window` instead.
+
+ You now have to create your windows inside the actively running event loop
+ (usually the `new_events(cause: StartCause::Init)` or `resumed()` events),
+ and can no longer do it before the application has properly launched.
+ This change is done to fix many long-standing issues on iOS and macOS, and
+ will improve things on Wayland once fully implemented.
+
+ To ease migration, we provide the deprecated `EventLoop::create_window` that
+ will allow you to bypass this restriction in this release.
+
+ Using the migration example from above, you can change your code as follows:
+
+ ```rust,no_run
+ use winit::application::ApplicationHandler;
+ use winit::event::{Event, WindowEvent, DeviceEvent, DeviceId};
+ use winit::event_loop::{EventLoop, ActiveEventLoop};
+ use winit::window::{Window, WindowId};
+
+ #[derive(Default)]
+ struct State {
+ // Use an `Option` to allow the window to not be available until the
+ // application is properly running.
+ window: Option,
+ counter: i32,
+ }
+
+ impl ApplicationHandler for State {
+ // This is a common indicator that you can create a window.
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap());
+ }
+ fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) {
+ // `unwrap` is fine, the window will always be available when
+ // receiving a window event.
+ let window = self.window.as_ref().unwrap();
+ // Handle window event.
+ }
+ fn device_event(&mut self, event_loop: &ActiveEventLoop, device_id: DeviceId, event: DeviceEvent) {
+ // Handle window event.
+ }
+ fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ if let Some(window) = self.window.as_ref() {
+ window.request_redraw();
+ self.counter += 1;
+ }
+ }
+ }
+
+ let event_loop = EventLoop::new().unwrap();
+ let mut state = State::default();
+ let _ = event_loop.run_app(&mut state);
+ ```
+
+- Remove `Deref` implementation for `EventLoop` that gave `EventLoopWindowTarget`.
+- Remove `WindowBuilder` in favor of `WindowAttributes`.
+- Remove Generic parameter `T` from `ActiveEventLoop`.
+- Remove `EventLoopBuilder::with_user_event`, use `EventLoop::with_user_event`.
+- Remove Redundant `EventLoopError::AlreadyRunning`.
+- Remove `WindowAttributes::fullscreen` and expose as field directly.
+- On X11, remove `platform::x11::XNotSupported` export.
+
+### Fixed
+
+- On Web, fix setting cursor icon overriding cursor visibility.
+- On Windows, fix cursor not confined to center of window when grabbed and hidden.
+- On macOS, fix sequence of mouse events being out of order when dragging on the trackpad.
+- On Wayland, fix decoration glitch on close with some compositors.
+- On Android, fix a regression introduced in #2748 to allow volume key events to be received again.
+- On Windows, don't return a valid window handle outside of the GUI thread.
+- On macOS, don't set the background color when initializing a window with transparency.
diff --git a/third_party/winit-0.30.13/src/changelog/v0.8.md b/third_party/winit-0.30.13/src/changelog/v0.8.md
new file mode 100644
index 0000000..1963429
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.8.md
@@ -0,0 +1,33 @@
+## 0.8.3
+
+- Fixed issue of calls to `set_inner_size` blocking on Windows.
+- Mapped `ISO_Left_Tab` to `VirtualKeyCode::Tab` to make the key work with modifiers
+- Fixed the X11 backed on 32bit targets
+
+## 0.8.2
+
+- Uniformize keyboard scancode values across Wayland and X11 (#297).
+- Internal rework of the wayland event loop
+- Added method `os::linux::WindowExt::is_ready`
+
+## 0.8.1
+
+- Added various methods to `os::linux::EventsLoopExt`, plus some hidden items necessary to make
+ glutin work.
+
+## 0.8.0
+
+- Added `Window::set_maximized`, `WindowAttributes::maximized` and `WindowBuilder::with_maximized`.
+- Added `Window::set_fullscreen`.
+- Changed `with_fullscreen` to take a `Option` instead of a `MonitorId`.
+- Removed `MonitorId::get_native_identifier()` in favor of platform-specific traits in the `os`
+ module.
+- Changed `get_available_monitors()` and `get_primary_monitor()` to be methods of `EventsLoop`
+ instead of stand-alone methods.
+- Changed `EventsLoop` to be tied to a specific X11 or Wayland connection.
+- Added a `os::linux::EventsLoopExt` trait that makes it possible to configure the connection.
+- Fixed the emscripten code, which now compiles.
+- Changed the X11 fullscreen code to use `xrandr` instead of `xxf86vm`.
+- Fixed the Wayland backend to produce `Refresh` event after window creation.
+- Changed the `Suspended` event to be outside of `WindowEvent`.
+- Fixed the X11 backend sometimes reporting the wrong virtual key (#273).
diff --git a/third_party/winit-0.30.13/src/changelog/v0.9.md b/third_party/winit-0.30.13/src/changelog/v0.9.md
new file mode 100644
index 0000000..2a9e8cc
--- /dev/null
+++ b/third_party/winit-0.30.13/src/changelog/v0.9.md
@@ -0,0 +1,22 @@
+## 0.9.0
+
+- Added event `WindowEvent::HiDPIFactorChanged`.
+- Added method `MonitorId::get_hidpi_factor`.
+- Deprecated `get_inner_size_pixels` and `get_inner_size_points` methods of `Window` in favor of
+ `get_inner_size`.
+- **Breaking:** `EventsLoop` is `!Send` and `!Sync` because of platform-dependant constraints,
+ but `Window`, `WindowId`, `DeviceId` and `MonitorId` guaranteed to be `Send`.
+- `MonitorId::get_position` now returns `(i32, i32)` instead of `(u32, u32)`.
+- Rewrite of the wayland backend to use wayland-client-0.11
+- Support for dead keys on wayland for keyboard utf8 input
+- Monitor enumeration on Windows is now implemented using `EnumDisplayMonitors` instead of
+ `EnumDisplayDevices`. This changes the value returned by `MonitorId::get_name()`.
+- On Windows added `MonitorIdExt::hmonitor` method
+- Impl `Clone` for `EventsLoopProxy`
+- `EventsLoop::get_primary_monitor()` on X11 will fallback to any available monitor if no primary is found
+- Support for touch event on wayland
+- `WindowEvent`s `MouseMoved`, `MouseEntered`, and `MouseLeft` have been renamed to
+ `CursorMoved`, `CursorEntered`, and `CursorLeft`.
+- New `DeviceEvent`s added, `MouseMotion` and `MouseWheel`.
+- Send `CursorMoved` event after `CursorEntered` and `Focused` events.
+- Add support for `ModifiersState`, `MouseMove`, `MouseInput`, `MouseMotion` for emscripten backend.
diff --git a/third_party/winit-0.30.13/src/cursor.rs b/third_party/winit-0.30.13/src/cursor.rs
new file mode 100644
index 0000000..7bcac54
--- /dev/null
+++ b/third_party/winit-0.30.13/src/cursor.rs
@@ -0,0 +1,263 @@
+use core::fmt;
+use std::error::Error;
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+use cursor_icon::CursorIcon;
+
+use crate::platform_impl::{PlatformCustomCursor, PlatformCustomCursorSource};
+
+/// The maximum width and height for a cursor when using [`CustomCursor::from_rgba`].
+pub const MAX_CURSOR_SIZE: u16 = 2048;
+
+const PIXEL_SIZE: usize = 4;
+
+/// See [`Window::set_cursor()`][crate::window::Window::set_cursor] for more details.
+#[derive(Clone, Debug, Eq, Hash, PartialEq)]
+pub enum Cursor {
+ Icon(CursorIcon),
+ Custom(CustomCursor),
+}
+
+impl Default for Cursor {
+ fn default() -> Self {
+ Self::Icon(CursorIcon::default())
+ }
+}
+
+impl From for Cursor {
+ fn from(icon: CursorIcon) -> Self {
+ Self::Icon(icon)
+ }
+}
+
+impl From for Cursor {
+ fn from(custom: CustomCursor) -> Self {
+ Self::Custom(custom)
+ }
+}
+
+/// Use a custom image as a cursor (mouse pointer).
+///
+/// Is guaranteed to be cheap to clone.
+///
+/// ## Platform-specific
+///
+/// **Web**: Some browsers have limits on cursor sizes usually at 128x128.
+///
+/// # Example
+///
+/// ```no_run
+/// # use winit::event_loop::ActiveEventLoop;
+/// # use winit::window::Window;
+/// # fn scope(event_loop: &ActiveEventLoop, window: &Window) {
+/// use winit::window::CustomCursor;
+///
+/// let w = 10;
+/// let h = 10;
+/// let rgba = vec![255; (w * h * 4) as usize];
+///
+/// #[cfg(not(target_family = "wasm"))]
+/// let source = CustomCursor::from_rgba(rgba, w, h, w / 2, h / 2).unwrap();
+///
+/// #[cfg(target_family = "wasm")]
+/// let source = {
+/// use winit::platform::web::CustomCursorExtWebSys;
+/// CustomCursor::from_url(String::from("http://localhost:3000/cursor.png"), 0, 0)
+/// };
+///
+/// let custom_cursor = event_loop.create_custom_cursor(source);
+///
+/// window.set_cursor(custom_cursor.clone());
+/// # }
+/// ```
+#[derive(Clone, Debug, Eq, Hash, PartialEq)]
+pub struct CustomCursor {
+ /// Platforms should make sure this is cheap to clone.
+ pub(crate) inner: PlatformCustomCursor,
+}
+
+impl CustomCursor {
+ /// Creates a new cursor from an rgba buffer.
+ ///
+ /// The alpha channel is assumed to be **not** premultiplied.
+ pub fn from_rgba(
+ rgba: impl Into>,
+ width: u16,
+ height: u16,
+ hotspot_x: u16,
+ hotspot_y: u16,
+ ) -> Result {
+ let _span =
+ tracing::debug_span!("winit::Cursor::from_rgba", width, height, hotspot_x, hotspot_y)
+ .entered();
+
+ Ok(CustomCursorSource {
+ inner: PlatformCustomCursorSource::from_rgba(
+ rgba.into(),
+ width,
+ height,
+ hotspot_x,
+ hotspot_y,
+ )?,
+ })
+ }
+}
+
+/// Source for [`CustomCursor`].
+///
+/// See [`CustomCursor`] for more details.
+#[derive(Debug)]
+pub struct CustomCursorSource {
+ pub(crate) inner: PlatformCustomCursorSource,
+}
+
+/// An error produced when using [`CustomCursor::from_rgba`] with invalid arguments.
+#[derive(Debug, Clone)]
+pub enum BadImage {
+ /// Produced when the image dimensions are larger than [`MAX_CURSOR_SIZE`]. This doesn't
+ /// guarantee that the cursor will work, but should avoid many platform and device specific
+ /// limits.
+ TooLarge { width: u16, height: u16 },
+ /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
+ /// safely interpreted as 32bpp RGBA pixels.
+ ByteCountNotDivisibleBy4 { byte_count: usize },
+ /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
+ /// At least one of your arguments is incorrect.
+ DimensionsVsPixelCount { width: u16, height: u16, width_x_height: u64, pixel_count: u64 },
+ /// Produced when the hotspot is outside the image bounds
+ HotspotOutOfBounds { width: u16, height: u16, hotspot_x: u16, hotspot_y: u16 },
+}
+
+impl fmt::Display for BadImage {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ BadImage::TooLarge { width, height } => write!(
+ f,
+ "The specified dimensions ({width:?}x{height:?}) are too large. The maximum is \
+ {MAX_CURSOR_SIZE:?}x{MAX_CURSOR_SIZE:?}.",
+ ),
+ BadImage::ByteCountNotDivisibleBy4 { byte_count } => write!(
+ f,
+ "The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making \
+ it impossible to interpret as 32bpp RGBA pixels.",
+ ),
+ BadImage::DimensionsVsPixelCount { width, height, width_x_height, pixel_count } => {
+ write!(
+ f,
+ "The specified dimensions ({width:?}x{height:?}) don't match the number of \
+ pixels supplied by the `rgba` argument ({pixel_count:?}). For those \
+ dimensions, the expected pixel count is {width_x_height:?}.",
+ )
+ },
+ BadImage::HotspotOutOfBounds { width, height, hotspot_x, hotspot_y } => write!(
+ f,
+ "The specified hotspot ({hotspot_x:?}, {hotspot_y:?}) is outside the image bounds \
+ ({width:?}x{height:?}).",
+ ),
+ }
+ }
+}
+
+impl Error for BadImage {}
+
+/// Platforms export this directly as `PlatformCustomCursorSource` if they need to only work with
+/// images.
+#[allow(dead_code)]
+#[derive(Debug)]
+pub(crate) struct OnlyCursorImageSource(pub(crate) CursorImage);
+
+#[allow(dead_code)]
+impl OnlyCursorImageSource {
+ pub(crate) fn from_rgba(
+ rgba: Vec,
+ width: u16,
+ height: u16,
+ hotspot_x: u16,
+ hotspot_y: u16,
+ ) -> Result {
+ CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y).map(Self)
+ }
+}
+
+/// Platforms export this directly as `PlatformCustomCursor` if they don't implement caching.
+#[allow(dead_code)]
+#[derive(Debug, Clone)]
+pub(crate) struct OnlyCursorImage(pub(crate) Arc);
+
+impl Hash for OnlyCursorImage {
+ fn hash(&self, state: &mut H) {
+ Arc::as_ptr(&self.0).hash(state);
+ }
+}
+
+impl PartialEq for OnlyCursorImage {
+ fn eq(&self, other: &Self) -> bool {
+ Arc::ptr_eq(&self.0, &other.0)
+ }
+}
+
+impl Eq for OnlyCursorImage {}
+
+#[derive(Debug)]
+#[allow(dead_code)]
+pub(crate) struct CursorImage {
+ pub(crate) rgba: Vec,
+ pub(crate) width: u16,
+ pub(crate) height: u16,
+ pub(crate) hotspot_x: u16,
+ pub(crate) hotspot_y: u16,
+}
+
+impl CursorImage {
+ pub(crate) fn from_rgba(
+ rgba: Vec,
+ width: u16,
+ height: u16,
+ hotspot_x: u16,
+ hotspot_y: u16,
+ ) -> Result {
+ if width > MAX_CURSOR_SIZE || height > MAX_CURSOR_SIZE {
+ return Err(BadImage::TooLarge { width, height });
+ }
+
+ if rgba.len() % PIXEL_SIZE != 0 {
+ return Err(BadImage::ByteCountNotDivisibleBy4 { byte_count: rgba.len() });
+ }
+
+ let pixel_count = (rgba.len() / PIXEL_SIZE) as u64;
+ let width_x_height = width as u64 * height as u64;
+ if pixel_count != width_x_height {
+ return Err(BadImage::DimensionsVsPixelCount {
+ width,
+ height,
+ width_x_height,
+ pixel_count,
+ });
+ }
+
+ if hotspot_x >= width || hotspot_y >= height {
+ return Err(BadImage::HotspotOutOfBounds { width, height, hotspot_x, hotspot_y });
+ }
+
+ Ok(CursorImage { rgba, width, height, hotspot_x, hotspot_y })
+ }
+}
+
+// Platforms that don't support cursors will export this as `PlatformCustomCursor`.
+#[derive(Debug, Clone, Hash, PartialEq, Eq)]
+pub(crate) struct NoCustomCursor;
+
+#[allow(dead_code)]
+impl NoCustomCursor {
+ pub(crate) fn from_rgba(
+ rgba: Vec,
+ width: u16,
+ height: u16,
+ hotspot_x: u16,
+ hotspot_y: u16,
+ ) -> Result {
+ CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y)?;
+ Ok(Self)
+ }
+}
diff --git a/third_party/winit-0.30.13/src/error.rs b/third_party/winit-0.30.13/src/error.rs
new file mode 100644
index 0000000..d15bb9e
--- /dev/null
+++ b/third_party/winit-0.30.13/src/error.rs
@@ -0,0 +1,131 @@
+use std::{error, fmt};
+
+use crate::platform_impl;
+
+// TODO: Rename
+/// An error that may be generated when requesting Winit state
+#[derive(Debug)]
+pub enum ExternalError {
+ /// The operation is not supported by the backend.
+ NotSupported(NotSupportedError),
+ /// The operation was ignored.
+ Ignored,
+ /// The OS cannot perform the operation.
+ Os(OsError),
+}
+
+/// The error type for when the requested operation is not supported by the backend.
+#[derive(Clone)]
+pub struct NotSupportedError {
+ _marker: (),
+}
+
+/// The error type for when the OS cannot perform the requested operation.
+#[derive(Debug)]
+pub struct OsError {
+ line: u32,
+ file: &'static str,
+ error: platform_impl::OsError,
+}
+
+/// A general error that may occur while running the Winit event loop
+#[derive(Debug)]
+pub enum EventLoopError {
+ /// The operation is not supported by the backend.
+ NotSupported(NotSupportedError),
+ /// The OS cannot perform the operation.
+ Os(OsError),
+ /// The event loop can't be re-created.
+ RecreationAttempt,
+ /// Application has exit with an error status.
+ ExitFailure(i32),
+}
+
+impl From for EventLoopError {
+ fn from(value: OsError) -> Self {
+ Self::Os(value)
+ }
+}
+
+impl NotSupportedError {
+ #[inline]
+ #[allow(dead_code)]
+ pub(crate) fn new() -> NotSupportedError {
+ NotSupportedError { _marker: () }
+ }
+}
+
+impl OsError {
+ #[allow(dead_code)]
+ pub(crate) fn new(line: u32, file: &'static str, error: platform_impl::OsError) -> OsError {
+ OsError { line, file, error }
+ }
+}
+
+#[allow(unused_macros)]
+macro_rules! os_error {
+ ($error:expr) => {{
+ crate::error::OsError::new(line!(), file!(), $error)
+ }};
+}
+
+impl fmt::Display for OsError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+ f.pad(&format!("os error at {}:{}: {}", self.file, self.line, self.error))
+ }
+}
+
+impl fmt::Display for ExternalError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+ match self {
+ ExternalError::NotSupported(e) => e.fmt(f),
+ ExternalError::Ignored => write!(f, "Operation was ignored"),
+ ExternalError::Os(e) => e.fmt(f),
+ }
+ }
+}
+
+impl fmt::Debug for NotSupportedError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+ f.debug_struct("NotSupportedError").finish()
+ }
+}
+
+impl fmt::Display for NotSupportedError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+ f.pad("the requested operation is not supported by Winit")
+ }
+}
+
+impl fmt::Display for EventLoopError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+ match self {
+ EventLoopError::RecreationAttempt => write!(f, "EventLoop can't be recreated"),
+ EventLoopError::NotSupported(e) => e.fmt(f),
+ EventLoopError::Os(e) => e.fmt(f),
+ EventLoopError::ExitFailure(status) => write!(f, "Exit Failure: {status}"),
+ }
+ }
+}
+
+impl error::Error for OsError {}
+impl error::Error for ExternalError {}
+impl error::Error for NotSupportedError {}
+impl error::Error for EventLoopError {}
+
+#[cfg(test)]
+#[allow(clippy::redundant_clone)]
+mod tests {
+ use super::*;
+
+ // Eat attributes for testing
+ #[test]
+ fn ensure_fmt_does_not_panic() {
+ let _ = format!("{:?}, {}", NotSupportedError::new(), NotSupportedError::new().clone());
+ let _ = format!(
+ "{:?}, {}",
+ ExternalError::NotSupported(NotSupportedError::new()),
+ ExternalError::NotSupported(NotSupportedError::new())
+ );
+ }
+}
diff --git a/third_party/winit-0.30.13/src/event.rs b/third_party/winit-0.30.13/src/event.rs
new file mode 100644
index 0000000..4e01420
--- /dev/null
+++ b/third_party/winit-0.30.13/src/event.rs
@@ -0,0 +1,1183 @@
+//! The [`Event`] enum and assorted supporting types.
+//!
+//! These are sent to the closure given to [`EventLoop::run_app(...)`], where they get
+//! processed and used to modify the program state. For more details, see the root-level
+//! documentation.
+//!
+//! Some of these events represent different "parts" of a traditional event-handling loop. You could
+//! approximate the basic ordering loop of [`EventLoop::run_app(...)`] like this:
+//!
+//! ```rust,ignore
+//! let mut start_cause = StartCause::Init;
+//!
+//! while !elwt.exiting() {
+//! app.new_events(event_loop, start_cause);
+//!
+//! for event in (window events, user events, device events) {
+//! // This will pick the right method on the application based on the event.
+//! app.handle_event(event_loop, event);
+//! }
+//!
+//! for window_id in (redraw windows) {
+//! app.window_event(event_loop, window_id, RedrawRequested);
+//! }
+//!
+//! app.about_to_wait(event_loop);
+//! start_cause = wait_if_necessary();
+//! }
+//!
+//! app.exiting(event_loop);
+//! ```
+//!
+//! This leaves out timing details like [`ControlFlow::WaitUntil`] but hopefully
+//! describes what happens in what order.
+//!
+//! [`EventLoop::run_app(...)`]: crate::event_loop::EventLoop::run_app
+//! [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil
+use std::path::PathBuf;
+use std::sync::{Mutex, Weak};
+#[cfg(not(web_platform))]
+use std::time::Instant;
+
+#[cfg(feature = "serde")]
+use serde::{Deserialize, Serialize};
+use smol_str::SmolStr;
+#[cfg(web_platform)]
+use web_time::Instant;
+
+use crate::dpi::{PhysicalPosition, PhysicalSize};
+use crate::error::ExternalError;
+use crate::event_loop::AsyncRequestSerial;
+use crate::keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState};
+use crate::platform_impl;
+#[cfg(doc)]
+use crate::window::Window;
+use crate::window::{ActivationToken, Theme, WindowId};
+
+/// Describes a generic event.
+///
+/// See the module-level docs for more information on the event loop manages each event.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Event {
+ /// See [`ApplicationHandler::new_events`] for details.
+ ///
+ /// [`ApplicationHandler::new_events`]: crate::application::ApplicationHandler::new_events
+ NewEvents(StartCause),
+
+ /// See [`ApplicationHandler::window_event`] for details.
+ ///
+ /// [`ApplicationHandler::window_event`]: crate::application::ApplicationHandler::window_event
+ WindowEvent { window_id: WindowId, event: WindowEvent },
+
+ /// See [`ApplicationHandler::device_event`] for details.
+ ///
+ /// [`ApplicationHandler::device_event`]: crate::application::ApplicationHandler::device_event
+ DeviceEvent { device_id: DeviceId, event: DeviceEvent },
+
+ /// See [`ApplicationHandler::user_event`] for details.
+ ///
+ /// [`ApplicationHandler::user_event`]: crate::application::ApplicationHandler::user_event
+ UserEvent(T),
+
+ /// See [`ApplicationHandler::suspended`] for details.
+ ///
+ /// [`ApplicationHandler::suspended`]: crate::application::ApplicationHandler::suspended
+ Suspended,
+
+ /// See [`ApplicationHandler::resumed`] for details.
+ ///
+ /// [`ApplicationHandler::resumed`]: crate::application::ApplicationHandler::resumed
+ Resumed,
+
+ /// See [`ApplicationHandler::about_to_wait`] for details.
+ ///
+ /// [`ApplicationHandler::about_to_wait`]: crate::application::ApplicationHandler::about_to_wait
+ AboutToWait,
+
+ /// See [`ApplicationHandler::exiting`] for details.
+ ///
+ /// [`ApplicationHandler::exiting`]: crate::application::ApplicationHandler::exiting
+ LoopExiting,
+
+ /// See [`ApplicationHandler::memory_warning`] for details.
+ ///
+ /// [`ApplicationHandler::memory_warning`]: crate::application::ApplicationHandler::memory_warning
+ MemoryWarning,
+}
+
+impl Event {
+ #[allow(clippy::result_large_err)]
+ pub fn map_nonuser_event(self) -> Result, Event> {
+ use self::Event::*;
+ match self {
+ UserEvent(_) => Err(self),
+ WindowEvent { window_id, event } => Ok(WindowEvent { window_id, event }),
+ DeviceEvent { device_id, event } => Ok(DeviceEvent { device_id, event }),
+ NewEvents(cause) => Ok(NewEvents(cause)),
+ AboutToWait => Ok(AboutToWait),
+ LoopExiting => Ok(LoopExiting),
+ Suspended => Ok(Suspended),
+ Resumed => Ok(Resumed),
+ MemoryWarning => Ok(MemoryWarning),
+ }
+ }
+}
+
+/// Describes the reason the event loop is resuming.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum StartCause {
+ /// Sent if the time specified by [`ControlFlow::WaitUntil`] has been reached. Contains the
+ /// moment the timeout was requested and the requested resume time. The actual resume time is
+ /// guaranteed to be equal to or after the requested resume time.
+ ///
+ /// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil
+ ResumeTimeReached { start: Instant, requested_resume: Instant },
+
+ /// Sent if the OS has new events to send to the window, after a wait was requested. Contains
+ /// the moment the wait was requested and the resume time, if requested.
+ WaitCancelled { start: Instant, requested_resume: Option },
+
+ /// Sent if the event loop is being resumed after the loop's control flow was set to
+ /// [`ControlFlow::Poll`].
+ ///
+ /// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
+ Poll,
+
+ /// Sent once, immediately after `run` is called. Indicates that the loop was just initialized.
+ Init,
+}
+
+/// Describes an event from a [`Window`].
+#[derive(Debug, Clone, PartialEq)]
+pub enum WindowEvent {
+ /// The activation token was delivered back and now could be used.
+ #[cfg_attr(not(any(x11_platform, wayland_platform)), allow(rustdoc::broken_intra_doc_links))]
+ /// Delivered in response to [`request_activation_token`].
+ ///
+ /// [`request_activation_token`]: crate::platform::startup_notify::WindowExtStartupNotify::request_activation_token
+ ActivationTokenDone { serial: AsyncRequestSerial, token: ActivationToken },
+
+ /// The size of the window has changed. Contains the client area's new dimensions.
+ Resized(PhysicalSize),
+
+ /// The position of the window has changed. Contains the window's new position.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **iOS / Android / Web / Wayland:** Unsupported.
+ Moved(PhysicalPosition),
+
+ /// The window has been requested to close.
+ CloseRequested,
+
+ /// The window has been destroyed.
+ Destroyed,
+
+ /// A file has been dropped into the window.
+ ///
+ /// When the user drops multiple files at once, this event will be emitted for each file
+ /// separately.
+ DroppedFile(PathBuf),
+
+ /// A file is being hovered over the window.
+ ///
+ /// When the user hovers multiple files at once, this event will be emitted for each file
+ /// separately.
+ HoveredFile(PathBuf),
+
+ /// A file was hovered, but has exited the window.
+ ///
+ /// There will be a single `HoveredFileCancelled` event triggered even if multiple files were
+ /// hovered.
+ HoveredFileCancelled,
+
+ /// The window gained or lost focus.
+ ///
+ /// The parameter is true if the window has gained focus, and false if it has lost focus.
+ Focused(bool),
+
+ /// An event from the keyboard has been received.
+ ///
+ /// ## Platform-specific
+ /// - **Windows:** The shift key overrides NumLock. In other words, while shift is held down,
+ /// numpad keys act as if NumLock wasn't active. When this is used, the OS sends fake key
+ /// events which are not marked as `is_synthetic`.
+ KeyboardInput {
+ device_id: DeviceId,
+ event: KeyEvent,
+
+ /// If `true`, the event was generated synthetically by winit
+ /// in one of the following circumstances:
+ ///
+ /// * Synthetic key press events are generated for all keys pressed when a window gains
+ /// focus. Likewise, synthetic key release events are generated for all keys pressed when
+ /// a window goes out of focus. ***Currently, this is only functional on X11 and
+ /// Windows***
+ ///
+ /// Otherwise, this value is always `false`.
+ is_synthetic: bool,
+ },
+
+ /// The keyboard modifiers have changed.
+ ModifiersChanged(Modifiers),
+
+ /// An event from an input method.
+ ///
+ /// **Note:** You have to explicitly enable this event using [`Window::set_ime_allowed`].
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **iOS / Android / Web / Orbital:** Unsupported.
+ Ime(Ime),
+
+ /// The cursor has moved on the window.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`].
+ ///
+ /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
+ /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
+ /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
+ CursorMoved {
+ device_id: DeviceId,
+
+ /// (x,y) coords in pixels relative to the top-left corner of the window. Because the range
+ /// of this data is limited by the display area and it may have been transformed by
+ /// the OS to implement effects such as cursor acceleration, it should not be used
+ /// to implement non-cursor-like interactions such as 3D camera control.
+ position: PhysicalPosition,
+ },
+
+ /// The cursor has entered the window.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`].
+ ///
+ /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
+ /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
+ /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
+ CursorEntered { device_id: DeviceId },
+
+ /// The cursor has left the window.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`].
+ ///
+ /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
+ /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
+ /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
+ CursorLeft { device_id: DeviceId },
+
+ /// A mouse wheel movement or touchpad scroll occurred.
+ MouseWheel { device_id: DeviceId, delta: MouseScrollDelta, phase: TouchPhase },
+
+ /// An mouse button press has been received.
+ MouseInput { device_id: DeviceId, state: ElementState, button: MouseButton },
+
+ /// Two-finger pinch gesture, often used for magnification.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - Only available on **macOS** and **iOS**.
+ /// - On iOS, not recognized by default. It must be enabled when needed.
+ PinchGesture {
+ device_id: DeviceId,
+ /// Positive values indicate magnification (zooming in) and negative
+ /// values indicate shrinking (zooming out).
+ ///
+ /// This value may be NaN.
+ delta: f64,
+ phase: TouchPhase,
+ },
+
+ /// N-finger pan gesture
+ ///
+ /// ## Platform-specific
+ ///
+ /// - Only available on **iOS**.
+ /// - On iOS, not recognized by default. It must be enabled when needed.
+ PanGesture {
+ device_id: DeviceId,
+ /// Change in pixels of pan gesture from last update.
+ delta: PhysicalPosition,
+ phase: TouchPhase,
+ },
+
+ /// Double tap gesture.
+ ///
+ /// On a Mac, smart magnification is triggered by a double tap with two fingers
+ /// on the trackpad and is commonly used to zoom on a certain object
+ /// (e.g. a paragraph of a PDF) or (sort of like a toggle) to reset any zoom.
+ /// The gesture is also supported in Safari, Pages, etc.
+ ///
+ /// The event is general enough that its generating gesture is allowed to vary
+ /// across platforms. It could also be generated by another device.
+ ///
+ /// Unfortunately, neither [Windows](https://support.microsoft.com/en-us/windows/touch-gestures-for-windows-a9d28305-4818-a5df-4e2b-e5590f850741)
+ /// nor [Wayland](https://wayland.freedesktop.org/libinput/doc/latest/gestures.html)
+ /// support this gesture or any other gesture with the same effect.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - Only available on **macOS 10.8** and later, and **iOS**.
+ /// - On iOS, not recognized by default. It must be enabled when needed.
+ DoubleTapGesture { device_id: DeviceId },
+
+ /// Two-finger rotation gesture.
+ ///
+ /// Positive delta values indicate rotation counterclockwise and
+ /// negative delta values indicate rotation clockwise.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - Only available on **macOS** and **iOS**.
+ /// - On iOS, not recognized by default. It must be enabled when needed.
+ RotationGesture {
+ device_id: DeviceId,
+ /// change in rotation in degrees
+ delta: f32,
+ phase: TouchPhase,
+ },
+
+ /// Touchpad pressure event.
+ ///
+ /// At the moment, only supported on Apple forcetouch-capable macbooks.
+ /// The parameters are: pressure level (value between 0 and 1 representing how hard the
+ /// touchpad is being pressed) and stage (integer representing the click level).
+ TouchpadPressure { device_id: DeviceId, pressure: f32, stage: i64 },
+
+ /// Motion on some analog axis. May report data redundant to other, more specific events.
+ AxisMotion { device_id: DeviceId, axis: AxisId, value: f64 },
+
+ /// Touch event has been received
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`].
+ /// - **macOS:** Unsupported.
+ ///
+ /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
+ /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
+ /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
+ Touch(Touch),
+
+ /// The window's scale factor has changed.
+ ///
+ /// The following user actions can cause DPI changes:
+ ///
+ /// * Changing the display's resolution.
+ /// * Changing the display's scale factor (e.g. in Control Panel on Windows).
+ /// * Moving the window to a display with a different scale factor.
+ ///
+ /// To update the window size, use the provided [`InnerSizeWriter`] handle. By default, the
+ /// window is resized to the value suggested by the OS, but it can be changed to any value.
+ ///
+ /// For more information about DPI in general, see the [`dpi`] crate.
+ ScaleFactorChanged {
+ scale_factor: f64,
+ /// Handle to update inner size during scale changes.
+ ///
+ /// See [`InnerSizeWriter`] docs for more details.
+ inner_size_writer: InnerSizeWriter,
+ },
+
+ /// The system window theme has changed.
+ ///
+ /// Applications might wish to react to this to change the theme of the content of the window
+ /// when the system changes the window theme.
+ ///
+ /// This only reports a change if the window theme was not overridden by [`Window::set_theme`].
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **iOS / Android / X11 / Wayland / Orbital:** Unsupported.
+ ThemeChanged(Theme),
+
+ /// The window has been occluded (completely hidden from view).
+ ///
+ /// This is different to window visibility as it depends on whether the window is closed,
+ /// minimised, set invisible, or fully occluded by another window.
+ ///
+ /// ## Platform-specific
+ ///
+ /// ### iOS
+ ///
+ /// On iOS, the `Occluded(false)` event is emitted in response to an
+ /// [`applicationWillEnterForeground`] callback which means the application should start
+ /// preparing its data. The `Occluded(true)` event is emitted in response to an
+ /// [`applicationDidEnterBackground`] callback which means the application should free
+ /// resources (according to the [iOS application lifecycle]).
+ ///
+ /// [`applicationWillEnterForeground`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623076-applicationwillenterforeground
+ /// [`applicationDidEnterBackground`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622997-applicationdidenterbackground
+ /// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
+ ///
+ /// ### Others
+ ///
+ /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`].
+ /// - **Android / Wayland / Windows / Orbital:** Unsupported.
+ ///
+ /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
+ /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
+ /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
+ Occluded(bool),
+
+ /// Emitted when a window should be redrawn.
+ ///
+ /// This gets triggered in two scenarios:
+ /// - The OS has performed an operation that's invalidated the window's contents (such as
+ /// resizing the window).
+ /// - The application has explicitly requested a redraw via [`Window::request_redraw`].
+ ///
+ /// Winit will aggregate duplicate redraw requests into a single event, to
+ /// help avoid duplicating rendering work.
+ RedrawRequested,
+}
+
+/// Identifier of an input device.
+///
+/// Whenever you receive an event arising from a particular input device, this event contains a
+/// `DeviceId` which identifies its origin. Note that devices may be virtual (representing an
+/// on-screen cursor and keyboard focus) or physical. Virtual devices typically aggregate inputs
+/// from multiple physical devices.
+#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct DeviceId(pub(crate) platform_impl::DeviceId);
+
+impl DeviceId {
+ /// Returns a dummy id, useful for unit testing.
+ ///
+ /// # Notes
+ ///
+ /// The only guarantee made about the return value of this function is that
+ /// it will always be equal to itself and to future values returned by this function.
+ /// No other guarantees are made. This may be equal to a real `DeviceId`.
+ pub const fn dummy() -> Self {
+ DeviceId(platform_impl::DeviceId::dummy())
+ }
+}
+
+/// Represents raw hardware events that are not associated with any particular window.
+///
+/// Useful for interactions that diverge significantly from a conventional 2D GUI, such as 3D camera
+/// or first-person game controls. Many physical actions, such as mouse movement, can produce both
+/// device and window events. Because window events typically arise from virtual devices
+/// (corresponding to GUI cursors and keyboard focus) the device IDs may not match.
+///
+/// Note that these events are delivered regardless of input focus.
+#[derive(Clone, Debug, PartialEq)]
+pub enum DeviceEvent {
+ Added,
+ Removed,
+
+ /// Change in physical position of a pointing device.
+ ///
+ /// This represents raw, unfiltered physical motion. Not to be confused with
+ /// [`WindowEvent::CursorMoved`].
+ MouseMotion {
+ /// (x, y) change in position in unspecified units.
+ ///
+ /// Different devices may use different units.
+ delta: (f64, f64),
+ },
+
+ /// Physical scroll event
+ MouseWheel {
+ delta: MouseScrollDelta,
+ },
+
+ /// Motion on some analog axis. This event will be reported for all arbitrary input devices
+ /// that winit supports on this platform, including mouse devices. If the device is a mouse
+ /// device then this will be reported alongside the MouseMotion event.
+ Motion {
+ axis: AxisId,
+ value: f64,
+ },
+
+ Button {
+ button: ButtonId,
+ state: ElementState,
+ },
+
+ Key(RawKeyEvent),
+}
+
+/// Describes a keyboard input as a raw device event.
+///
+/// Note that holding down a key may produce repeated `RawKeyEvent`s. The
+/// operating system doesn't provide information whether such an event is a
+/// repeat or the initial keypress. An application may emulate this by, for
+/// example keeping a Map/Set of pressed keys and determining whether a keypress
+/// corresponds to an already pressed key.
+#[derive(Debug, Clone, Eq, PartialEq, Hash)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct RawKeyEvent {
+ pub physical_key: keyboard::PhysicalKey,
+ pub state: ElementState,
+}
+
+/// Describes a keyboard input targeting a window.
+#[derive(Debug, Clone, Eq, PartialEq, Hash)]
+pub struct KeyEvent {
+ /// Represents the position of a key independent of the currently active layout.
+ ///
+ /// It also uniquely identifies the physical key (i.e. it's mostly synonymous with a scancode).
+ /// The most prevalent use case for this is games. For example the default keys for the player
+ /// to move around might be the W, A, S, and D keys on a US layout. The position of these keys
+ /// is more important than their label, so they should map to Z, Q, S, and D on an "AZERTY"
+ /// layout. (This value is `KeyCode::KeyW` for the Z key on an AZERTY layout.)
+ ///
+ /// ## Caveats
+ ///
+ /// - Certain niche hardware will shuffle around physical key positions, e.g. a keyboard that
+ /// implements DVORAK in hardware (or firmware)
+ /// - Your application will likely have to handle keyboards which are missing keys that your
+ /// own keyboard has.
+ /// - Certain `KeyCode`s will move between a couple of different positions depending on what
+ /// layout the keyboard was manufactured to support.
+ ///
+ /// **Because of these caveats, it is important that you provide users with a way to configure
+ /// most (if not all) keybinds in your application.**
+ ///
+ /// ## `Fn` and `FnLock`
+ ///
+ /// `Fn` and `FnLock` key events are *exceedingly unlikely* to be emitted by Winit. These keys
+ /// are usually handled at the hardware or OS level, and aren't surfaced to applications. If
+ /// you somehow see this in the wild, we'd like to know :)
+ pub physical_key: keyboard::PhysicalKey,
+
+ // Allowing `broken_intra_doc_links` for `logical_key`, because
+ // `key_without_modifiers` is not available on all platforms
+ #[cfg_attr(
+ not(any(windows_platform, macos_platform, x11_platform, wayland_platform)),
+ allow(rustdoc::broken_intra_doc_links)
+ )]
+ /// This value is affected by all modifiers except Ctrl .
+ ///
+ /// This has two use cases:
+ /// - Allows querying whether the current input is a Dead key.
+ /// - Allows handling key-bindings on platforms which don't support [`key_without_modifiers`].
+ ///
+ /// If you use this field (or [`key_without_modifiers`] for that matter) for keyboard
+ /// shortcuts, **it is important that you provide users with a way to configure your
+ /// application's shortcuts so you don't render your application unusable for users with an
+ /// incompatible keyboard layout.**
+ ///
+ /// ## Platform-specific
+ /// - **Web:** Dead keys might be reported as the real key instead of `Dead` depending on the
+ /// browser/OS.
+ ///
+ /// [`key_without_modifiers`]: crate::platform::modifier_supplement::KeyEventExtModifierSupplement::key_without_modifiers
+ pub logical_key: keyboard::Key,
+
+ /// Contains the text produced by this keypress.
+ ///
+ /// In most cases this is identical to the content
+ /// of the `Character` variant of `logical_key`.
+ /// However, on Windows when a dead key was pressed earlier
+ /// but cannot be combined with the character from this
+ /// keypress, the produced text will consist of two characters:
+ /// the dead-key-character followed by the character resulting
+ /// from this keypress.
+ ///
+ /// An additional difference from `logical_key` is that
+ /// this field stores the text representation of any key
+ /// that has such a representation. For example when
+ /// `logical_key` is `Key::Named(NamedKey::Enter)`, this field is `Some("\r")`.
+ ///
+ /// This is `None` if the current keypress cannot
+ /// be interpreted as text.
+ ///
+ /// See also: `text_with_all_modifiers()`
+ pub text: Option,
+
+ /// Contains the location of this key on the keyboard.
+ ///
+ /// Certain keys on the keyboard may appear in more than once place. For example, the "Shift"
+ /// key appears on the left side of the QWERTY keyboard as well as the right side. However,
+ /// both keys have the same symbolic value. Another example of this phenomenon is the "1"
+ /// key, which appears both above the "Q" key and as the "Keypad 1" key.
+ ///
+ /// This field allows the user to differentiate between keys like this that have the same
+ /// symbolic value but different locations on the keyboard.
+ ///
+ /// See the [`KeyLocation`] type for more details.
+ ///
+ /// [`KeyLocation`]: crate::keyboard::KeyLocation
+ pub location: keyboard::KeyLocation,
+
+ /// Whether the key is being pressed or released.
+ ///
+ /// See the [`ElementState`] type for more details.
+ pub state: ElementState,
+
+ /// Whether or not this key is a key repeat event.
+ ///
+ /// 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 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::{ElementState, KeyEvent, WindowEvent};
+ /// 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,
+
+ /// Platform-specific key event information.
+ ///
+ /// On Windows, Linux and macOS, this type contains the key without modifiers and the text with
+ /// all modifiers applied.
+ ///
+ /// On Android, iOS, Redox and Web, this type is a no-op.
+ pub(crate) platform_specific: platform_impl::KeyEventExtra,
+}
+
+/// Describes keyboard modifiers event.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub struct Modifiers {
+ pub(crate) state: ModifiersState,
+
+ // NOTE: Currently pressed modifiers keys.
+ //
+ // The field providing a metadata, it shouldn't be used as a source of truth.
+ pub(crate) pressed_mods: ModifiersKeys,
+}
+
+impl Modifiers {
+ /// The state of the modifiers.
+ pub fn state(&self) -> ModifiersState {
+ self.state
+ }
+
+ /// The state of the left shift key.
+ pub fn lshift_state(&self) -> ModifiersKeyState {
+ self.mod_state(ModifiersKeys::LSHIFT)
+ }
+
+ /// The state of the right shift key.
+ pub fn rshift_state(&self) -> ModifiersKeyState {
+ self.mod_state(ModifiersKeys::RSHIFT)
+ }
+
+ /// The state of the left alt key.
+ pub fn lalt_state(&self) -> ModifiersKeyState {
+ self.mod_state(ModifiersKeys::LALT)
+ }
+
+ /// The state of the right alt key.
+ pub fn ralt_state(&self) -> ModifiersKeyState {
+ self.mod_state(ModifiersKeys::RALT)
+ }
+
+ /// The state of the left control key.
+ pub fn lcontrol_state(&self) -> ModifiersKeyState {
+ self.mod_state(ModifiersKeys::LCONTROL)
+ }
+
+ /// The state of the right control key.
+ pub fn rcontrol_state(&self) -> ModifiersKeyState {
+ self.mod_state(ModifiersKeys::RCONTROL)
+ }
+
+ /// The state of the left super key.
+ pub fn lsuper_state(&self) -> ModifiersKeyState {
+ self.mod_state(ModifiersKeys::LSUPER)
+ }
+
+ /// The state of the right super key.
+ pub fn rsuper_state(&self) -> ModifiersKeyState {
+ self.mod_state(ModifiersKeys::RSUPER)
+ }
+
+ fn mod_state(&self, modifier: ModifiersKeys) -> ModifiersKeyState {
+ if self.pressed_mods.contains(modifier) {
+ ModifiersKeyState::Pressed
+ } else {
+ ModifiersKeyState::Unknown
+ }
+ }
+}
+
+impl From for Modifiers {
+ fn from(value: ModifiersState) -> Self {
+ Self { state: value, pressed_mods: Default::default() }
+ }
+}
+
+/// Describes [input method](https://en.wikipedia.org/wiki/Input_method) events.
+///
+/// This is also called a "composition event".
+///
+/// Most keypresses using a latin-like keyboard layout simply generate a
+/// [`WindowEvent::KeyboardInput`]. However, one couldn't possibly have a key for every single
+/// unicode character that the user might want to type
+/// - so the solution operating systems employ is to allow the user to type these using _a sequence
+/// of keypresses_ instead.
+///
+/// A prominent example of this is accents - many keyboard layouts allow you to first click the
+/// "accent key", and then the character you want to apply the accent to. In this case, some
+/// platforms will generate the following event sequence:
+///
+/// ```ignore
+/// // Press "`" key
+/// Ime::Preedit("`", Some((0, 0)))
+/// // Press "E" key
+/// Ime::Preedit("", None) // Synthetic event generated by winit to clear preedit.
+/// Ime::Commit("é")
+/// ```
+///
+/// Additionally, certain input devices are configured to display a candidate box that allow the
+/// user to select the desired character interactively. (To properly position this box, you must use
+/// [`Window::set_ime_cursor_area`].)
+///
+/// An example of a keyboard layout which uses candidate boxes is pinyin. On a latin keyboard the
+/// following event sequence could be obtained:
+///
+/// ```ignore
+/// // Press "A" key
+/// Ime::Preedit("a", Some((1, 1)))
+/// // Press "B" key
+/// Ime::Preedit("a b", Some((3, 3)))
+/// // Press left arrow key
+/// Ime::Preedit("a b", Some((1, 1)))
+/// // Press space key
+/// Ime::Preedit("啊b", Some((3, 3)))
+/// // Press space key
+/// Ime::Preedit("", None) // Synthetic event generated by winit to clear preedit.
+/// Ime::Commit("啊不")
+/// ```
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum Ime {
+ /// Notifies when the IME was enabled.
+ ///
+ /// After getting this event you could receive [`Preedit`][Self::Preedit] and
+ /// [`Commit`][Self::Commit] events. You should also start performing IME related requests
+ /// like [`Window::set_ime_cursor_area`].
+ Enabled,
+
+ /// Notifies when a new composing text should be set at the cursor position.
+ ///
+ /// The value represents a pair of the preedit string and the cursor begin position and end
+ /// position. When it's `None`, the cursor should be hidden. When `String` is an empty string
+ /// this indicates that preedit was cleared.
+ ///
+ /// The cursor position is byte-wise indexed.
+ Preedit(String, Option<(usize, usize)>),
+
+ /// Notifies when text should be inserted into the editor widget.
+ ///
+ /// Right before this event winit will send empty [`Self::Preedit`] event.
+ Commit(String),
+
+ /// Notifies when the IME was disabled.
+ ///
+ /// After receiving this event you won't get any more [`Preedit`][Self::Preedit] or
+ /// [`Commit`][Self::Commit] events until the next [`Enabled`][Self::Enabled] event. You should
+ /// also stop issuing IME related requests like [`Window::set_ime_cursor_area`] and clear
+ /// pending preedit text.
+ Disabled,
+}
+
+/// Describes touch-screen input state.
+#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum TouchPhase {
+ Started,
+ Moved,
+ Ended,
+ Cancelled,
+}
+
+/// Represents a touch event
+///
+/// Every time the user touches the screen, a new [`TouchPhase::Started`] event with an unique
+/// identifier for the finger is generated. When the finger is lifted, an [`TouchPhase::Ended`]
+/// event is generated with the same finger id.
+///
+/// After a `Started` event has been emitted, there may be zero or more `Move`
+/// events when the finger is moved or the touch pressure changes.
+///
+/// The finger id may be reused by the system after an `Ended` event. The user
+/// should assume that a new `Started` event received with the same id has nothing
+/// to do with the old finger and is a new finger.
+///
+/// A [`TouchPhase::Cancelled`] event is emitted when the system has canceled tracking this
+/// touch, such as when the window loses focus, or on iOS if the user moves the
+/// device against their face.
+///
+/// ## Platform-specific
+///
+/// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`].
+/// - **macOS:** Unsupported.
+///
+/// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
+/// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
+/// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Touch {
+ pub device_id: DeviceId,
+ pub phase: TouchPhase,
+ pub location: PhysicalPosition,
+ /// Describes how hard the screen was pressed. May be `None` if the platform
+ /// does not support pressure sensitivity.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - Only available on **iOS** 9.0+, **Windows** 8+, **Web**, and **Android**.
+ /// - **Android**: This will never be [None]. If the device doesn't support pressure
+ /// sensitivity, force will either be 0.0 or 1.0. Also see the
+ /// [android documentation](https://developer.android.com/reference/android/view/MotionEvent#AXIS_PRESSURE).
+ pub force: Option,
+ /// Unique identifier of a finger.
+ pub id: u64,
+}
+
+/// Describes the force of a touch event
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum Force {
+ /// On iOS, the force is calibrated so that the same number corresponds to
+ /// roughly the same amount of pressure on the screen regardless of the
+ /// device.
+ Calibrated {
+ /// The force of the touch, where a value of 1.0 represents the force of
+ /// an average touch (predetermined by the system, not user-specific).
+ ///
+ /// The force reported by Apple Pencil is measured along the axis of the
+ /// pencil. If you want a force perpendicular to the device, you need to
+ /// calculate this value using the `altitude_angle` value.
+ force: f64,
+ /// The maximum possible force for a touch.
+ ///
+ /// The value of this field is sufficiently high to provide a wide
+ /// dynamic range for values of the `force` field.
+ max_possible_force: f64,
+ /// The altitude (in radians) of the stylus.
+ ///
+ /// A value of 0 radians indicates that the stylus is parallel to the
+ /// surface. The value of this property is Pi/2 when the stylus is
+ /// perpendicular to the surface.
+ altitude_angle: Option,
+ },
+ /// If the platform reports the force as normalized, we have no way of
+ /// knowing how much pressure 1.0 corresponds to – we know it's the maximum
+ /// amount of force, but as to how much force, you might either have to
+ /// press really really hard, or not hard at all, depending on the device.
+ Normalized(f64),
+}
+
+impl Force {
+ /// Returns the force normalized to the range between 0.0 and 1.0 inclusive.
+ ///
+ /// Instead of normalizing the force, you should prefer to handle
+ /// [`Force::Calibrated`] so that the amount of force the user has to apply is
+ /// consistent across devices.
+ pub fn normalized(&self) -> f64 {
+ match self {
+ Force::Calibrated { force, max_possible_force, altitude_angle } => {
+ let force = match altitude_angle {
+ Some(altitude_angle) => force / altitude_angle.sin(),
+ None => *force,
+ };
+ force / max_possible_force
+ },
+ Force::Normalized(force) => *force,
+ }
+ }
+}
+
+/// Identifier for a specific analog axis on some device.
+pub type AxisId = u32;
+
+/// Identifier for a specific button on some device.
+pub type ButtonId = u32;
+
+/// Describes the input state of a key.
+#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum ElementState {
+ Pressed,
+ Released,
+}
+
+impl ElementState {
+ /// True if `self == Pressed`.
+ pub fn is_pressed(self) -> bool {
+ self == ElementState::Pressed
+ }
+}
+
+/// Describes a button of a mouse controller.
+///
+/// ## Platform-specific
+///
+/// **macOS:** `Back` and `Forward` might not work with all hardware.
+/// **Orbital:** `Back` and `Forward` are unsupported due to orbital not supporting them.
+#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum MouseButton {
+ Left,
+ Right,
+ Middle,
+ Back,
+ Forward,
+ Other(u16),
+}
+
+/// Describes a difference in the mouse scroll wheel state.
+#[derive(Debug, Clone, Copy, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum MouseScrollDelta {
+ /// Amount in lines or rows to scroll in the horizontal
+ /// and vertical directions.
+ ///
+ /// Positive values indicate that the content that is being scrolled should move
+ /// right and down (revealing more content left and up).
+ LineDelta(f32, f32),
+
+ /// Amount in pixels to scroll in the horizontal and
+ /// vertical direction.
+ ///
+ /// Scroll events are expressed as a `PixelDelta` if
+ /// supported by the device (eg. a touchpad) and
+ /// platform.
+ ///
+ /// Positive values indicate that the content being scrolled should
+ /// move right/down.
+ ///
+ /// For a 'natural scrolling' touch pad (that acts like a touch screen)
+ /// this means moving your fingers right and down should give positive values,
+ /// and move the content right and down (to reveal more things left and up).
+ PixelDelta(PhysicalPosition),
+}
+
+/// Handle to synchronously change the size of the window from the
+/// [`WindowEvent`].
+#[derive(Debug, Clone)]
+pub struct InnerSizeWriter {
+ pub(crate) new_inner_size: Weak>>,
+}
+
+impl InnerSizeWriter {
+ #[cfg(not(orbital_platform))]
+ pub(crate) fn new(new_inner_size: Weak>>) -> Self {
+ Self { new_inner_size }
+ }
+
+ /// Try to request inner size which will be set synchronously on the window.
+ pub fn request_inner_size(
+ &mut self,
+ new_inner_size: PhysicalSize,
+ ) -> Result<(), ExternalError> {
+ if let Some(inner) = self.new_inner_size.upgrade() {
+ *inner.lock().unwrap() = new_inner_size;
+ Ok(())
+ } else {
+ Err(ExternalError::Ignored)
+ }
+ }
+}
+
+impl PartialEq for InnerSizeWriter {
+ fn eq(&self, other: &Self) -> bool {
+ self.new_inner_size.as_ptr() == other.new_inner_size.as_ptr()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::dpi::PhysicalPosition;
+ use crate::event;
+ use std::collections::{BTreeSet, HashSet};
+
+ macro_rules! foreach_event {
+ ($closure:expr) => {{
+ #[allow(unused_mut)]
+ let mut x = $closure;
+ let did = event::DeviceId::dummy();
+
+ #[allow(deprecated)]
+ {
+ use crate::event::Event::*;
+ use crate::event::Ime::Enabled;
+ use crate::event::WindowEvent::*;
+ use crate::window::WindowId;
+
+ // Mainline events.
+ let wid = WindowId::dummy();
+ x(UserEvent(()));
+ x(NewEvents(event::StartCause::Init));
+ x(AboutToWait);
+ x(LoopExiting);
+ x(Suspended);
+ x(Resumed);
+
+ // Window events.
+ let with_window_event = |wev| x(WindowEvent { window_id: wid, event: wev });
+
+ with_window_event(CloseRequested);
+ with_window_event(Destroyed);
+ with_window_event(Focused(true));
+ with_window_event(Moved((0, 0).into()));
+ with_window_event(Resized((0, 0).into()));
+ with_window_event(DroppedFile("x.txt".into()));
+ with_window_event(HoveredFile("x.txt".into()));
+ with_window_event(HoveredFileCancelled);
+ with_window_event(Ime(Enabled));
+ with_window_event(CursorMoved { device_id: did, position: (0, 0).into() });
+ with_window_event(ModifiersChanged(event::Modifiers::default()));
+ with_window_event(CursorEntered { device_id: did });
+ with_window_event(CursorLeft { device_id: did });
+ with_window_event(MouseWheel {
+ device_id: did,
+ delta: event::MouseScrollDelta::LineDelta(0.0, 0.0),
+ phase: event::TouchPhase::Started,
+ });
+ with_window_event(MouseInput {
+ device_id: did,
+ state: event::ElementState::Pressed,
+ button: event::MouseButton::Other(0),
+ });
+ with_window_event(PinchGesture {
+ device_id: did,
+ delta: 0.0,
+ phase: event::TouchPhase::Started,
+ });
+ with_window_event(DoubleTapGesture { device_id: did });
+ with_window_event(RotationGesture {
+ device_id: did,
+ delta: 0.0,
+ phase: event::TouchPhase::Started,
+ });
+ with_window_event(PanGesture {
+ device_id: did,
+ delta: PhysicalPosition::::new(0.0, 0.0),
+ phase: event::TouchPhase::Started,
+ });
+ with_window_event(TouchpadPressure { device_id: did, pressure: 0.0, stage: 0 });
+ with_window_event(AxisMotion { device_id: did, axis: 0, value: 0.0 });
+ with_window_event(Touch(event::Touch {
+ device_id: did,
+ phase: event::TouchPhase::Started,
+ location: (0.0, 0.0).into(),
+ id: 0,
+ force: Some(event::Force::Normalized(0.0)),
+ }));
+ with_window_event(ThemeChanged(crate::window::Theme::Light));
+ with_window_event(Occluded(true));
+ }
+
+ #[allow(deprecated)]
+ {
+ use event::DeviceEvent::*;
+
+ let with_device_event =
+ |dev_ev| x(event::Event::DeviceEvent { device_id: did, event: dev_ev });
+
+ with_device_event(Added);
+ with_device_event(Removed);
+ with_device_event(MouseMotion { delta: (0.0, 0.0).into() });
+ with_device_event(MouseWheel {
+ delta: event::MouseScrollDelta::LineDelta(0.0, 0.0),
+ });
+ with_device_event(Motion { axis: 0, value: 0.0 });
+ with_device_event(Button { button: 0, state: event::ElementState::Pressed });
+ }
+ }};
+ }
+
+ #[allow(clippy::redundant_clone)]
+ #[test]
+ fn test_event_clone() {
+ foreach_event!(|event: event::Event<()>| {
+ let event2 = event.clone();
+ assert_eq!(event, event2);
+ })
+ }
+
+ #[test]
+ fn test_map_nonuser_event() {
+ foreach_event!(|event: event::Event<()>| {
+ let is_user = matches!(event, event::Event::UserEvent(()));
+ let event2 = event.map_nonuser_event::<()>();
+ if is_user {
+ assert_eq!(event2, Err(event::Event::UserEvent(())));
+ } else {
+ assert!(event2.is_ok());
+ }
+ })
+ }
+
+ #[test]
+ fn test_force_normalize() {
+ let force = event::Force::Normalized(0.0);
+ assert_eq!(force.normalized(), 0.0);
+
+ let force2 =
+ event::Force::Calibrated { force: 5.0, max_possible_force: 2.5, altitude_angle: None };
+ assert_eq!(force2.normalized(), 2.0);
+
+ let force3 = event::Force::Calibrated {
+ force: 5.0,
+ max_possible_force: 2.5,
+ altitude_angle: Some(std::f64::consts::PI / 2.0),
+ };
+ assert_eq!(force3.normalized(), 2.0);
+ }
+
+ #[allow(clippy::clone_on_copy)]
+ #[test]
+ fn ensure_attrs_do_not_panic() {
+ foreach_event!(|event: event::Event<()>| {
+ let _ = format!("{event:?}");
+ });
+ let _ = event::StartCause::Init.clone();
+
+ let did = crate::event::DeviceId::dummy().clone();
+ HashSet::new().insert(did);
+ let mut set = [did, did, did];
+ set.sort_unstable();
+ let mut set2 = BTreeSet::new();
+ set2.insert(did);
+ set2.insert(did);
+
+ HashSet::new().insert(event::TouchPhase::Started.clone());
+ HashSet::new().insert(event::MouseButton::Left.clone());
+ HashSet::new().insert(event::Ime::Enabled);
+
+ let _ = event::Touch {
+ device_id: did,
+ phase: event::TouchPhase::Started,
+ location: (0.0, 0.0).into(),
+ id: 0,
+ force: Some(event::Force::Normalized(0.0)),
+ }
+ .clone();
+ let _ =
+ event::Force::Calibrated { force: 0.0, max_possible_force: 0.0, altitude_angle: None }
+ .clone();
+ }
+}
diff --git a/third_party/winit-0.30.13/src/event_loop.rs b/third_party/winit-0.30.13/src/event_loop.rs
new file mode 100644
index 0000000..233374b
--- /dev/null
+++ b/third_party/winit-0.30.13/src/event_loop.rs
@@ -0,0 +1,651 @@
+//! The [`EventLoop`] struct and assorted supporting types, including
+//! [`ControlFlow`].
+//!
+//! If you want to send custom events to the event loop, use
+//! [`EventLoop::create_proxy`] to acquire an [`EventLoopProxy`] and call its
+//! [`send_event`][EventLoopProxy::send_event] method.
+//!
+//! See the root-level documentation for information on how to create and use an event loop to
+//! handle events.
+use std::marker::PhantomData;
+#[cfg(any(x11_platform, wayland_platform))]
+use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::{error, fmt};
+
+#[cfg(not(web_platform))]
+use std::time::{Duration, Instant};
+#[cfg(web_platform)]
+use web_time::{Duration, Instant};
+
+use crate::application::ApplicationHandler;
+use crate::error::{EventLoopError, OsError};
+use crate::event::Event;
+use crate::monitor::MonitorHandle;
+use crate::platform_impl;
+use crate::window::{CustomCursor, CustomCursorSource, Theme, Window, WindowAttributes};
+
+/// Provides a way to retrieve events from the system and from the windows that were registered to
+/// the events loop.
+///
+/// An `EventLoop` can be seen more or less as a "context". Calling [`EventLoop::new`]
+/// initializes everything that will be required to create windows. For example on Linux creating
+/// an event loop opens a connection to the X or Wayland server.
+///
+/// To wake up an `EventLoop` from a another thread, see the [`EventLoopProxy`] docs.
+///
+/// Note that this cannot be shared across threads (due to platform-dependant logic
+/// forbidding it), as such it is neither [`Send`] nor [`Sync`]. If you need cross-thread access,
+/// the [`Window`] created from this _can_ be sent to an other thread, and the
+/// [`EventLoopProxy`] allows you to wake up an `EventLoop` from another thread.
+///
+/// [`Window`]: crate::window::Window
+pub struct EventLoop {
+ pub(crate) event_loop: platform_impl::EventLoop,
+ pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
+}
+
+/// Target that associates windows with an [`EventLoop`].
+///
+/// This type exists to allow you to create new windows while Winit executes
+/// your callback.
+pub struct ActiveEventLoop {
+ pub(crate) p: platform_impl::ActiveEventLoop,
+ pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
+}
+
+/// Object that allows building the event loop.
+///
+/// This is used to make specifying options that affect the whole application
+/// easier. But note that constructing multiple event loops is not supported.
+///
+/// This can be created using [`EventLoop::new`] or [`EventLoop::with_user_event`].
+#[derive(Default)]
+pub struct EventLoopBuilder {
+ pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes,
+ _p: PhantomData,
+}
+
+static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false);
+
+impl EventLoopBuilder<()> {
+ /// Start building a new event loop.
+ #[inline]
+ #[deprecated = "use `EventLoop::builder` instead"]
+ pub fn new() -> Self {
+ EventLoop::builder()
+ }
+}
+
+impl EventLoopBuilder {
+ /// Builds a new event loop.
+ ///
+ /// ***For cross-platform compatibility, the [`EventLoop`] must be created on the main thread,
+ /// and only once per application.***
+ ///
+ /// Calling this function will result in display backend initialisation.
+ ///
+ /// ## Panics
+ ///
+ /// Attempting to create the event loop off the main thread will panic. This
+ /// restriction isn't strictly necessary on all platforms, but is imposed to
+ /// eliminate any nasty surprises when porting to platforms that require it.
+ /// `EventLoopBuilderExt::any_thread` functions are exposed in the relevant
+ /// [`platform`] module if the target platform supports creating an event
+ /// loop on any thread.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY` or
+ /// `DISPLAY` respectively when building the event loop.
+ /// - **Android:** must be configured with an `AndroidApp` from `android_main()` by calling
+ /// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic.
+ ///
+ /// [`platform`]: crate::platform
+ #[cfg_attr(
+ android_platform,
+ doc = "[`.with_android_app(app)`]: \
+ crate::platform::android::EventLoopBuilderExtAndroid::with_android_app"
+ )]
+ #[cfg_attr(
+ not(android_platform),
+ doc = "[`.with_android_app(app)`]: #only-available-on-android"
+ )]
+ #[inline]
+ pub fn build(&mut self) -> Result, EventLoopError> {
+ let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered();
+
+ if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
+ return Err(EventLoopError::RecreationAttempt);
+ }
+
+ // Certain platforms accept a mutable reference in their API.
+ #[allow(clippy::unnecessary_mut_passed)]
+ Ok(EventLoop {
+ event_loop: platform_impl::EventLoop::new(&mut self.platform_specific)?,
+ _marker: PhantomData,
+ })
+ }
+
+ #[cfg(web_platform)]
+ pub(crate) fn allow_event_loop_recreation() {
+ EVENT_LOOP_CREATED.store(false, Ordering::Relaxed);
+ }
+}
+
+impl fmt::Debug for EventLoop {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.pad("EventLoop { .. }")
+ }
+}
+
+impl fmt::Debug for ActiveEventLoop {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.pad("ActiveEventLoop { .. }")
+ }
+}
+
+/// Set through [`ActiveEventLoop::set_control_flow()`].
+///
+/// Indicates the desired behavior of the event loop after [`Event::AboutToWait`] is emitted.
+///
+/// Defaults to [`Wait`].
+///
+/// [`Wait`]: Self::Wait
+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
+pub enum ControlFlow {
+ /// When the current loop iteration finishes, immediately begin a new iteration regardless of
+ /// whether or not new events are available to process.
+ Poll,
+
+ /// When the current loop iteration finishes, suspend the thread until another event arrives.
+ #[default]
+ Wait,
+
+ /// When the current loop iteration finishes, suspend the thread until either another event
+ /// arrives or the given time is reached.
+ ///
+ /// Useful for implementing efficient timers. Applications which want to render at the
+ /// display's native refresh rate should instead use [`Poll`] and the VSync functionality
+ /// of a graphics API to reduce odds of missed frames.
+ ///
+ /// [`Poll`]: Self::Poll
+ WaitUntil(Instant),
+}
+
+impl ControlFlow {
+ /// Creates a [`ControlFlow`] that waits until a timeout has expired.
+ ///
+ /// In most cases, this is set to [`WaitUntil`]. However, if the timeout overflows, it is
+ /// instead set to [`Wait`].
+ ///
+ /// [`WaitUntil`]: Self::WaitUntil
+ /// [`Wait`]: Self::Wait
+ pub fn wait_duration(timeout: Duration) -> Self {
+ match Instant::now().checked_add(timeout) {
+ Some(instant) => Self::WaitUntil(instant),
+ None => Self::Wait,
+ }
+ }
+}
+
+impl EventLoop<()> {
+ /// Create the event loop.
+ ///
+ /// This is an alias of `EventLoop::builder().build()`.
+ #[inline]
+ pub fn new() -> Result, EventLoopError> {
+ Self::builder().build()
+ }
+
+ /// Start building a new event loop.
+ ///
+ /// This returns an [`EventLoopBuilder`], to allow configuring the event loop before creation.
+ ///
+ /// To get the actual event loop, call [`build`][EventLoopBuilder::build] on that.
+ #[inline]
+ pub fn builder() -> EventLoopBuilder<()> {
+ Self::with_user_event()
+ }
+}
+
+impl EventLoop {
+ /// Start building a new event loop, with the given type as the user event
+ /// type.
+ pub fn with_user_event() -> EventLoopBuilder {
+ EventLoopBuilder { platform_specific: Default::default(), _p: PhantomData }
+ }
+
+ /// See [`run_app`].
+ ///
+ /// [`run_app`]: Self::run_app
+ #[inline]
+ #[deprecated = "use `EventLoop::run_app` instead"]
+ #[cfg(not(all(web_platform, target_feature = "exception-handling")))]
+ pub fn run(self, event_handler: F) -> Result<(), EventLoopError>
+ where
+ F: FnMut(Event, &ActiveEventLoop),
+ {
+ let _span = tracing::debug_span!("winit::EventLoop::run").entered();
+
+ self.event_loop.run(event_handler)
+ }
+
+ /// Run the application with the event loop on the calling thread.
+ ///
+ /// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **iOS:** Will never return to the caller and so values not passed to this function will
+ /// *not* be dropped before the process exits.
+ /// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript
+ /// exception (that Rust doesn't see) that will also mean that the rest of the function is
+ /// never executed and any values not passed to this function will *not* be dropped.
+ ///
+ /// Web applications are recommended to use
+ #[cfg_attr(
+ web_platform,
+ doc = "[`EventLoopExtWebSys::spawn_app()`][crate::platform::web::EventLoopExtWebSys::spawn_app()]"
+ )]
+ #[cfg_attr(not(web_platform), doc = "`EventLoopExtWebSys::spawn()`")]
+ /// [^1] instead of [`run_app()`] to avoid the need
+ /// for the Javascript exception trick, and to make it clearer that the event loop runs
+ /// asynchronously (via the browser's own, internal, event loop) and doesn't block the
+ /// current thread of execution like it does on other platforms.
+ ///
+ /// This function won't be available with `target_feature = "exception-handling"`.
+ ///
+ /// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
+ /// [`run_app()`]: Self::run_app()
+ /// [^1]: `EventLoopExtWebSys::spawn_app()` is only available on Web.
+ #[inline]
+ #[cfg(not(all(web_platform, target_feature = "exception-handling")))]
+ pub fn run_app>(self, app: &mut A) -> Result<(), EventLoopError> {
+ self.event_loop.run(|event, event_loop| dispatch_event_for_app(app, event_loop, event))
+ }
+
+ /// Creates an [`EventLoopProxy`] that can be used to dispatch user events
+ /// to the main event loop, possibly from another thread.
+ pub fn create_proxy(&self) -> EventLoopProxy {
+ EventLoopProxy { event_loop_proxy: self.event_loop.create_proxy() }
+ }
+
+ /// Gets a persistent reference to the underlying platform display.
+ ///
+ /// See the [`OwnedDisplayHandle`] type for more information.
+ pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
+ OwnedDisplayHandle { platform: self.event_loop.window_target().p.owned_display_handle() }
+ }
+
+ /// Change if or when [`DeviceEvent`]s are captured.
+ ///
+ /// See [`ActiveEventLoop::listen_device_events`] for details.
+ ///
+ /// [`DeviceEvent`]: crate::event::DeviceEvent
+ pub fn listen_device_events(&self, allowed: DeviceEvents) {
+ let _span = tracing::debug_span!(
+ "winit::EventLoop::listen_device_events",
+ allowed = ?allowed
+ )
+ .entered();
+
+ self.event_loop.window_target().p.listen_device_events(allowed);
+ }
+
+ /// Sets the [`ControlFlow`].
+ pub fn set_control_flow(&self, control_flow: ControlFlow) {
+ self.event_loop.window_target().p.set_control_flow(control_flow)
+ }
+
+ /// Create a window.
+ ///
+ /// Creating window without event loop running often leads to improper window creation;
+ /// use [`ActiveEventLoop::create_window`] instead.
+ #[deprecated = "use `ActiveEventLoop::create_window` instead"]
+ #[inline]
+ pub fn create_window(&self, window_attributes: WindowAttributes) -> Result {
+ let _span = tracing::debug_span!(
+ "winit::EventLoop::create_window",
+ window_attributes = ?window_attributes
+ )
+ .entered();
+
+ let window =
+ platform_impl::Window::new(&self.event_loop.window_target().p, window_attributes)?;
+ Ok(Window { window })
+ }
+
+ /// Create custom cursor.
+ pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
+ self.event_loop.window_target().p.create_custom_cursor(custom_cursor)
+ }
+}
+
+#[cfg(feature = "rwh_06")]
+impl rwh_06::HasDisplayHandle for EventLoop {
+ fn display_handle(&self) -> Result, rwh_06::HandleError> {
+ rwh_06::HasDisplayHandle::display_handle(self.event_loop.window_target())
+ }
+}
+
+#[cfg(feature = "rwh_05")]
+unsafe impl rwh_05::HasRawDisplayHandle for EventLoop {
+ /// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
+ fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
+ rwh_05::HasRawDisplayHandle::raw_display_handle(self.event_loop.window_target())
+ }
+}
+
+#[cfg(any(x11_platform, wayland_platform))]
+impl AsFd for EventLoop {
+ /// Get the underlying [EventLoop]'s `fd` which you can register
+ /// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
+ /// loop must be polled with the [`pump_app_events`] API.
+ ///
+ /// [`calloop`]: https://crates.io/crates/calloop
+ /// [`mio`]: https://crates.io/crates/mio
+ /// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events
+ fn as_fd(&self) -> BorrowedFd<'_> {
+ self.event_loop.as_fd()
+ }
+}
+
+#[cfg(any(x11_platform, wayland_platform))]
+impl AsRawFd for EventLoop {
+ /// Get the underlying [EventLoop]'s raw `fd` which you can register
+ /// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
+ /// loop must be polled with the [`pump_app_events`] API.
+ ///
+ /// [`calloop`]: https://crates.io/crates/calloop
+ /// [`mio`]: https://crates.io/crates/mio
+ /// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events
+ fn as_raw_fd(&self) -> RawFd {
+ self.event_loop.as_raw_fd()
+ }
+}
+
+impl ActiveEventLoop {
+ /// Create the window.
+ ///
+ /// Possible causes of error include denied permission, incompatible system, and lack of memory.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **Web:** The window is created but not inserted into the web page automatically. Please
+ /// see the web platform module for more information.
+ #[inline]
+ pub fn create_window(&self, window_attributes: WindowAttributes) -> Result {
+ let _span = tracing::debug_span!(
+ "winit::ActiveEventLoop::create_window",
+ window_attributes = ?window_attributes
+ )
+ .entered();
+
+ let window = platform_impl::Window::new(&self.p, window_attributes)?;
+ Ok(Window { window })
+ }
+
+ /// Create custom cursor.
+ 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)
+ }
+
+ /// Returns the list of all the monitors available on the system.
+ #[inline]
+ pub fn available_monitors(&self) -> impl Iterator- {
+ let _span = tracing::debug_span!("winit::ActiveEventLoop::available_monitors",).entered();
+
+ #[allow(clippy::useless_conversion)] // false positive on some platforms
+ self.p.available_monitors().into_iter().map(|inner| MonitorHandle { inner })
+ }
+
+ /// Returns the primary monitor of the system.
+ ///
+ /// Returns `None` if it can't identify any monitor as a primary one.
+ ///
+ /// ## Platform-specific
+ ///
+ /// **Wayland / Web:** Always returns `None`.
+ #[inline]
+ pub fn primary_monitor(&self) -> Option
{
+ let _span = tracing::debug_span!("winit::ActiveEventLoop::primary_monitor",).entered();
+
+ self.p.primary_monitor().map(|inner| MonitorHandle { inner })
+ }
+
+ /// Change if or when [`DeviceEvent`]s are captured.
+ ///
+ /// Since the [`DeviceEvent`] capture can lead to high CPU usage for unfocused windows, winit
+ /// will ignore them by default for unfocused windows on Linux/BSD. This method allows changing
+ /// this at runtime to explicitly capture them again.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **Wayland / macOS / iOS / Android / Orbital:** Unsupported.
+ ///
+ /// [`DeviceEvent`]: crate::event::DeviceEvent
+ 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);
+ }
+
+ /// Returns the current system theme.
+ ///
+ /// Returns `None` if it cannot be determined on the current platform.
+ ///
+ /// ## Platform-specific
+ ///
+ /// - **iOS / Android / Wayland / x11 / Orbital:** Unsupported.
+ pub fn system_theme(&self) -> Option {
+ self.p.system_theme()
+ }
+
+ /// Sets the [`ControlFlow`].
+ pub fn set_control_flow(&self, control_flow: ControlFlow) {
+ self.p.set_control_flow(control_flow)
+ }
+
+ /// Gets the current [`ControlFlow`].
+ pub fn control_flow(&self) -> ControlFlow {
+ self.p.control_flow()
+ }
+
+ /// This exits the event loop.
+ ///
+ /// See [`LoopExiting`][Event::LoopExiting].
+ pub fn exit(&self) {
+ let _span = tracing::debug_span!("winit::ActiveEventLoop::exit",).entered();
+
+ self.p.exit()
+ }
+
+ /// Returns if the [`EventLoop`] is about to stop.
+ ///
+ /// See [`exit()`][Self::exit].
+ pub fn exiting(&self) -> bool {
+ self.p.exiting()
+ }
+
+ /// Gets a persistent reference to the underlying platform display.
+ ///
+ /// See the [`OwnedDisplayHandle`] type for more information.
+ pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
+ OwnedDisplayHandle { platform: self.p.owned_display_handle() }
+ }
+}
+
+#[cfg(feature = "rwh_06")]
+impl rwh_06::HasDisplayHandle for ActiveEventLoop {
+ fn display_handle(&self) -> Result, rwh_06::HandleError> {
+ let raw = self.p.raw_display_handle_rwh_06()?;
+ // SAFETY: The display will never be deallocated while the event loop is alive.
+ Ok(unsafe { rwh_06::DisplayHandle::borrow_raw(raw) })
+ }
+}
+
+#[cfg(feature = "rwh_05")]
+unsafe impl rwh_05::HasRawDisplayHandle for ActiveEventLoop {
+ /// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
+ fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
+ self.p.raw_display_handle_rwh_05()
+ }
+}
+
+/// A proxy for the underlying display handle.
+///
+/// The purpose of this type is to provide a cheaply cloneable handle to the underlying
+/// display handle. This is often used by graphics APIs to connect to the underlying APIs.
+/// It is difficult to keep a handle to the [`EventLoop`] type or the [`ActiveEventLoop`]
+/// type. In contrast, this type involves no lifetimes and can be persisted for as long as
+/// needed.
+///
+/// For all platforms, this is one of the following:
+///
+/// - A zero-sized type that is likely optimized out.
+/// - A reference-counted pointer to the underlying type.
+#[derive(Clone)]
+pub struct OwnedDisplayHandle {
+ #[cfg_attr(not(any(feature = "rwh_05", feature = "rwh_06")), allow(dead_code))]
+ platform: platform_impl::OwnedDisplayHandle,
+}
+
+impl fmt::Debug for OwnedDisplayHandle {
+ #[inline]
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("OwnedDisplayHandle").finish_non_exhaustive()
+ }
+}
+
+#[cfg(feature = "rwh_06")]
+impl rwh_06::HasDisplayHandle for OwnedDisplayHandle {
+ #[inline]
+ fn display_handle(&self) -> Result, rwh_06::HandleError> {
+ let raw = self.platform.raw_display_handle_rwh_06()?;
+
+ // SAFETY: The underlying display handle should be safe.
+ let handle = unsafe { rwh_06::DisplayHandle::borrow_raw(raw) };
+
+ Ok(handle)
+ }
+}
+
+#[cfg(feature = "rwh_05")]
+unsafe impl rwh_05::HasRawDisplayHandle for OwnedDisplayHandle {
+ #[inline]
+ fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
+ self.platform.raw_display_handle_rwh_05()
+ }
+}
+
+/// Used to send custom events to [`EventLoop`].
+pub struct EventLoopProxy {
+ event_loop_proxy: platform_impl::EventLoopProxy,
+}
+
+impl Clone for EventLoopProxy {
+ fn clone(&self) -> Self {
+ Self { event_loop_proxy: self.event_loop_proxy.clone() }
+ }
+}
+
+impl EventLoopProxy {
+ /// Send an event to the [`EventLoop`] from which this proxy was created. This emits a
+ /// `UserEvent(event)` event in the event loop, where `event` is the value passed to this
+ /// function.
+ ///
+ /// Returns an `Err` if the associated [`EventLoop`] no longer exists.
+ ///
+ /// [`UserEvent(event)`]: Event::UserEvent
+ pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> {
+ let _span = tracing::debug_span!("winit::EventLoopProxy::send_event",).entered();
+
+ self.event_loop_proxy.send_event(event)
+ }
+}
+
+impl fmt::Debug for EventLoopProxy {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.pad("EventLoopProxy { .. }")
+ }
+}
+
+/// The error that is returned when an [`EventLoopProxy`] attempts to wake up an [`EventLoop`] that
+/// no longer exists.
+///
+/// Contains the original event given to [`EventLoopProxy::send_event`].
+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
+pub struct EventLoopClosed(pub T);
+
+impl fmt::Display for EventLoopClosed {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("Tried to wake up a closed `EventLoop`")
+ }
+}
+
+impl error::Error for EventLoopClosed {}
+
+/// Control when device events are captured.
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
+pub enum DeviceEvents {
+ /// Report device events regardless of window focus.
+ Always,
+ /// Only capture device events while the window is focused.
+ #[default]
+ WhenFocused,
+ /// Never capture device events.
+ Never,
+}
+
+/// A unique identifier of the winit's async request.
+///
+/// This could be used to identify the async request once it's done
+/// and a specific action must be taken.
+///
+/// One of the handling scenarios could be to maintain a working list
+/// containing [`AsyncRequestSerial`] and some closure associated with it.
+/// Then once event is arriving the working list is being traversed and a job
+/// executed and removed from the list.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AsyncRequestSerial {
+ serial: usize,
+}
+
+impl AsyncRequestSerial {
+ // TODO(kchibisov): Remove `cfg` when the clipboard will be added.
+ #[allow(dead_code)]
+ pub(crate) fn get() -> Self {
+ static CURRENT_SERIAL: AtomicUsize = AtomicUsize::new(0);
+ // NOTE: We rely on wrap around here, while the user may just request
+ // in the loop usize::MAX times that's issue is considered on them.
+ let serial = CURRENT_SERIAL.fetch_add(1, Ordering::Relaxed);
+ Self { serial }
+ }
+}
+
+/// Shim for various run APIs.
+#[inline(always)]
+pub(crate) fn dispatch_event_for_app>(
+ app: &mut A,
+ event_loop: &ActiveEventLoop,
+ event: Event,
+) {
+ match event {
+ Event::NewEvents(cause) => app.new_events(event_loop, cause),
+ Event::WindowEvent { window_id, event } => app.window_event(event_loop, window_id, event),
+ Event::DeviceEvent { device_id, event } => app.device_event(event_loop, device_id, event),
+ Event::UserEvent(event) => app.user_event(event_loop, event),
+ Event::Suspended => app.suspended(event_loop),
+ Event::Resumed => app.resumed(event_loop),
+ Event::AboutToWait => app.about_to_wait(event_loop),
+ Event::LoopExiting => app.exiting(event_loop),
+ Event::MemoryWarning => app.memory_warning(event_loop),
+ }
+}
diff --git a/third_party/winit-0.30.13/src/icon.rs b/third_party/winit-0.30.13/src/icon.rs
new file mode 100644
index 0000000..b013d2f
--- /dev/null
+++ b/third_party/winit-0.30.13/src/icon.rs
@@ -0,0 +1,117 @@
+use crate::platform_impl::PlatformIcon;
+use std::error::Error;
+use std::{fmt, io, mem};
+
+#[repr(C)]
+#[derive(Debug)]
+pub(crate) struct Pixel {
+ pub(crate) r: u8,
+ pub(crate) g: u8,
+ pub(crate) b: u8,
+ pub(crate) a: u8,
+}
+
+pub(crate) const PIXEL_SIZE: usize = mem::size_of::();
+
+#[derive(Debug)]
+/// An error produced when using [`Icon::from_rgba`] with invalid arguments.
+pub enum BadIcon {
+ /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
+ /// safely interpreted as 32bpp RGBA pixels.
+ ByteCountNotDivisibleBy4 { byte_count: usize },
+ /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
+ /// At least one of your arguments is incorrect.
+ DimensionsVsPixelCount { width: u32, height: u32, width_x_height: usize, pixel_count: usize },
+ /// Produced when underlying OS functionality failed to create the icon
+ OsError(io::Error),
+}
+
+impl fmt::Display for BadIcon {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(
+ f,
+ "The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making \
+ it impossible to interpret as 32bpp RGBA pixels.",
+ ),
+ BadIcon::DimensionsVsPixelCount { width, height, width_x_height, pixel_count } => {
+ write!(
+ f,
+ "The specified dimensions ({width:?}x{height:?}) don't match the number of \
+ pixels supplied by the `rgba` argument ({pixel_count:?}). For those \
+ dimensions, the expected pixel count is {width_x_height:?}.",
+ )
+ },
+ BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {e:?}"),
+ }
+ }
+}
+
+impl Error for BadIcon {}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct RgbaIcon {
+ pub(crate) rgba: Vec,
+ pub(crate) width: u32,
+ pub(crate) height: u32,
+}
+
+/// For platforms which don't have window icons (e.g. web)
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct NoIcon;
+
+#[allow(dead_code)] // These are not used on every platform
+mod constructors {
+ use super::*;
+
+ impl RgbaIcon {
+ pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result {
+ if rgba.len() % PIXEL_SIZE != 0 {
+ return Err(BadIcon::ByteCountNotDivisibleBy4 { byte_count: rgba.len() });
+ }
+ let pixel_count = rgba.len() / PIXEL_SIZE;
+ if pixel_count != (width * height) as usize {
+ Err(BadIcon::DimensionsVsPixelCount {
+ width,
+ height,
+ width_x_height: (width * height) as usize,
+ pixel_count,
+ })
+ } else {
+ Ok(RgbaIcon { rgba, width, height })
+ }
+ }
+ }
+
+ impl NoIcon {
+ pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result {
+ // Create the rgba icon anyway to validate the input
+ let _ = RgbaIcon::from_rgba(rgba, width, height)?;
+ Ok(NoIcon)
+ }
+ }
+}
+
+/// An icon used for the window titlebar, taskbar, etc.
+#[derive(Clone)]
+pub struct Icon {
+ pub(crate) inner: PlatformIcon,
+}
+
+impl fmt::Debug for Icon {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+ fmt::Debug::fmt(&self.inner, formatter)
+ }
+}
+
+impl Icon {
+ /// Creates an icon from 32bpp RGBA data.
+ ///
+ /// The length of `rgba` must be divisible by 4, and `width * height` must equal
+ /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
+ pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result {
+ let _span = tracing::debug_span!("winit::Icon::from_rgba", width, height).entered();
+
+ Ok(Icon { inner: PlatformIcon::from_rgba(rgba, width, height)? })
+ }
+}
diff --git a/third_party/winit-0.30.13/src/keyboard.rs b/third_party/winit-0.30.13/src/keyboard.rs
new file mode 100644
index 0000000..7b406f0
--- /dev/null
+++ b/third_party/winit-0.30.13/src/keyboard.rs
@@ -0,0 +1,1804 @@
+//! Types related to the keyboard.
+
+// This file contains a substantial portion of the UI Events Specification by the W3C. In
+// particular, the variant names within `Key` and `KeyCode` and their documentation are modified
+// versions of contents of the aforementioned specification.
+//
+// The original documents are:
+//
+// ### For `Key`
+// UI Events KeyboardEvent key Values
+// https://www.w3.org/TR/2017/CR-uievents-key-20170601/
+// Copyright © 2017 W3C® (MIT, ERCIM, Keio, Beihang).
+//
+// ### For `KeyCode`
+// UI Events KeyboardEvent code Values
+// https://www.w3.org/TR/2017/CR-uievents-code-20170601/
+// Copyright © 2017 W3C® (MIT, ERCIM, Keio, Beihang).
+//
+// These documents were used under the terms of the following license. This W3C license as well as
+// the W3C short notice apply to the `Key` and `KeyCode` enums and their variants and the
+// documentation attached to their variants.
+
+// --------- BEGINNING OF W3C LICENSE --------------------------------------------------------------
+//
+// License
+//
+// By obtaining and/or copying this work, you (the licensee) agree that you have read, understood,
+// and will comply with the following terms and conditions.
+//
+// Permission to copy, modify, and distribute this work, with or without modification, for any
+// purpose and without fee or royalty is hereby granted, provided that you include the following on
+// ALL copies of the work or portions thereof, including modifications:
+//
+// - The full text of this NOTICE in a location viewable to users of the redistributed or derivative
+// work.
+// - Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none
+// exist, the W3C Software and Document Short Notice should be included.
+// - Notice of any changes or modifications, through a copyright statement on the new code or
+// document such as "This software or document includes material copied from or derived from
+// [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)."
+//
+// Disclaimers
+//
+// THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR
+// ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD
+// PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
+//
+// COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES
+// ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT.
+//
+// The name and trademarks of copyright holders may NOT be used in advertising or publicity
+// pertaining to the work without specific, written prior permission. Title to copyright in this
+// work will at all times remain with copyright holders.
+//
+// --------- END OF W3C LICENSE --------------------------------------------------------------------
+
+// --------- BEGINNING OF W3C SHORT NOTICE ---------------------------------------------------------
+//
+// winit: https://github.com/rust-windowing/winit
+//
+// Copyright © 2021 World Wide Web Consortium, (Massachusetts Institute of Technology, European
+// Research Consortium for Informatics and Mathematics, Keio University, Beihang). All Rights
+// Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will
+// be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+// FITNESS FOR A PARTICULAR PURPOSE.
+//
+// [1] http://www.w3.org/Consortium/Legal/copyright-software
+//
+// --------- END OF W3C SHORT NOTICE ---------------------------------------------------------------
+
+use bitflags::bitflags;
+#[cfg(feature = "serde")]
+use serde::{Deserialize, Serialize};
+pub use smol_str::SmolStr;
+
+/// Contains the platform-native physical key identifier
+///
+/// The exact values vary from platform to platform (which is part of why this is a per-platform
+/// enum), but the values are primarily tied to the key's physical location on the keyboard.
+///
+/// This enum is primarily used to store raw keycodes when Winit doesn't map a given native
+/// physical key identifier to a meaningful [`KeyCode`] variant. In the presence of identifiers we
+/// haven't mapped for you yet, this lets you use use [`KeyCode`] to:
+///
+/// - Correctly match key press and release events.
+/// - On non-web platforms, support assigning keybinds to virtually any key through a UI.
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum NativeKeyCode {
+ Unidentified,
+ /// An Android "scancode".
+ Android(u32),
+ /// A macOS "scancode".
+ MacOS(u16),
+ /// A Windows "scancode".
+ Windows(u16),
+ /// An XKB "keycode".
+ Xkb(u32),
+}
+
+impl std::fmt::Debug for NativeKeyCode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ use NativeKeyCode::{Android, MacOS, Unidentified, Windows, Xkb};
+ let mut debug_tuple;
+ match self {
+ Unidentified => {
+ debug_tuple = f.debug_tuple("Unidentified");
+ },
+ Android(code) => {
+ debug_tuple = f.debug_tuple("Android");
+ debug_tuple.field(&format_args!("0x{code:04X}"));
+ },
+ MacOS(code) => {
+ debug_tuple = f.debug_tuple("MacOS");
+ debug_tuple.field(&format_args!("0x{code:04X}"));
+ },
+ Windows(code) => {
+ debug_tuple = f.debug_tuple("Windows");
+ debug_tuple.field(&format_args!("0x{code:04X}"));
+ },
+ Xkb(code) => {
+ debug_tuple = f.debug_tuple("Xkb");
+ debug_tuple.field(&format_args!("0x{code:04X}"));
+ },
+ }
+ debug_tuple.finish()
+ }
+}
+
+/// Contains the platform-native logical key identifier
+///
+/// Exactly what that means differs from platform to platform, but the values are to some degree
+/// tied to the currently active keyboard layout. The same key on the same keyboard may also report
+/// different values on different platforms, which is one of the reasons this is a per-platform
+/// enum.
+///
+/// This enum is primarily used to store raw keysym when Winit doesn't map a given native logical
+/// key identifier to a meaningful [`Key`] variant. This lets you use [`Key`], and let the user
+/// define keybinds which work in the presence of identifiers we haven't mapped for you yet.
+#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum NativeKey {
+ Unidentified,
+ /// An Android "keycode", which is similar to a "virtual-key code" on Windows.
+ Android(u32),
+ /// A macOS "scancode". There does not appear to be any direct analogue to either keysyms or
+ /// "virtual-key" codes in macOS, so we report the scancode instead.
+ MacOS(u16),
+ /// A Windows "virtual-key code".
+ Windows(u16),
+ /// An XKB "keysym".
+ Xkb(u32),
+ /// A "key value string".
+ Web(SmolStr),
+}
+
+impl std::fmt::Debug for NativeKey {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ use NativeKey::{Android, MacOS, Unidentified, Web, Windows, Xkb};
+ let mut debug_tuple;
+ match self {
+ Unidentified => {
+ debug_tuple = f.debug_tuple("Unidentified");
+ },
+ Android(code) => {
+ debug_tuple = f.debug_tuple("Android");
+ debug_tuple.field(&format_args!("0x{code:04X}"));
+ },
+ MacOS(code) => {
+ debug_tuple = f.debug_tuple("MacOS");
+ debug_tuple.field(&format_args!("0x{code:04X}"));
+ },
+ Windows(code) => {
+ debug_tuple = f.debug_tuple("Windows");
+ debug_tuple.field(&format_args!("0x{code:04X}"));
+ },
+ Xkb(code) => {
+ debug_tuple = f.debug_tuple("Xkb");
+ debug_tuple.field(&format_args!("0x{code:04X}"));
+ },
+ Web(code) => {
+ debug_tuple = f.debug_tuple("Web");
+ debug_tuple.field(code);
+ },
+ }
+ debug_tuple.finish()
+ }
+}
+
+impl From for NativeKey {
+ #[inline]
+ fn from(code: NativeKeyCode) -> Self {
+ match code {
+ NativeKeyCode::Unidentified => NativeKey::Unidentified,
+ NativeKeyCode::Android(x) => NativeKey::Android(x),
+ NativeKeyCode::MacOS(x) => NativeKey::MacOS(x),
+ NativeKeyCode::Windows(x) => NativeKey::Windows(x),
+ NativeKeyCode::Xkb(x) => NativeKey::Xkb(x),
+ }
+ }
+}
+
+impl PartialEq for NativeKeyCode {
+ #[allow(clippy::cmp_owned)] // uses less code than direct match; target is stack allocated
+ #[inline]
+ fn eq(&self, rhs: &NativeKey) -> bool {
+ NativeKey::from(*self) == *rhs
+ }
+}
+
+impl PartialEq for NativeKey {
+ #[inline]
+ fn eq(&self, rhs: &NativeKeyCode) -> bool {
+ rhs == self
+ }
+}
+
+/// Represents the location of a physical key.
+///
+/// This type is a superset of [`KeyCode`], including an [`Unidentified`][Self::Unidentified]
+/// variant.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum PhysicalKey {
+ /// A known key code
+ Code(KeyCode),
+ /// This variant is used when the key cannot be translated to a [`KeyCode`]
+ ///
+ /// The native keycode is provided (if available) so you're able to more reliably match
+ /// key-press and key-release events by hashing the [`PhysicalKey`]. It is also possible to use
+ /// this for keybinds for non-standard keys, but such keybinds are tied to a given platform.
+ Unidentified(NativeKeyCode),
+}
+
+impl From for PhysicalKey {
+ #[inline]
+ fn from(code: KeyCode) -> Self {
+ PhysicalKey::Code(code)
+ }
+}
+
+impl From for PhysicalKey {
+ #[inline]
+ fn from(code: NativeKeyCode) -> Self {
+ PhysicalKey::Unidentified(code)
+ }
+}
+
+impl PartialEq for PhysicalKey {
+ #[inline]
+ fn eq(&self, rhs: &KeyCode) -> bool {
+ match self {
+ PhysicalKey::Code(ref code) => code == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq for KeyCode {
+ #[inline]
+ fn eq(&self, rhs: &PhysicalKey) -> bool {
+ rhs == self
+ }
+}
+
+impl PartialEq for PhysicalKey {
+ #[inline]
+ fn eq(&self, rhs: &NativeKeyCode) -> bool {
+ match self {
+ PhysicalKey::Unidentified(ref code) => code == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq for NativeKeyCode {
+ #[inline]
+ fn eq(&self, rhs: &PhysicalKey) -> bool {
+ rhs == self
+ }
+}
+
+/// Code representing the location of a physical key
+///
+/// This mostly conforms to the UI Events Specification's [`KeyboardEvent.code`] with a few
+/// exceptions:
+/// - The keys that the specification calls "MetaLeft" and "MetaRight" are named "SuperLeft" and
+/// "SuperRight" here.
+/// - The key that the specification calls "Super" is reported as `Unidentified` here.
+///
+/// [`KeyboardEvent.code`]: https://w3c.github.io/uievents-code/#code-value-tables
+#[non_exhaustive]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum KeyCode {
+ /// ` on a US keyboard. This is also called a backtick or grave.
+ /// This is the 半角 /全角 /漢字
+ /// (hankaku/zenkaku/kanji) key on Japanese keyboards
+ Backquote,
+ /// Used for both the US \\ (on the 101-key layout) and also for the key
+ /// located between the " and Enter keys on row C of the 102-,
+ /// 104- and 106-key layouts.
+ /// Labeled # on a UK (102) keyboard.
+ Backslash,
+ /// [ on a US keyboard.
+ BracketLeft,
+ /// ] on a US keyboard.
+ BracketRight,
+ /// , on a US keyboard.
+ Comma,
+ /// 0 on a US keyboard.
+ Digit0,
+ /// 1 on a US keyboard.
+ Digit1,
+ /// 2 on a US keyboard.
+ Digit2,
+ /// 3 on a US keyboard.
+ Digit3,
+ /// 4 on a US keyboard.
+ Digit4,
+ /// 5 on a US keyboard.
+ Digit5,
+ /// 6 on a US keyboard.
+ Digit6,
+ /// 7 on a US keyboard.
+ Digit7,
+ /// 8 on a US keyboard.
+ Digit8,
+ /// 9 on a US keyboard.
+ Digit9,
+ /// = on a US keyboard.
+ Equal,
+ /// Located between the left Shift and Z keys.
+ /// Labeled \\ on a UK keyboard.
+ IntlBackslash,
+ /// Located between the / and right Shift keys.
+ /// Labeled \\ (ro) on a Japanese keyboard.
+ IntlRo,
+ /// Located between the = and Backspace keys.
+ /// Labeled ¥ (yen) on a Japanese keyboard. \\ on a
+ /// Russian keyboard.
+ IntlYen,
+ /// a on a US keyboard.
+ /// Labeled q on an AZERTY (e.g., French) keyboard.
+ KeyA,
+ /// b on a US keyboard.
+ KeyB,
+ /// c on a US keyboard.
+ KeyC,
+ /// d on a US keyboard.
+ KeyD,
+ /// e on a US keyboard.
+ KeyE,
+ /// f on a US keyboard.
+ KeyF,
+ /// g on a US keyboard.
+ KeyG,
+ /// h on a US keyboard.
+ KeyH,
+ /// i on a US keyboard.
+ KeyI,
+ /// j on a US keyboard.
+ KeyJ,
+ /// k on a US keyboard.
+ KeyK,
+ /// l on a US keyboard.
+ KeyL,
+ /// m on a US keyboard.
+ KeyM,
+ /// n on a US keyboard.
+ KeyN,
+ /// o on a US keyboard.
+ KeyO,
+ /// p on a US keyboard.
+ KeyP,
+ /// q on a US keyboard.
+ /// Labeled a on an AZERTY (e.g., French) keyboard.
+ KeyQ,
+ /// r on a US keyboard.
+ KeyR,
+ /// s on a US keyboard.
+ KeyS,
+ /// t on a US keyboard.
+ KeyT,
+ /// u on a US keyboard.
+ KeyU,
+ /// v on a US keyboard.
+ KeyV,
+ /// w on a US keyboard.
+ /// Labeled z on an AZERTY (e.g., French) keyboard.
+ KeyW,
+ /// x on a US keyboard.
+ KeyX,
+ /// y on a US keyboard.
+ /// Labeled z on a QWERTZ (e.g., German) keyboard.
+ KeyY,
+ /// z on a US keyboard.
+ /// Labeled w on an AZERTY (e.g., French) keyboard, and y on a
+ /// QWERTZ (e.g., German) keyboard.
+ KeyZ,
+ /// - on a US keyboard.
+ Minus,
+ /// . on a US keyboard.
+ Period,
+ /// ' on a US keyboard.
+ Quote,
+ /// ; on a US keyboard.
+ Semicolon,
+ /// / on a US keyboard.
+ Slash,
+ /// Alt , Option , or ⌥ .
+ AltLeft,
+ /// Alt , Option , or ⌥ .
+ /// This is labeled AltGr on many keyboard layouts.
+ AltRight,
+ /// Backspace or ⌫ .
+ /// Labeled Delete on Apple keyboards.
+ Backspace,
+ /// CapsLock or ⇪
+ CapsLock,
+ /// The application context menu key, which is typically found between the right
+ /// Super key and the right Control key.
+ ContextMenu,
+ /// Control or ⌃
+ ControlLeft,
+ /// Control or ⌃
+ ControlRight,
+ /// Enter or ↵ . Labeled Return on Apple keyboards.
+ Enter,
+ /// The Windows, ⌘ , Command , or other OS symbol key.
+ SuperLeft,
+ /// The Windows, ⌘ , Command , or other OS symbol key.
+ SuperRight,
+ /// Shift or ⇧
+ ShiftLeft,
+ /// Shift or ⇧
+ ShiftRight,
+ /// (space)
+ Space,
+ /// Tab or ⇥
+ Tab,
+ /// Japanese: 変 (henkan)
+ Convert,
+ /// Japanese: カタカナ /ひらがな /ローマ字
+ /// (katakana/hiragana/romaji)
+ KanaMode,
+ /// Korean: HangulMode 한/영 (han/yeong)
+ ///
+ /// Japanese (Mac keyboard): か (kana)
+ Lang1,
+ /// Korean: Hanja 한 (hanja)
+ ///
+ /// Japanese (Mac keyboard): 英 (eisu)
+ Lang2,
+ /// Japanese (word-processing keyboard): Katakana
+ Lang3,
+ /// Japanese (word-processing keyboard): Hiragana
+ Lang4,
+ /// Japanese (word-processing keyboard): Zenkaku/Hankaku
+ Lang5,
+ /// Japanese: 無変換 (muhenkan)
+ NonConvert,
+ /// ⌦ . The forward delete key.
+ /// Note that on Apple keyboards, the key labelled Delete on the main part of
+ /// the keyboard is encoded as [`Backspace`].
+ ///
+ /// [`Backspace`]: Self::Backspace
+ Delete,
+ /// Page Down , End , or ↘
+ End,
+ /// Help . Not present on standard PC keyboards.
+ Help,
+ /// Home or ↖
+ Home,
+ /// Insert or Ins . Not present on Apple keyboards.
+ Insert,
+ /// Page Down , PgDn , or ⇟
+ PageDown,
+ /// Page Up , PgUp , or ⇞
+ PageUp,
+ /// ↓
+ ArrowDown,
+ /// ←
+ ArrowLeft,
+ /// →
+ ArrowRight,
+ /// ↑
+ ArrowUp,
+ /// On the Mac, this is used for the numpad Clear key.
+ NumLock,
+ /// 0 Ins on a keyboard. 0 on a phone or remote control
+ Numpad0,
+ /// 1 End on a keyboard. 1 or 1 QZ on a phone or remote
+ /// control
+ Numpad1,
+ /// 2 ↓ on a keyboard. 2 ABC on a phone or remote control
+ Numpad2,
+ /// 3 PgDn on a keyboard. 3 DEF on a phone or remote control
+ Numpad3,
+ /// 4 ← on a keyboard. 4 GHI on a phone or remote control
+ Numpad4,
+ /// 5 on a keyboard. 5 JKL on a phone or remote control
+ Numpad5,
+ /// 6 → on a keyboard. 6 MNO on a phone or remote control
+ Numpad6,
+ /// 7 Home on a keyboard. 7 PQRS or 7 PRS on a phone
+ /// or remote control
+ Numpad7,
+ /// 8 ↑ on a keyboard. 8 TUV on a phone or remote control
+ Numpad8,
+ /// 9 PgUp on a keyboard. 9 WXYZ or 9 WXY on a phone
+ /// or remote control
+ Numpad9,
+ /// +
+ NumpadAdd,
+ /// Found on the Microsoft Natural Keyboard.
+ NumpadBackspace,
+ /// C or A (All Clear). Also for use with numpads that have a
+ /// Clear key that is separate from the NumLock key. On the Mac, the
+ /// numpad Clear key is encoded as [`NumLock`].
+ ///
+ /// [`NumLock`]: Self::NumLock
+ NumpadClear,
+ /// C (Clear Entry)
+ NumpadClearEntry,
+ /// , (thousands separator). For locales where the thousands separator
+ /// is a "." (e.g., Brazil), this key may generate a . .
+ NumpadComma,
+ /// . Del . For locales where the decimal separator is "," (e.g.,
+ /// Brazil), this key may generate a , .
+ NumpadDecimal,
+ /// /
+ NumpadDivide,
+ NumpadEnter,
+ /// =
+ NumpadEqual,
+ /// # on a phone or remote control device. This key is typically found
+ /// below the 9 key and to the right of the 0 key.
+ NumpadHash,
+ /// M Add current entry to the value stored in memory.
+ NumpadMemoryAdd,
+ /// M Clear the value stored in memory.
+ NumpadMemoryClear,
+ /// M Replace the current entry with the value stored in memory.
+ NumpadMemoryRecall,
+ /// M Replace the value stored in memory with the current entry.
+ NumpadMemoryStore,
+ /// M Subtract current entry from the value stored in memory.
+ NumpadMemorySubtract,
+ /// * on a keyboard. For use with numpads that provide mathematical
+ /// operations (+ , - * and / ).
+ ///
+ /// Use `NumpadStar` for the * key on phones and remote controls.
+ NumpadMultiply,
+ /// ( Found on the Microsoft Natural Keyboard.
+ NumpadParenLeft,
+ /// ) Found on the Microsoft Natural Keyboard.
+ NumpadParenRight,
+ /// * on a phone or remote control device.
+ ///
+ /// This key is typically found below the 7 key and to the left of
+ /// the 0 key.
+ ///
+ /// Use "NumpadMultiply" for the * key on
+ /// numeric keypads.
+ NumpadStar,
+ /// -
+ NumpadSubtract,
+ /// Esc or ⎋
+ Escape,
+ /// Fn This is typically a hardware key that does not generate a separate code.
+ Fn,
+ /// FLock or FnLock . Function Lock key. Found on the Microsoft
+ /// Natural Keyboard.
+ FnLock,
+ /// PrtScr SysRq or Print Screen
+ PrintScreen,
+ /// Scroll Lock
+ ScrollLock,
+ /// Pause Break
+ Pause,
+ /// Some laptops place this key to the left of the ↑ key.
+ ///
+ /// This also the "back" button (triangle) on Android.
+ BrowserBack,
+ BrowserFavorites,
+ /// Some laptops place this key to the right of the ↑ key.
+ BrowserForward,
+ /// The "home" button on Android.
+ BrowserHome,
+ BrowserRefresh,
+ BrowserSearch,
+ BrowserStop,
+ /// Eject or ⏏ . This key is placed in the function section on some Apple
+ /// keyboards.
+ Eject,
+ /// Sometimes labelled My Computer on the keyboard
+ LaunchApp1,
+ /// Sometimes labelled Calculator on the keyboard
+ LaunchApp2,
+ LaunchMail,
+ MediaPlayPause,
+ MediaSelect,
+ MediaStop,
+ MediaTrackNext,
+ MediaTrackPrevious,
+ /// This key is placed in the function section on some Apple keyboards, replacing the
+ /// Eject key.
+ Power,
+ Sleep,
+ AudioVolumeDown,
+ AudioVolumeMute,
+ AudioVolumeUp,
+ WakeUp,
+ // Legacy modifier key. Also called "Super" in certain places.
+ Meta,
+ // Legacy modifier key.
+ Hyper,
+ Turbo,
+ Abort,
+ Resume,
+ Suspend,
+ /// Found on Sun’s USB keyboard.
+ Again,
+ /// Found on Sun’s USB keyboard.
+ Copy,
+ /// Found on Sun’s USB keyboard.
+ Cut,
+ /// Found on Sun’s USB keyboard.
+ Find,
+ /// Found on Sun’s USB keyboard.
+ Open,
+ /// Found on Sun’s USB keyboard.
+ Paste,
+ /// Found on Sun’s USB keyboard.
+ Props,
+ /// Found on Sun’s USB keyboard.
+ Select,
+ /// Found on Sun’s USB keyboard.
+ Undo,
+ /// Use for dedicated ひらがな key found on some Japanese word processing keyboards.
+ Hiragana,
+ /// Use for dedicated カタカナ key found on some Japanese word processing keyboards.
+ Katakana,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F1,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F2,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F3,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F4,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F5,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F6,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F7,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F8,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F9,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F10,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F11,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F12,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F13,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F14,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F15,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F16,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F17,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F18,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F19,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F20,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F21,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F22,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F23,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F24,
+ /// General-purpose function key.
+ F25,
+ /// General-purpose function key.
+ F26,
+ /// General-purpose function key.
+ F27,
+ /// General-purpose function key.
+ F28,
+ /// General-purpose function key.
+ F29,
+ /// General-purpose function key.
+ F30,
+ /// General-purpose function key.
+ F31,
+ /// General-purpose function key.
+ F32,
+ /// General-purpose function key.
+ F33,
+ /// General-purpose function key.
+ F34,
+ /// General-purpose function key.
+ F35,
+}
+
+/// A [`Key::Named`] value
+///
+/// This mostly conforms to the UI Events Specification's [`KeyboardEvent.key`] with a few
+/// exceptions:
+/// - The `Super` variant here, is named `Meta` in the aforementioned specification. (There's
+/// another key which the specification calls `Super`. That does not exist here.)
+/// - The `Space` variant here, can be identified by the character it generates in the
+/// specification.
+///
+/// [`KeyboardEvent.key`]: https://w3c.github.io/uievents-key/
+#[non_exhaustive]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum NamedKey {
+ /// The `Alt` (Alternative) key.
+ ///
+ /// This key enables the alternate modifier function for interpreting concurrent or subsequent
+ /// keyboard input. This key value is also used for the Apple Option key.
+ Alt,
+ /// The Alternate Graphics (AltGr or AltGraph ) key.
+ ///
+ /// This key is used enable the ISO Level 3 shift modifier (the standard `Shift` key is the
+ /// level 2 modifier).
+ AltGraph,
+ /// The `Caps Lock` (Capital) key.
+ ///
+ /// Toggle capital character lock function for interpreting subsequent keyboard input event.
+ CapsLock,
+ /// The `Control` or `Ctrl` key.
+ ///
+ /// Used to enable control modifier function for interpreting concurrent or subsequent keyboard
+ /// input.
+ Control,
+ /// The Function switch `Fn` key. Activating this key simultaneously with another key changes
+ /// that key’s value to an alternate character or function. This key is often handled directly
+ /// in the keyboard hardware and does not usually generate key events.
+ Fn,
+ /// The Function-Lock (`FnLock` or `F-Lock`) key. Activating this key switches the mode of the
+ /// keyboard to changes some keys' values to an alternate character or function. This key is
+ /// often handled directly in the keyboard hardware and does not usually generate key events.
+ FnLock,
+ /// The `NumLock` or Number Lock key. Used to toggle numpad mode function for interpreting
+ /// subsequent keyboard input.
+ NumLock,
+ /// Toggle between scrolling and cursor movement modes.
+ ScrollLock,
+ /// Used to enable shift modifier function for interpreting concurrent or subsequent keyboard
+ /// input.
+ Shift,
+ /// The Symbol modifier key (used on some virtual keyboards).
+ Symbol,
+ SymbolLock,
+ // Legacy modifier key. Also called "Super" in certain places.
+ Meta,
+ // Legacy modifier key.
+ Hyper,
+ /// Used to enable "super" modifier function for interpreting concurrent or subsequent keyboard
+ /// input. This key value is used for the "Windows Logo" key and the Apple `Command` or `⌘`
+ /// key.
+ ///
+ /// Note: In some contexts (e.g. the Web) this is referred to as the "Meta" key.
+ Super,
+ /// The `Enter` or `↵` key. Used to activate current selection or accept current input. This
+ /// key value is also used for the `Return` (Macintosh numpad) key. This key value is also
+ /// used for the Android `KEYCODE_DPAD_CENTER`.
+ Enter,
+ /// The Horizontal Tabulation `Tab` key.
+ Tab,
+ /// Used in text to insert a space between words. Usually located below the character keys.
+ Space,
+ /// Navigate or traverse downward. (`KEYCODE_DPAD_DOWN`)
+ ArrowDown,
+ /// Navigate or traverse leftward. (`KEYCODE_DPAD_LEFT`)
+ ArrowLeft,
+ /// Navigate or traverse rightward. (`KEYCODE_DPAD_RIGHT`)
+ ArrowRight,
+ /// Navigate or traverse upward. (`KEYCODE_DPAD_UP`)
+ ArrowUp,
+ /// The End key, used with keyboard entry to go to the end of content (`KEYCODE_MOVE_END`).
+ End,
+ /// The Home key, used with keyboard entry, to go to start of content (`KEYCODE_MOVE_HOME`).
+ /// For the mobile phone `Home` key (which goes to the phone’s main screen), use [`GoHome`].
+ ///
+ /// [`GoHome`]: Self::GoHome
+ Home,
+ /// Scroll down or display next page of content.
+ PageDown,
+ /// Scroll up or display previous page of content.
+ PageUp,
+ /// Used to remove the character to the left of the cursor. This key value is also used for
+ /// the key labeled `Delete` on MacOS keyboards.
+ Backspace,
+ /// Remove the currently selected input.
+ Clear,
+ /// Copy the current selection. (`APPCOMMAND_COPY`)
+ Copy,
+ /// The Cursor Select key.
+ CrSel,
+ /// Cut the current selection. (`APPCOMMAND_CUT`)
+ Cut,
+ /// Used to delete the character to the right of the cursor. This key value is also used for
+ /// the key labeled `Delete` on MacOS keyboards when `Fn` is active.
+ Delete,
+ /// The Erase to End of Field key. This key deletes all characters from the current cursor
+ /// position to the end of the current field.
+ EraseEof,
+ /// The Extend Selection (Exsel) key.
+ ExSel,
+ /// Toggle between text modes for insertion or overtyping.
+ /// (`KEYCODE_INSERT`)
+ Insert,
+ /// The Paste key. (`APPCOMMAND_PASTE`)
+ Paste,
+ /// Redo the last action. (`APPCOMMAND_REDO`)
+ Redo,
+ /// Undo the last action. (`APPCOMMAND_UNDO`)
+ Undo,
+ /// The Accept (Commit, OK) key. Accept current option or input method sequence conversion.
+ Accept,
+ /// Redo or repeat an action.
+ Again,
+ /// The Attention (Attn) key.
+ Attn,
+ Cancel,
+ /// Show the application’s context menu.
+ /// This key is commonly found between the right `Super` key and the right `Control` key.
+ ContextMenu,
+ /// The `Esc` key. This key was originally used to initiate an escape sequence, but is
+ /// now more generally used to exit or "escape" the current context, such as closing a dialog
+ /// or exiting full screen mode.
+ Escape,
+ Execute,
+ /// Open the Find dialog. (`APPCOMMAND_FIND`)
+ Find,
+ /// Open a help dialog or toggle display of help information. (`APPCOMMAND_HELP`,
+ /// `KEYCODE_HELP`)
+ Help,
+ /// Pause the current state or application (as appropriate).
+ ///
+ /// Note: Do not use this value for the `Pause` button on media controllers. Use `"MediaPause"`
+ /// instead.
+ Pause,
+ /// Play or resume the current state or application (as appropriate).
+ ///
+ /// Note: Do not use this value for the `Play` button on media controllers. Use `"MediaPlay"`
+ /// instead.
+ Play,
+ /// The properties (Props) key.
+ Props,
+ Select,
+ /// The ZoomIn key. (`KEYCODE_ZOOM_IN`)
+ ZoomIn,
+ /// The ZoomOut key. (`KEYCODE_ZOOM_OUT`)
+ ZoomOut,
+ /// The Brightness Down key. Typically controls the display brightness.
+ /// (`KEYCODE_BRIGHTNESS_DOWN`)
+ BrightnessDown,
+ /// The Brightness Up key. Typically controls the display brightness. (`KEYCODE_BRIGHTNESS_UP`)
+ BrightnessUp,
+ /// Toggle removable media to eject (open) and insert (close) state. (`KEYCODE_MEDIA_EJECT`)
+ Eject,
+ LogOff,
+ /// Toggle power state. (`KEYCODE_POWER`)
+ /// Note: Note: Some devices might not expose this key to the operating environment.
+ Power,
+ /// The `PowerOff` key. Sometime called `PowerDown`.
+ PowerOff,
+ /// Initiate print-screen function.
+ PrintScreen,
+ /// The Hibernate key. This key saves the current state of the computer to disk so that it can
+ /// be restored. The computer will then shutdown.
+ Hibernate,
+ /// The Standby key. This key turns off the display and places the computer into a low-power
+ /// mode without completely shutting down. It is sometimes labelled `Suspend` or `Sleep` key.
+ /// (`KEYCODE_SLEEP`)
+ Standby,
+ /// The WakeUp key. (`KEYCODE_WAKEUP`)
+ WakeUp,
+ /// Initiate the multi-candidate mode.
+ AllCandidates,
+ Alphanumeric,
+ /// Initiate the Code Input mode to allow characters to be entered by
+ /// their code points.
+ CodeInput,
+ /// The Compose key, also known as "Multi_key" on the X Window System. This key acts in a
+ /// manner similar to a dead key, triggering a mode where subsequent key presses are combined
+ /// to produce a different character.
+ Compose,
+ /// Convert the current input method sequence.
+ Convert,
+ /// The Final Mode `Final` key used on some Asian keyboards, to enable the final mode for IMEs.
+ FinalMode,
+ /// Switch to the first character group. (ISO/IEC 9995)
+ GroupFirst,
+ /// Switch to the last character group. (ISO/IEC 9995)
+ GroupLast,
+ /// Switch to the next character group. (ISO/IEC 9995)
+ GroupNext,
+ /// Switch to the previous character group. (ISO/IEC 9995)
+ GroupPrevious,
+ /// Toggle between or cycle through input modes of IMEs.
+ ModeChange,
+ NextCandidate,
+ /// Accept current input method sequence without
+ /// conversion in IMEs.
+ NonConvert,
+ PreviousCandidate,
+ Process,
+ SingleCandidate,
+ /// Toggle between Hangul and English modes.
+ HangulMode,
+ HanjaMode,
+ JunjaMode,
+ /// The Eisu key. This key may close the IME, but its purpose is defined by the current IME.
+ /// (`KEYCODE_EISU`)
+ Eisu,
+ /// The (Half-Width) Characters key.
+ Hankaku,
+ /// The Hiragana (Japanese Kana characters) key.
+ Hiragana,
+ /// The Hiragana/Katakana toggle key. (`KEYCODE_KATAKANA_HIRAGANA`)
+ HiraganaKatakana,
+ /// The Kana Mode (Kana Lock) key. This key is used to enter hiragana mode (typically from
+ /// romaji mode).
+ KanaMode,
+ /// The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. This key
+ /// is typically used to switch to a hiragana keyboard for the purpose of converting input
+ /// into kanji. (`KEYCODE_KANA`)
+ KanjiMode,
+ /// The Katakana (Japanese Kana characters) key.
+ Katakana,
+ /// The Roman characters function key.
+ Romaji,
+ /// The Zenkaku (Full-Width) Characters key.
+ Zenkaku,
+ /// The Zenkaku/Hankaku (full-width/half-width) toggle key. (`KEYCODE_ZENKAKU_HANKAKU`)
+ ZenkakuHankaku,
+ /// General purpose virtual function key, as index 1.
+ Soft1,
+ /// General purpose virtual function key, as index 2.
+ Soft2,
+ /// General purpose virtual function key, as index 3.
+ Soft3,
+ /// General purpose virtual function key, as index 4.
+ Soft4,
+ /// Select next (numerically or logically) lower channel. (`APPCOMMAND_MEDIA_CHANNEL_DOWN`,
+ /// `KEYCODE_CHANNEL_DOWN`)
+ ChannelDown,
+ /// Select next (numerically or logically) higher channel. (`APPCOMMAND_MEDIA_CHANNEL_UP`,
+ /// `KEYCODE_CHANNEL_UP`)
+ ChannelUp,
+ /// Close the current document or message (Note: This doesn’t close the application).
+ /// (`APPCOMMAND_CLOSE`)
+ Close,
+ /// Open an editor to forward the current message. (`APPCOMMAND_FORWARD_MAIL`)
+ MailForward,
+ /// Open an editor to reply to the current message. (`APPCOMMAND_REPLY_TO_MAIL`)
+ MailReply,
+ /// Send the current message. (`APPCOMMAND_SEND_MAIL`)
+ MailSend,
+ /// Close the current media, for example to close a CD or DVD tray. (`KEYCODE_MEDIA_CLOSE`)
+ MediaClose,
+ /// Initiate or continue forward playback at faster than normal speed, or increase speed if
+ /// already fast forwarding. (`APPCOMMAND_MEDIA_FAST_FORWARD`, `KEYCODE_MEDIA_FAST_FORWARD`)
+ MediaFastForward,
+ /// Pause the currently playing media. (`APPCOMMAND_MEDIA_PAUSE`, `KEYCODE_MEDIA_PAUSE`)
+ ///
+ /// Note: Media controller devices should use this value rather than `"Pause"` for their pause
+ /// keys.
+ MediaPause,
+ /// Initiate or continue media playback at normal speed, if not currently playing at normal
+ /// speed. (`APPCOMMAND_MEDIA_PLAY`, `KEYCODE_MEDIA_PLAY`)
+ MediaPlay,
+ /// Toggle media between play and pause states. (`APPCOMMAND_MEDIA_PLAY_PAUSE`,
+ /// `KEYCODE_MEDIA_PLAY_PAUSE`)
+ MediaPlayPause,
+ /// Initiate or resume recording of currently selected media. (`APPCOMMAND_MEDIA_RECORD`,
+ /// `KEYCODE_MEDIA_RECORD`)
+ MediaRecord,
+ /// Initiate or continue reverse playback at faster than normal speed, or increase speed if
+ /// already rewinding. (`APPCOMMAND_MEDIA_REWIND`, `KEYCODE_MEDIA_REWIND`)
+ MediaRewind,
+ /// Stop media playing, pausing, forwarding, rewinding, or recording, if not already stopped.
+ /// (`APPCOMMAND_MEDIA_STOP`, `KEYCODE_MEDIA_STOP`)
+ MediaStop,
+ /// Seek to next media or program track. (`APPCOMMAND_MEDIA_NEXTTRACK`, `KEYCODE_MEDIA_NEXT`)
+ MediaTrackNext,
+ /// Seek to previous media or program track. (`APPCOMMAND_MEDIA_PREVIOUSTRACK`,
+ /// `KEYCODE_MEDIA_PREVIOUS`)
+ MediaTrackPrevious,
+ /// Open a new document or message. (`APPCOMMAND_NEW`)
+ New,
+ /// Open an existing document or message. (`APPCOMMAND_OPEN`)
+ Open,
+ /// Print the current document or message. (`APPCOMMAND_PRINT`)
+ Print,
+ /// Save the current document or message. (`APPCOMMAND_SAVE`)
+ Save,
+ /// Spellcheck the current document or selection. (`APPCOMMAND_SPELL_CHECK`)
+ SpellCheck,
+ /// The `11` key found on media numpads that
+ /// have buttons from `1` ... `12`.
+ Key11,
+ /// The `12` key found on media numpads that
+ /// have buttons from `1` ... `12`.
+ Key12,
+ /// Adjust audio balance leftward. (`VK_AUDIO_BALANCE_LEFT`)
+ AudioBalanceLeft,
+ /// Adjust audio balance rightward. (`VK_AUDIO_BALANCE_RIGHT`)
+ AudioBalanceRight,
+ /// Decrease audio bass boost or cycle down through bass boost states. (`APPCOMMAND_BASS_DOWN`,
+ /// `VK_BASS_BOOST_DOWN`)
+ AudioBassBoostDown,
+ /// Toggle bass boost on/off. (`APPCOMMAND_BASS_BOOST`)
+ AudioBassBoostToggle,
+ /// Increase audio bass boost or cycle up through bass boost states. (`APPCOMMAND_BASS_UP`,
+ /// `VK_BASS_BOOST_UP`)
+ AudioBassBoostUp,
+ /// Adjust audio fader towards front. (`VK_FADER_FRONT`)
+ AudioFaderFront,
+ /// Adjust audio fader towards rear. (`VK_FADER_REAR`)
+ AudioFaderRear,
+ /// Advance surround audio mode to next available mode. (`VK_SURROUND_MODE_NEXT`)
+ AudioSurroundModeNext,
+ /// Decrease treble. (`APPCOMMAND_TREBLE_DOWN`)
+ AudioTrebleDown,
+ /// Increase treble. (`APPCOMMAND_TREBLE_UP`)
+ AudioTrebleUp,
+ /// Decrease audio volume. (`APPCOMMAND_VOLUME_DOWN`, `KEYCODE_VOLUME_DOWN`)
+ AudioVolumeDown,
+ /// Increase audio volume. (`APPCOMMAND_VOLUME_UP`, `KEYCODE_VOLUME_UP`)
+ AudioVolumeUp,
+ /// Toggle between muted state and prior volume level. (`APPCOMMAND_VOLUME_MUTE`,
+ /// `KEYCODE_VOLUME_MUTE`)
+ AudioVolumeMute,
+ /// Toggle the microphone on/off. (`APPCOMMAND_MIC_ON_OFF_TOGGLE`)
+ MicrophoneToggle,
+ /// Decrease microphone volume. (`APPCOMMAND_MICROPHONE_VOLUME_DOWN`)
+ MicrophoneVolumeDown,
+ /// Increase microphone volume. (`APPCOMMAND_MICROPHONE_VOLUME_UP`)
+ MicrophoneVolumeUp,
+ /// Mute the microphone. (`APPCOMMAND_MICROPHONE_VOLUME_MUTE`, `KEYCODE_MUTE`)
+ MicrophoneVolumeMute,
+ /// Show correction list when a word is incorrectly identified. (`APPCOMMAND_CORRECTION_LIST`)
+ SpeechCorrectionList,
+ /// Toggle between dictation mode and command/control mode.
+ /// (`APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE`)
+ SpeechInputToggle,
+ /// The first generic "LaunchApplication" key. This is commonly associated with launching "My
+ /// Computer", and may have a computer symbol on the key. (`APPCOMMAND_LAUNCH_APP1`)
+ LaunchApplication1,
+ /// The second generic "LaunchApplication" key. This is commonly associated with launching
+ /// "Calculator", and may have a calculator symbol on the key. (`APPCOMMAND_LAUNCH_APP2`,
+ /// `KEYCODE_CALCULATOR`)
+ LaunchApplication2,
+ /// The "Calendar" key. (`KEYCODE_CALENDAR`)
+ LaunchCalendar,
+ /// The "Contacts" key. (`KEYCODE_CONTACTS`)
+ LaunchContacts,
+ /// The "Mail" key. (`APPCOMMAND_LAUNCH_MAIL`)
+ LaunchMail,
+ /// The "Media Player" key. (`APPCOMMAND_LAUNCH_MEDIA_SELECT`)
+ LaunchMediaPlayer,
+ LaunchMusicPlayer,
+ LaunchPhone,
+ LaunchScreenSaver,
+ LaunchSpreadsheet,
+ LaunchWebBrowser,
+ LaunchWebCam,
+ LaunchWordProcessor,
+ /// Navigate to previous content or page in current history. (`APPCOMMAND_BROWSER_BACKWARD`)
+ BrowserBack,
+ /// Open the list of browser favorites. (`APPCOMMAND_BROWSER_FAVORITES`)
+ BrowserFavorites,
+ /// Navigate to next content or page in current history. (`APPCOMMAND_BROWSER_FORWARD`)
+ BrowserForward,
+ /// Go to the user’s preferred home page. (`APPCOMMAND_BROWSER_HOME`)
+ BrowserHome,
+ /// Refresh the current page or content. (`APPCOMMAND_BROWSER_REFRESH`)
+ BrowserRefresh,
+ /// Call up the user’s preferred search page. (`APPCOMMAND_BROWSER_SEARCH`)
+ BrowserSearch,
+ /// Stop loading the current page or content. (`APPCOMMAND_BROWSER_STOP`)
+ BrowserStop,
+ /// The Application switch key, which provides a list of recent apps to switch between.
+ /// (`KEYCODE_APP_SWITCH`)
+ AppSwitch,
+ /// The Call key. (`KEYCODE_CALL`)
+ Call,
+ /// The Camera key. (`KEYCODE_CAMERA`)
+ Camera,
+ /// The Camera focus key. (`KEYCODE_FOCUS`)
+ CameraFocus,
+ /// The End Call key. (`KEYCODE_ENDCALL`)
+ EndCall,
+ /// The Back key. (`KEYCODE_BACK`)
+ GoBack,
+ /// The Home key, which goes to the phone’s main screen. (`KEYCODE_HOME`)
+ GoHome,
+ /// The Headset Hook key. (`KEYCODE_HEADSETHOOK`)
+ HeadsetHook,
+ LastNumberRedial,
+ /// The Notification key. (`KEYCODE_NOTIFICATION`)
+ Notification,
+ /// Toggle between manner mode state: silent, vibrate, ring, ... (`KEYCODE_MANNER_MODE`)
+ MannerMode,
+ VoiceDial,
+ /// Switch to viewing TV. (`KEYCODE_TV`)
+ TV,
+ /// TV 3D Mode. (`KEYCODE_3D_MODE`)
+ TV3DMode,
+ /// Toggle between antenna and cable input. (`KEYCODE_TV_ANTENNA_CABLE`)
+ TVAntennaCable,
+ /// Audio description. (`KEYCODE_TV_AUDIO_DESCRIPTION`)
+ TVAudioDescription,
+ /// Audio description mixing volume down. (`KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN`)
+ TVAudioDescriptionMixDown,
+ /// Audio description mixing volume up. (`KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP`)
+ TVAudioDescriptionMixUp,
+ /// Contents menu. (`KEYCODE_TV_CONTENTS_MENU`)
+ TVContentsMenu,
+ /// Contents menu. (`KEYCODE_TV_DATA_SERVICE`)
+ TVDataService,
+ /// Switch the input mode on an external TV. (`KEYCODE_TV_INPUT`)
+ TVInput,
+ /// Switch to component input #1. (`KEYCODE_TV_INPUT_COMPONENT_1`)
+ TVInputComponent1,
+ /// Switch to component input #2. (`KEYCODE_TV_INPUT_COMPONENT_2`)
+ TVInputComponent2,
+ /// Switch to composite input #1. (`KEYCODE_TV_INPUT_COMPOSITE_1`)
+ TVInputComposite1,
+ /// Switch to composite input #2. (`KEYCODE_TV_INPUT_COMPOSITE_2`)
+ TVInputComposite2,
+ /// Switch to HDMI input #1. (`KEYCODE_TV_INPUT_HDMI_1`)
+ TVInputHDMI1,
+ /// Switch to HDMI input #2. (`KEYCODE_TV_INPUT_HDMI_2`)
+ TVInputHDMI2,
+ /// Switch to HDMI input #3. (`KEYCODE_TV_INPUT_HDMI_3`)
+ TVInputHDMI3,
+ /// Switch to HDMI input #4. (`KEYCODE_TV_INPUT_HDMI_4`)
+ TVInputHDMI4,
+ /// Switch to VGA input #1. (`KEYCODE_TV_INPUT_VGA_1`)
+ TVInputVGA1,
+ /// Media context menu. (`KEYCODE_TV_MEDIA_CONTEXT_MENU`)
+ TVMediaContext,
+ /// Toggle network. (`KEYCODE_TV_NETWORK`)
+ TVNetwork,
+ /// Number entry. (`KEYCODE_TV_NUMBER_ENTRY`)
+ TVNumberEntry,
+ /// Toggle the power on an external TV. (`KEYCODE_TV_POWER`)
+ TVPower,
+ /// Radio. (`KEYCODE_TV_RADIO_SERVICE`)
+ TVRadioService,
+ /// Satellite. (`KEYCODE_TV_SATELLITE`)
+ TVSatellite,
+ /// Broadcast Satellite. (`KEYCODE_TV_SATELLITE_BS`)
+ TVSatelliteBS,
+ /// Communication Satellite. (`KEYCODE_TV_SATELLITE_CS`)
+ TVSatelliteCS,
+ /// Toggle between available satellites. (`KEYCODE_TV_SATELLITE_SERVICE`)
+ TVSatelliteToggle,
+ /// Analog Terrestrial. (`KEYCODE_TV_TERRESTRIAL_ANALOG`)
+ TVTerrestrialAnalog,
+ /// Digital Terrestrial. (`KEYCODE_TV_TERRESTRIAL_DIGITAL`)
+ TVTerrestrialDigital,
+ /// Timer programming. (`KEYCODE_TV_TIMER_PROGRAMMING`)
+ TVTimer,
+ /// Switch the input mode on an external AVR (audio/video receiver). (`KEYCODE_AVR_INPUT`)
+ AVRInput,
+ /// Toggle the power on an external AVR (audio/video receiver). (`KEYCODE_AVR_POWER`)
+ AVRPower,
+ /// General purpose color-coded media function key, as index 0 (red). (`VK_COLORED_KEY_0`,
+ /// `KEYCODE_PROG_RED`)
+ ColorF0Red,
+ /// General purpose color-coded media function key, as index 1 (green). (`VK_COLORED_KEY_1`,
+ /// `KEYCODE_PROG_GREEN`)
+ ColorF1Green,
+ /// General purpose color-coded media function key, as index 2 (yellow). (`VK_COLORED_KEY_2`,
+ /// `KEYCODE_PROG_YELLOW`)
+ ColorF2Yellow,
+ /// General purpose color-coded media function key, as index 3 (blue). (`VK_COLORED_KEY_3`,
+ /// `KEYCODE_PROG_BLUE`)
+ ColorF3Blue,
+ /// General purpose color-coded media function key, as index 4 (grey). (`VK_COLORED_KEY_4`)
+ ColorF4Grey,
+ /// General purpose color-coded media function key, as index 5 (brown). (`VK_COLORED_KEY_5`)
+ ColorF5Brown,
+ /// Toggle the display of Closed Captions. (`VK_CC`, `KEYCODE_CAPTIONS`)
+ ClosedCaptionToggle,
+ /// Adjust brightness of device, by toggling between or cycling through states. (`VK_DIMMER`)
+ Dimmer,
+ /// Swap video sources. (`VK_DISPLAY_SWAP`)
+ DisplaySwap,
+ /// Select Digital Video Recorder. (`KEYCODE_DVR`)
+ DVR,
+ /// Exit the current application. (`VK_EXIT`)
+ Exit,
+ /// Clear program or content stored as favorite 0. (`VK_CLEAR_FAVORITE_0`)
+ FavoriteClear0,
+ /// Clear program or content stored as favorite 1. (`VK_CLEAR_FAVORITE_1`)
+ FavoriteClear1,
+ /// Clear program or content stored as favorite 2. (`VK_CLEAR_FAVORITE_2`)
+ FavoriteClear2,
+ /// Clear program or content stored as favorite 3. (`VK_CLEAR_FAVORITE_3`)
+ FavoriteClear3,
+ /// Select (recall) program or content stored as favorite 0. (`VK_RECALL_FAVORITE_0`)
+ FavoriteRecall0,
+ /// Select (recall) program or content stored as favorite 1. (`VK_RECALL_FAVORITE_1`)
+ FavoriteRecall1,
+ /// Select (recall) program or content stored as favorite 2. (`VK_RECALL_FAVORITE_2`)
+ FavoriteRecall2,
+ /// Select (recall) program or content stored as favorite 3. (`VK_RECALL_FAVORITE_3`)
+ FavoriteRecall3,
+ /// Store current program or content as favorite 0. (`VK_STORE_FAVORITE_0`)
+ FavoriteStore0,
+ /// Store current program or content as favorite 1. (`VK_STORE_FAVORITE_1`)
+ FavoriteStore1,
+ /// Store current program or content as favorite 2. (`VK_STORE_FAVORITE_2`)
+ FavoriteStore2,
+ /// Store current program or content as favorite 3. (`VK_STORE_FAVORITE_3`)
+ FavoriteStore3,
+ /// Toggle display of program or content guide. (`VK_GUIDE`, `KEYCODE_GUIDE`)
+ Guide,
+ /// If guide is active and displayed, then display next day’s content. (`VK_NEXT_DAY`)
+ GuideNextDay,
+ /// If guide is active and displayed, then display previous day’s content. (`VK_PREV_DAY`)
+ GuidePreviousDay,
+ /// Toggle display of information about currently selected context or media. (`VK_INFO`,
+ /// `KEYCODE_INFO`)
+ Info,
+ /// Toggle instant replay. (`VK_INSTANT_REPLAY`)
+ InstantReplay,
+ /// Launch linked content, if available and appropriate. (`VK_LINK`)
+ Link,
+ /// List the current program. (`VK_LIST`)
+ ListProgram,
+ /// Toggle display listing of currently available live content or programs. (`VK_LIVE`)
+ LiveContent,
+ /// Lock or unlock current content or program. (`VK_LOCK`)
+ Lock,
+ /// Show a list of media applications: audio/video players and image viewers. (`VK_APPS`)
+ ///
+ /// Note: Do not confuse this key value with the Windows' `VK_APPS` / `VK_CONTEXT_MENU` key,
+ /// which is encoded as `"ContextMenu"`.
+ MediaApps,
+ /// Audio track key. (`KEYCODE_MEDIA_AUDIO_TRACK`)
+ MediaAudioTrack,
+ /// Select previously selected channel or media. (`VK_LAST`, `KEYCODE_LAST_CHANNEL`)
+ MediaLast,
+ /// Skip backward to next content or program. (`KEYCODE_MEDIA_SKIP_BACKWARD`)
+ MediaSkipBackward,
+ /// Skip forward to next content or program. (`VK_SKIP`, `KEYCODE_MEDIA_SKIP_FORWARD`)
+ MediaSkipForward,
+ /// Step backward to next content or program. (`KEYCODE_MEDIA_STEP_BACKWARD`)
+ MediaStepBackward,
+ /// Step forward to next content or program. (`KEYCODE_MEDIA_STEP_FORWARD`)
+ MediaStepForward,
+ /// Media top menu. (`KEYCODE_MEDIA_TOP_MENU`)
+ MediaTopMenu,
+ /// Navigate in. (`KEYCODE_NAVIGATE_IN`)
+ NavigateIn,
+ /// Navigate to next key. (`KEYCODE_NAVIGATE_NEXT`)
+ NavigateNext,
+ /// Navigate out. (`KEYCODE_NAVIGATE_OUT`)
+ NavigateOut,
+ /// Navigate to previous key. (`KEYCODE_NAVIGATE_PREVIOUS`)
+ NavigatePrevious,
+ /// Cycle to next favorite channel (in favorites list). (`VK_NEXT_FAVORITE_CHANNEL`)
+ NextFavoriteChannel,
+ /// Cycle to next user profile (if there are multiple user profiles). (`VK_USER`)
+ NextUserProfile,
+ /// Access on-demand content or programs. (`VK_ON_DEMAND`)
+ OnDemand,
+ /// Pairing key to pair devices. (`KEYCODE_PAIRING`)
+ Pairing,
+ /// Move picture-in-picture window down. (`VK_PINP_DOWN`)
+ PinPDown,
+ /// Move picture-in-picture window. (`VK_PINP_MOVE`)
+ PinPMove,
+ /// Toggle display of picture-in-picture window. (`VK_PINP_TOGGLE`)
+ PinPToggle,
+ /// Move picture-in-picture window up. (`VK_PINP_UP`)
+ PinPUp,
+ /// Decrease media playback speed. (`VK_PLAY_SPEED_DOWN`)
+ PlaySpeedDown,
+ /// Reset playback to normal speed. (`VK_PLAY_SPEED_RESET`)
+ PlaySpeedReset,
+ /// Increase media playback speed. (`VK_PLAY_SPEED_UP`)
+ PlaySpeedUp,
+ /// Toggle random media or content shuffle mode. (`VK_RANDOM_TOGGLE`)
+ RandomToggle,
+ /// Not a physical key, but this key code is sent when the remote control battery is low.
+ /// (`VK_RC_LOW_BATTERY`)
+ RcLowBattery,
+ /// Toggle or cycle between media recording speeds. (`VK_RECORD_SPEED_NEXT`)
+ RecordSpeedNext,
+ /// Toggle RF (radio frequency) input bypass mode (pass RF input directly to the RF output).
+ /// (`VK_RF_BYPASS`)
+ RfBypass,
+ /// Toggle scan channels mode. (`VK_SCAN_CHANNELS_TOGGLE`)
+ ScanChannelsToggle,
+ /// Advance display screen mode to next available mode. (`VK_SCREEN_MODE_NEXT`)
+ ScreenModeNext,
+ /// Toggle display of device settings screen. (`VK_SETTINGS`, `KEYCODE_SETTINGS`)
+ Settings,
+ /// Toggle split screen mode. (`VK_SPLIT_SCREEN_TOGGLE`)
+ SplitScreenToggle,
+ /// Switch the input mode on an external STB (set top box). (`KEYCODE_STB_INPUT`)
+ STBInput,
+ /// Toggle the power on an external STB (set top box). (`KEYCODE_STB_POWER`)
+ STBPower,
+ /// Toggle display of subtitles, if available. (`VK_SUBTITLE`)
+ Subtitle,
+ /// Toggle display of teletext, if available (`VK_TELETEXT`, `KEYCODE_TV_TELETEXT`).
+ Teletext,
+ /// Advance video mode to next available mode. (`VK_VIDEO_MODE_NEXT`)
+ VideoModeNext,
+ /// Cause device to identify itself in some manner, e.g., audibly or visibly. (`VK_WINK`)
+ Wink,
+ /// Toggle between full-screen and scaled content, or alter magnification level. (`VK_ZOOM`,
+ /// `KEYCODE_TV_ZOOM_MODE`)
+ ZoomToggle,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F1,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F2,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F3,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F4,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F5,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F6,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F7,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F8,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F9,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F10,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F11,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F12,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F13,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F14,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F15,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F16,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F17,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F18,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F19,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F20,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F21,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F22,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F23,
+ /// General-purpose function key.
+ /// Usually found at the top of the keyboard.
+ F24,
+ /// General-purpose function key.
+ F25,
+ /// General-purpose function key.
+ F26,
+ /// General-purpose function key.
+ F27,
+ /// General-purpose function key.
+ F28,
+ /// General-purpose function key.
+ F29,
+ /// General-purpose function key.
+ F30,
+ /// General-purpose function key.
+ F31,
+ /// General-purpose function key.
+ F32,
+ /// General-purpose function key.
+ F33,
+ /// General-purpose function key.
+ F34,
+ /// General-purpose function key.
+ F35,
+}
+
+/// Key represents the meaning of a keypress.
+///
+/// This is a superset of the UI Events Specification's [`KeyboardEvent.key`] with
+/// additions:
+/// - All simple variants are wrapped under the `Named` variant
+/// - The `Unidentified` variant here, can still identify a key through it's `NativeKeyCode`.
+/// - The `Dead` variant here, can specify the character which is inserted when pressing the
+/// dead-key twice.
+///
+/// [`KeyboardEvent.key`]: https://w3c.github.io/uievents-key/
+#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum Key {
+ /// A simple (unparameterised) action
+ Named(NamedKey),
+
+ /// A key string that corresponds to the character typed by the user, taking into account the
+ /// user’s current locale setting, and any system-level keyboard mapping overrides that are in
+ /// effect.
+ Character(Str),
+
+ /// This variant is used when the key cannot be translated to any other variant.
+ ///
+ /// The native key is provided (if available) in order to allow the user to specify keybindings
+ /// for keys which are not defined by this API, mainly through some sort of UI.
+ Unidentified(NativeKey),
+
+ /// Contains the text representation of the dead-key when available.
+ ///
+ /// ## Platform-specific
+ /// - **Web:** Always contains `None`
+ Dead(Option),
+}
+
+impl From for Key {
+ #[inline]
+ fn from(action: NamedKey) -> Self {
+ Key::Named(action)
+ }
+}
+
+impl From for Key {
+ #[inline]
+ fn from(code: NativeKey) -> Self {
+ Key::Unidentified(code)
+ }
+}
+
+impl PartialEq for Key {
+ #[inline]
+ fn eq(&self, rhs: &NamedKey) -> bool {
+ match self {
+ Key::Named(ref a) => a == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl> PartialEq for Key