app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
[package]
name = "overlay-lab"
default-run = "overlay-lab"
version = "0.0.1"
edition.workspace = true
license.workspace = true
[dependencies]
rune = { workspace = true, default-features = true, features = ["keys-overlay"] }
[lints]
workspace = true
+223
View File
@@ -0,0 +1,223 @@
# Overlay lab
## Native layer-filter proof
`layer-filter-overlay` draws two static exiting-chip samples in a prewarmed native panel.
Both use a 400×40 pt capsule, nested dissolve/blur, sigma 1.5 pt and opacity .65. The upper
row is unmasked; the lower row uses `clip_rounded(20)`. Run from the repo root:
```sh
cargo build -p overlay-lab --bin layer-filter-overlay -j 2
python3 examples/overlay-lab/native/run-filter-probe.py examples/overlay-lab/artifacts/layer-filters/native-overlay
```
Run it on a GUI test Mac, never on a developer's desk display. The runner holds the host's GUI lock, waits for visible alpha and positive Metal presentation,
then captures that exact window with Cua. It closes the app's stdin to quit, ends the Cua
session and removes its diagnostic dylib. Evidence includes `native-overlay.png`, the
presentation log and Cua's valid-frame/window metadata. This proves Rune's native rendering
of a blurred, rounded capsule; the separate headless regression covers fully off-wall sources.
## Interactive lab
`cargo run -p overlay-lab` opens a transparent pill on the display under the pointer.
Only its chips intercept clicks; the background and hover label pass through. iPhone/Paste
change its contents inside a fixed maximum canvas. Area/Window/Screen open one picker per
display. Drag selects an area; Escape closes all pickers on platforms with overlay keys.
Headless stills use the same views, selected as the ordinary `lab` host:
```
cargo run -p overlay-lab -- --scene pill --snap pill.png
cargo run -p overlay-lab -- --scene expanded --snap expanded.png
cargo run -p overlay-lab -- --scene picker --size 960x600 --snap picker.png
```
Set `OVERLAY_LAB_SECONDS=15` for a bounded desktop probe with panel-ID/capture-request
logging. `OVERLAY_LAB_PICKER=1` opens the picker immediately. Run desktop probes in a GUI test
Mac's logged-in session, at normal priority, not on a developer's desk display.
`OVERLAY_LAB_UNDERLAY=1` runs a separate normal-window process that logs clicks, for
cross-process pass-through/focus checks. `OVERLAY_LAB_INCLUDE_IN_CAPTURE=1` disables the
capture request while grounding input coordinates; omit it for the exclusion check.
Linux capture exclusion is unavailable. Wayland only observes pointer movement inside its
input region, and the compositor chooses an output for UnderPointer. It cannot follow the
global pointer. OnDemand permits click-to-focus on layer-shell v4, X11 and Windows (where
`request_keys` takes the foreground only when Windows lets the process); XWayland has no key
focus. Capture requests on macOS must be supplemented with an explicit ScreenCaptureKit
window-ID filter when the OS capture path ignores NSWindow sharingType.
Wayland keeps all three levels on the compositor's overlay layer; it has no higher layer and
does not guarantee ordering among peers. Native status/status+1 levels are macOS-specific.
## Integrating an app's overlays
- The lab prewarms hidden hosts and logs `on_created` with the actual macOS CGWindowID.
`window_number()` is available after that callback and stays stable through hide/show.
Host creation happens on the event loop, not synchronously in `App::overlay`.
- Use `set_input(OverlayInput::All)` for selection and `set_input(OverlayInput::None)` for
pass-through ink/glow on the same host. Mode changes wait for an owned drag's release.
`Regions` uses `.hit()` geometry; `Legacy` restores the spec's `interactive` behavior.
- `set_follow_pointer(bool)` enables/disables following independently of placement/input.
An app can keep it disabled and supply its own `Rect` and `set_display` requests.
- `ConfiguredOverlay::poll(fn(&mut T, f64, &mut Tx) -> bool)` overrides the app's poll.
Overlays with the same state type inherit `AppSpec::poll`; different state types use the
builder. Return true when state changed, and use `Tx::wake_after` for the next deadline.
Hidden deadlines poll without drawing, matching the window host.
- `ConfiguredOverlay::compositor(...)` takes the same `Compositor<T>` as `App::compositor`.
Call `frame.draw_ui()` and then `frame.rt.elements()` to trace each rendered overlay frame,
including alpha-zero/offscreen prewarm. Runtime-only hidden updates do not call it.
`animating()` keeps visible frames running; false allows them to go idle.
- Standalone modifier transitions (for example, pressing/releasing Shift without another
key) are not delivered; the desktop and Wayland overlay callbacks have TODOs for a
shared modifier-only key event. Pressed keys
still carry modifier state, and Escape works.
- `Display::native_id()` maps to `DisplayTarget::Native`: macOS CGDirectDisplayID, Windows
full-width HMONITOR, X11 RandR CRTC, Wayland wl_output registry name. X11 output IDs can
also be targeted with `NativeDisplayId::X11Output`. `native_bounds()` is global top-left
(macOS/Wayland points, Windows/X11 pixels); `scale` converts local lengths.
- The pill uses `AboveOverlays` (macOS 27), above the picker's `AboveStatus` (26). Both use
CanJoinAllSpaces, FullScreenAuxiliary and Stationary. Wayland ordering remains compositor-owned.
- Desktop hide retains the native window, GPU surface and renderer. With `prewarm`, macOS
renders a frame into the panel's actual surface at alpha zero, then orders it out.
An unchanged show orders it back in and restores input and alpha; stale hidden changes render
before reveal, preserving elapsed motion from hidden commits (see below).
Hidden hosts have no pointer observers or draw loop. Wayland recreates its
layer after hide.
- macOS Regions mode samples native pointer position/buttons at up to 120 Hz while visible.
Monitors wake the loop; native local downs establish ownership through delivery of Up.
Input changes also wait for native ownership when `.hit()` has no Runtime press handler.
A known queued Up stays protected until dispatch. If no native Up was queued, 100 ms of
observed button-up clears ownership and forwards one recovered release to Runtime at the
first observed release position. Every Left Up acknowledges native ownership, even in None.
None/All and hidden modes stop the polling deadline. Unchanged hover does not draw.
- Release measurements on a shared M2 Max: 30 retained re-shows reached the alpha setter in
**0.369 ms median / 0.776 ms p95**. This is **not a presentation timestamp**. Alpha-only
reveal reuses a drawable; Metal does not timestamp its compositor reveal. Opt-in diagnostic
redraws reached positive `presentedTime` at **49.728 ms median / 75.907 ms p95**.
**Sub-16 ms visible presentation remains unproven.**
- Ten-second idle intervals measured **0.044% CPU / 104 interrupt wakes/s** for a visible
Regions pill with the pointer elsewhere and about **0.002% CPU** hidden. Neither interval
produced drawable callbacks. All/None stopped polling and also produced no drawable callbacks.
The idle path filters outside-canvas motion and skips unchanged hover redraws. Windows hooks
run on a separate message-loop thread; X11 observes XI2 raw motion instead of polling. The
shared Wayland socket wakes its private queue; legacy noninteractive HUDs bind no seat and
reuse their empty input region.
## Commit an entrance, then show
For a prewarmed macOS overlay, initialize the view in its entry pose A (for example, a
collapsed capsule), then commit target B. Request `show()` in that poll or a later turn:
```rust,ignore
fn poll(s: &mut Capsule, _now: f64, tx: &mut Tx) -> bool {
// Keep the app's existing wake scheduling here (Tx::wake_after, for example).
let Ok(Command::Enter) = s.events.try_recv() else { return false; };
s.expanded = true; // B: normal motion, not tx.instant().
s.overlay.as_ref().unwrap().show(); // Reveal the current pose on the way to B.
true
}
let configured = OverlaySpec::new("capsule", canvas_size, view)
.options(OverlayOptions { prewarm: true, ..Default::default() })
.poll(poll);
// Initialize expanded=false, install the returned OverlayHandle in the state,
// and let startup prewarm finish before accepting Enter commands.
```
No early show or delay is needed. Hidden transitions keep their own render-clock time:
show 16 ms after the commit and the entrance is near its start; show 2 s later and it is
already at rest. Rune catches motion up when polling or preparing the reveal, without a
hidden draw loop. Time before a commit is never charged to that new transition.
The revealed frame contains current content, geometry and live values, including instant
and text-only changes. Only motion keeps its original timing. Initial prewarm and
ordinary/unretained overlays still settle their first frame. Updates after `show()` can
also animate normally.
You can kick the first hidden poll with a queued `update()` or schedule it with
`tx.wake_after(..)`. A queued update makes the prepared frame stale, but refreshing it now
preserves the entry's elapsed motion instead of settling it.
## Native measurement harness (macOS)
Ordinary windows can opt into the same native switches without changing exhaustive
`WindowOptions` literals:
```rust
WindowSpec::from_app("capsule", app).configured_options(
WindowOptions { transparent: true, borderless: true, ..Default::default() }
.macos(MacWindowOptions::default()
.shadow(false).level(27)
.collection_behavior(1 | 16 | 64 | 256)
.exclude_from_capture(true))
)
```
The mask above is CanJoinAllSpaces | Stationary | IgnoresCycle | FullScreenAuxiliary.
These settings apply at each native creation; other platforms ignore them. They do not
change an ordinary window into a nonactivating panel. Runtime `set_always_on_top` overrides
the configured native level, including after recreation. `OVERLAY_LAB_UNDERLAY=1` plus
`OVERLAY_LAB_NATIVE_WINDOW=1` exercises native options; `OVERLAY_PROBE_NATIVE_OPTIONS=1`
logs native readbacks when the diagnostic library is loaded.
Use `configured_options` for native builders; `options(WindowOptions)` remains concrete so
existing `.options(Default::default())` calls keep compiling.
`native/` contains diagnostic tools, loaded only into the lab process. Build them, then
copy the products into a fresh temporary directory on the GUI test host:
```sh
cargo build --release -p overlay-lab -j 2
xcrun clang -dynamiclib -fobjc-arc -framework AppKit -framework QuartzCore -framework Metal \
examples/overlay-lab/native/presentation-probe.m -o presentation-probe.dylib
xcrun swiftc -parse-as-library examples/overlay-lab/native/capture-probe.swift -o capture-probe
```
Put `overlay-lab`, `presentation-probe.dylib` and `capture-probe` in that directory. Hold
the host's GUI lock file (`fcntl.LOCK_EX`), then run
`python3 examples/overlay-lab/native/run-native-probe.py <directory>` at normal priority.
`OVERLAY_LAB_CONTROL` names a unique Unix socket and starts the pill prewarmed but hidden.
Newline-terminated `show`, `hide`, `status`, `none`, `all`, `regions`, and `quit` commands are accepted. The driver
records the request's `CACurrentMediaTime` immediately before `handle.show()` and the
drawable's actual `presentedTime`, not queue submission or callback arrival time. Zero
timestamps are reported separately, with a two-second deadline for a positive timestamp.
It checks WindowServer identity before 31 shows (initial plus 30 re-shows). Set
`OVERLAY_PROBE_RETAINED=1` for alpha-zero hosts; the old order-out baseline omits it.
The retained run fails before showing if the pill has no alpha-zero `nextDrawable`
acquisition before `on_created`. This catches regressions in the wgpu occlusion override.
`python3 native/prewarm_trace.py <presentation.log>` checks every created overlay in a saved
trace; keep `prewarm_trace.py` beside the runner when copying the harness to another host.
`OVERLAY_PROBE_REDRAW=1` adds diagnostic redraws until a positive timestamp. Report this
endpoint separately from the alpha-only reveal; it includes work absent in normal showing.
`results.json` and `presentation.log` are the evidence; the lab has a bounded shutdown timer.
`run-idle-probe.py` samples process CPU and interrupt wake counters over ten-second intervals,
without redraw assistance, and counts drawable callbacks. `--modes` measures All/None/Regions.
`run-pill-probe.py <installed-binary> <directory>` runs 30 `lab pill tap-then-screen`
cycles of an installed reference app using the same diagnostic library without redraw
assistance. It measures native already-visible `orderFrontRegardless` entry to positive
presentation, not the beginning of the app's request.
`run-input-probe.py` drives an independent underlay and twenty raw-motion enter/click/leave/click
cycles. Build `mouse-path.swift`, copy it to a stable path and ad-hoc sign once before the
user grants Accessibility. Do not replace the granted binary. Point
`OVERLAY_MOUSE_HELPER` at it; the runner's default path is machine-specific. Set
`RUNE_OVERLAY_TRACE_INPUT=1` to log regions, monitor callbacks, polls, and native input flips.
`run-cua-input-probe.py <directory> prepare` drives the same checks through CuaDriver.
It holds the GUI lock file, starts two disposable lab processes, captures `grounding.png`,
then waits up to two minutes on `cua-control.sock`. After inspecting that screenshot and
its backing scale, send JSON `{"run":true,"scale":2}` over the socket. It verifies twenty
enter/click/leave/click cycles, hide-mid-press recovery, and `hit-only` → None during an
owned press; `hit-only` and `chips` control commands switch the fixture. The final None
assertion checks underlay delivery because None stops polling. `cycles:0,hide_case:false`
runs only the handlerless case. Preserve `actions.jsonl`, `steps.jsonl`, and both process
logs.
The capture helper uses ScreenCaptureKit with and without the exact CGWindowID in
`excludingWindows`. It checks permission first and exits 77 if unavailable. The probe does not change TCC;
an app verifies its own CGWindowID exclusion filter with its Screen Recording permission.
For click-through checks, use an independent underlay process. A coordinate-only synthetic
click does not establish that native mouse-move observation ran first. Check actual pointer
movement and both directions across the region boundary, and verify underlay/overlay logs.
@@ -0,0 +1,3 @@
*.json
*.log
*.dylib
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

