Compare commits

..
Author SHA1 Message Date
千川白浪 e68e3ce939 Merge pull request #4 from reiasu2/fix/export-unattached-cb-deadlock
🐛 Fix snapshot save deadlock when >64 unattached surface caches are dirty
2026-12-04 13:51:42 +08:00
Xiaochi You 9324949b55 Merge pull request #9 from yxc0915/steelbrain/backport-hidpi-cursor
🐛 Backport HiDPI cursor crossing on x86 macOS
2026-12-03 23:48:54 +08:00
YXC0915 48dd6d2fad 🐛 Backport HiDPI cursor crossing on x86 macOS
Backport porcelainhorse's 4c6acb5e from steelbrain/reims-vgpu#180.

Rebuild both guest prebuilt sets with Xcode 27.2 from the maintenance tree to preserve its bundled guest changes.
2026-12-03 23:47:57 +08:00
YXC0915 2df30ffea9 🆕 Pin the organization runtime dependencies [skip ci]
Resolve metal2vulkan and reims-util from the maintained Reims-Go repositories. The new Vulkan pin establishes a suspend baseline for these build inputs.
2026-12-03 02:53:58 +08:00
Xiaochi You 6b7e7d7cad Merge pull request #1 from YinLiaoCo/feat/window-file-drop
feat(window): forward SDL3 file and text drops with normalized coords to host bridge
2026-12-03 02:08:14 +08:00
棠渚听潮 0427583422 🐛 Commit each unattached surface cache writeback before acquiring the next command buffer 2026-12-02 23:58:44 +08:00
Shroap bfea2dc988 feat(window): forward SDL3 text and URL drops to host bridge 2026-12-02 04:00:53 +08:00
Shroap 3fdde46abd feat(window): forward SDL3 file drops with normalized coords to host bridge 2026-12-02 03:56:21 +08:00
20 changed files with 1058 additions and 71 deletions

No files matched your search

