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..9da152932 --- /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 the default; nothing needs to be set. + +## 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 2b26ae4f7..09e03d056 100644 --- a/renderer/desktop/src/AppKitWindow.kt +++ b/renderer/desktop/src/AppKitWindow.kt @@ -33,7 +33,9 @@ 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.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 @@ -114,10 +116,11 @@ internal fun runAppKitWindow(autoExitMillis: Long? = null) { val asked = host.table.window val options = nativeWindowOptions(host, backdropSupported = true) val backdrop = options.backdrop + val minimum = contentMinimum(options.minWidth, options.minHeight) configureNativeWindow( resizable = options.resizable, - minWidth = options.minWidth, - minHeight = options.minHeight, + minWidth = minimum?.first?.toInt() ?: 0, + minHeight = minimum?.second?.toInt() ?: 0, systemChrome = options.systemChrome, backdrop = backdrop, ) @@ -191,7 +194,16 @@ internal fun runAppKitWindow(autoExitMillis: Long? = null) { installApplicationMenu(options.title) 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 @@ -208,19 +220,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()) { @@ -279,6 +281,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 6bea04aa6..9a02b1feb 100644 --- a/renderer/desktop/src/NativeClipboard.kt +++ b/renderer/desktop/src/NativeClipboard.kt @@ -11,6 +11,10 @@ import androidx.compose.ui.text.AnnotatedString import java.awt.datatransfer.DataFlavor import java.awt.datatransfer.ClipboardOwner 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 import java.awt.datatransfer.Transferable @@ -36,10 +40,16 @@ import java.awt.datatransfer.Transferable * toolkit; only its text flavour is answered. */ internal class PasteboardClipboard( - private val read: () -> String, - private val write: (String) -> Unit, + readText: () -> String?, + writeText: (String) -> Unit, ) : java.awt.datatransfer.Clipboard("pasteboard") { - private fun text(): String? = read().takeIf { it.isNotEmpty() } + // The fork's pasteboard rules: an empty string is nothing to paste, null clears. + private val pasteboard = object : TextPasteboard { + override fun read(): String? = readText() + override fun write(text: String) = writeText(text) + } + + private fun text(): String? = pasteboard.pasteText() override fun getContents(requestor: Any?): Transferable? = text()?.let(::StringSelection) @@ -47,14 +57,14 @@ internal class PasteboardClipboard( val text = contents?.let { runCatching { it.getTransferData(DataFlavor.stringFlavor) as? String }.getOrNull() } - write(text.orEmpty()) + pasteboard.copyText(text) } override fun getAvailableDataFlavors(): Array = - if (text() != null) arrayOf(DataFlavor.stringFlavor) else emptyArray() + if (pasteboard.hasText()) arrayOf(DataFlavor.stringFlavor) else emptyArray() override fun isDataFlavorAvailable(flavor: DataFlavor): Boolean = - flavor == DataFlavor.stringFlavor && text() != null + flavor == DataFlavor.stringFlavor && pasteboard.hasText() override fun getData(flavor: DataFlavor): Any { val text = text() 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..35ec21728 100644 --- a/renderer/desktop/src/SystemAppearance.kt +++ b/renderer/desktop/src/SystemAppearance.kt @@ -9,6 +9,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import kotlinx.coroutines.delay import org.jetbrains.skiko.SystemTheme +import org.thisisthepy.compose.window.SystemDarkMonitor import org.jetbrains.skiko.currentSystemTheme /** @@ -28,15 +29,22 @@ import org.jetbrains.skiko.currentSystemTheme */ @Composable internal fun rememberSystemDark(): State { - val state = remember { mutableStateOf(currentSystemTheme == SystemTheme.DARK) } + val state = remember { mutableStateOf(systemIsDarkNow()) } + // The same monitor the Kotlin/Native window uses, polled here because the setting is + // read through the toolkit-free theme query rather than announced. + val monitor = remember { SystemDarkMonitor(read = ::systemIsDarkNow, onChange = { state.value = it }) } LaunchedEffect(Unit) { while (true) { delay(POLL_INTERVAL_MILLIS) - val dark = currentSystemTheme == SystemTheme.DARK - if (dark != state.value) state.value = dark + monitor.refresh() } } 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/DockIconImage.kt b/renderer/macos/src/DockIconImage.kt new file mode 100644 index 000000000..7835e3957 --- /dev/null +++ b/renderer/macos/src/DockIconImage.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) +} 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 77471bb5d..6e540591b 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 @@ -88,10 +103,24 @@ internal fun runRenderer(connection: () -> HostConnection): Int { chrome = asked?.chrome ?: Chrome.Modern, titleBar = asked?.titleBar ?: TitleBar.Normal, ) + // 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 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, + minimumSize = contentMinimum(asked?.minWidth ?: 0, asked?.minHeight ?: 0), chrome = org.thisisthepy.compose.window.macos.MacosWindowChrome( fullSizeContentView = chrome.fullSizeContentView, titlebarAppearsTransparent = chrome.titlebarAppearsTransparent, @@ -99,18 +128,38 @@ internal fun runRenderer(connection: () -> HostConnection): Int { unifiedToolbar = chrome.unifiedToolbar, ), ) + 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, - cornerRadius = strip.cornerRadius, - ), - ) + 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, + cornerRadius = strip.cornerRadius, + ), + ) + } } application.activateIgnoringOtherApps(true) 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