@@ -0,0 +1,54 @@
import AppKit
import ScreenCaptureKit
@main struct CaptureProbe {
static func main() async throws {
let args = CommandLine.arguments
let id = CGWindowID(args[1])!
if args.count > 2 && args[2] == "--geometry" {
let windows = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[String: Any]] ?? []
guard let match = windows.first(where: { ($0[kCGWindowNumber as String] as? UInt32) == id }),
let bounds = match[kCGWindowBounds as String] else { exit(1) }
let data = try JSONSerialization.data(withJSONObject: bounds, options: [.sortedKeys])
print(String(decoding: data, as: UTF8.self))
return
}
if args.count == 2 || args[2] == "--hidden" {
let started = ProcessInfo.processInfo.systemUptime
var match: [String: Any]?
// AppKit orderOut returns before WindowServer publishes its window list.
// Bound this readiness check; it is outside the show/presentation interval.
repeat {
let windows = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[String: Any]] ?? []
match = windows.first { ($0[kCGWindowNumber as String] as? UInt32) == id }
if args.count == 2 || (match?[kCGWindowIsOnscreen as String] as? Bool) != true { break }
try await Task.sleep(for: .milliseconds(10))
} while ProcessInfo.processInfo.systemUptime - started < 1
print("window=\(id) exists=\(match != nil) onScreen=\(match?[kCGWindowIsOnscreen as String] ?? false)")
return
}
guard CGPreflightScreenCaptureAccess() else {
print("BLOCKED: ScreenCaptureKit probe lacks screen-recording permission; no permission requested")
Foundation.exit(77)
}
let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: false)
guard let window = content.windows.first(where: { $0.windowID == id }),
let display = content.displays.first(where: { $0.frame.intersects(window.frame) }) else {
fatalError("window not found: \(id)")
}
print("window=\(id) frame=\(window.frame) onScreen=\(window.isOnScreen) pid=\(window.owningApplication?.processID ?? 0)")
let config = SCStreamConfiguration()
config.sourceRect = window.frame.offsetBy(dx: -display.frame.minX, dy: -display.frame.minY)
config.width = Int(window.frame.width * 2)
config.height = Int(window.frame.height * 2)
config.showsCursor = false
for exclude in [false, true] {
let filter = SCContentFilter(display: display, excludingWindows: exclude ? [window] : [])
let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config)
let bitmap = NSBitmapImageRep(cgImage: image)
let suffix = exclude ? "excluded" : "included"
try bitmap.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: "\(args[2])-\(suffix).png"))
print("capture=\(suffix) width=\(image.width) height=\(image.height)")
}
}
}
@@ -0,0 +1,29 @@
// Native input probe. Explicitly posts motion events; never substitutes cursor warps.
import ApplicationServices
import Foundation
let args = CommandLine.arguments
guard CGPreflightPostEventAccess() else {
print("BLOCKED: input helper lacks event-posting permission; no permission requested")
exit(77)
}
let source = CGEventSource(stateID: .hidSystemState)!
source.localEventsSuppressionInterval = 0
let from = CGPoint(x: Double(args[1])!, y: Double(args[2])!)
let to = CGPoint(x: Double(args[3])!, y: Double(args[4])!)
let steps = Int(args[5])!
for step in 0...steps {
let t = Double(step) / Double(max(1, steps))
let p = CGPoint(x: from.x + (to.x-from.x)*t, y: from.y + (to.y-from.y)*t)
let event = CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: p, mouseButton: .left)!
event.post(tap: .cghidEventTap)
// Fixed input cadence, not a readiness poll. Exercise multiple native callbacks.
Thread.sleep(forTimeInterval: 0.008)
}
if args.count > 6 && args[6] == "click" {
for kind in [CGEventType.leftMouseDown, .leftMouseUp] {
CGEvent(mouseEventSource: source, mouseType: kind, mouseCursorPosition: to, mouseButton: .left)!.post(tap: .cghidEventTap)
Thread.sleep(forTimeInterval: 0.008)
}
}
print("posted moves=\(steps+1) from=\(from) to=\(to) click=\(args.count > 6)")
@@ -0,0 +1,79 @@
// Diagnostic injection into overlay-lab only. No cross-process hooks are installed.
// Correlate Metal's actual presentedTime with the lab's CACurrentMediaTime show requests.
#import <AppKit/AppKit.h>
#import <QuartzCore/CAMetalLayer.h>
#import <Metal/Metal.h>
#import <objc/runtime.h>
static id<CAMetalDrawable> (*originalNext)(id, SEL);
static void (*originalOut)(id, SEL, id);
static void (*originalAlpha)(id, SEL, CGFloat);
static void (*originalFront)(id, SEL);
static void orderFront(NSWindow *window, SEL selector) {
double requested = CACurrentMediaTime();
BOOL wasVisible = window.visible;
originalFront(window, selector);
fprintf(stderr, "probe front window=%ld requested=%.9f was_visible=%d panel=%d level=%ld view=%s\n",
(long)window.windowNumber, requested, wasVisible, [window isKindOfClass:NSPanel.class],
(long)window.level, class_getName(window.contentView.class));
}
static void setAlpha(NSWindow *window, SEL selector, CGFloat alpha) {
originalAlpha(window, selector, alpha);
if (![window isKindOfClass:NSPanel.class]) return;
fprintf(stderr, "probe alpha window=%ld alpha=%.1f time=%.9f\n", (long)window.windowNumber, alpha, CACurrentMediaTime());
// Opt-in measurement assistance, not Rune behavior. Alpha-only reveal reuses a
// previously submitted drawable; Metal cannot timestamp its compositor reveal.
if (alpha == 1 && getenv("OVERLAY_PROBE_REDRAW")) {
double deadline = CACurrentMediaTime() + 2;
objc_setAssociatedObject(window, @selector(setAlphaValue:), @(deadline), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
window.contentView.needsDisplay = YES;
}
}
static void orderOut(NSWindow *window, SEL selector, id sender) {
originalOut(window, selector, sender);
if ([window isKindOfClass:NSPanel.class])
fprintf(stderr, "probe hidden window=%ld visible=%d time=%.9f\n", (long)window.windowNumber, window.visible, CACurrentMediaTime());
}
static id<CAMetalDrawable> nextDrawable(id layer, SEL selector) {
id<CAMetalDrawable> drawable = originalNext(layer, selector);
if (!drawable) return drawable;
NSInteger windowID = 0;
for (NSWindow *window in NSApp.windows) {
CALayer *root = window.contentView.layer;
for (CALayer *p = layer; p; p = p.superlayer) {
// Rune forwards source-window readbacks to the adopted content view. Its
// real NSView.window identifies the panel rather than the hidden source.
if (p == root) { windowID = window.contentView.window.windowNumber; break; }
}
if (windowID) break;
}
double acquired = CACurrentMediaTime();
__weak NSWindow *owner;
for (NSWindow *window in NSApp.windows)
if (window.windowNumber == windowID) { owner = window; break; }
fprintf(stderr, "probe acquired window=%ld alpha=%.1f time=%.9f\n", (long)windowID, owner.alphaValue, acquired);
if (getenv("OVERLAY_PROBE_NATIVE_OPTIONS"))
fprintf(stderr, "probe native window=%ld shadow=%d level=%ld collection=%lu sharing=%lu\n",
(long)owner.windowNumber, owner.hasShadow, (long)owner.level,
(unsigned long)owner.collectionBehavior, (unsigned long)owner.sharingType);
[drawable addPresentedHandler:^(id<MTLDrawable> d) {
fprintf(stderr, "probe presented window=%ld acquired=%.9f presented=%.9f callback=%.9f\n",
(long)windowID, acquired, d.presentedTime, CACurrentMediaTime());
if (d.presentedTime == 0 && getenv("OVERLAY_PROBE_REDRAW")) dispatch_async(dispatch_get_main_queue(), ^{
NSWindow *window = owner;
NSNumber *deadline = objc_getAssociatedObject(window, @selector(setAlphaValue:));
if (window.alphaValue == 1 && deadline.doubleValue > CACurrentMediaTime()) window.contentView.needsDisplay = YES;
});
}];
return drawable;
}
__attribute__((constructor)) static void install(void) {
Method method = class_getInstanceMethod(CAMetalLayer.class, @selector(nextDrawable));
originalNext = (void *)method_setImplementation(method, (IMP)nextDrawable);
Method out = class_getInstanceMethod(NSWindow.class, @selector(orderOut:));
originalOut = (void *)method_setImplementation(out, (IMP)orderOut);
Method alpha = class_getInstanceMethod(NSWindow.class, @selector(setAlphaValue:));
originalAlpha = (void *)method_setImplementation(alpha, (IMP)setAlpha);
Method front = class_getInstanceMethod(NSWindow.class, @selector(orderFrontRegardless));
originalFront = (void *)method_setImplementation(front, (IMP)orderFront);
}
@@ -0,0 +1,28 @@
"""Assert native alpha-zero drawable acquisition before an overlay's creation callback."""
import re
def assert_prewarmed(lines, window):
acquired = False
for line in lines:
match = re.match(r'probe acquired window=(\d+) alpha=([\d.]+) time=', line)
if match and int(match[1]) == window:
acquired |= float(match[2]) == 0.0
if ' created OverlayCreated ' in line and f'window_number: Some({window})' in line:
if not acquired:
raise AssertionError(f'window {window}: no alpha-zero drawable acquired before on_created; check prewarm/occlusion')
return
raise AssertionError(f'window {window}: missing on_created marker')
if __name__ == '__main__':
import pathlib
import sys
lines = pathlib.Path(sys.argv[1]).read_text().splitlines()
windows = [int(match[1]) for line in lines if ' created OverlayCreated ' in line
and (match := re.search(r'window_number: Some\((\d+)\)', line))]
if not windows:
raise AssertionError('no created overlays in trace')
for window in windows:
assert_prewarmed(lines, window)
print(f'Alpha-zero prewarm verified before on_created for {len(windows)} overlays: {windows}')
@@ -0,0 +1,233 @@
"""Authorized Pro desktop proof via CuaDriver; holds the GUI lock for the whole run.
prepare starts a bounded worker and returns after its grounding screenshot. Read that
image, then send {"run":true,"scale":2} to cua-control.sock to run the proof. The
worker streams its result on that socket and exits, closing its own apps/session.
"""
import ast, fcntl, json, os, pathlib, re, selectors, socket, subprocess, sys, threading, time
root = pathlib.Path(sys.argv[1]).resolve()
driver = str(pathlib.Path.home()/'.local/bin/cua-driver')
session = 'rune-overlay-boundary'
target = {'kind': 'desktop', 'display_id': 'primary'}
if len(sys.argv) > 2 and sys.argv[2] == 'prepare':
with (root/'worker.log').open('w') as log:
worker = subprocess.Popen([sys.executable, '-u', __file__, str(root)],
stdout=subprocess.PIPE, stderr=log, start_new_session=True)
ready = selectors.DefaultSelector()
ready.register(worker.stdout, selectors.EVENT_READ)
if not ready.select(90): raise TimeoutError('worker did not prepare in 90 seconds')
line = worker.stdout.readline().decode()
if not line: raise RuntimeError('worker exited; inspect worker.log')
print(line, end='')
sys.exit(0)
lock = open('/tmp/pro-gui.lock', 'a')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if subprocess.run(['pgrep', '-f', '[r]une-smoke/ci/Hex.app'], capture_output=True).returncode == 0:
raise RuntimeError('competing Hex smoke app')
condition = threading.Condition()
state = {'clicks': 0, 'chips': 0, 'window': None, 'trace': None, 'seq': 0, 'regions': []}
actions = (root/'actions.jsonl').open('w')
steps = (root/'steps.jsonl').open('w')
apps = []
def record(file, value):
file.write(json.dumps(value)+'\n'); file.flush()
def cua(tool, **args):
payload = dict(args, session=session)
run = subprocess.run([driver, tool, json.dumps(payload)], capture_output=True, text=True, timeout=35)
record(actions, {'tool': tool, 'args': payload, 'stdout': run.stdout, 'stderr': run.stderr, 'exit': run.returncode})
if run.returncode: raise RuntimeError(f'Cua {tool}: {run.stdout} {run.stderr}')
result = json.loads(run.stdout)
if result.get('isError') or result.get('error'): raise RuntimeError(f'Cua {tool}: {result}')
return result
def read_logs(name, app):
with (root/f'input-{name}.log').open('w') as log:
for line in app.stdout:
log.write(line); log.flush()
with condition:
if name == 'underlay' and 'underlay click ' in line:
state['clicks'] = int(line.rsplit(' ', 1)[1])
if name == 'overlay' and 'overlay-lab chip iPhone' in line: state['chips'] += 1
if name == 'overlay' and 'pill created' in line:
state['window'] = int(re.search(r'window_number: Some\((\d+)\)', line)[1])
if name == 'overlay' and line.startswith('overlay-input '):
window = int(re.search(r'window=(\d+)', line)[1])
if window == state['window']:
state['seq'] += 1
state['regions'] = ast.literal_eval(line.split('regions=', 1)[1])
state['trace'] = line.strip()
condition.notify_all()
def wait(test, seconds=8):
with condition:
if not condition.wait_for(lambda: test(state), timeout=seconds):
raise TimeoutError(f'predicate timed out: {state}')
return dict(state)
def snapshot(label, fresh=True, ignore=None):
with condition: seq = state['seq']
# Region publication logs precede observe() in the same frame. Wait for a
# subsequent poll readback, not that intentionally pre-update diagnostic row.
value = wait(lambda s: s['seq'] > seq and 'source=poll ' in (s['trace'] or '')
and (ignore is None or f'ignore={str(ignore).lower()}' in s['trace'])) if fresh else dict(state)
record(steps, {'step': label, **value})
return value
def command(value):
with socket.socket(socket.AF_UNIX) as client:
client.settimeout(8); client.connect(str(root/'input.sock'))
client.sendall((value+'\n').encode())
result = client.recv(4096).decode()
record(actions, {'command': value, 'result': result})
def launch(name, **extra):
env = dict(os.environ, OVERLAY_LAB_SECONDS='600', RUNE_OVERLAY_TRACE_INPUT='1',
OVERLAY_LAB_INCLUDE_IN_CAPTURE='1', **extra)
app = subprocess.Popen([str(root/'overlay-lab')], env=env, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, bufsize=1)
apps.append(app)
threading.Thread(target=read_logs, args=(name, app), daemon=True).start()
return app
def move(point):
cua('move_cursor', target=target, x=point[0]*scale, y=point[1]*scale)
def click(point):
cua('click', target=target, x=point[0]*scale, y=point[1]*scale)
def center(region):
return (origin[0]+(region[0]+region[2])/2, origin[1]+(region[1]+region[3])/2)
def drag_while(start, end, action):
result = []
def run():
try:
result.append(cua('drag', target=target, from_x=start[0]*scale, from_y=start[1]*scale,
to_x=end[0]*scale, to_y=end[1]*scale, duration_ms=2500, steps=100))
except Exception as error: result.append(error)
thread = threading.Thread(target=run)
thread.start()
try:
wait(lambda s: s['trace'] and 'captured=true' in s['trace'] and 'buttons=1 ' in s['trace'])
snapshot('held-before-'+action)
command(action)
if action == 'none':
current = snapshot('held-after-none')
assert 'input=Regions ' in current['trace'] and 'captured=true' in current['trace']
finally:
thread.join(timeout=35)
if thread.is_alive(): raise TimeoutError('Cua drag did not return')
if not result or isinstance(result[0], Exception): raise RuntimeError(str(result))
connection = None
try:
cua('start_session')
launch('underlay', OVERLAY_LAB_UNDERLAY='1')
overlay = launch('overlay', OVERLAY_LAB_CONTROL=str(root/'input.sock'))
wait(lambda s: s['window'] is not None)
command('show')
wait(lambda s: len(s['regions']) >= 4)
geometry = json.loads(subprocess.check_output([str(root/'capture-probe'), str(state['window']), '--geometry'], text=True))
origin = (geometry['X'], geometry['Y'])
desktop = cua('get_desktop_state', screenshot_out_file=str(root/'grounding.png'))
(root/'grounding.json').write_text(json.dumps(desktop, indent=2))
server = socket.socket(socket.AF_UNIX)
server.bind(str(root/'cua-control.sock')); server.listen(1); server.settimeout(120)
print(json.dumps({'ready': True, 'worker': os.getpid(), 'window': state['window'], 'geometry': geometry,
'screenshot': str(root/'grounding.png')}), flush=True)
connection, _ = server.accept(); connection.settimeout(400)
request = json.loads(connection.recv(4096))
if not request.get('run'): raise RuntimeError('run not authorized')
scale = request['scale']
cycles = request.get('cycles', 20)
hide_case = request.get('hide_case', True)
outside = (origin[0]+20, origin[1]+80)
move(outside)
initial = snapshot('initial-outside', ignore=True)
assert 'ignore=true' in initial['trace']
for trial in range(cycles):
inside = center(state['regions'][3])
move(inside)
entered = snapshot(f'{trial+1}:enter', ignore=False)
assert 'ignore=false' in entered['trace'], entered
click(inside)
wait(lambda s: s['chips'] == trial+1 or s['clicks'] > trial)
pressed = snapshot(f'{trial+1}:inside-click')
assert pressed['chips'] == trial+1 and pressed['clicks'] == trial, pressed
move(outside)
left = snapshot(f'{trial+1}:leave', ignore=True)
assert 'ignore=true' in left['trace'], left
click(outside)
wait(lambda s: s['clicks'] == trial+1)
passed = snapshot(f'{trial+1}:outside-click')
assert passed['chips'] == trial+1 and passed['clicks'] == trial+1, passed
(root/'boundary-results.json').write_text(json.dumps({'cycles': cycles, 'overlay_clicks': state['chips'],
'underlay_clicks': state['clicks'], 'window': state['window']}, indent=2))
# Cancel an owned press by hiding mid-drag, then prove both routes recover.
if hide_case:
inside = center(state['regions'][3])
move(inside)
drag_while(inside, outside, 'hide')
command('show')
move(outside); click(outside)
wait(lambda s: s['clicks'] == cycles+1)
snapshot('hide-mid-press-outside-recovered')
inside = center(state['regions'][3])
move(inside); click(inside)
wait(lambda s: s['chips'] == cycles+1)
snapshot('hide-mid-press-inside-recovered')
count = cycles + int(hide_case)
# No Runtime press/drag handler: native capture alone must defer None.
command('hit-only')
wait(lambda s: len(s['regions']) == 1)
hit = center(state['regions'][0])
move(hit)
click(hit)
bare = snapshot('hit-only-click')
assert bare['clicks'] == count and bare['chips'] == count, bare
drag_while(hit, outside, 'none')
# None stops polling. The final release row can precede applying the deferred
# mode, so prove None by actual cross-process delivery instead of another tick.
wait(lambda s: 'captured=false' in (s['trace'] or ''))
snapshot('hit-only-none-after-up', fresh=False)
move(hit); click(hit)
wait(lambda s: s['clicks'] == count+1)
record(steps, {'step': 'hit-only-through-after-none', **state})
command('regions')
move(outside)
snapshot('regions-restored')
cua('get_desktop_state', screenshot_out_file=str(root/'final.png'))
result = {'cycles': cycles, 'overlay_clicks': cycles, 'underlay_clicks': cycles,
'hide_mid_press': 'passed' if hide_case else 'not run', 'handlerless_hit_none_mid_press': 'passed',
'final_overlay_clicks': state['chips'], 'final_underlay_clicks': state['clicks'],
'window': state['window'], 'input_driver': 'CuaDriver desktop global input',
'lost_up_limit': 'hide-mid-press cancellation; 100ms recovery remains unit-covered'}
(root/'results.json').write_text(json.dumps(result, indent=2))
connection.sendall((json.dumps(result)+'\n').encode())
except Exception as error:
(root/'failure.txt').write_text(repr(error))
try: cua('get_desktop_state', screenshot_out_file=str(root/'failure.png'))
except Exception: pass
if connection:
connection.sendall((json.dumps({'error': repr(error)})+'\n').encode())
raise
finally:
try: command('quit')
except OSError: pass
for app in apps:
if app.poll() is None:
# These are the two disposable probe processes created above, not user apps.
app.terminate()
app.wait(timeout=15)
try: cua('end_session')
except Exception as error: record(actions, {'cleanup_error': repr(error)})
for name in ['input.sock', 'cua-control.sock']: (root/name).unlink(missing_ok=True)
actions.close(); steps.close()
lock.close()
(root/'finished').write_text('apps exited; Cua session ended; GUI lock released\n')
if connection: connection.close()
@@ -0,0 +1,89 @@
"""One native capsule still on the build Mac, while holding its shared GUI lock. Run on a build worker."""
import fcntl
import json
import os
import pathlib
import re
import selectors
import subprocess
import sys
import time
root = pathlib.Path(sys.argv[1]).resolve()
root.mkdir(parents=True, exist_ok=True)
lock = open('/tmp/pro-gui.lock', 'a')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
driver = pathlib.Path.home() / '.local/bin/cua-driver'
session = 'rune-layer-filter-overlay'
binary = pathlib.Path(os.environ['CARGO_TARGET_DIR']) / 'debug/layer-filter-overlay'
probe = root / 'presentation-probe.dylib'
subprocess.run(['xcrun', 'clang', '-dynamiclib', '-fobjc-arc', '-framework', 'AppKit',
'-framework', 'QuartzCore', '-framework', 'Metal',
'examples/overlay-lab/native/presentation-probe.m', '-o', str(probe)], check=True)
def cua(tool, **args):
run = subprocess.run([str(driver), tool, json.dumps(dict(args, session=session))],
capture_output=True, text=True, timeout=45)
(root / (tool + '.json')).write_text(run.stdout)
if run.returncode:
raise RuntimeError(run.stdout + run.stderr)
value = json.loads(run.stdout)
if value.get('isError') or value.get('error'):
raise RuntimeError(run.stdout)
return value
app = None
try:
cua('start_session')
app = subprocess.Popen([str(binary)], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, env=dict(os.environ, DYLD_INSERT_LIBRARIES=str(probe)))
ready = selectors.DefaultSelector()
ready.register(app.stdout, selectors.EVENT_READ)
deadline = time.monotonic() + 60
pending = b''
lines = []
window = None
shown = set()
presented = set()
while time.monotonic() < deadline:
if not ready.select(max(0, deadline - time.monotonic())):
break
chunk = os.read(app.stdout.fileno(), 65536)
if not chunk:
raise RuntimeError('overlay exited before presentation')
pending += chunk
while b'\n' in pending:
raw, pending = pending.split(b'\n', 1)
line = raw.decode(errors='replace')
lines.append(line)
if 'filter-overlay created' in line:
window = int(re.search(r'window_number: Some\((\d+)\)', line)[1])
match = re.search(r'probe alpha window=(\d+) alpha=1\.0 ', line)
if match:
shown.add(int(match[1]))
match = re.search(r'probe presented window=(\d+) .*presented=([\d.]+)', line)
if match and float(match[2]) > 0:
presented.add(int(match[1]))
if window in shown and window in presented:
break
(root / 'presentation.log').write_text('\n'.join(lines) + '\n')
if window not in shown or window not in presented:
raise TimeoutError('no visible, positively presented overlay drawable')
cua('get_window_state', pid=app.pid, window_id=window, include_accessibility_tree=False,
max_image_dimension=0, screenshot_out_file=str(root / 'native-overlay.png'))
if not (root / 'native-overlay.png').is_file():
raise RuntimeError('Cua did not capture the requested window')
result = dict(pid=app.pid, window=window, positive_presentation=True,
screenshot='native-overlay.png', fixture='400x40pt; sigma 1.5pt; opacity .65')
(root / 'result.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result), flush=True)
finally:
if app is not None:
app.stdin.close()
try:
app.wait(timeout=15)
except subprocess.TimeoutExpired:
app.terminate()
app.wait(timeout=10)
cua('end_session')
probe.unlink(missing_ok=True)
@@ -0,0 +1,74 @@
"""Measure normal-priority idle costs on an authorized Mac; caller holds its GUI lock."""
import ctypes, json, os, pathlib, selectors, socket, subprocess, sys, time
root = pathlib.Path(sys.argv[1])
control = root/'idle.sock'
env = dict(os.environ, OVERLAY_LAB_SECONDS='70', OVERLAY_LAB_CONTROL=str(control),
DYLD_INSERT_LIBRARIES=str(root/'presentation-probe.dylib'))
env.pop('OVERLAY_PROBE_REDRAW', None)
env.pop('RUNE_OVERLAY_TRACE_INPUT', None)
log = (root/'idle.log').open('w')
process = subprocess.Popen([str(root/'overlay-lab')], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
selector = selectors.DefaultSelector()
selector.register(process.stdout, selectors.EVENT_READ)
buffer, frames = b'', 0
def drain(seconds):
global buffer, frames
deadline = time.monotonic()+seconds
while True:
while b'\n' in buffer:
raw, buffer = buffer.split(b'\n',1)
line = raw.decode(errors='replace'); log.write(line+'\n'); log.flush()
if line.startswith('probe presented '): frames += 1
if seconds == 0 and 'pill created' in line: return
remaining = 10 if seconds == 0 else deadline-time.monotonic()
if remaining <= 0: return
if not selector.select(remaining):
if seconds == 0: raise TimeoutError('no created callback')
return
chunk = os.read(process.stdout.fileno(),65536)
if not chunk: raise RuntimeError('app exited')
buffer += chunk
class Usage(ctypes.Structure):
_fields_ = [('uuid',ctypes.c_uint8*16)] + [(name,ctypes.c_uint64) for name in
['user','system','package_wakes','interrupt_wakes','pageins','wired','resident','footprint','start','exit']]
lib = ctypes.CDLL('/usr/lib/libproc.dylib')
def usage():
value = Usage()
if lib.proc_pid_rusage(process.pid,0,ctypes.byref(value)) != 0: raise OSError('proc_pid_rusage failed')
return value
def command(value):
with socket.socket(socket.AF_UNIX) as client:
client.settimeout(5); client.connect(str(control)); client.sendall((value+'\n').encode())
return client.recv(4096).decode()
results = []
try:
drain(0)
phases = [('hidden','status'),('visible','show'),('hidden-again','hide')]
if '--modes' in sys.argv:
command('show')
phases = [('all','all'),('none','none'),('regions','regions')]
for phase, action in phases:
command(action)
# Exclude transition work; drain logs continuously during the measurement.
drain(1)
before, count, started = usage(), frames, time.monotonic()
drain(10)
elapsed, after = time.monotonic()-started, usage()
result = dict(phase=phase, seconds=elapsed,
cpu_percent=(after.user+after.system-before.user-before.system)/1e9/elapsed*100,
interrupt_wakes_per_second=(after.interrupt_wakes-before.interrupt_wakes)/elapsed,
package_wakes_per_second=(after.package_wakes-before.package_wakes)/elapsed,
drawable_callbacks=frames-count)
results.append(result); print(json.dumps(result),flush=True)
(root/'idle-results.json').write_text(json.dumps(results,indent=2))
finally:
try: command('quit')
except OSError: pass
process.wait(timeout=75)
log.close(); control.unlink(missing_ok=True)
@@ -0,0 +1,82 @@
"""Explicitly authorized native input test; caller holds the host GUI lock."""
import ast, json, os, pathlib, re, selectors, socket, subprocess, sys, time
root = pathlib.Path(sys.argv[1])
control = root / 'input.sock'
env = dict(os.environ, OVERLAY_LAB_SECONDS='90', RUNE_OVERLAY_TRACE_INPUT='1',
OVERLAY_LAB_INCLUDE_IN_CAPTURE='1')
underlay = subprocess.Popen([str(root/'overlay-lab')], env=dict(env, OVERLAY_LAB_UNDERLAY='1'),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
overlay = subprocess.Popen([str(root/'overlay-lab')], env=dict(env, OVERLAY_LAB_CONTROL=str(control)),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
selector = selectors.DefaultSelector()
for name, process in [('underlay', underlay), ('overlay', overlay)]:
selector.register(process.stdout, selectors.EVENT_READ, name)
buffers = {'underlay': b'', 'overlay': b''}
logs = {name: (root/f'input-{name}.log').open('w') for name in buffers}
regions, clicks, chips, window = [], 0, 0, None
snapshots = {}
def pump(until, seconds=5):
global regions, clicks, chips, window
deadline = time.monotonic() + seconds
while not until():
if time.monotonic() >= deadline: raise TimeoutError('input assertion timed out')
for key, _ in selector.select(max(0, deadline-time.monotonic())):
name = key.data
chunk = os.read(key.fileobj.fileno(), 65536)
if not chunk: raise RuntimeError(f'{name} exited')
buffers[name] += chunk
while b'\n' in buffers[name]:
line, buffers[name] = buffers[name].split(b'\n', 1)
line = line.decode(errors='replace')
logs[name].write(line+'\n'); logs[name].flush()
if name == 'underlay' and 'underlay click ' in line:
clicks = int(line.rsplit(' ', 1)[1])
if name == 'overlay' and 'overlay-lab chip iPhone' in line: chips += 1
if name == 'overlay' and 'pill created' in line:
window = int(re.search(r'window_number: Some\((\d+)\)', line)[1])
if line.startswith('overlay-input ') and 'regions=' in line:
observed = int(re.search(r'window=(\d+)', line)[1])
snapshots[observed] = ast.literal_eval(line.split('regions=', 1)[1])
regions = snapshots.get(window, [])
def command(value):
with socket.socket(socket.AF_UNIX) as client:
client.settimeout(5); client.connect(str(control)); client.sendall((value+'\n').encode())
return client.recv(4096).decode()
def move(start, finish, click=False):
helper = os.environ.get('OVERLAY_MOUSE_HELPER', str(pathlib.Path.home()/'tmp/rune-overlay-probe/mouse-path'))
result = subprocess.run([helper, *map(str, start+finish), '32'] + (['click'] if click else []),
capture_output=True, text=True, timeout=5)
print(result.stdout.strip(), flush=True)
if result.returncode: raise RuntimeError(f'input helper failed: {result.returncode} {result.stderr}')
try:
pump(lambda: window is not None and len(regions) >= 4)
command('show')
geometry = json.loads(subprocess.check_output([str(root/'capture-probe'), str(window), '--geometry'], text=True))
x, y = geometry['X'], geometry['Y']
outside = (x+20, y+80)
move((x+20, y+200), outside)
for trial in range(20):
# iPhone is the fourth hit chip; its geometry shifts when Route appears.
r = regions[3]
inside = (x+(r[0]+r[2])/2, y+(r[1]+r[3])/2)
move(outside, inside, True)
pump(lambda: chips == trial+1 or clicks > trial)
assert chips == trial+1 and clicks == trial, f'inside: chips={chips} underlay={clicks} trial={trial+1}'
move(inside, outside, True)
pump(lambda: clicks == trial+1)
assert chips == trial+1 and clicks == trial+1
print(f'PASS cycle={trial+1} overlay={chips} underlay={clicks}', flush=True)
(root/'input-results.json').write_text(json.dumps({'cycles':20, 'overlay_clicks':chips, 'underlay_clicks':clicks, 'window':window}, indent=2))
finally:
try: command('quit')
except OSError: pass
# Underlay has its own bounded app timer; do not terminate unrelated processes.
overlay.wait(timeout=100)
underlay.wait(timeout=100)
for file in logs.values(): file.close()
control.unlink(missing_ok=True)
@@ -0,0 +1,101 @@
"""Run on an authorized Mac, while the caller holds its GUI lock."""
import json, math, os, pathlib, re, selectors, socket, statistics, subprocess, sys, time
from prewarm_trace import assert_prewarmed
root = pathlib.Path(sys.argv[1])
retained = os.environ.get('OVERLAY_PROBE_RETAINED') == '1'
if subprocess.run(['pgrep', '-f', '[r]une-smoke/ci/Hex.app'], capture_output=True).returncode == 0:
raise SystemExit('BLOCKED: competing Hex GUI probe is still alive')
control = root / 'control.sock'
env = dict(os.environ, OVERLAY_LAB_SECONDS='100', OVERLAY_LAB_CONTROL=str(control),
DYLD_INSERT_LIBRARIES=str(root / 'presentation-probe.dylib'))
process = subprocess.Popen([str(root / 'overlay-lab')], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
selector = selectors.DefaultSelector()
selector.register(process.stdout, selectors.EVENT_READ)
buffer = b''
lines = []
log = (root / 'presentation.log').open('w')
def wait_for(predicate, seconds=20):
global buffer
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
while b'\n' in buffer:
raw, buffer = buffer.split(b'\n', 1)
line = raw.decode(errors='replace')
log.write(line + '\n'); log.flush(); lines.append(line)
if predicate(line): return line
if not selector.select(max(0, deadline - time.monotonic())): break
chunk = os.read(process.stdout.fileno(), 65536)
if not chunk: raise RuntimeError('overlay exited before expected event')
buffer += chunk
raise TimeoutError('native event did not arrive')
def command(value):
with socket.socket(socket.AF_UNIX) as connection:
connection.settimeout(5)
connection.connect(str(control))
connection.sendall((value+'\n').encode())
reply = connection.recv(4096).decode().strip()
print(reply, flush=True)
return reply
try:
created = wait_for(lambda line: 'pill created' in line)
window = int(re.search(r'window_number: Some\((\d+)\)', created)[1])
if retained:
assert_prewarmed(lines, window)
samples, identities, timed_out, alpha_ms, dropped = [], [], [], [], 0
for trial in range(31):
if trial:
hidden = command('hide')
assert f'window=Some({window})' in hidden, hidden
prefix = f'probe alpha window={window} alpha=0.0 ' if retained else f'probe hidden window={window} visible=0 '
wait_for(lambda line: line.startswith(prefix))
state = subprocess.check_output([str(root / 'capture-probe'), str(window)] + ([] if retained else ['--hidden']), text=True, timeout=10).strip()
assert 'exists=true' in state, state
if not retained: assert 'onScreen=0' in state or 'onScreen=false' in state, state
shown = command('show')
assert f'window=Some({window})' in shown, shown
requested = float(re.search(r'time=([\d.]+)', shown)[1])
if retained:
flipped = wait_for(lambda line: line.startswith(f'probe alpha window={window} alpha=1.0 '))
alpha_ms.append((float(re.search(r'time=([\d.]+)', flipped)[1])-requested)*1000)
def first_presentation(line):
global dropped
if not line.startswith(f'probe presented window={window} '): return False
if float(re.search(r'acquired=([\d.]+)', line)[1]) < requested: return False
presented = float(re.search(r'presented=([\d.]+)', line)[1])
if presented == 0: dropped += 1
return presented >= requested
try:
# Never hide after a discarded drawable. Wait for a positive timestamp;
# a two-second absence is a failed trial, not a zero-latency success.
frame = wait_for(first_presentation, seconds=2)
except TimeoutError:
timed_out.append(trial+1)
delta = None
else:
presented = float(re.search(r'presented=([\d.]+)', frame)[1])
assert presented >= requested, frame
delta = (presented - requested) * 1000
samples.append(delta)
identities.append(window)
print(f'trial={trial+1} show_to_present_ms={delta} window={window}', flush=True)
capture = subprocess.run([str(root / 'capture-probe'), str(window), str(root / 'capture')], capture_output=True, text=True, timeout=20)
print(capture.stdout, capture.stderr, flush=True)
result = dict(samples_ms=samples, window_ids=identities, capture_exit=capture.returncode,
unpresented_callbacks=dropped, timed_out_trials=timed_out, alpha_ms=alpha_ms,
diagnostic_redraw=bool(os.environ.get('OVERLAY_PROBE_REDRAW')),
min_ms=min(samples) if samples else None, median_ms=statistics.median(samples) if samples else None,
p95_ms=sorted(samples)[math.ceil(len(samples)*.95)-1] if samples else None,
max_ms=max(samples) if samples else None, under_16=sum(v < 16 for v in samples))
(root / 'results.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result), flush=True)
finally:
# Ask the lab to quit; its bounded timer is a fallback if the socket is unavailable.
try: command('quit')
except (OSError, TimeoutError): pass
process.wait(timeout=110)
log.close()
control.unlink(missing_ok=True)
@@ -0,0 +1,45 @@
"""Compare the installed Metal pill; caller holds /tmp/pro-gui.lock on the authorized Mac.
Endpoint is native orderFrontRegardless entry during an app's already-visible panel sync,
not the beginning of the app's coordinator request. No redraw assistance is injected.
"""
import hashlib, json, math, os, pathlib, re, statistics, subprocess, sys
binary, root = map(pathlib.Path, sys.argv[1:3])
env = dict(os.environ, DYLD_INSERT_LIBRARIES=str(root/'presentation-probe.dylib'))
for key in ['OVERLAY_PROBE_REDRAW', 'OVERLAY_PROBE_NATIVE_OPTIONS']:
env.pop(key, None)
args = [str(binary), 'lab', 'pill', 'tap-then-screen', '--repeat', '30',
'--time-scale', '1', '--no-backdrop', '--trace', str(root/'motion.jsonl')]
(root/'load-before.txt').write_bytes(subprocess.check_output(['top','-l','1','-n','0']))
run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=160)
(root/'presentation.log').write_text(run.stdout+run.stderr)
(root/'load-after.txt').write_bytes(subprocess.check_output(['top','-l','1','-n','0']))
if run.returncode: raise RuntimeError(f'Reference app lab exited {run.returncode}; see presentation.log')
fronts, frames = [], []
for line in run.stderr.splitlines():
front = re.match(r'probe front window=(\d+) requested=([\d.]+) was_visible=1 panel=1 level=30 view=(.*)',line)
if front and 'PillView' in front[3]: fronts.append((int(front[1]),float(front[2])))
frame = re.match(r'probe presented window=(\d+) acquired=([\d.]+) presented=([\d.]+)',line)
if frame: frames.append((int(frame[1]),float(frame[2]),float(frame[3])))
trials = []
for i, (window, requested) in enumerate(fronts):
limit = min(requested+2, fronts[i+1][1]) if i+1 < len(fronts) else requested+2
candidates = [presented for owner, acquired, presented in frames
if owner == window and requested <= acquired < limit and requested <= presented < limit]
trials.append(dict(window=window, requested=requested,
latency_ms=(min(candidates)-requested)*1000 if candidates else None))
samples = [t['latency_ms'] for t in trials if t['latency_ms'] is not None]
result = dict(binary=str(binary), sha256=hashlib.sha256(binary.read_bytes()).hexdigest(),
profile='installed app; optimization profile not established',
start='native orderFrontRegardless entry during already-visible pill sync',
end='first positive Metal presentedTime acquired after that entry',
diagnostic_redraw=False, trials=trials,
min_ms=min(samples) if samples else None, median_ms=statistics.median(samples) if samples else None,
p95_ms=sorted(samples)[math.ceil(len(samples)*.95)-1] if samples else None,
max_ms=max(samples) if samples else None, under_16=sum(v<16 for v in samples),
zero_callbacks=sum(presented==0 for _,_,presented in frames))
(root/'results.json').write_text(json.dumps(result,indent=2))
print(json.dumps({k:v for k,v in result.items() if k!='trials'},indent=2),flush=True)
print(f'trials={len(trials)} valid={len(samples)}',flush=True)
if len(trials)!=30 or len(samples)!=30: raise RuntimeError('Expected 30 native show markers and valid presentations')
@@ -0,0 +1,51 @@
"""One bounded Pro GUI lease; serve explicit Cua/fixture actions under the GUI lock."""
import fcntl, json, os, pathlib, socket, subprocess, sys, time
assert socket.gethostname().startswith('Kits-Shiny-Computer')
root = pathlib.Path(sys.argv[1]).resolve()
root.mkdir(parents=True, exist_ok=True)
driver = str(pathlib.Path.home()/'.local/bin/cua-driver')
session = 'rune-window-panel'
def command(text):
with socket.socket(socket.AF_UNIX) as client:
client.settimeout(8)
client.connect(str(root/'app.sock'))
client.sendall((text+'\n').encode())
return client.makefile().readline().strip()
with open('/tmp/pro-gui.lock', 'a') as lock, (root/'app.log').open('w') as log, (root/'actions.jsonl').open('w') as actions:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
subprocess.run([driver, 'start_session', json.dumps({'session':session})], capture_output=True, check=True, timeout=15)
with socket.socket(socket.AF_UNIX) as server:
server.bind(str(root/'proof.sock'))
server.listen()
server.settimeout(600)
app = subprocess.Popen([sys.argv[2]], env=dict(os.environ, WINDOW_PANEL_SOCKET=str(root/'app.sock')), stdout=log, stderr=subprocess.STDOUT)
try:
print(json.dumps({'ready':str(root/'proof.sock'),'pid':app.pid}), flush=True)
while True:
client, _ = server.accept()
with client:
request = json.loads(client.makefile().readline())
try:
if 'command' in request:
result = command(request['command'])
elif 'tool' in request:
args = dict(request.get('args', {}), session=session)
run = subprocess.run([driver, request['tool'], json.dumps(args)], capture_output=True, text=True, timeout=45)
result = {'exit':run.returncode,'stdout':run.stdout,'stderr':run.stderr}
else:
result = 'finished'
actions.write(json.dumps({'time':time.time(),'request':request,'result':result})+'\n'); actions.flush()
client.sendall((json.dumps(result)+'\n').encode())
if request.get('finish'): break
except Exception as error:
client.sendall((json.dumps({'error':str(error)})+'\n').encode())
finally:
if app.poll() is None:
try: command('quit'); app.wait(timeout=5)
except Exception: app.terminate(); app.wait(timeout=5)
subprocess.run([driver,'end_session',json.dumps({'session':session})], capture_output=True, timeout=15)
for name in ['app.sock','proof.sock']: (root/name).unlink(missing_ok=True)
print('Fixture exited; GUI lock released on exit.', flush=True)
@@ -0,0 +1,23 @@
import unittest
from prewarm_trace import assert_prewarmed
class PrewarmTraceTests(unittest.TestCase):
created = 'overlay-lab pill created OverlayCreated { window_number: Some(12), capabilities: ... }'
acquired = 'probe acquired window=12 alpha=0.0 time=1.0'
def test_accepts_alpha_zero_acquisition_before_creation(self):
assert_prewarmed([self.acquired, self.created], 12)
def test_rejects_occlusion_skip_late_or_visible_acquisition(self):
for lines in ([self.created], [self.created, self.acquired],
[self.acquired.replace('alpha=0.0', 'alpha=1.0'), self.created],
[self.acquired.replace('window=12', 'window=11'), self.created],
[self.acquired]):
with self.subTest(lines=lines), self.assertRaises(AssertionError):
assert_prewarmed(lines, 12)
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,5 @@
[
{"t": 0, "focus": true},
{"t": 0.1, "focus": false},
{"t": 0.2, "focus": false}
]
@@ -0,0 +1,44 @@
//! Static exit samples on a real native overlay, for capsule/filter integration review.
#![forbid(unsafe_code)]
use rune::{App, AppSpec, Color, Cx, DisplayTarget, El, OverlayInput, OverlayLevel,
OverlayOptions, OverlaySpec, RunOptions, WindowSpec, el, text};
const INK: Color = Color { r: 0.06, g: 0.32, b: 1.0, a: 1.0 };
const SURFACE: Color = Color { r: 0.035, g: 0.035, b: 0.035, a: 1.0 };
fn view(_: &(), _: &mut Cx<()>) -> El {
let mut root = el().size(620.0, 176.0);
for (label, y, clipped) in [("Unmasked", 32.0, false), ("Clipped", 112.0, true)] {
let mut capsule = el().size(400.0, 40.0).absolute(112.0, y).radius(20.0).fill(SURFACE);
if clipped { capsule = capsule.clip_rounded(20.0); }
// Shared background stays outside the dissolve; blur is on the leaving state.
let state = el().size(72.0, 28.0).absolute(370.0, 6.0).opacity(0.65).blur(1.5)
.radius(8.0).fill(INK).child(text("Leaving").absolute(8.0, 6.0));
root = root.child(text(label).absolute(12.0, y + 11.0))
.child(capsule.child(el().size(400.0, 40.0).dissolve().child(state)));
}
root
}
fn main() {
let spec = AppSpec { title: "Layer filter overlay", size: (620.0, 176.0), min_size: None,
init: || (), view, scenes: &[], fonts: &[], families: ("sans-serif", "monospace"),
setup: None, poll: None, on_key: None };
rune::run_windows_with(RunOptions { accessory: true }, |_| {
let mut app = App::new(spec).windowless();
let pill = app.overlay(OverlaySpec::new("Layer filter capsule proof", (620.0, 176.0), view)
.options(OverlayOptions { display: DisplayTarget::Primary, input: OverlayInput::None,
level: OverlayLevel::AboveOverlays, exclude_from_capture: false, prewarm: true, ..Default::default() })
.on_created(|created| eprintln!("filter-overlay created {created:?}")), ());
pill.show();
let handle = app.handle();
// The probe owns stdin and closes it even on capture failure. No persistent GUI job.
std::thread::spawn(move || {
std::io::stdin().read_line(&mut String::new()).ok();
handle.quit();
});
vec![WindowSpec::from_app("filter-proof", app)]
});
}
@@ -0,0 +1,93 @@
//! An overlay with a repeating 100 ms timer, for measuring idle cost while the panel is
//! covered or the displays sleep. Prints its timer count once a second.
//!
//! `OCCLUDED_TIMER_SECONDS=n` quits after n seconds; `OCCLUDED_TIMER_PREWARM=1` prewarms the
//! panel; `OCCLUDED_TIMER_REGIONS=1` takes pointer input over its pill only;
//! `OCCLUDED_TIMER_BOTTOM=1` puts it at the bottom edge; `OCCLUDED_TIMER_WINDOW=1` runs the
//! timer in a regular window instead. `OCCLUDED_TIMER_UPDATE=1` replaces the repeating timer
//! with one 100 ms `wake_after` that an update from another thread sets each second, and also
//! prints the latest that timer fired.
#![forbid(unsafe_code)]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use rune::{App, AppSpec, Color, Cx, El, OverlayInput, OverlayOptions, OverlaySpec, RunOptions, ScreenEdge, Tx, WindowOptions, WindowSpec, el, text};
const PERIOD: f64 = 0.1;
const ARMED: Duration = Duration::from_millis(100);
static FIRED: AtomicUsize = AtomicUsize::new(0);
static WORST_MS: AtomicUsize = AtomicUsize::new(0);
#[derive(Default)]
struct State { next: f64, armed: Option<Instant> }
fn view(_: &State, _: &mut Cx<State>) -> El {
el().key("pill").hit().padding(12.0).radius(16.0).fill(Color { r: 0.1, g: 0.12, b: 0.16, a: 0.95 })
.child(text(format!("fired {}", FIRED.load(Ordering::Relaxed))).color(Color::WHITE))
}
fn poll(s: &mut State, t: f64, tx: &mut Tx) -> bool {
if updates() { return poll_armed(s); }
let fired = t >= s.next;
if fired {
FIRED.fetch_add(1, Ordering::Relaxed);
s.next = t + PERIOD;
}
tx.wake_after(Duration::from_secs_f64((s.next - t).max(0.0)));
fired
}
/// Counts the update's timer once it is due, and how late it ran.
fn poll_armed(s: &mut State) -> bool {
let Some(at) = s.armed.filter(|at| at.elapsed() >= ARMED) else { return false };
s.armed = None;
FIRED.fetch_add(1, Ordering::Relaxed);
WORST_MS.fetch_max(at.elapsed().as_millis() as usize, Ordering::Relaxed);
true
}
fn arm(s: &mut State, tx: &mut Tx) {
s.armed = Some(rune::time::now());
tx.wake_after(ARMED);
}
fn updates() -> bool { std::env::var_os("OCCLUDED_TIMER_UPDATE").is_some() }
fn main() {
rune::run_windows_with(RunOptions { accessory: true }, |_| {
let window = std::env::var_os("OCCLUDED_TIMER_WINDOW").is_some();
let spec = AppSpec { poll: window.then_some(poll as fn(&mut State, f64, &mut Tx) -> bool), ..AppSpec::new("Occluded timer", (420.0, 400.0), State::default, view) };
let mut app = App::new(spec);
if window {
let handle = app.handle();
report(app.handle(), move || handle.update(arm));
// Side by side, so neither covers the other.
let x = if std::env::var_os("OCCLUDED_TIMER_BOTTOM").is_some() { 900 } else { 100 };
return vec![WindowSpec::from_app("occluded-timer", app).options(WindowOptions { position: Some((x, 200)), ..Default::default() })];
}
app = app.windowless();
let input = if std::env::var_os("OCCLUDED_TIMER_REGIONS").is_some() { OverlayInput::Regions } else { OverlayInput::All };
let edge = if std::env::var_os("OCCLUDED_TIMER_BOTTOM").is_some() { ScreenEdge::Bottom } else { ScreenEdge::Top };
let overlay = app.overlay(OverlaySpec { edge, ..OverlaySpec::new("Occluded timer", (220.0, 60.0), view) }.options(OverlayOptions {
input, prewarm: std::env::var_os("OCCLUDED_TIMER_PREWARM").is_some(), ..Default::default()
}).poll(poll), State::default());
overlay.show();
report(app.handle(), move || overlay.update(arm));
vec![WindowSpec::from_app("occluded-timer", app)]
});
}
fn report(handle: rune::AppHandle<State>, arm: impl Fn() + Send + 'static) {
let quit = rune::env::var("OCCLUDED_TIMER_SECONDS").and_then(|s| s.parse::<u64>().ok());
std::thread::spawn(move || {
let start = rune::time::now();
loop {
std::thread::sleep(Duration::from_secs(1));
let elapsed = start.elapsed().as_secs();
eprintln!("occluded-timer t={elapsed} fired={} worst_ms={}", FIRED.load(Ordering::Relaxed), WORST_MS.load(Ordering::Relaxed));
if quit.is_some_and(|q| elapsed >= q) { handle.quit(); return; }
if updates() { arm(); }
}
});
}
+186
View File
@@ -0,0 +1,186 @@
use std::sync::{Arc, Mutex};
use rune::{App, AppSpec, Color, Cx, DisplayTarget, El, Key, KeyEvent, KeyPolicy, OverlayHandle, OverlayInput, OverlayLevel, OverlayOptions, OverlayPlacement, OverlaySpec, Phase, RunOptions, Tx, WindowSpec, col, el, row, text};
const BLUE: Color = Color { r: 0.25, g: 0.55, b: 1.0, a: 1.0 };
const DARK: Color = Color { r: 0.055, g: 0.065, b: 0.085, a: 0.97 };
#[derive(Default)]
struct Handles { pill: Option<OverlayHandle<State>>, pickers: Vec<OverlayHandle<State>> }
struct State {
underlay: bool,
hit_only: bool,
clicks: u32,
picker: bool,
expanded: bool,
hovered: String,
selection: Option<[f32; 4]>,
selection_at_press: Option<[f32; 4]>,
pointer: rune::Live<[f32; 2]>,
handles: Arc<Mutex<Handles>>,
}
fn init() -> State {
State { underlay: false, hit_only: false, clicks: 0, picker: false, expanded: false, hovered: String::new(), selection: None, selection_at_press: None, pointer: rune::Live::new([160.0, 100.0]), handles: Arc::default() }
}
fn show_picker(s: &mut State) {
let handles = s.handles.lock().unwrap();
for picker in &handles.pickers { picker.show(); }
// One key owner, even with several full-display surfaces.
if let Some(picker) = handles.pickers.first() { picker.request_keys(); }
eprintln!("overlay-lab picker shown");
}
fn hide_picker(s: &mut State) {
for picker in &s.handles.lock().unwrap().pickers { picker.hide(); }
eprintln!("overlay-lab picker hidden");
}
fn key(s: &mut State, event: &KeyEvent, _: &mut Tx) -> bool {
eprintln!("overlay-lab key {event:?}");
if event.key == Key::Escape { hide_picker(s); return true; }
false
}
fn chip(label: &'static str, action: fn(&mut State)) -> El {
el().key(label).hit().padding(10.0).radius(16.0).fill(BLUE.alpha(0.16))
.child(text(label).color(Color::WHITE))
.on_hover(move |s: &mut State| { s.hovered = label.into(); })
.on_press(move |s: &mut State| { eprintln!("overlay-lab chip {label}"); action(s); })
}
fn view(s: &State, _: &mut Cx<State>) -> El {
if s.underlay {
return el().w_full().h_full().fill(DARK).padding(40.0)
.child(text(format!("Underlay clicks: {}", s.clicks)).color(Color::WHITE))
.on_press(|s: &mut State| { s.clicks += 1; eprintln!("overlay-lab underlay click {}", s.clicks); });
}
if s.picker {
let mut root = el().w_full().h_full().hit().fill(BLUE.alpha(0.06))
.on_pointer_move_local(|s: &mut State, p, tx| {
s.pointer.set([p.window_x, p.window_y]);
tx.live_only();
})
.on_drag(|s: &mut State, drag, tx| {
tx.instant();
if drag.phase == Phase::Down { s.selection_at_press = s.selection; }
if drag.cancelled() { s.selection = s.selection_at_press.take(); return; }
let (x, y) = (drag.x.min(drag.start_x), drag.y.min(drag.start_y));
s.selection = Some([x, y, (drag.x - drag.start_x).abs(), (drag.y - drag.start_y).abs()]);
if drag.phase == Phase::Up { eprintln!("overlay-lab selection {:?}", s.selection); }
})
.child(text("Drag an area · Escape to close").color(Color::WHITE).pin(Some(24.0), Some(24.0), None, None))
.child(el().size(8.0, 8.0).radius(4.0).fill(BLUE).pin(Some(0.0), Some(0.0), None, None).live_offset(&s.pointer));
if let Some([x, y, w, h]) = s.selection {
root = root.child(el().key("selection").size(w, h).border(2.0, BLUE).fill(BLUE.alpha(0.12)).pin(Some(x), Some(y), None, None));
}
return root;
}
if s.hit_only {
return col().w_full().h_full().center().child(el().key("hit-only").size(300.0, 48.0).hit()
.fill(DARK).child(text("Native hit region").color(Color::WHITE)));
}
let mut chips = row().key("pill").padding(8.0).gap(4.0).radius(28.0).fill(DARK)
.child(chip("Area", show_picker)).child(chip("Window", show_picker))
.child(chip("Screen", show_picker)).child(chip("iPhone", |s| s.expanded = !s.expanded));
if s.expanded { chips = chips.child(chip("Route", |s| s.expanded = false)); }
chips = chips.child(chip("Paste", |s| s.expanded = !s.expanded))
.child(chip("×", |s| { if let Some(pill) = &s.handles.lock().unwrap().pill { pill.hide(); } }));
col().w_full().h_full().center().gap(8.0).child(chips)
.child(text(&s.hovered).color(BLUE))
}
fn spec() -> AppSpec<State> {
AppSpec { title: "Overlay lab", size: (680.0, 160.0), min_size: None, init, view,
scenes: &[("pill", |_| {}), ("expanded", |s| s.expanded = true), ("picker", |s| { s.picker = true; s.selection = Some([140.0, 100.0, 560.0, 320.0]); })],
fonts: &[], families: ("sans-serif", "monospace"), setup: None, poll: None, on_key: Some(key) }
}
/// Optional local control socket for bounded native lifecycle/presentation probes.
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
fn native_probe(pill: OverlayHandle<State>, app: rune::AppHandle<State>) {
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixListener;
#[link(name = "QuartzCore", kind = "framework")]
unsafe extern "C" { fn CACurrentMediaTime() -> f64; }
let Some(path) = std::env::var_os("OVERLAY_LAB_CONTROL") else { return };
let listener = UnixListener::bind(&path).expect("unique overlay probe socket");
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { break };
let mut command = String::new();
if BufReader::new(&stream).read_line(&mut command).is_err() { continue; }
// SAFETY: `CACurrentMediaTime` takes no arguments and is safe to call from any thread.
let at = unsafe { CACurrentMediaTime() };
match command.trim() {
"show" => pill.show(),
"hide" => pill.hide(),
"none" => pill.set_input(OverlayInput::None),
"all" => pill.set_input(OverlayInput::All),
"regions" => pill.set_input(OverlayInput::Regions),
"hit-only" => pill.update(|s, _| s.hit_only = true),
"chips" => pill.update(|s, _| s.hit_only = false),
"status" => {},
"quit" => app.quit(),
_ => { writeln!(stream, "unknown command").ok(); continue; }
}
let line = format!("probe command={} time={at:.9} window={:?}", command.trim(), pill.window_number());
eprintln!("{line}");
writeln!(stream, "{line}").ok();
}
});
}
fn main() {
if std::env::var_os("OVERLAY_LAB_UNDERLAY").is_some() {
rune::run_windows(|displays| {
let mut state = init(); state.underlay = true;
let app = App::new(spec()).init(move || state);
if let Ok(seconds) = rune::env::var("OVERLAY_LAB_SECONDS").unwrap_or_default().parse::<u64>() {
let handle = app.handle();
std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_secs(seconds)); handle.quit(); });
}
let options = displays.iter().find(|d| d.primary).or_else(|| displays.first()).map(|display| rune::WindowOptions {
borderless: true, position: Some(display.position), physical_size: Some(display.size), ..Default::default()
}).unwrap_or_default();
let options = if std::env::var_os("OVERLAY_LAB_NATIVE_WINDOW").is_some() {
options.macos(rune::MacWindowOptions::default().shadow(false).level(24)
.collection_behavior(1 | 16 | 64 | 256).exclude_from_capture(true))
} else { options.into() };
vec![WindowSpec::from_app("underlay", app).configured_options(options)]
});
return;
}
rune::run_windows_with(RunOptions { accessory: true }, |displays| {
let exclude = std::env::var_os("OVERLAY_LAB_INCLUDE_IN_CAPTURE").is_none();
let handles = Arc::new(Mutex::new(Handles::default()));
let mut app = App::new(spec()).windowless();
for display in displays {
let mut state = init();
state.picker = true;
state.handles = handles.clone();
let target = display.id.clone().map_or(DisplayTarget::Primary, DisplayTarget::Id);
let picker = app.overlay(OverlaySpec::new("Rune picker", (680.0, 160.0), view).options(OverlayOptions {
display: target, placement: Some(OverlayPlacement::FullScreen), level: OverlayLevel::AboveStatus,
input: OverlayInput::All, exclude_from_capture: exclude, keys: KeyPolicy::OnDemand, prewarm: true, ..Default::default()
}).on_key(key).on_created(|created| eprintln!("overlay-lab picker created {created:?}")), state);
handles.lock().unwrap().pickers.push(picker);
}
let mut state = init();
state.handles = handles.clone();
let pill = app.overlay(OverlaySpec { margin: 40.0, ..OverlaySpec::new("Rune pill", (680.0, 160.0), view) }.options(OverlayOptions {
display: DisplayTarget::UnderPointer, follow_pointer: true,
input: OverlayInput::Regions, exclude_from_capture: exclude, level: OverlayLevel::AboveOverlays, prewarm: true, ..Default::default()
}).on_created(|created| eprintln!("overlay-lab pill created {created:?}")), state);
handles.lock().unwrap().pill = Some(pill.clone());
#[cfg(target_os = "macos")]
native_probe(pill.clone(), app.handle());
if !cfg!(target_os = "macos") || std::env::var_os("OVERLAY_LAB_CONTROL").is_none() { pill.show(); }
if std::env::var_os("OVERLAY_LAB_PICKER").is_some() {
let mut state = init(); state.handles = handles; show_picker(&mut state);
}
if let Ok(seconds) = rune::env::var("OVERLAY_LAB_SECONDS").unwrap_or_default().parse::<u64>() {
let app_handle = app.handle();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(750));
eprintln!("overlay-lab window={:?} capture={:?}", pill.window_number(), pill.capture_exclusion());
std::thread::sleep(std::time::Duration::from_secs(seconds));
app_handle.quit();
});
}
vec![WindowSpec::from_app("lab", app).options(rune::WindowOptions { transparent: true, ..Default::default() })]
});
}
+103
View File
@@ -0,0 +1,103 @@
# Ordinary quick panels
## Cached launcher panels
Launcher-style apps can use a retained quick panel:
```rust,ignore
WindowSpec::from_app("quick", App::new(spec).keep_running())
.configured_options(WindowOptions::launcher_panel())
.on_focus(|_, focused, tx| { if !focused { tx.close_window(); } })
.on_ready(|window| {
// Hidden, with a completed cached frame. Register your shortcut here.
assert!(window.is_ready());
})
```
For a single-window app, use `App::configured_options(WindowOptions::launcher_panel())`.
Keep using accessory launch policy as described below. The preset is initially hidden,
borderless, transparent and non-resizable, with no inherited minimum size. AppSpec sets its
size. On macOS it prepares even with `App::windowless()`. `on_created` still means native
creation; `on_ready` means the first surface frame completed on the GPU, not merely submission.
Both callbacks run on the event thread. Readiness is per native lifetime, not a freshness
guarantee for later state updates. Headless rendering does not invoke native callbacks.
`WindowHandle::set_visible(true)`/`show()` and `AppHandle::show()`/`open()` reveal cached
pixels and take keys without app activation. A show before readiness waits behind the
first-frame fence; hide cancels that pending show. Hide leaves the panel ordered in at
alpha zero, ignores mouse input, and returns keys through AppKit. It retains the surface
even when `release_gpu_when_closed()` is set. Use `keep_running()` if closing should hide
rather than end this host. Ordinary non-launcher windows keep their existing show semantics.
The reveal itself does no settling, layout, surface configuration or drawable acquisition.
Queued state updates, focus handlers and later input can draw fresh frames normally.
Hidden updates, and `poll` changes after `AppHandle::wake()`, render at alpha zero: the first
after a quiet spell at once, later ones at most every 250 ms; hidden animations do not drive a
continuous loop. A shown launcher redraws on every wake. A show whose state changed since the
cached frame (an `update()` in the same turn, or one still waiting for that pace) first renders
one fenced hidden frame, so it never reveals stale pixels. That frame commits the new state
without settling it: content is fresh on reveal and the update's motion runs on from there.
First preparation retries unavailable drawables for at most two seconds, then reports through
`AppHandle::window_error()` and remains hidden; a later show retries preparation. A late
successful frame still completes readiness. Other platforms use an ordinary hidden
window; their `on_ready` fires after the first shown frame completes on the GPU.
The implementation ports the spike's retained reveal and uses a GPU fence for hidden preparation
(a never-shown alpha-zero layer need not emit a positive `presentedTime`). Existing spike
measurements (cached alpha 7.9/12.7 ms; native 6.2/15.8 ms) describe that experiment, not a new
benchmark of this API. `WINDOW_PANEL_LAUNCHER=1` selects the launcher in the native fixture;
its `visible`/`invisible` commands exercise WindowHandle directly.
## Ordinary panels and focus
`AppSpec`, `WindowSpec`, `WindowOptions` and `OverlaySpec` literals retain their fields.
Configure focus callbacks on `App::on_focus`, `WindowSpec::on_focus`, or
`ConfiguredOverlay::on_focus`. Each callback takes `fn(&mut S, bool, &mut Tx)`.
Repeated focus notifications are deduplicated per runtime. Callbacks run on the event
thread even when the window is hidden/occluded, before requiring a drawable.
`Tx::close_window()` dismisses a keep-running ordinary window or hides an overlay.
```rust,ignore
let quick = App::new(spec).windowless().on_focus(|_, focused, tx| {
if !focused { tx.close_window(); }
});
let handle = quick.handle();
let window = WindowSpec::from_app("quick", quick).configured_options(
WindowOptions { borderless: true, ..Default::default() }
.macos(MacWindowOptions::default().nonactivating_panel(true))
);
// From a shortcut callback on any thread:
handle.place(DisplayTarget::UnderPointer, OverlayPlacement::Edge {
edge: ScreenEdge::Top, margin: 160.0, align: Align::Center, inset: 0.0,
});
handle.open();
```
The macOS panel takes keys without activating its application. `show()` does not take
keys; `open()`/`focus()` do. Hiding lets AppKit return keys to the prior application.
For a single-window app use `App::macos_window(...)`. Use `App::accessory()` or
`run_windows_with(RunOptions { accessory: true }, ...)` to prevent launch activation too.
Panel policy is ignored on other platforms; poll, scenes, on_key and headless tooling
remain ordinary-window features.
Both AppHandle and WindowHandle have `place(display, placement)`. UnderPointer samples
at the calling thread, not after a delayed event-loop wake. Placement is retained across
recreation and re-resolved on open and scale changes; disconnected display IDs fall back
to primary. Rect and FullScreen resize as well as place; Edge uses the current window size.
Coordinates are display-local points, as for overlays. Wayland ignores placement requests.
`set_position` replaces a pending/retained display placement, and vice versa.
Headless runs resolve `AppHandle::place` against displays a `--script` object declares,
`{"displays":[{"id":1,"frame":[0,0,1512,982],"scale":2,"primary":true}],"pointer":[800,400],"events":[]}`
(frames and pointer in global points; ids match `DisplayTarget::Native`). Without them there is
one 1920x1080-pixel primary display, which `run_windows` factories also receive. Each
placement prints `rune-placed {"t":…,"display":1,"frame":[x,y,w,h]}` and the latest one
appears as `"placed"` in `--tree`. The headless viewport keeps its size.
Headless scripts accept `{"t": 0.1, "focus": false}` (time defaults to zero), delivering
the same app callback as native input. Existing root `El::on_window_focus` callbacks also
receive the queued focus event when Runtime next advances.
`cargo run -p rune --example window-panel --release` supplies two independent windows with
the same state type. `WINDOW_PANEL_SOCKET` enables the fixture's open/focus/hide/status/quit
commands. `native/run-window-panel-probe.py` holds the GUI test host's lock for a bounded Cua proof.