Generated
+3
View File
@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "metal2vulkan"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=19090d5f2e60185359200046e0b72e96ce60099a#19090d5f2e60185359200046e0b72e96ce60099a"
dependencies = [
"ash",
"metal2vulkan-air",
@@ -223,6 +224,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-air"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=19090d5f2e60185359200046e0b72e96ce60099a#19090d5f2e60185359200046e0b72e96ce60099a"
dependencies = [
"sha2 0.11.1",
]
@@ -230,6 +232,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-runtime"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=19090d5f2e60185359200046e0b72e96ce60099a#19090d5f2e60185359200046e0b72e96ce60099a"
dependencies = [
"ash",
"libc",
+2 -2
View File
@@ -33,11 +33,11 @@ reims-vgpu-graphics = { path = "crates/reims-vgpu-graphics" }
reims-vgpu-video = { path = "crates/reims-vgpu-video" }
# metal2vulkan's Metal types, for the Metal enums and descriptor values the runtime's calls take,
# from metal2vulkan's public repository at the commit both name.
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
metal2vulkan = { git = "https://github.com/reims-go/metal2vulkan", rev = "19090d5f2e60185359200046e0b72e96ce60099a" }
# The Vulkan platform's runtime (architecture D1), metal2vulkan-runtime: a Metal-shaped API on
# Vulkan, one path for every device, under reims-vgpu-vulkan's `rt_platform` and `seam` and
# reims-vgpu's `pool::rt_blocks`.
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
metal2vulkan-runtime = { git = "https://github.com/reims-go/metal2vulkan", rev = "19090d5f2e60185359200046e0b72e96ce60099a" }
# The hashes of the Vulkan platform's metallib sources (reims-vgpu-vulkan/build.rs).
sha2 = "0.10.9"
# A display window's swapchain on Linux (reims-vgpu-vulkan/src/swapchain.rs), at the runtime's
+3 -3
View File
@@ -1,4 +1,4 @@
//! reims-util (<https://github.com/steelbrain/reims-util>) makes what a new x86-64 VM boots from:
//! reims-util (<https://github.com/reims-go/reims-util>) makes what a new x86-64 VM boots from:
//! an OpenCore image, with OVMF's code and variables beside it, and a macOS installer, downloaded
//! from Apple and checked against Apple's chunklists. It also makes an existing VM a new OpenCore
//! image presenting the same Mac (opencore.rs). For a VM on reims-vgpu's own device, an image
@@ -43,9 +43,9 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
pub const REPO: &str = "https://github.com/steelbrain/reims-util";
pub const REPO: &str = "https://github.com/reims-go/reims-util";
/// The commit [`install`] installs.
pub const REV: &str = "7867384c0ab703b4c6aae36cbbb1a35fcffc8321";
pub const REV: &str = "573d4a5ffacfc31430ff7372727fce287fef89e1";
/// The reims-util binary: `REIMS_CTL_UTIL`, else the one beside reims-ctl, where both are
/// installed, else the first on PATH.
+500
View File
@@ -0,0 +1,500 @@
//! Collects a window's SDL file or text drop and forwards it to the local host bridge.
use std::fmt::Write as _;
use std::io::{self, Write as _};
use std::net::{SocketAddr, TcpStream};
use std::sync::OnceLock;
use std::sync::mpsc::{self, SyncSender, TrySendError};
use std::time::Duration;
use crate::geometry::{self, Rect};
/// Maximum number of files forwarded in a single drop.
const MAX_DROP_PATHS: usize = 256;
/// Maximum joined UTF-8 text size forwarded in a single drop.
const MAX_DROP_TEXT_BYTES: usize = 128 << 10;
/// Drop contents and guest-image coordinates for one completed host drop.
#[derive(Debug)]
pub(crate) struct DropPayload {
/// Guest display port that received the drop.
pub display_index: u64,
/// Horizontal position, clamped to the guest image.
pub norm_x: f64,
/// Vertical position, clamped to the guest image.
pub norm_y: f64,
/// Whether the original position was inside the guest image.
pub in_image: bool,
/// Host paths in the order SDL delivered them.
pub paths: Vec<String>,
/// Joined text for a drop without files.
pub text: Option<String>,
}
/// Maps a window point to the guest image, using its center when geometry is unavailable.
pub(crate) fn normalize_point(point: Option<(f64, f64)>, image: Rect) -> (f64, f64, bool) {
let Some((x, y)) = point else {
return (0.5, 0.5, false);
};
if ![x, y, image.x, image.y, image.width, image.height]
.into_iter()
.all(f64::is_finite)
|| image.width <= 0.0
|| image.height <= 0.0
{
return (0.5, 0.5, false);
}
(
((x - image.x) / image.width).clamp(0.0, 1.0),
((y - image.y) / image.height).clamp(0.0, 1.0),
geometry::contains(image, (x, y)),
)
}
/// Drop state for one SDL window, active from begin or the first file, text or position.
#[derive(Debug, Default)]
pub(crate) struct DropBatch {
/// Host paths collected for this batch.
paths: Option<Vec<String>>,
/// Nonempty input chunks in delivery order, bounded before joining.
texts: Option<Vec<String>>,
/// Joined bytes consumed, saturated at the limit once a chunk is truncated.
text_bytes: usize,
/// Most recent finite position, in SDL window coordinates.
last_pos: Option<(f64, f64)>,
}
impl DropBatch {
/// Starts a new batch, discarding an unfinished drop.
pub(crate) fn begin(&mut self) {
self.paths = Some(Vec::new());
self.texts = None;
self.text_bytes = 0;
self.last_pos = None;
}
/// Records the most recent usable position.
pub(crate) fn position(&mut self, x: f64, y: f64) {
if x.is_finite() && y.is_finite() {
self.last_pos = Some((x, y));
}
}
/// Accepts a file even if SDL omitted begin, taking its position as a fallback.
pub(crate) fn file(&mut self, path: String, pos: Option<(f64, f64)>) {
if path.is_empty() {
return;
}
let paths = self.paths.get_or_insert_with(Vec::new);
if paths.len() < MAX_DROP_PATHS {
paths.push(path);
}
if self.last_pos.is_none() && let Some((x, y)) = pos {
self.position(x, y);
}
}
/// Collects UTF-8 text up to the byte limit, including separators between chunks.
pub(crate) fn text(&mut self, chunk: String, pos: Option<(f64, f64)>) {
if chunk.is_empty() {
return;
}
if self.last_pos.is_none() && let Some((x, y)) = pos {
self.position(x, y);
}
if self.text_bytes == MAX_DROP_TEXT_BYTES {
return;
}
let separator = usize::from(self.texts.is_some());
let remaining = MAX_DROP_TEXT_BYTES - self.text_bytes - separator;
let texts = self.texts.get_or_insert_with(Vec::new);
if chunk.len() > remaining {
let kept = &chunk[..chunk.floor_char_boundary(remaining)];
if !kept.is_empty() {
texts.push(kept.to_owned());
}
self.text_bytes = MAX_DROP_TEXT_BYTES;
} else {
self.text_bytes += separator + chunk.len();
texts.push(chunk);
}
}
/// Finishes this batch and yields its files or text and normalized drop position.
pub(crate) fn complete(
&mut self,
display_index: u64,
image: Rect,
pos: Option<(f64, f64)>,
) -> Option<DropPayload> {
let point = self.last_pos.take().or(pos);
let paths = self.paths.take().unwrap_or_default();
let texts = self.texts.take();
self.text_bytes = 0;
let text = if paths.is_empty() {
Some(texts.filter(|chunks| !chunks.is_empty())?.join("\n"))
} else {
None
};
let (norm_x, norm_y, in_image) = normalize_point(point, image);
Some(DropPayload {
display_index,
norm_x,
norm_y,
in_image,
paths,
text,
})
}
/// Discards drop contents and position when the window closes.
pub(crate) fn reset(&mut self) {
*self = Self::default();
}
}
/// Appends one quoted string with RFC 8259 escapes.
fn push_json_string(json: &mut String, value: &str) {
json.push('"');
for ch in value.chars() {
match ch {
'"' => json.push_str("\\\""),
'\\' => json.push_str("\\\\"),
'\u{8}' => json.push_str("\\b"),
'\u{c}' => json.push_str("\\f"),
'\n' => json.push_str("\\n"),
'\r' => json.push_str("\\r"),
'\t' => json.push_str("\\t"),
'\0'..='\u{1f}' => {
// Writing to a String is infallible.
let _ = write!(json, "\\u{:04x}", u32::from(ch));
}
_ => json.push(ch),
}
}
json.push('"');
}
/// Encodes a file or text drop as UTF-8 JSON.
pub(crate) fn encode_drop_json(payload: &DropPayload) -> String {
let mut json = format!(
r#"{{"display_index":{},"norm_x":{},"norm_y":{},"in_image":{}"#,
payload.display_index, payload.norm_x, payload.norm_y, payload.in_image,
);
if !payload.paths.is_empty() {
json.push_str(r#","paths":["#);
for (i, path) in payload.paths.iter().enumerate() {
if i != 0 {
json.push(',');
}
push_json_string(&mut json, path);
}
json.push(']');
} else if let Some(text) = &payload.text {
json.push_str(r#","text":"#);
push_json_string(&mut json, text);
}
json.push('}');
json
}
/// Parses the explicit IPv4 loopback endpoint used by the host drop bridge.
fn parse_loopback_drop_url(raw: &str) -> Option<(SocketAddr, String)> {
let rest = raw.strip_prefix("http://127.0.0.1:")?;
let (port, path) = match rest.find('/') {
Some(i) => (&rest[..i], &rest[i..]),
None => (rest, "/v1/host-drop"),
};
if !port.bytes().all(|b| b.is_ascii_digit())
|| path.bytes().any(|b| b.is_ascii_control() || b == b' ')
{
return None;
}
let port: u16 = port.parse().ok()?;
(port != 0).then(|| (SocketAddr::from(([127, 0, 0, 1], port)), path.to_owned()))
}
/// SDL's bounded queue to the HTTP worker.
static DROP_TX: OnceLock<SyncSender<DropPayload>> = OnceLock::new();
/// Starts the HTTP worker when the runtime provides a valid local URL and bearer token.
#[cfg_attr(
not(any(target_os = "linux", target_os = "windows")),
expect(dead_code, reason = "only the SDL thread starts the host drop forwarder")
)]
pub(crate) fn install_host_drop_forwarder() {
let Ok(url) = std::env::var("REIMS_GO_DROP_URL") else {
return;
};
let Ok(token) = std::env::var("REIMS_GO_DROP_TOKEN") else {
return;
};
if token.is_empty() || token.contains(['\r', '\n']) || DROP_TX.get().is_some() {
return;
}
let Some((addr, path)) = parse_loopback_drop_url(&url) else {
log::warn!(target: "reims_vgpu_window", "ignoring invalid REIMS_GO_DROP_URL");
return;
};
let (tx, rx) = mpsc::sync_channel(16);
match std::thread::Builder::new()
.name("reims-vgpu.drop".into())
.spawn(move || {
for payload in rx {
if let Err(err) = post_loopback_drop(addr, &path, &token, &payload) {
log::warn!(target: "reims_vgpu_window", "could not forward file drop: {err}");
}
}
}) {
Ok(_) => {
let _ = DROP_TX.set(tx);
}
Err(err) => log::warn!(target: "reims_vgpu_window", "could not start drop worker: {err}"),
}
}
/// Enqueues a drop without waiting for network I/O or queue space on the UI thread.
pub(crate) fn submit(payload: DropPayload) {
if let Some(tx) = DROP_TX.get()
&& let Err(TrySendError::Full(_)) = tx.try_send(payload)
{
log::warn!(target: "reims_vgpu_window", "file drop queue is full");
}
}
/// Posts one complete JSON payload to the authenticated IPv4 loopback bridge.
fn post_loopback_drop(
addr: SocketAddr,
path: &str,
token: &str,
payload: &DropPayload,
) -> io::Result<()> {
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_millis(500))?;
stream.set_write_timeout(Some(Duration::from_millis(2000)))?;
let body = encode_drop_json(payload);
write!(
stream,
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\n\
Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
)?;
stream.write_all(body.as_bytes())
}
/// Offline tests for window drops and the host bridge protocol.
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
use std::net::TcpListener;
/// Guest image offset from the window edges.
const IMAGE: Rect = Rect { x: 10.0, y: 20.0, width: 40.0, height: 80.0 };
/// Coordinates use half-open image bounds and clamp outside those bounds.
#[test]
fn normalizes_window_points() {
for (point, expected) in [
((20.0, 80.0), (0.25, 0.75, true)),
((10.0, 20.0), (0.0, 0.0, true)),
((50.0, 100.0), (1.0, 1.0, false)),
((0.0, 120.0), (0.0, 1.0, false)),
] {
assert_eq!(normalize_point(Some(point), IMAGE), expected);
}
let center = (0.5, 0.5, false);
for point in [None, Some((f64::NAN, 40.0)), Some((20.0, f64::INFINITY))] {
assert_eq!(normalize_point(point, IMAGE), center);
}
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
for image in [Rect { width: bad, ..IMAGE }, Rect { height: bad, ..IMAGE }] {
assert_eq!(normalize_point(Some((20.0, 80.0)), image), center);
}
}
}
/// Position events override file and completion coordinates, retaining file order.
#[test]
#[allow(clippy::expect_used)]
fn batch_completes_with_latest_position() {
let mut batch = DropBatch::default();
batch.begin();
batch.file("first".into(), Some((50.0, 100.0)));
batch.position(20.0, 80.0);
batch.position(f64::NAN, 90.0);
batch.file("second".into(), Some((40.0, 30.0)));
let p = batch.complete(42, IMAGE, Some((30.0, 60.0))).expect("two files");
assert_eq!(p.display_index, 42);
assert_eq!(p.paths, ["first", "second"]);
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
assert!(batch.complete(42, IMAGE, None).is_none());
}
/// Missing begin, invalid file coordinates, completion fallback and reset are independent.
#[test]
#[allow(clippy::expect_used)]
fn handles_partial_batches() {
let mut batch = DropBatch::default();
batch.file("".into(), Some((10.0, 20.0)));
batch.file("first".into(), Some((1.0, f64::NAN)));
batch.file("second".into(), Some((20.0, 80.0)));
batch.file("third".into(), Some((40.0, 30.0)));
let p = batch.complete(1, IMAGE, None).expect("file-only drop");
assert_eq!(p.paths, ["first", "second", "third"]);
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
batch.file("abandoned".into(), Some((20.0, 80.0)));
batch.begin();
assert!(batch.complete(1, IMAGE, None).is_none());
batch.file("closed".into(), Some((20.0, 80.0)));
batch.reset();
assert!(batch.complete(1, IMAGE, None).is_none());
batch.position(20.0, 80.0);
assert!(batch.complete(1, IMAGE, None).is_none());
batch.file("next".into(), None);
let p = batch.complete(2, IMAGE, Some((60.0, 60.0))).expect("fresh drop");
assert_eq!((p.norm_x, p.norm_y, p.in_image), (1.0, 0.5, false));
}
/// Oversized drops retain the first 256 paths in order.
#[test]
#[allow(clippy::expect_used)]
fn caps_paths() {
let mut batch = DropBatch::default();
for i in 0..260 {
batch.file(i.to_string(), None);
}
let p = batch.complete(0, IMAGE, None).expect("bounded drop");
assert_eq!(p.paths, (0..256).map(|i| i.to_string()).collect::<Vec<_>>());
}
/// URL drops keep their position and subsequent batches join chunks in order.
#[test]
#[allow(clippy::expect_used)]
fn collects_url_and_multiline_text() {
let mut batch = DropBatch::default();
let url = "https://example.org/路径";
batch.text(url.into(), Some((20.0, 80.0)));
let p = batch.complete(1, IMAGE, None).expect("URL drop");
assert_eq!(p.text.as_deref(), Some(url));
assert!(p.paths.is_empty());
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
batch.text("abandoned".into(), None);
batch.begin();
batch.text("one\ntwo".into(), None);
batch.text(String::new(), None);
batch.text("three".into(), None);
let p = batch.complete(1, IMAGE, None).expect("multiline drop");
assert_eq!(p.text.as_deref(), Some("one\ntwo\nthree"));
}
/// A split UTF-8 character ends collection even when a smaller chunk would fit.
#[test]
#[allow(clippy::expect_used)]
fn truncates_text_at_utf8_boundary() {
let mut batch = DropBatch::default();
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 6);
batch.text(prefix.clone(), None);
batch.text("界界".into(), None);
batch.text("x".into(), None);
let p = batch.complete(0, IMAGE, None).expect("bounded text drop");
assert_eq!(p.text, Some(format!("{prefix}\n界")));
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 3);
batch.text(prefix.clone(), None);
batch.text("界".into(), None);
let p = batch.complete(0, IMAGE, None).expect("two bytes remaining");
assert_eq!(p.text, Some(prefix));
}
/// Files take precedence over text regardless of arrival order.
#[test]
#[allow(clippy::expect_used)]
fn files_take_precedence() {
let mut batch = DropBatch::default();
batch.text("before".into(), None);
batch.file("path".into(), None);
batch.text("after".into(), None);
let p = batch.complete(0, IMAGE, None).expect("mixed drop");
assert_eq!(p.paths, ["path"]);
assert_eq!(p.text, None);
assert!(batch.complete(0, IMAGE, None).is_none());
}
/// Text JSON preserves Unicode and escapes quotes, backslashes and newlines.
#[test]
fn encodes_json_text() {
let p = DropPayload {
text: Some("你好 \"\\\n".into()),
paths: Vec::new(),
..sample()
};
assert_eq!(encode_drop_json(&p), concat!(
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"#,
r#""text":"你好 \"\\\n"}"#,
));
}
/// An example drop containing Unicode, delimiters and control characters.
fn sample() -> DropPayload {
DropPayload {
display_index: 17,
norm_x: 0.25,
norm_y: 0.75,
in_image: true,
text: None,
paths: vec![r"D:\Downloads\测试.pdf".into(), "\"\u{8}\u{c}\n\r\t\0\u{10}".into()],
}
}
/// Checks UTF-8 preservation and each class of RFC 8259 escape.
#[test]
fn encodes_json_paths() {
assert_eq!(encode_drop_json(&sample()), concat!(
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"paths":["#,
r#""D:\\Downloads\\测试.pdf","\"\b\f\n\r\t\u0000\u0010"]}"#,
));
}
/// Only the literal loopback host, a numeric nonzero port and a safe path are accepted.
#[test]
fn validates_loopback_urls() {
let addr = SocketAddr::from(([127, 0, 0, 1], 42));
assert_eq!(parse_loopback_drop_url("http://127.0.0.1:42"), Some((addr, "/v1/host-drop".into())));
assert_eq!(parse_loopback_drop_url("http://127.0.0.1:42/drop?q=1"), Some((addr, "/drop?q=1".into())));
for raw in [
"https://127.0.0.1:42/drop", "http://localhost:42/drop", "http://127.0.0.2:42/drop",
"http://[::1]:42/drop", "http://127.0.0.1:/drop", "http://127.0.0.1:0/drop",
"http://127.0.0.1:65536/drop", "http://127.0.0.1:+42/drop", "http://127.0.0.1:42@evil/drop",
"http://127.0.0.1:42/a b", "http://127.0.0.1:42/a\rheader", "http://127.0.0.1:42/a\nheader",
" http://127.0.0.1:42", "http://127.0.0.1:42/drop\r\n",
] {
assert!(parse_loopback_drop_url(raw).is_none(), "{raw:?}");
}
}
/// A real loopback peer receives the authenticated request and exact UTF-8 byte count.
#[test]
#[allow(clippy::expect_used)]
fn posts_the_complete_drop_to_loopback() -> io::Result<()> {
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
listener.set_nonblocking(true)?;
let payload = sample();
post_loopback_drop(listener.local_addr()?, "/custom/drop", "test-token", &payload)?;
let (mut stream, _) = listener.accept()?;
stream.set_nonblocking(false)?;
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
let mut request = String::new();
stream.read_to_string(&mut request)?;
let (headers, body) = request.split_once("\r\n\r\n").expect("HTTP headers");
assert_eq!(headers.lines().next(), Some("POST /custom/drop HTTP/1.1"));
for field in ["Host: 127.0.0.1", "Authorization: Bearer test-token",
"Content-Type: application/json", "Connection: close"] {
assert!(headers.lines().any(|line| line == field), "{field}");
}
assert!(headers.lines().any(|line| line == format!("Content-Length: {}", body.len())));
assert_eq!(body, encode_drop_json(&payload));
Ok(())
}
}
+2
View File
@@ -64,6 +64,8 @@ pub mod scroll;
// The SDL3 window: Linux's and Windows's (`native/sdl_thread.rs`), and macOS's with the
// `macos-sdl` feature, behind `REIMS_VGPU_WINDOW_IMPL`.
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
mod drop;
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
mod sdl;
pub use config::{
@@ -185,6 +185,7 @@ fn start_video() -> bool {
}
#[cfg(target_os = "windows")]
super::super::windows::install_unicode_input_hook();
crate::drop::install_host_drop_forwarder();
// SAFETY: SDL's video runs.
let kind = unsafe { SDL_RegisterEvents(1) };
WAKE.store(kind, Ordering::Release);
+72 -1
View File
@@ -83,6 +83,8 @@ pub(crate) struct Shell {
density: f64,
/// Its input.
pub(crate) input: Input,
/// Files and coordinates supplied by SDL for the current drop.
drop_batch: crate::drop::DropBatch,
/// What its OS keeps of it.
pub(crate) os: os::State,
/// The guest's cursor, built for SDL.
@@ -177,6 +179,7 @@ pub(crate) fn open(window: &Arc<Window>) {
layout: Layout::default(),
density: 1.0,
input: opened.input,
drop_batch: crate::drop::DropBatch::default(),
os: opened.state,
cursor: CursorCache::default(),
over_image: false,
@@ -204,6 +207,7 @@ pub(crate) fn open(window: &Arc<Window>) {
pub(crate) fn close(id: u64) {
let gone = with_shell(id, |shell| {
ended(shell);
shell.drop_batch.reset();
shell.closed = true;
os::close(shell) || shell.released
});
@@ -312,6 +316,14 @@ fn settled(before: Option<bool>, kind: u32) -> Option<bool> {
pub(crate) fn event(event: &SDL_Event) {
// SAFETY: every event starts with its type, and each arm reads the variant its type names.
let kind = unsafe { event.r#type };
let is_drop = [
SDL_EVENT_DROP_BEGIN.0,
SDL_EVENT_DROP_POSITION.0,
SDL_EVENT_DROP_FILE.0,
SDL_EVENT_DROP_TEXT.0,
SDL_EVENT_DROP_COMPLETE.0,
]
.contains(&kind);
let sdl_id = match kind {
k if (SDL_EVENT_WINDOW_FIRST.0..=SDL_EVENT_WINDOW_LAST.0).contains(&k) => unsafe {
event.window.windowID.0
@@ -324,9 +336,20 @@ pub(crate) fn event(event: &SDL_Event) {
event.button.windowID.0
},
k if k == SDL_EVENT_MOUSE_WHEEL.0 => unsafe { event.wheel.windowID.0 },
_ if is_drop => unsafe { event.drop.windowID.0 },
_ => return,
};
let Some(id) = window_of(sdl_id) else {
let target = if is_drop && sdl_id == 0 {
OPEN.with(|open| {
let open = open.borrow();
let mut live = open.iter().filter(|shell| !shell.closed);
let first = live.next()?;
live.next().is_none().then(|| first.window.id())
})
} else {
window_of(sdl_id)
};
let Some(id) = target else {
return;
};
with_shell(id, |shell| {
@@ -390,6 +413,54 @@ impl Shell {
self.refresh_cursor();
false
}
k if k == SDL_EVENT_DROP_BEGIN.0 => {
self.drop_batch.begin();
false
}
k if k == SDL_EVENT_DROP_POSITION.0 => {
// SAFETY: the event type selects the drop member.
let (x, y) = unsafe { (event.drop.x, event.drop.y) };
self.drop_batch.position(f64::from(x), f64::from(y));
false
}
k if k == SDL_EVENT_DROP_FILE.0 => {
// SAFETY: the event type selects the drop member.
let drop = unsafe { event.drop };
if !drop.data.is_null() {
// SAFETY: SDL3 owns this NUL-terminated path for the event's lifetime.
let path = unsafe { std::ffi::CStr::from_ptr(drop.data) }
.to_string_lossy()
.into_owned();
self.drop_batch
.file(path, Some((f64::from(drop.x), f64::from(drop.y))));
}
false
}
k if k == SDL_EVENT_DROP_TEXT.0 => {
// SAFETY: the event type selects the drop member.
let drop = unsafe { event.drop };
if !drop.data.is_null() {
// SAFETY: SDL3 owns this NUL-terminated text for the event's lifetime.
let text = unsafe { std::ffi::CStr::from_ptr(drop.data) }
.to_string_lossy()
.into_owned();
self.drop_batch
.text(text, Some((f64::from(drop.x), f64::from(drop.y))));
}
false
}
k if k == SDL_EVENT_DROP_COMPLETE.0 => {
// SAFETY: the event type selects the drop member.
let drop = unsafe { event.drop };
if let Some(payload) = self.drop_batch.complete(
self.window.port(),
self.layout.image,
Some((f64::from(drop.x), f64::from(drop.y))),
) {
crate::drop::submit(payload);
}
false
}
_ => os::input_event(self, kind, event),
};
self.flush();
@@ -529,7 +529,7 @@ use reims_vgpu_vulkan::core::platform::os::clock::MonoTime;
#[cfg(unix)]
use reims_vgpu_vulkan::core::platform::resource::SurfaceHandle;
use reims_vgpu_vulkan::core::platform::resource::{Buffer as _, MemoryFor};
use reims_vgpu_vulkan::core::platform::types::NsRange;
use reims_vgpu_vulkan::core::platform::types::{CommandBufferStatus, NsRange};
use reims_vgpu_vulkan::core::platform::values::{PagesPlane, TextureDesc};
use reims_vgpu_vulkan::core::platform::{Handle, Platform};
use reims_vgpu_vulkan::core::raise::{OnFault, Raise, RaiseResult, refusals};
@@ -8366,6 +8366,25 @@ impl<P: Platform> Caches<P> {
pub(crate) fn export_unattached(
&self,
device: &P::Device,
) -> Result<Vec<(u64, Vec<u8>)>, &'static str> {
self.export_unattached_with(
device,
|queue| queue.command_buffer(ON),
|cb| cb.commit(ON),
|| device.wait_idle(),
|cb| cb.wait_until_completed(ON),
|buffer| device.read_standalone_buffer(buffer),
)
}
fn export_unattached_with(
&self,
device: &P::Device,
mut command_buffer: impl FnMut(&P::CommandQueue) -> RaiseResult<Option<P::CommandBuffer>>,
mut commit: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
mut wait_idle: impl FnMut(),
mut wait_completed: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
mut read_buffer: impl FnMut(&P::Buffer) -> Result<Option<Vec<u8>>, &'static str>,
) -> Result<Vec<(u64, Vec<u8>)>, &'static str> {
let need_mem: Vec<P::Buffer> = {
let state = self.lock();
@@ -8373,17 +8392,14 @@ impl<P: Platform> Caches<P> {
.by_block
.values()
.filter(|c| {
c.pages.is_none()
&& !c.device.memory_made()
&& c.shapes.iter().any(|s| s.dirty)
c.pages.is_none() && !c.device.memory_made() && c.shapes.iter().any(|s| s.dirty)
})
.map(|c| c.device.clone_ref())
.collect()
};
self.make_memory(need_mem, MemoryFor::WriteBack);
let mut flushed_any = false;
{
let (dirty_blocks, queue) = {
let mut state = self.lock();
let dirty_blocks: Vec<u64> = state
.by_block
@@ -8391,45 +8407,85 @@ impl<P: Platform> Caches<P> {
.filter(|(_, c)| c.pages.is_none() && c.shapes.iter().any(|s| s.dirty))
.map(|(&b, _)| b)
.collect();
if !dirty_blocks.is_empty() {
let queue = if dirty_blocks.is_empty() {
None
} else {
if !state
.make_transfer(device)
.map_err(|_| "snapshot_save: surface cache transfer init failed")?
{
return Err("snapshot_save: surface cache transfer queue unavailable");
}
state
.transfer
.as_ref()
.map(|transfer| transfer.queue.clone_ref())
};
(dirty_blocks, queue)
};
if let Some(queue) = queue {
let mut submitted = Vec::new();
let flushed = (|| {
for block in dirty_blocks {
let cb_opt = {
let transfer = state
.transfer
.as_mut()
.ok_or("snapshot_save: surface cache transfer missing")?;
transfer
.queue
.command_buffer(ON)
.map_err(|_| "snapshot_save: surface cache command buffer failed")?
};
let Some(cb) = cb_opt else {
return Err("snapshot_save: surface cache command buffer unavailable");
};
let Some(cache) = state.by_block.get_mut(&block) else {
let cb = command_buffer(&queue)
.map_err(|_| "snapshot_save: surface cache command buffer failed")?
.ok_or("snapshot_save: surface cache command buffer unavailable")?;
let mut state = self.lock();
let Some(cache) = state.by_block.get_mut(&block).filter(|cache| {
cache.pages.is_none() && cache.shapes.iter().any(|s| s.dirty)
}) else {
continue;
};
if !cache.copy_through(MemoryFor::WriteBack) {
return Err("snapshot_save: deferred surface cache allocation failed");
}
let back = shapes::write_back::<P>(&cb, &cache.device, &cache.shapes, |s| {
s.dirty
})
.map_err(|_| "snapshot_save: surface cache shape write_back failed")?;
cache.wrote_shapes(&back);
state.owed_commits.push(cb);
flushed_any = true;
let back =
shapes::write_back::<P>(&cb, &cache.device, &cache.shapes, |s| s.dirty)
.map_err(|_| "snapshot_save: surface cache shape write_back failed")?;
if back.is_empty() {
return Err("snapshot_save: surface cache blit encoder unavailable");
}
// Retirement frees the queue slot even while we keep the handle for status.
let commit_failed = "snapshot_save: surface cache command buffer commit failed";
state.unlocked(|| commit(&cb)).map_err(|_| commit_failed)?;
let status = cb.status();
if status.raw() < CommandBufferStatus::COMMITTED.raw()
|| status == CommandBufferStatus::ERROR
{
return Err(commit_failed);
}
drop(state);
submitted.push((block, back, cb));
}
Ok(())
})();
let mut wait_failed = false;
if !submitted.is_empty() {
wait_idle();
for (_, _, cb) in &submitted {
if wait_completed(cb).is_err() {
wait_failed = true;
}
}
}
flushed?;
if wait_failed
|| submitted
.iter()
.any(|(_, _, cb)| cb.status() != CommandBufferStatus::COMPLETED)
{
return Err(
"snapshot_save: surface cache command buffer did not complete successfully",
);
}
let mut state = self.lock();
let state = &mut *state;
for (block, back, _) in &submitted {
if let Some(cache) = state.by_block.get_mut(block) {
cache.wrote_shapes(back);
cache.shapes.written_back(back, &mut state.counts.shapes);
}
}
}
if flushed_any {
device.wait_idle();
}
let mut to_read: Vec<(u64, P::Buffer)> = {
@@ -8445,7 +8501,7 @@ impl<P: Platform> Caches<P> {
let mut out = Vec::with_capacity(to_read.len());
for (block, buf) in to_read {
match device.read_standalone_buffer(&buf)? {
match read_buffer(&buf)? {
Some(bytes) => out.push((block, bytes)),
None => return Err("snapshot_save: unattached surface cache buffer unreadable"),
}
@@ -16385,6 +16441,325 @@ pub(super) mod tests {
r.pages_flagged(block, 0, &[], length, flags)
}
const SNAPSHOT_CACHE_LENGTH: u64 = 0x1000;
fn snapshot_rig(blocks: u64) -> Rig {
let r = rig(8);
r.dec.set_deferred_budget(blocks * SNAPSHOT_CACHE_LENGTH);
r.dec.caches().shaped = true;
r
}
fn dirty_unattached_cache(r: &mut Rig, block: u64) -> reims_vgpu_vulkan::core::platform::ObjId {
assert_eq!(defer(r, block, SNAPSHOT_CACHE_LENGTH), RGFX_STATUS_OK);
let key = ShapeKey {
plane: 0,
offset: 128,
bytes_per_row: 128,
width: 16,
height: 2,
texel_bytes: 4,
storage: false,
};
let desc = r.p.texture_descriptor(&TextureDesc {
pixel_format: 80,
width: key.width,
height: key.height,
..TextureDesc::default()
});
let image = r.device.new_texture(ON, &desc).unwrap().unwrap();
let id = image.id();
let mut state = r.dec.caches();
let cache = state.by_block.get_mut(&block).unwrap();
assert!(cache.pages.is_none());
assert!(!cache.device.memory_made());
let (reference, _) = cache.shapes.insert(key, image, false, 0);
assert!(cache.shapes.mark_dirty(reference.id()));
id
}
#[test]
fn snapshot_exports_more_dirty_unattached_caches_than_the_transfer_queue_holds() {
use reims_vgpu_vulkan::core::platform::types::MtlSize;
const BLOCKS: u64 = 80;
const CAPACITY: usize = 64;
let mut r = snapshot_rig(BLOCKS + 1);
let mut textures = HashMap::default();
let mut expected = Vec::new();
for i in 0..BLOCKS {
let block = BLOCK + i * 0x2000;
let texture = dirty_unattached_cache(&mut r, block);
let texels = [[i as u8; 64], [255 - i as u8; 64]];
let mut bytes = vec![0; SNAPSHOT_CACHE_LENGTH.to_usize()];
for (row, texels) in bytes[128..].chunks_mut(128).zip(&texels) {
row[..64].copy_from_slice(texels);
}
textures.insert(texture, texels);
expected.push((block, bytes));
}
assert_eq!(
defer(&mut r, BLOCK + BLOCKS * 0x2000, SNAPSHOT_CACHE_LENGTH),
RGFX_STATUS_OK
);
let mark = r.p.call_log().mark();
let world = r.p.world();
let mut acquired = 0;
let retired = Cell::new(0);
let caches = &r.dec.surface_caches;
let exported = caches.export_unattached_with(
&r.device,
|queue| {
assert!(
caches.try_lock().is_some(),
"queue acquisition holds the cache lock"
);
let in_flight = world.committed().len();
assert_eq!(
world.live("MTLCommandBuffer").len(),
in_flight + retired.get(),
"a previous buffer is uncommitted"
);
if in_flight == CAPACITY {
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
}
assert!(world.committed().len() < CAPACITY);
acquired += 1;
queue.command_buffer(ON)
},
|cb| cb.commit(ON),
|| {
assert_eq!(caches.try_lock().unwrap().counts.shapes.written_back, 0);
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
},
|cb| cb.wait_until_completed(ON),
|buffer| {
assert!(world.live("MTLCommandBuffer").is_empty());
// The fake logs blits without executing them. Reproduce each logged GPU copy.
let calls = r.p.call_log().since(mark);
let mut copies = calls.iter().filter(|call| {
call.sel.starts_with("copyFromTexture:")
&& call.args[5].as_obj() == Some(buffer.id())
});
let copy = copies.next().expect("a copy into this cache");
assert!(copies.next().is_none());
assert_eq!(copy.args[4], Arg::val(&MtlSize::new(16, 2, 1)));
let source = &textures[&copy.args[0].as_obj().unwrap()];
let offset = copy.args[6].as_u64().unwrap().to_usize();
let pitch = copy.args[7].as_u64().unwrap().to_usize();
let mut bytes = vec![0; buffer.length().to_usize()];
for (row, texels) in source.iter().enumerate() {
let at = offset + row * pitch;
bytes[at..at + 64].copy_from_slice(texels);
}
Ok(Some(bytes))
},
);
assert_eq!(acquired, BLOCKS);
assert_eq!(retired.get(), BLOCKS.to_usize());
assert_eq!(exported.unwrap(), expected);
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, BLOCKS);
assert!(
state
.by_block
.values()
.all(|cache| cache.shapes.iter().all(|s| !s.dirty))
);
}
#[test]
fn snapshot_drops_uncommitted_unattached_writebacks_on_error() {
use reims_vgpu_vulkan::core::testkit::Step;
use reims_vgpu_vulkan::core::testkit::impls::resource::MAKE_MEMORY;
for (selector, steps, error) in [
(
"commandBuffer",
vec![Step::Nil],
"snapshot_save: surface cache command buffer unavailable",
),
(
MAKE_MEMORY,
vec![Step::value(false); 2],
"snapshot_save: deferred surface cache allocation failed",
),
(
"blitCommandEncoder",
vec![Step::Nil],
"snapshot_save: surface cache blit encoder unavailable",
),
(
"endEncoding",
vec![Step::unrecognized("endEncoding")],
"snapshot_save: surface cache shape write_back failed",
),
(
"commit",
vec![Step::unrecognized("commit")],
"snapshot_save: surface cache command buffer commit failed",
),
] {
let mut r = snapshot_rig(1);
dirty_unattached_cache(&mut r, BLOCK);
for step in steps {
r.p.script().push(selector, step);
}
let caches = &r.dec.surface_caches;
assert_eq!(caches.export_unattached(&r.device), Err(error));
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
assert!(
r.dec.caches().by_block[&BLOCK]
.shapes
.iter()
.all(|s| s.dirty)
);
}
}
#[test]
fn snapshot_stops_before_readback_if_a_later_writeback_fails() {
let mut r = snapshot_rig(2);
dirty_unattached_cache(&mut r, BLOCK);
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
r.p.faults()
.at("MTLCommandQueue", "commandBuffer", 1, Fault::Nil);
let caches = &r.dec.surface_caches;
let world = r.p.world();
let mut retired = 0;
let exported = caches.export_unattached_with(
&r.device,
|queue| queue.command_buffer(ON),
|cb| cb.commit(ON),
|| retired += world.complete_all(CompleteOn::Caller),
|cb| cb.wait_until_completed(ON),
|_| panic!("a failed writeback must stop the snapshot before readback"),
);
assert_eq!(
exported,
Err("snapshot_save: surface cache command buffer unavailable")
);
assert_eq!(retired, 1);
assert!(world.live("MTLCommandBuffer").is_empty());
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, 0);
assert_eq!(
state
.by_block
.values()
.filter(|c| c.shapes.iter().any(|s| s.dirty))
.count(),
2
);
}
#[test]
fn snapshot_preserves_dirty_shapes_if_writeback_commit_is_silently_refused() {
let mut r = snapshot_rig(1);
dirty_unattached_cache(&mut r, BLOCK);
let exported = r.dec.surface_caches.export_unattached_with(
&r.device,
|queue| queue.command_buffer(ON),
|_| Ok(()),
|| panic!("a refused commit leaves no submitted work to wait for"),
|_| panic!("a refused commit leaves no submitted work to wait for"),
|_| panic!("a refused commit must stop the snapshot before readback"),
);
assert_eq!(
exported,
Err("snapshot_save: surface cache command buffer commit failed")
);
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, 0);
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| s.dirty));
}
#[test]
fn snapshot_preserves_dirty_shapes_if_a_submitted_writeback_fails() {
let mut r = snapshot_rig(2);
dirty_unattached_cache(&mut r, BLOCK);
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
let world = r.p.world();
let exported = r.dec.surface_caches.export_unattached_with(
&r.device,
|queue| queue.command_buffer(ON),
|cb| cb.commit(ON),
|| {
let [first, second] = world.committed().try_into().unwrap();
assert!(world.complete(
first,
CommandBufferStatus::COMPLETED,
None,
CompleteOn::Caller
));
assert!(world.complete(
second,
CommandBufferStatus::ERROR,
None,
CompleteOn::Caller
));
},
|cb| cb.wait_until_completed(ON),
|_| panic!("a failed writeback must stop the snapshot before readback"),
);
assert_eq!(
exported,
Err("snapshot_save: surface cache command buffer did not complete successfully")
);
assert!(world.live("MTLCommandBuffer").is_empty());
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, 0);
assert!(
state
.by_block
.values()
.all(|cache| cache.shapes.iter().all(|s| s.dirty))
);
}
#[test]
fn snapshot_waits_for_each_submitted_writeback_status_after_wait_idle() {
let mut r = snapshot_rig(1);
dirty_unattached_cache(&mut r, BLOCK);
let world = r.p.world();
let mut waited_completed = 0;
let exported = r.dec.surface_caches.export_unattached_with(
&r.device,
|queue| queue.command_buffer(ON),
|cb| cb.commit(ON),
|| {
// Simulate wait_idle returning before the completion worker has
// published the command buffer's final COMPLETED status.
assert_eq!(world.committed().len(), 1);
},
|cb| {
waited_completed += 1;
assert_eq!(cb.status(), CommandBufferStatus::SCHEDULED);
assert_eq!(world.complete_all(CompleteOn::Caller), 1);
cb.wait_until_completed(ON)
},
|buffer| {
assert!(world.live("MTLCommandBuffer").is_empty());
Ok(Some(vec![0xAB; buffer.length().to_usize()]))
},
);
assert_eq!(waited_completed, 1);
assert_eq!(
exported,
Ok(vec![(BLOCK, vec![0xAB; SNAPSHOT_CACHE_LENGTH.to_usize()])])
);
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, 1);
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| !s.dirty));
}
/// A `SURFACE_PAGES` naming the pages of the deferred block at `block`, `runs` as
/// [`Rig::pages`]'s, from context `context`; its answer.
fn attach(r: &mut Rig, block: u64, context: u32, runs: &[(u64, u64)], length: u64) -> u32 {
+6 -6
View File
@@ -23,9 +23,9 @@
* moved the cursor yet: the latest is where the host's pointer is.
*
* Where the point lies, and the rectangles the host is told:
* - on x86-64, each framebuffer holds its display's rectangle as WindowServer placed it
* (getBoundingRect), and a move of the cursor on any display tells the host each display's
* that changed (tellBounds);
* - on x86-64, each framebuffer holds its display's virtual desktop rectangle as WindowServer
* placed it (getBoundingRect), and a move of the cursor on any display tells the host each
* virtual rectangle that changed (tellBounds);
* - on arm64, WindowServer tells the displays nothing of where it placed them, so the kext
* learns it from its own posts: a crossing posts at the display's pixel of the rectangle held
* for it, and again beside the other displays where the cursor did not reach it, at most
@@ -185,7 +185,7 @@ void ReimsGraphics::movePointer(thread_call_param_t self, thread_call_param_t)
IOSimpleLockUnlock(me->interruptLock);
if (!me->hasStarted())
return;
// The display's mode and its rectangle in the global space.
// The display's scanout size and its virtual desktop rectangle.
ReimsGraphics *fb = me->copyDisplay(me->drivenIndex(at.display));
if (!fb)
return;
@@ -221,7 +221,7 @@ void ReimsGraphics::movePointer(thread_call_param_t self, thread_call_param_t)
move == RgfxPointerMove::moved ? "moves" : "is dragged", globalX, globalY, posted);
}
// Each framebuffer holds its display's rectangle as WindowServer placed it (getBoundingRect).
// The virtual rectangles used for both IOHIDSystem posts and DISPLAY_BOUNDS.
void ReimsGraphics::displayPlaces(RgfxGlobalRect *rects, bool *placed)
{
ReimsGraphics *fbs[RGFX_DISPLAYS_MAX];
@@ -232,7 +232,7 @@ void ReimsGraphics::displayPlaces(RgfxGlobalRect *rects, bool *placed)
fbs[i]->getBoundingRect(&bounds);
if (!bounds || display >= RGFX_DISPLAYS_MAX)
continue;
rects[display] = {bounds->minx, bounds->miny, bounds->maxx, bounds->maxy};
rects[display] = rgfxFramebufferDesktopBounds(bounds);
placed[display] = true;
}
releaseDisplays(fbs, n);
+11 -2
View File
@@ -1,7 +1,7 @@
// RgfxDisplayBounds: which displays' rectangles the kext tells the host in DISPLAY_BOUNDS
// (design.md, "Multiple displays", "A drag across displays"). On x86-64 each framebuffer holds its
// display's rectangle in WindowServer's global space as WindowServer placed it (IOFBSetBounds,
// which IOFramebuffer::getBoundingRect reads; RgfxPointerOver.hpp), and on arm64 the kext holds
// display's virtual desktop rectangle as WindowServer placed it (IOFBSetBounds, which
// IOFramebuffer::getBoundingRect reads; RgfxPointerOver.hpp), and on arm64 the kext holds
// each one a landing of its own moves of the cursor confirmed (RgfxDisplayPlaces.hpp); the host
// carries its captured pointer past one display's edge onto the display whose rectangle meets it
// there. Each move of the cursor, on any display, tells the host every display's rectangle that
@@ -21,6 +21,15 @@
#include "RgfxPointerOver.hpp"
#include "reims_graphics_wire.h"
// IOFramebuffer's getBoundingRect returns its physical and virtual rectangles in order.
// IOFBSetBounds supplies both, or IOFramebuffer uses the sole rectangle for both.
template <class Bounds>
inline RgfxGlobalRect rgfxFramebufferDesktopBounds(const Bounds *bounds)
{
const Bounds &rect = bounds[1];
return {rect.minx, rect.miny, rect.maxx, rect.maxy};
}
// The rectangle the host was last told of each display, by id, where it was told one.
struct RgfxBoundsTold {
RgfxGlobalRect rects[RGFX_DISPLAYS_MAX];
+6 -10
View File
@@ -4,16 +4,12 @@
// the display its cursor is on, so the kext moves the cursor onto that display, at that point,
// before the tablet's next position comes (ReimsGraphicsPointer.cpp).
//
// The point is in WindowServer's global space, in which it placed each display: on x86-64 each
// framebuffer holds its display's rectangle there as WindowServer gave it (IOFBSetBounds, which
// IOFramebuffer::getBoundingRect reads), the space the cursor's moves arrive in
// (IOFramebuffer::extSetCursorPosition); on arm64 the kext learns each one from its own moves
// (RgfxDisplayPlaces.hpp). The display's pixel lies in that rectangle as the pixel
// lies in the display's mode, scaled from the mode's pixels to the rectangle's size. Measured on
// x86-64 macOS 11.7.11, 15.8.2 and 26.7.2 with two 1920 x 1080 displays side by side: each
// framebuffer's rectangle is the display's CGDisplayBounds, and IOHIDSystem's mouse-moved posted
// at a point of display 1's rectangle puts the cursor there (lane ptrcross, potluck jobs
// m3-max-34583 to 34585).
// IOHIDSystem's post takes a point in WindowServer's virtual desktop. On x86-64 the framebuffer
// holds the virtual rectangle WindowServer gave it (IOFBSetBounds); on arm64 the kext learns
// each rectangle from its own moves (RgfxDisplayPlaces.hpp). Scale the scanout pixels into that
// rectangle. Measured on x86-64 macOS 11.7.11, 15.8.2 and 26.7.2 with two 1920 x 1080 displays
// side by side: a mouse-moved posted at a point in display 1's CGDisplayBounds puts the cursor
// there (lane ptrcross, potluck jobs m3-max-34583 to 34585).
//
// The move is a mouse-moved where no button is held, and the drag of the button held where one is,
// as IOHIDSystem's own moves are (the left button's before the right's, the right's before any
+28
View File
@@ -19,10 +19,38 @@ void check(bool ok, const char *what)
std::exit(1);
}
}
void mixedScaleDesktop()
{
// IOFramebuffer keeps the physical and virtual desktop rectangles, in that order.
const RgfxGlobalRect framebuffers[2][2] = {
{{0, 0, 3840, 2160}, {0, 0, 1920, 1080}},
{{3840, 0, 6400, 1440}, {1920, 0, 4480, 1440}},
};
const RgfxGlobalRect left = rgfxFramebufferDesktopBounds(framebuffers[0]);
const RgfxGlobalRect right = rgfxFramebufferDesktopBounds(framebuffers[1]);
int32_t x = 0, y = 0;
check(rgfxPointerGlobal(right, 2560, 1440, 2, 653, &x, &y) && x == 1922 && y == 653,
"crossing onto the native display uses its virtual origin");
check(rgfxPointerGlobal(left, 3840, 2160, 3834, 943, &x, &y) && x == 1917 && y == 471,
"crossing back scales scanout pixels into the HiDPI desktop rectangle");
// Both displays were native before the switch. Their physical rectangles stay the same.
RgfxBoundsTold told = {};
rgfxBoundsWereTold(&told, 0, framebuffers[0][0]);
rgfxBoundsWereTold(&told, 1, framebuffers[1][0]);
check(rgfxBoundsToTell(told, 0, left) && rgfxBoundsToTell(told, 1, right),
"a HiDPI switch reports the resized display and the moved neighbor");
const RgfxDisplayBounds command = rgfxBoundsCommand(1, right);
check(command.min_x == 1920 && command.max_x == 4480 && command.max_y == 1440,
"DISPLAY_BOUNDS uses the same desktop rectangle as the pointer post");
}
} // namespace
int main()
{
mixedScaleDesktop();
// The wire's command: 40 bytes, the display then the rectangle past the 16-byte header.
check(sizeof(RgfxDisplayBounds) == 40 && RGFX_CMD_DISPLAY_BOUNDS == 9, "the wire's");
check(offsetof(RgfxDisplayBounds, display) == 16 && offsetof(RgfxDisplayBounds, min_x) == 20 &&
+1 -1
View File
@@ -34,4 +34,4 @@ Arch = "arm64e"
MinKernel = "23.0.0"
MaxKernel = ""
Comment = "Installs the reims-graphics Metal bundle and admits it"
sha256 = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
sha256 = "969de78746515a49078709af17268af29ee398262dd45911e897c8ce2e806792"
+5 -5
View File
@@ -331,7 +331,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/ReimsGraphics.cpp" = "7ea4b22d26781eb7f673968cf77e33b65cd09042f4a949f600d27d1f9024ebec"
"guest/kext/src/ReimsGraphics.hpp" = "e4162466ced71dd89ca50a38dcdf26c874765aab471bd96375fcb99f0766f20d"
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
"guest/kext/src/ReimsGraphicsPointer.cpp" = "7b3482545b8e5e459327ab31648e32d83fd8317587b453b4133a5974fa44e35d"
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
@@ -359,7 +359,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
"guest/kext/src/RgfxDisplayBounds.hpp" = "7aafbc6d1c2bb28e50c973f77d21c1aa00b322fb5fc934d4b1238b50f3aa89db"
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
"guest/kext/src/RgfxDisplayPipeUserClient.cpp" = "460c7d61a305d7d145b3318bb4fbe940c0d2d48d63afbbfeb6f273cd929aa3af"
@@ -397,7 +397,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/RgfxPointerDevice.cpp" = "a4f88cc9b272259c3a85325b2295feea6a22221f52035fc5130d72f52cb88891"
"guest/kext/src/RgfxPointerDevice.hpp" = "a393c90bed65528495868778e4130851e98aeafcb11401aef05d2d41d5b90d3f"
"guest/kext/src/RgfxPointerMotion.hpp" = "d5cbe1a09db996980319d0b907782675fa82b5a03fd84a51f7c7d12c5dada926"
"guest/kext/src/RgfxPointerOver.hpp" = "c2c38dbd101b1f59400bb159bd8cb44ed8c937bf25b93e9d62a03d6c2fd9ae50"
"guest/kext/src/RgfxPointerOver.hpp" = "757946b2332ba278201f4c2f44ec1ee2bb21ca10b017a7c7933f696d8ee8f10c"
"guest/kext/src/RgfxPointerReporting.cpp" = "c9f33023f3acea2e638353e8943c65f28f8befa984989ae88e7abc24858b961e"
"guest/kext/src/RgfxPoolBlocks.hpp" = "a657b67922b04b75ccef6f12e10d775867f4037e50b89a8cf0d4972af43747fe"
"guest/kext/src/RgfxQueueLimits.hpp" = "13f8ecd60e8d19f438b8ddc1cf3a0273fba1028bc049110776b637fa2097173c"
@@ -466,5 +466,5 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"ReimsGraphics.kext/Contents/Info.plist" = "9683153587659c4bd4d5c52167eff1f3d2ae51dae575f60c15a27d89240f46c5"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "33a086b90fa116b3cf0c6bb826c27f8a55cd83f15522ee794e20186d469bdbc7"
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
"set.toml" = "a4da2409f25dd7bf12260de752c38c474b60d4b2d993810a44de0f4b07cb6dfd"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "969de78746515a49078709af17268af29ee398262dd45911e897c8ce2e806792"
"set.toml" = "934935a19dea7d19f09c411552120e3290f2f534bf12d97c8b4900e140aa4140"
Binary file not shown.
+2 -2
View File
@@ -24,7 +24,7 @@ Arch = "x86_64"
MinKernel = "20.0.0"
MaxKernel = ""
Comment = "The reims-graphics display, accelerator and device control"
sha256 = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
sha256 = "2f15b6a13b44e98d4af81240c44720c0004f3c7d5c9dfecfde3b39f069930349"
[[kext]]
BundlePath = "RgfxGate.kext"
@@ -34,4 +34,4 @@ Arch = "x86_64"
MinKernel = "20.0.0"
MaxKernel = ""
Comment = "Installs the reims-graphics Metal bundle and admits it"
sha256 = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
sha256 = "534ab7e2f0b39ce9f6403b8988e89419889893b68ea91687b5aaeff38f5a9be6"
+6 -6
View File
@@ -331,7 +331,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/ReimsGraphics.cpp" = "7ea4b22d26781eb7f673968cf77e33b65cd09042f4a949f600d27d1f9024ebec"
"guest/kext/src/ReimsGraphics.hpp" = "e4162466ced71dd89ca50a38dcdf26c874765aab471bd96375fcb99f0766f20d"
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
"guest/kext/src/ReimsGraphicsPointer.cpp" = "7b3482545b8e5e459327ab31648e32d83fd8317587b453b4133a5974fa44e35d"
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
@@ -359,7 +359,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
"guest/kext/src/RgfxDisplayBounds.hpp" = "7aafbc6d1c2bb28e50c973f77d21c1aa00b322fb5fc934d4b1238b50f3aa89db"
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
"guest/kext/src/RgfxDisplayPipeUserClient.cpp" = "460c7d61a305d7d145b3318bb4fbe940c0d2d48d63afbbfeb6f273cd929aa3af"
@@ -397,7 +397,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/RgfxPointerDevice.cpp" = "a4f88cc9b272259c3a85325b2295feea6a22221f52035fc5130d72f52cb88891"
"guest/kext/src/RgfxPointerDevice.hpp" = "a393c90bed65528495868778e4130851e98aeafcb11401aef05d2d41d5b90d3f"
"guest/kext/src/RgfxPointerMotion.hpp" = "d5cbe1a09db996980319d0b907782675fa82b5a03fd84a51f7c7d12c5dada926"
"guest/kext/src/RgfxPointerOver.hpp" = "c2c38dbd101b1f59400bb159bd8cb44ed8c937bf25b93e9d62a03d6c2fd9ae50"
"guest/kext/src/RgfxPointerOver.hpp" = "757946b2332ba278201f4c2f44ec1ee2bb21ca10b017a7c7933f696d8ee8f10c"
"guest/kext/src/RgfxPointerReporting.cpp" = "c9f33023f3acea2e638353e8943c65f28f8befa984989ae88e7abc24858b961e"
"guest/kext/src/RgfxPoolBlocks.hpp" = "a657b67922b04b75ccef6f12e10d775867f4037e50b89a8cf0d4972af43747fe"
"guest/kext/src/RgfxQueueLimits.hpp" = "13f8ecd60e8d19f438b8ddc1cf3a0273fba1028bc049110776b637fa2097173c"
@@ -464,7 +464,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"Graft.kext/Contents/Info.plist" = "fa8533d5ec06430f3ede502e6f9e739e9c8c3f6b6909c46d854effe6028cbc7f"
"Graft.kext/Contents/MacOS/Graft" = "04a1d44c0c80c20a71f3a662c46b56a1732b8134f095fb2ac57ec790f72baf72"
"ReimsGraphics.kext/Contents/Info.plist" = "ae0dafd3b6c36c24d1c92467d8203d76360eb6e4f6ad5c496167a21033b2c209"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "2f15b6a13b44e98d4af81240c44720c0004f3c7d5c9dfecfde3b39f069930349"
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
"set.toml" = "49182c19c3d961b251901e19a09016df684f1f102527a0d3274697eaaf3dbab5"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "534ab7e2f0b39ce9f6403b8988e89419889893b68ea91687b5aaeff38f5a9be6"
"set.toml" = "c2f6659892f049da4bc81ec2854915cdb5cd1c4de8b15728582264b64f166131"
+3 -1
View File
@@ -7,6 +7,8 @@
"win10-compat",
"win10-startup-ipis",
"win32-coroutine-fiber",
"win32-unicode-input"
"win32-unicode-input",
"window-file-drop",
"window-text-drop"
]
}