From d94c60d82f8026fbee88944ff37d8890834cf4cc Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Mon, 5 Oct 2026 03:40:12 +0900 Subject: [PATCH 1/3] Feat: Wire the fork's window parity logic into the renderer and bring over the parity harness Stacked on #165. The window code is the fork's now; the Compose half of what #147 and #155 added is not, and was on neither develop nor #165. - macOS Kotlin/Native: contentMinimum, DockIcon (with ImageBitmap.toNSImage), SystemDarkMonitor fed by the appearance notification, and the fork's MacosClipboard and MacosClipboardManager, so Paste is offered by what the pasteboard holds. - GraalVM macOS: the same DockIcon, contentMinimum and a polled SystemDarkMonitor, the clipboard through TextPasteboard, window options read once by NativeWindowOptions, and the synthetic exit. - The K/N-portable LatencyTrace and SyntheticInput (no String.format, System.nanoTime shim, exit after the resize), the JvmCompatShims they need, and ParityMeasurementTest. - The hand-check app and its consumer fixture changes. Not here, with reasons: NativeWindowShell, the Win32 letter and digit keys and the default window switches depend on #134 (beginNativeWindowDrag, win32ComposeKey, the X11 and Win32 defaults, also #160, #170, #172) and come with it. The GraalVM text menu needs the fork's setTextMenu, which is not in the pinned fork commit yet. The resize header counter on Kotlin/Native is dropped: the fork's FramePresentLog replaces it. Covers FR-33.6 (clipboard and text menu enablement), FR-19 (min size, Dock icon), NFR-14. --- .gitignore | 1 + .../tests/fixtures/consumer/src/main.rs | 32 ++- .../tests/fixtures/hand-check/Cargo.toml | 16 ++ .../tests/fixtures/hand-check/README.md | 35 ++++ .../tests/fixtures/hand-check/src/main.rs | 189 ++++++++++++++++++ renderer/desktop/src/AppKitWindow.kt | 62 +++--- renderer/desktop/src/LatencyTrace.kt | 89 +++++++-- renderer/desktop/src/NativeClipboard.kt | 19 +- renderer/desktop/src/NativeWindowOptions.kt | 45 +++++ renderer/desktop/src/SyntheticInput.kt | 17 +- renderer/desktop/src/SystemAppearance.kt | 7 +- .../desktop/test/ParityMeasurementTest.kt | 40 ++++ renderer/linux/src/JvmCompatShims.kt | 13 ++ renderer/macos/src/JvmCompatShims.kt | 8 + renderer/macos/src/MacosRenderer.kt | 72 ++++++- renderer/macos/src/MacosWindowChrome.kt | 24 +++ 16 files changed, 610 insertions(+), 59 deletions(-) create mode 100644 compose-rust/tests/fixtures/hand-check/Cargo.toml create mode 100644 compose-rust/tests/fixtures/hand-check/README.md create mode 100644 compose-rust/tests/fixtures/hand-check/src/main.rs create mode 100644 renderer/desktop/src/NativeWindowOptions.kt create mode 100644 renderer/desktop/test/ParityMeasurementTest.kt create mode 100644 renderer/macos/src/MacosWindowChrome.kt diff --git a/.gitignore b/.gitignore index a3bc153eb..9713178c2 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ target # needs at the time, and tracking it would mean a second lock file to update on every # dependency change, plus a dirty working tree every time the test runs. compose-rust/tests/fixtures/consumer/Cargo.lock +compose-rust/tests/fixtures/hand-check/Cargo.lock # The Host's wasm module, built next to the page by # renderer/web/scripts/build-host.sh. The loader beside it is generated and diff --git a/compose-rust/tests/fixtures/consumer/src/main.rs b/compose-rust/tests/fixtures/consumer/src/main.rs index ad9538e3b..4b8f974ad 100644 --- a/compose-rust/tests/fixtures/consumer/src/main.rs +++ b/compose-rust/tests/fixtures/consumer/src/main.rs @@ -24,13 +24,16 @@ //! each press of the button. That is the only way the check can tell that an event arrived //! all the way at the Host. //! +//! `--parity` is that window with a title and a smallest size of its own, for +//! `scripts/parity/linux.sh`, which reads both back from the display server. +//! //! The call to launch stays in the binary because the branch is decided at run time. //! That is what makes the renderer a load-time dependency of this executable rather than //! a library the linker drops for being unused. use compose_rust::boundary::STATUS_OK; use compose_rust::protocol::{HostEvent, Mutation, PropertyValue, ProtocolError}; -use compose_rust::schema::{EventPayload, PropertyKind, WidgetKind}; +use compose_rust::schema::{EventPayload, PropertyKind, WidgetKind, Window}; use compose_rust::{Batch, LaunchBuilder, Runtime}; use std::ffi::c_int; use std::sync::atomic::{AtomicU32, Ordering}; @@ -151,6 +154,10 @@ impl Runtime for Screen { } } +/// The smallest size `--parity` asks the window to allow, which the parity check reads back. +const PARITY_MIN_WIDTH: u16 = 300; +const PARITY_MIN_HEIGHT: u16 = 260; + const FORM: u32 = 10; const FIELD: u32 = 11; const SAVE: u32 = 12; @@ -160,12 +167,23 @@ const ON_CLICK: u64 = 2; /// A column holding a text field and a button, and nothing else. struct Form { batch: Batch, + /// Asks for a window of its own: a title and a smallest size, which the parity check reads + /// back from the display server on every path. + parity: bool, } impl Form { fn new() -> Self { Self { batch: Batch::new(), + parity: false, + } + } + + fn for_parity() -> Self { + Self { + batch: Batch::new(), + parity: true, } } @@ -196,6 +214,14 @@ impl Runtime for Form { } fn rebuild(&mut self) { + if self.parity { + self.batch.write(Mutation::SetWindow(Window { + title: "compose-rust parity", + min_width: PARITY_MIN_WIDTH, + min_height: PARITY_MIN_HEIGHT, + ..Window::new() + })); + } for (node_id, widget) in [ (FORM, WidgetKind::Column), (FIELD, WidgetKind::TextField), @@ -301,6 +327,10 @@ fn main() { LaunchBuilder::new().launch_runtime(|| Box::new(Form::new()) as Box); return; } + if std::env::args().any(|argument| argument == "--parity") { + LaunchBuilder::new().launch_runtime(|| Box::new(Form::for_parity()) as Box); + return; + } if std::env::args().any(|argument| argument == "--launch") { LaunchBuilder::new().launch_runtime(|| Box::new(Screen::new(false)) as Box); return; diff --git a/compose-rust/tests/fixtures/hand-check/Cargo.toml b/compose-rust/tests/fixtures/hand-check/Cargo.toml new file mode 100644 index 000000000..1062f8cb3 --- /dev/null +++ b/compose-rust/tests/fixtures/hand-check/Cargo.toml @@ -0,0 +1,16 @@ +# A window to check by hand on a real desktop: text shortcuts, live resize, an input method, +# focus between two fields, a click and a scrolling list with Korean in it. +# +# Like the consumer fixture next to it, this is its own workspace root, so `cargo run` works +# in this directory on Windows, macOS and Linux whatever the enclosing workspace says. It +# names its edition outright for the same reason: an excluded crate cannot inherit one. +[workspace] + +[package] +name = "hand-check" +version = "0.0.0" +edition = "2024" +publish = false + +[dependencies] +compose-rust = { path = "../../.." } diff --git a/compose-rust/tests/fixtures/hand-check/README.md b/compose-rust/tests/fixtures/hand-check/README.md new file mode 100644 index 000000000..648c070b7 --- /dev/null +++ b/compose-rust/tests/fixtures/hand-check/README.md @@ -0,0 +1,35 @@ +# hand-check + +A window to check a renderer by hand on a real desktop. It has a click counter, two text +fields, a line showing the window's size class, and a scrolling list with Korean rows. What +the fields hold is echoed under each, and every change is printed to standard output as an +`event:` line. + +Set `COMPOSE_RUST_RENDERER_DIR` to the renderer you want to try, then run it from this +directory. The commands are the same on every desktop apart from how the variable is set. + +```sh +# macOS and Linux +COMPOSE_RUST_RENDERER_DIR=/path/to/renderer/dist cargo run --release +``` + +```powershell +# Windows (PowerShell). The renderer's bin folder has to be on PATH as well. +$env:COMPOSE_RUST_RENDERER_DIR = "C:\path\to\renderer\dist" +$env:PATH = "C:\path\to\renderer\dist\bin;$env:PATH" +cargo run --release +``` + +On Linux the X11 window is opt-in until it is the default: add `DXC_X11_WINDOW=1`. + +## What to check + +| Check | How | What you should see | +| --- | --- | --- | +| Text shortcuts | In the first field select with ctrl or cmd+A, then C, X, V and Z | The echo line under the field shows the paste, the cut and the undo; `event: first ...` lines print | +| Clipboard across apps | Copy in another app, paste here, and the other way round | The text, Korean included, arrives | +| Live resize | Drag an edge and a corner, at 100% and at 200% scale | Content follows the edge with no lag or flash; the `window:` line shows the size class and size when it changes | +| Input method | Type Korean (`han-geul`) in a field | Underlined text while composing, and the candidate window beside the caret, not at the corner | +| Focus | Click each field, press Tab | Only one field has the caret, and typing goes to it | +| Click | Press the button | The counter counts and `event: click N` prints | +| Scrolling | Scroll the list with the wheel and the scrollbar | 60 rows move smoothly | diff --git a/compose-rust/tests/fixtures/hand-check/src/main.rs b/compose-rust/tests/fixtures/hand-check/src/main.rs new file mode 100644 index 000000000..c2c908ba2 --- /dev/null +++ b/compose-rust/tests/fixtures/hand-check/src/main.rs @@ -0,0 +1,189 @@ +//! A window for checking a renderer by hand. Nothing in it is a test: a person uses it and +//! reads what it says, on screen and as `event:` lines on standard output. +//! +//! What is in the window, top to bottom: +//! +//! - a label counting clicks, and the button that counts them; +//! - two text fields, to see which has the keyboard, with what each holds echoed below it, so +//! that what ctrl or cmd with C, V, X, Z and A did is on screen: a paste shows up as the new +//! text, an undo as the text going back, a cut as the text shrinking; +//! - the window's size class and size, as the renderer last reported them (it reports when +//! the class changes, not on every pixel of a resize); +//! - a scrolling list of 60 rows with Korean in them. +//! +//! For an input method, type Korean in either field and watch where the candidate window +//! opens: it should be beside the caret. +//! +//! The renderer comes from `COMPOSE_RUST_RENDERER_DIR`, as it does for any application. + +use compose_rust::protocol::{HostEvent, Mutation, PropertyValue, ProtocolError}; +use compose_rust::schema::{EventPayload, PropertyKind, WidgetKind, Window}; +use compose_rust::{Batch, LaunchBuilder, Runtime}; + +const COLUMN: u32 = 1; +const CLICKS: u32 = 2; +const BUTTON: u32 = 3; +const FIRST: u32 = 4; +const FIRST_ECHO: u32 = 5; +const SECOND: u32 = 6; +const SECOND_ECHO: u32 = 7; +const SIZE: u32 = 8; +const LIST: u32 = 9; +const ROW0: u32 = 100; + +const ON_CLICK: i64 = 1; +const ON_FIRST: i64 = 2; +const ON_SECOND: i64 = 3; + +struct App { + batch: Batch, + clicks: u32, + first: String, + second: String, + size: String, + dirty: bool, +} + +impl App { + fn text(&mut self, node_id: u32, text: &str) { + self.batch.write(Mutation::SetProp { + node_id, + property: PropertyKind::Text, + value: PropertyValue::String(text), + }); + } + + fn handler(&mut self, node_id: u32, property: PropertyKind, id: i64) { + self.batch.write(Mutation::SetProp { + node_id, + property, + value: PropertyValue::Integer(id), + }); + } +} + +impl Runtime for App { + fn batch(&self) -> &Batch { + &self.batch + } + + fn batch_mut(&mut self) -> &mut Batch { + &mut self.batch + } + + fn rebuild(&mut self) { + let mut window = Window::new(); + window.title = "compose-rust hand check"; + window.width = 480; + window.height = 700; + window.min_width = 320; + window.min_height = 320; + window.resizable = true; + self.batch.write(Mutation::SetWindow(window)); + for (node_id, widget) in [ + (COLUMN, WidgetKind::Column), + (CLICKS, WidgetKind::Text), + (BUTTON, WidgetKind::Button), + (FIRST, WidgetKind::TextField), + (FIRST_ECHO, WidgetKind::Text), + (SECOND, WidgetKind::TextField), + (SECOND_ECHO, WidgetKind::Text), + (SIZE, WidgetKind::Text), + (LIST, WidgetKind::ScrollColumn), + ] { + self.batch.write(Mutation::Create { node_id, widget }); + } + self.text(CLICKS, "clicks: 0"); + self.text(BUTTON, "Click me"); + self.text(FIRST, "first field: select, copy, paste, undo here"); + self.text(FIRST_ECHO, "first holds: first field: select, copy, paste, undo here"); + self.text(SECOND, "second field"); + self.text(SECOND_ECHO, "second holds: second field"); + self.text(SIZE, "window: not reported yet"); + self.handler(BUTTON, PropertyKind::OnClick, ON_CLICK); + self.handler(FIRST, PropertyKind::OnValueChange, ON_FIRST); + self.handler(SECOND, PropertyKind::OnValueChange, ON_SECOND); + for row in 0..60u32 { + self.batch.write(Mutation::Create { + node_id: ROW0 + row, + widget: WidgetKind::Text, + }); + self.text(ROW0 + row, &format!("List row {row} \u{d55c}\u{ae00} \u{c785}\u{b825}")); + self.batch.write(Mutation::Insert { + parent_id: LIST, + node_id: ROW0 + row, + index: row, + }); + } + for (index, node_id) in [CLICKS, BUTTON, FIRST, FIRST_ECHO, SECOND, SECOND_ECHO, SIZE, LIST] + .into_iter() + .enumerate() + { + self.batch.write(Mutation::Insert { + parent_id: COLUMN, + node_id, + index: index as u32, + }); + } + } + + fn render(&mut self) { + if !self.dirty { + return; + } + self.dirty = false; + let clicks = format!("clicks: {}", self.clicks); + let first = format!("first holds: {}", self.first); + let second = format!("second holds: {}", self.second); + let size = format!("window: {}", self.size); + self.text(CLICKS, &clicks); + self.text(FIRST_ECHO, &first); + self.text(SECOND_ECHO, &second); + self.text(SIZE, &size); + } + + fn handle_event(&mut self, event: &HostEvent<'_>) -> Result { + match (event.handler_id as i64, &event.payload) { + (ON_CLICK, EventPayload::Clicked) => { + self.clicks += 1; + println!("event: click {}", self.clicks); + } + (ON_FIRST, EventPayload::TextChanged(text)) => { + self.first = (*text).to_owned(); + println!("event: first {text}"); + } + (ON_SECOND, EventPayload::TextChanged(text)) => { + self.second = (*text).to_owned(); + println!("event: second {text}"); + } + ( + _, + EventPayload::WindowSizeChanged { + width_dp, + height_dp, + class, + .. + }, + ) => { + self.size = format!("{width_dp:.0} x {height_dp:.0} dp, {class:?}"); + println!("event: window {width_dp:.0}x{height_dp:.0} {class:?}"); + } + _ => return Err(ProtocolError::InvalidValueKind(0)), + } + self.dirty = true; + Ok(0) + } +} + +fn main() { + LaunchBuilder::new().launch_runtime(|| { + Box::new(App { + batch: Batch::new(), + clicks: 0, + first: "first field: select, copy, paste, undo here".to_owned(), + second: "second field".to_owned(), + size: "not reported yet".to_owned(), + dirty: false, + }) as Box + }); +} diff --git a/renderer/desktop/src/AppKitWindow.kt b/renderer/desktop/src/AppKitWindow.kt index 41545a434..f39c1901e 100644 --- a/renderer/desktop/src/AppKitWindow.kt +++ b/renderer/desktop/src/AppKitWindow.kt @@ -25,13 +25,15 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.asComposeCanvas import androidx.compose.ui.graphics.asSkiaBitmap -import dev.darkpyonix.composerust.runtime.asksForWindowMaterial import androidx.compose.ui.scene.CanvasLayersComposeScene import androidx.compose.ui.scene.ComposeScene import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import org.thisisthepy.compose.window.DockIcon +import org.thisisthepy.compose.window.SystemDarkMonitor import org.thisisthepy.compose.window.WindowEvent +import org.thisisthepy.compose.window.contentMinimum import org.thisisthepy.compose.window.graalvm.macos.AppKitUpcallSlots import org.thisisthepy.compose.window.graalvm.macos.NativeWindow import org.thisisthepy.compose.window.graalvm.macos.configureNativeWindow @@ -118,19 +120,17 @@ internal fun runAppKitWindow(autoExitMillis: Long? = null) { val host = dev.darkpyonix.composerust.runtime.ComposeRustHost(NativeHostConnection()) host.start() val asked = host.table.window - val backdrop = host.table.asksForWindowMaterial(host.roots) + val options = nativeWindowOptions(host, backdropSupported = true) + val backdrop = options.backdrop + val minimum = contentMinimum(options.minWidth, options.minHeight) configureNativeWindow( - resizable = asked?.resizable ?: true, - minWidth = asked?.minWidth?.takeIf { it > 0 } ?: 0, - minHeight = asked?.minHeight?.takeIf { it > 0 } ?: 0, - systemChrome = asked?.chrome == dev.darkpyonix.composerust.protocol.Chrome.System, + resizable = options.resizable, + minWidth = minimum?.first?.toInt() ?: 0, + minHeight = minimum?.second?.toInt() ?: 0, + systemChrome = options.systemChrome, backdrop = backdrop, ) - val window = openNativeWindow( - asked?.title?.takeIf { it.isNotEmpty() } ?: "compose-rust", - if (asked != null && asked.width > 0) asked.width else 520, - if (asked != null && asked.height > 0) asked.height else 360, - ) + val window = openNativeWindow(options.title, options.width, options.height) if (window == null) { System.err.println("compose-rust: this machine has no Metal device") return @@ -176,10 +176,20 @@ internal fun runAppKitWindow(autoExitMillis: Long? = null) { val clipboard = WindowClipboard() @Suppress("DEPRECATION") val clipboardManager = WindowClipboardManager() + // The same monitor the Kotlin/Native window uses. This one is polled, because the setting + // is read through the toolkit-free theme query rather than announced. + val dark = androidx.compose.runtime.mutableStateOf(systemIsDarkNow()) + val appearance = SystemDarkMonitor(read = ::systemIsDarkNow, onChange = { dark.value = it }) scene.setContent { androidx.compose.runtime.CompositionLocalProvider( dev.darkpyonix.composerust.runtime.LocalSystemDarkObserver provides { - rememberSystemDark().value + androidx.compose.runtime.LaunchedEffect(Unit) { + while (true) { + kotlinx.coroutines.delay(SYSTEM_DARK_POLL_MILLIS) + appearance.refresh() + } + } + dark.value }, androidx.compose.ui.platform.LocalClipboard provides clipboard, androidx.compose.ui.platform.LocalClipboardManager provides clipboardManager, @@ -194,7 +204,16 @@ internal fun runAppKitWindow(autoExitMillis: Long? = null) { installApplicationMenu(asked?.title?.takeIf { it.isNotEmpty() } ?: "compose-rust") val started = System.nanoTime() - var iconId = 0 + val dockIcon = DockIcon( + lookup = { id -> + (host.table.assets.asset(id) as? dev.darkpyonix.composerust.ui.node.Asset.Raster)?.bitmap + }, + apply = { picture -> + iconPixels(picture)?.let { (pixels, width, height) -> + setApplicationIcon(pixels, width, height) + } + }, + ) var painted = false var frame = 0 var drew = false @@ -211,19 +230,9 @@ internal fun runAppKitWindow(autoExitMillis: Long? = null) { // The scene's own work first, before anything is read from it: a list that asked // for rows on the last frame wants them in hand before this one is measured. work.runPending() - // The application's picture, once the asset it named has arrived. The id is - // known from the first batch and the bitmap a little later, so this asks each - // frame until it is there and then stops. - if (iconId == 0 && asked != null && asked.icon != 0) { - val raster = host.table.assets.asset(asked.icon) - as? dev.darkpyonix.composerust.ui.node.Asset.Raster - if (raster != null) { - iconId = asked.icon - iconPixels(raster.bitmap)?.let { (pixels, width, height) -> - setApplicationIcon(pixels, width, height) - } - } - } + // The application's picture, once the asset it named has arrived. Asked each frame + // until it is there and then not at all, by the same rule the other macOS window uses. + if (!dockIcon.applied && asked != null) dockIcon.tryApply(asked.icon) var heard = false val events = drainWindowEvents() for (event in synthetic?.due(System.nanoTime(), size) ?: emptyList()) { @@ -282,6 +291,7 @@ internal fun runAppKitWindow(autoExitMillis: Long? = null) { ) { break } + if (synthetic?.exitDue(System.nanoTime()) == true) break // Cleared before the window is given its turn, because a resize inside it // draws its own frames and the semantics below must hear of them. drew = false diff --git a/renderer/desktop/src/LatencyTrace.kt b/renderer/desktop/src/LatencyTrace.kt index 2e692e586..b09a1030d 100644 --- a/renderer/desktop/src/LatencyTrace.kt +++ b/renderer/desktop/src/LatencyTrace.kt @@ -1,13 +1,23 @@ package dev.darkpyonix.composerust.ui.platform +import java.lang.System +import kotlin.math.roundToLong +import org.jetbrains.skiko.currentSystemTheme + /** - * Timestamps along the path from a key press to the pixels, on request. + * Timestamps along the path from a key press to the pixels, on request, and the numbers the + * parity check reads. * * Off unless `DXC_REPORT_LATENCY` is set, because it prints a line per step. Each line * carries milliseconds on the monotonic clock, so two lines can be subtracted, and the * label says which step was reached: the window heard the key, the field changed, the Host * was called, it asked for a frame, the frame was rendered, the batch applied, the pixels * drawn. + * + * Shared by every window that draws a scene, so the same run on any of them ends in the same + * lines. [summary] prints them: one `parity` line per measurement, `parity + * ` with the path left to whoever reads the log, because the window does not know which + * of the two builds it is in and a log is read next to the command that made it. */ internal object LatencyTrace { val enabled: Boolean = System.getenv("DXC_REPORT_LATENCY") != null @@ -15,29 +25,84 @@ internal object LatencyTrace { fun mark(label: String) { if (enabled) { val millis = System.nanoTime() / 1_000.0 / 1_000.0 - System.err.println("compose-rust: latency t=${"%.3f".format(millis)} $label") + System.err.println("compose-rust: latency t=${fixed(millis, 3)} $label") } } - private var frames = 0 - private var totalNanos = 0L - private var worstNanos = 0L + /** What is being measured now, so a drag of the window and a quiet window are counted apart. */ + var phase: String = "idle" + + private class Frames { + var count = 0 + var total = 0L + var worst = 0L + } + + private val byPhase = LinkedHashMap() + private var inputSentAt = 0L + private var inputSamples = 0 + private var inputTotal = 0L + private var inputWorst = 0L /** Counts one drawn frame and how long it took, for [summary]. */ fun frameDrawn(nanos: Long) { if (!enabled) return - frames++ - totalNanos += nanos - if (nanos > worstNanos) worstNanos = nanos + val frames = byPhase.getOrPut(phase) { Frames() } + frames.count++ + frames.total += nanos + if (nanos > frames.worst) frames.worst = nanos + if (inputSentAt != 0L) { + // From the input being handed to the scene to the frame it changed being drawn. + val spent = System.nanoTime() - inputSentAt + inputSentAt = 0L + inputSamples++ + inputTotal += spent + if (spent > inputWorst) inputWorst = spent + } + } + + /** Notes that a typed letter was just handed to the scene. The next frame drawn answers it. */ + fun inputSent() { + if (enabled && inputSentAt == 0L) inputSentAt = System.nanoTime() } - /** One line at the end of a run: how many frames were drawn and what each cost. */ + /** The lines at the end of a run: what each frame cost, per phase, and what an input cost. */ fun summary() { - if (enabled && frames > 0) { + if (!enabled) return + System.err.println("compose-rust: parity system_theme ${currentSystemTheme.name.lowercase()}") + var frames = 0 + var total = 0L + var worst = 0L + for ((_, one) in byPhase) { + frames += one.count + total += one.total + if (one.worst > worst) worst = one.worst + } + if (frames > 0) { System.err.println( - "compose-rust: latency frames=$frames average=${"%.2f".format(totalNanos / frames / 1.0e6)}ms " + - "worst=${"%.2f".format(worstNanos / 1.0e6)}ms", + "compose-rust: latency frames=$frames average=${fixed(total / frames / 1.0e6, 2)}ms " + + "worst=${fixed(worst / 1.0e6, 2)}ms", + ) + } + for ((name, one) in byPhase) { + System.err.println( + "compose-rust: parity frame_${name}_avg_ms ${fixed(one.total / one.count / 1.0e6, 2)} " + + "frames=${one.count} worst_ms=${fixed(one.worst / 1.0e6, 2)}", + ) + } + if (inputSamples > 0) { + System.err.println( + "compose-rust: parity input_latency_avg_ms ${fixed(inputTotal / inputSamples / 1.0e6, 2)} " + + "samples=$inputSamples worst_ms=${fixed(inputWorst / 1.0e6, 2)}", ) } } } + +/** [value] with [digits] places after the point, which Kotlin/Native has no `format` for. */ +internal fun fixed(value: Double, digits: Int): String { + var factor = 1L + repeat(digits) { factor *= 10 } + val scaled = (value.coerceAtLeast(0.0) * factor).roundToLong() + return "${scaled / factor}.${(scaled % factor).toString().padStart(digits, '0')}" +} diff --git a/renderer/desktop/src/NativeClipboard.kt b/renderer/desktop/src/NativeClipboard.kt index 1eef060d0..90d9bedaf 100644 --- a/renderer/desktop/src/NativeClipboard.kt +++ b/renderer/desktop/src/NativeClipboard.kt @@ -10,6 +10,10 @@ import androidx.compose.ui.platform.asAwtTransferable import androidx.compose.ui.text.AnnotatedString import java.awt.datatransfer.DataFlavor import java.awt.datatransfer.StringSelection +import org.thisisthepy.compose.window.TextPasteboard +import org.thisisthepy.compose.window.copyText +import org.thisisthepy.compose.window.hasText +import org.thisisthepy.compose.window.pasteText import org.thisisthepy.compose.window.graalvm.macos.readClipboard import org.thisisthepy.compose.window.graalvm.macos.writeClipboard @@ -23,16 +27,21 @@ import org.thisisthepy.compose.window.graalvm.macos.writeClipboard // The entry Compose passes around is a toolkit data object on desktop. Only its text is // read and written here, which is all a text field asks for. -/** The text on the clipboard, or null where there is none. */ -private fun clipboardText(): String? = readClipboard().takeIf { it.isNotEmpty() } +/** The window's own pasteboard, reached through the two calls every window of ours shares. */ +private object WindowPasteboard : TextPasteboard { + override fun read(): String? = readClipboard() + override fun write(text: String) = writeClipboard(text) +} + +private fun clipboardText(): String? = WindowPasteboard.pasteText() @Suppress("DEPRECATION") internal class WindowClipboardManager : ClipboardManager { override fun getText(): AnnotatedString? = clipboardText()?.let(::AnnotatedString) - override fun setText(annotatedString: AnnotatedString) = writeClipboard(annotatedString.text) + override fun setText(annotatedString: AnnotatedString) = WindowPasteboard.copyText(annotatedString.text) - override fun hasText(): Boolean = clipboardText() != null + override fun hasText(): Boolean = WindowPasteboard.hasText() } internal class WindowClipboard : Clipboard { @@ -43,7 +52,7 @@ internal class WindowClipboard : Clipboard { val text = clipEntry?.asAwtTransferable?.let { runCatching { it.getTransferData(DataFlavor.stringFlavor) as? String }.getOrNull() } - writeClipboard(text.orEmpty()) + WindowPasteboard.copyText(text) } override val nativeClipboard: NativeClipboard get() = this diff --git a/renderer/desktop/src/NativeWindowOptions.kt b/renderer/desktop/src/NativeWindowOptions.kt new file mode 100644 index 000000000..9a0f46d31 --- /dev/null +++ b/renderer/desktop/src/NativeWindowOptions.kt @@ -0,0 +1,45 @@ +package dev.darkpyonix.composerust.ui.platform + +import dev.darkpyonix.composerust.protocol.Chrome +import dev.darkpyonix.composerust.runtime.ComposeRustHost +import dev.darkpyonix.composerust.runtime.asksForWindowMaterial + +// What the application asked of its window, read the same way by every window of our own: +// the native image windows and the Kotlin/Native ones. One reading, so that a title, a size or +// a smallest size means the same thing on every path. + +/** What the application asked of its window in its first batch. */ +internal data class NativeWindowOptions( + val title: String, + val width: Int, + val height: Int, + val resizable: Boolean, + val minWidth: Int, + val minHeight: Int, + val systemChrome: Boolean, + val backdrop: Boolean, +) + +/** + * Reads the window's options from the Host's first batch. + * + * [backdropSupported] says whether this platform's window can show what is behind it, + * because asking for a material the window cannot draw would leave a design drawing for a + * desktop that never shows through. + */ +internal fun nativeWindowOptions(host: ComposeRustHost, backdropSupported: Boolean): NativeWindowOptions { + val asked = host.table.window + return NativeWindowOptions( + title = asked?.title?.takeIf { it.isNotEmpty() } ?: "compose-rust", + width = if (asked != null && asked.width > 0) asked.width else DEFAULT_WIDTH, + height = if (asked != null && asked.height > 0) asked.height else DEFAULT_HEIGHT, + resizable = asked?.resizable ?: true, + minWidth = asked?.minWidth?.takeIf { it > 0 } ?: 0, + minHeight = asked?.minHeight?.takeIf { it > 0 } ?: 0, + systemChrome = asked?.chrome == Chrome.System, + backdrop = backdropSupported && host.table.asksForWindowMaterial(host.roots), + ) +} + +private const val DEFAULT_WIDTH = 520 +private const val DEFAULT_HEIGHT = 360 diff --git a/renderer/desktop/src/SyntheticInput.kt b/renderer/desktop/src/SyntheticInput.kt index 0d3c69bc2..e65291f4c 100644 --- a/renderer/desktop/src/SyntheticInput.kt +++ b/renderer/desktop/src/SyntheticInput.kt @@ -4,6 +4,7 @@ import androidx.compose.ui.unit.IntSize import org.thisisthepy.compose.window.AccessibleElement import org.thisisthepy.compose.window.ElementRole import org.thisisthepy.compose.window.WindowEvent +import java.lang.System /** * Input and resizing made up from inside the window, for measuring without a hand. @@ -11,15 +12,21 @@ import org.thisisthepy.compose.window.WindowEvent * A session with no accessibility permission cannot post a click, type a letter or drag * an edge, and the two things worth timing here are exactly those: how long a typed letter * takes to show, and what a drag does to the picture. Asked for with `DXC_SYNTH`, a - * comma separated list of `type` and `resize`; unset, nothing here runs. + * comma separated list of `type`, `resize` and `exit`; unset, nothing here runs. * * `type` presses on the first text field the window describes, then commits one letter * every 700 ms from two seconds in. `resize` takes the window from its size to 360x420 in - * 60 steps, six seconds in, from a single call that holds the thread as a drag does. + * 60 steps, six seconds in (`DXC_SYNTH_RESIZE_AT` seconds, where set), from a single call + * that holds the thread as a drag does. `exit` ends the window two seconds after the resize + * (`DXC_SYNTH_EXIT_AT` seconds in, where set), so a run measures and finishes by itself and + * the summary at the end of the loop is printed. */ internal class SyntheticInput(what: String) { private val wantsType = "type" in what.split(',') private val wantsResize = "resize" in what.split(',') + private val wantsExit = "exit" in what.split(',') + private val resizeAt = System.getenv("DXC_SYNTH_RESIZE_AT")?.toDoubleOrNull() ?: 6.0 + private val exitAt = System.getenv("DXC_SYNTH_EXIT_AT")?.toDoubleOrNull() ?: (resizeAt + 2.0) private val started = System.nanoTime() private var field: AccessibleElement? = null private var clicked = false @@ -69,11 +76,15 @@ internal class SyntheticInput(what: String) { /** True once, when it is time to take the window through its sizes. */ fun resizeDue(now: Long): Boolean { - if (!wantsResize || resized || seconds(now) < 6.0) return false + if (!wantsResize || resized || seconds(now) < resizeAt) return false resized = true return true } + /** True once the run has done what it was asked to and should close the window. */ + fun exitDue(now: Long): Boolean = + wantsExit && (!wantsResize || resized) && seconds(now) >= exitAt + /** Remembers where the field is, and says when the echo line has caught up. */ fun noteElements(elements: List) { if (field == null) field = elements.firstOrNull { it.role == ElementRole.FIELD } diff --git a/renderer/desktop/src/SystemAppearance.kt b/renderer/desktop/src/SystemAppearance.kt index c9a4b53c8..12810ab24 100644 --- a/renderer/desktop/src/SystemAppearance.kt +++ b/renderer/desktop/src/SystemAppearance.kt @@ -39,4 +39,9 @@ internal fun rememberSystemDark(): State { return state } -private const val POLL_INTERVAL_MILLIS = 1_000L +/** The system's setting, read now. */ +internal fun systemIsDarkNow(): Boolean = currentSystemTheme == SystemTheme.DARK + +internal const val SYSTEM_DARK_POLL_MILLIS = 1_000L + +private const val POLL_INTERVAL_MILLIS = SYSTEM_DARK_POLL_MILLIS diff --git a/renderer/desktop/test/ParityMeasurementTest.kt b/renderer/desktop/test/ParityMeasurementTest.kt new file mode 100644 index 000000000..ef2dd6509 --- /dev/null +++ b/renderer/desktop/test/ParityMeasurementTest.kt @@ -0,0 +1,40 @@ +package dev.darkpyonix.composerust.test + +import dev.darkpyonix.composerust.ui.platform.SyntheticInput +import dev.darkpyonix.composerust.ui.platform.fixed +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The pieces of the parity run that are plain logic: how a number is printed, which Kotlin/Native + * has no `format` for, and when the synthetic input does each thing. + */ +class ParityMeasurementTest { + @Test + fun a_number_is_printed_with_the_places_asked_for() { + assertEquals("1.23", fixed(1.2345, 2)) + assertEquals("0.050", fixed(0.05, 3)) + assertEquals("12.00", fixed(12.0, 2)) + assertEquals("0.00", fixed(0.0, 2)) + } + + @Test + fun a_number_below_zero_is_printed_as_zero() { + assertEquals("0.00", fixed(-3.0, 2)) + } + + @Test + fun the_run_exits_only_when_asked_to_and_after_the_resize() { + val quiet = SyntheticInput("type") + assertFalse(quiet.exitDue(System.nanoTime() + 60_000_000_000L), "no exit was asked for") + + val measuring = SyntheticInput("resize,exit") + val later = System.nanoTime() + 60_000_000_000L + assertFalse(measuring.exitDue(later), "the resize has not happened yet") + assertTrue(measuring.resizeDue(later)) + assertTrue(measuring.exitDue(later), "the resize is done and the time has come") + assertFalse(measuring.resizeDue(later), "a resize happens once") + } +} diff --git a/renderer/linux/src/JvmCompatShims.kt b/renderer/linux/src/JvmCompatShims.kt index e44fa740c..0f1a6ee36 100644 --- a/renderer/linux/src/JvmCompatShims.kt +++ b/renderer/linux/src/JvmCompatShims.kt @@ -2,7 +2,13 @@ package java.lang +import kotlinx.cinterop.alloc +import kotlinx.cinterop.memScoped +import kotlinx.cinterop.ptr import kotlinx.cinterop.toKString +import platform.posix.CLOCK_MONOTONIC +import platform.posix.clock_gettime +import platform.posix.timespec import platform.posix.fflush import platform.posix.fputs import platform.posix.stderr @@ -42,6 +48,13 @@ object System { fun getenv(name: String): String? = platform.posix.getenv(name)?.toKString() + /** The monotonic clock in nanoseconds, which is what the JVM's call of this name answers. */ + fun nanoTime(): Long = memScoped { + val now = alloc() + clock_gettime(CLOCK_MONOTONIC, now.ptr) + now.tv_sec * 1_000_000_000L + now.tv_nsec + } + class ErrorStream internal constructor() { fun println(line: String) { fputs(line + "\n", stderr) diff --git a/renderer/macos/src/JvmCompatShims.kt b/renderer/macos/src/JvmCompatShims.kt index a977b0592..290dd7fdd 100644 --- a/renderer/macos/src/JvmCompatShims.kt +++ b/renderer/macos/src/JvmCompatShims.kt @@ -32,6 +32,14 @@ object System { fun getenv(name: String): String? = platform.posix.getenv(name)?.toKString() + private val origin = kotlin.time.TimeSource.Monotonic.markNow() + + /** + * The monotonic clock in nanoseconds from when this was first asked, which is all the JVM's + * call of this name promises: only the difference between two answers means anything. + */ + fun nanoTime(): Long = origin.elapsedNow().inWholeNanoseconds + class ErrorStream internal constructor() { fun println(line: String) = NSLog("%s", line) } diff --git a/renderer/macos/src/MacosRenderer.kt b/renderer/macos/src/MacosRenderer.kt index 4bd10c1b0..6a6a32c15 100644 --- a/renderer/macos/src/MacosRenderer.kt +++ b/renderer/macos/src/MacosRenderer.kt @@ -11,7 +11,22 @@ import dev.darkpyonix.composerust.runtime.ComposeRustContent import dev.darkpyonix.composerust.runtime.ComposeRustHost import dev.darkpyonix.composerust.runtime.HostConnection import dev.darkpyonix.composerust.runtime.WindowCaption +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.platform.LocalClipboard +import androidx.compose.ui.platform.LocalClipboardManager +import dev.darkpyonix.composerust.runtime.LocalSystemDarkObserver +import dev.darkpyonix.composerust.ui.node.Asset +import kotlinx.coroutines.delay +import org.thisisthepy.compose.window.DockIcon +import org.thisisthepy.compose.window.SystemDarkMonitor +import org.thisisthepy.compose.window.contentMinimum +import org.thisisthepy.compose.window.macos.MacosClipboard +import org.thisisthepy.compose.window.macos.MacosClipboardManager import org.thisisthepy.compose.window.macos.MacosWindow +import org.thisisthepy.compose.window.macos.observeSystemAppearance +import org.thisisthepy.compose.window.macos.systemIsDark import platform.AppKit.NSApplication import platform.AppKit.NSApplicationActivationPolicy import platform.AppKit.NSApplicationWillTerminateNotification @@ -91,29 +106,64 @@ internal fun runRenderer(connection: () -> HostConnection): Int { // // The theme is resolved for this platform at the narrowest class: neither answer // depends on how wide the window is, and the window does not exist yet to be measured. + // Whether the system is dark, now and as it changes. Held here so the first answer is the + // real one and the window is not drawn light and corrected a moment later. + var requestFrame: () -> Unit = {} + val dark = mutableStateOf(systemIsDark()) + val appearance = SystemDarkMonitor( + read = ::systemIsDark, + requestFrame = { requestFrame() }, + onChange = { dark.value = it }, + ) + observeSystemAppearance(appearance::refresh) val dressing = resolveTheme( theme = host.table.theme, platform = HostPlatform.MacOs, - systemDark = false, + systemDark = dark.value, ).let { it.rules.caption(it, asked?.titleBar ?: TitleBar.Normal) } + val clipboard = MacosClipboard() + @Suppress("DEPRECATION") + val clipboardManager = MacosClipboardManager() val window = MacosWindow( name = asked?.title?.takeIf { it.isNotEmpty() } ?: "compose-rust", width = if (asked != null && asked.width > 0) asked.width else 520, height = if (asked != null && asked.height > 0) asked.height else 360, buttonInset = dressing.platformButtonInset, cornerRadius = dressing.windowCornerRadius, + minimumSize = contentMinimum(asked?.minWidth ?: 0, asked?.minHeight ?: 0), + clipboardHasText = { clipboard.hasText() }, + ) + requestFrame = window::requestFrame + val dockIcon = DockIcon( + lookup = { id -> (host.table.assets.asset(id) as? Asset.Raster)?.bitmap }, + apply = { picture -> picture.toNSImage()?.let { application.applicationIconImage = it } }, ) + val iconAsset = asked?.icon ?: 0 + @Suppress("DEPRECATION") window.setContent { - val strip = window.caption.value - ComposeRustContent( - host, - caption = WindowCaption( - height = strip.height, - buttonsWidth = strip.buttonsWidth, - buttonsAtStart = strip.buttonsAtStart, - insetTop = strip.insetTop, - ), - ) + CompositionLocalProvider( + LocalSystemDarkObserver provides { dark.value }, + LocalClipboard provides clipboard, + LocalClipboardManager provides clipboardManager, + ) { + // The asset arrives a little after the first batch names it, so it is looked for + // until it is there. + if (iconAsset != 0) { + LaunchedEffect(Unit) { + while (!dockIcon.tryApply(iconAsset)) delay(100) + } + } + val strip = window.caption.value + ComposeRustContent( + host, + caption = WindowCaption( + height = strip.height, + buttonsWidth = strip.buttonsWidth, + buttonsAtStart = strip.buttonsAtStart, + insetTop = strip.insetTop, + ), + ) + } } application.activateIgnoringOtherApps(true) diff --git a/renderer/macos/src/MacosWindowChrome.kt b/renderer/macos/src/MacosWindowChrome.kt new file mode 100644 index 000000000..7835e3957 --- /dev/null +++ b/renderer/macos/src/MacosWindowChrome.kt @@ -0,0 +1,24 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) + +package dev.darkpyonix.composerust.ui.platform + +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asSkiaBitmap +import kotlinx.cinterop.addressOf +import kotlinx.cinterop.usePinned +import org.jetbrains.skia.EncodedImageFormat +import org.jetbrains.skia.Image +import platform.AppKit.NSImage +import platform.Foundation.NSData +import platform.Foundation.create + +// The operating system call the Dock icon needs. When the icon is put on, and what size a window is +// given, are decided in WindowParity.kt. + +/** The picture as the system's image type, by way of the encoded form every reader of images accepts. */ +internal fun ImageBitmap.toNSImage(): NSImage? { + val bytes = Image.makeFromBitmap(asSkiaBitmap()).encodeToData(EncodedImageFormat.PNG)?.bytes + ?: return null + val data = bytes.usePinned { NSData.create(bytes = it.addressOf(0), length = bytes.size.toULong()) } + return NSImage(data = data) +} From 306bce00dafbfa15a6fb965297fef5aa23cf2c63 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Mon, 5 Oct 2026 03:40:21 +0900 Subject: [PATCH 2/3] Chore: Bring the parity run scripts over from the shared window logic branch They read the numbers LatencyTrace and the resize accounting print, so they stay with the renderer harness rather than going to the fork. Same content as on the #155 branch. --- scripts/parity/common.sh | 58 +++++++++++++++ scripts/parity/linux.sh | 151 +++++++++++++++++++++++++++++++++++++++ scripts/parity/macos.sh | 63 ++++++++++++++++ 3 files changed, 272 insertions(+) create mode 100755 scripts/parity/common.sh create mode 100755 scripts/parity/linux.sh create mode 100755 scripts/parity/macos.sh diff --git a/scripts/parity/common.sh b/scripts/parity/common.sh new file mode 100755 index 000000000..6b01c52f8 --- /dev/null +++ b/scripts/parity/common.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Sourced by scripts/parity/linux.sh and scripts/parity/macos.sh. What the two have in common is +# everything that does not touch a display server: how a window's end-of-run output becomes +# rows, and how the table is printed. A row is `nameresult`; a result that starts with FAIL +# is a failure. + +row() { printf '%s\t%s\n' "$1" "$2" >> "$table"; } + +# Rows from what the window printed on standard error ($err): the numbers LatencyTrace and the +# resize accounting leave, which every window that draws a scene prints in the same words. +report_measurements() { +value() { sed -nE "s/.*parity $1 ([^ ]+).*/\1/p" "$err" | tail -1; } +field() { sed -nE "s/.*parity $1 [^ ]+ .*$2=([^ ]+).*/\1/p" "$err" | tail -1; } +latency="$(value input_latency_avg_ms)" +resize="$(value frame_resize_avg_ms)" +idle="$(value frame_idle_avg_ms)" +row input_latency_avg_ms "${latency:-FAIL not reported}" +row frame_resize_avg_ms "${resize:-FAIL not reported}" +row frame_resize_worst_ms "$(field frame_resize_avg_ms worst_ms)" +row frame_idle_avg_ms "${idle:-FAIL not reported}" +resize_line="$(grep -E 'dxc resize: ' "$err" | tail -1)" +resize_field() { echo "$resize_line" | sed -nE "s/.*$1=([0-9]+).*/\1/p"; } +row resize_steps "$(resize_field steps || true)" +row resize_presented "$(resize_field presented || true)" +row resize_stale "$(resize_field stale || true)" +row resize_stretched "$(resize_field stretched || true)" +ratio="$(echo "$resize_line" | sed -nE 's/.*stale_ratio=([0-9.]+).*/\1/p')" +if [[ -z "$ratio" ]]; then + row resize_stale_ratio "FAIL not reported" +elif [[ "$ratio" == "0" || "$ratio" =~ ^0\.0*$ ]]; then + row resize_stale_ratio "ok $ratio" +else + row resize_stale_ratio "FAIL $ratio of the frames were drawn at a size other than the window's" +fi +row system_theme "$(sed -nE 's/.*parity system_theme ([a-z]+).*/\1/p' "$err" | tail -1)" + +} + +# Prints the table, adds it to the job summary, and fails only when PARITY_STRICT=1. +print_table() { + echo "== parity: $label" + column -t -s $'\t' "$table" 2>/dev/null || cat "$table" + if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then + { + echo "### Parity: $label" + echo + echo "| check | $label |" + echo "|---|---|" + while IFS=$'\t' read -r name result; do echo "| $name | $result |"; done < "$table" + echo + } >> "$GITHUB_STEP_SUMMARY" + fi + if grep -q $'\tFAIL' "$table"; then + echo "::warning::parity $label has failing rows" + [[ "${PARITY_STRICT:-}" == "1" ]] && exit 1 + fi + exit 0 +} diff --git a/scripts/parity/linux.sh b/scripts/parity/linux.sh new file mode 100755 index 000000000..540365999 --- /dev/null +++ b/scripts/parity/linux.sh @@ -0,0 +1,151 @@ +#!/usr/bin/env bash +# Usage: scripts/parity/linux.sh