diff --git a/bindings/csharp/src/CNativeAPI/generated/View.cs b/bindings/csharp/src/CNativeAPI/generated/View.cs index e84f8bcf..c22f8220 100644 --- a/bindings/csharp/src/CNativeAPI/generated/View.cs +++ b/bindings/csharp/src/CNativeAPI/generated/View.cs @@ -68,6 +68,14 @@ public static partial class Interop [return: MarshalAs(UnmanagedType.I1)] public static extern bool native_view_is_supported(); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.I1)] + public static extern bool native_view_is_update_pending(ulong self); + + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.I1)] + public static extern bool native_view_is_updating(); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.I1)] public static extern bool native_view_is_visible(ulong self); @@ -84,6 +92,10 @@ public static partial class Interop [return: MarshalAs(UnmanagedType.I1)] public static extern bool native_view_remove_subview_at(ulong self, CULong index); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.I1)] + public static extern bool native_view_request_update(ulong self); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.I1)] public static extern bool native_view_set_default_backend(int backend); @@ -256,12 +268,21 @@ public static partial class Interop [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] public static extern void native_view_add_subview(ulong self, ulong subview); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] + public static extern void native_view_begin_updates(); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] public static extern void native_view_blur(ulong self); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] + public static extern void native_view_cancel_update(ulong self); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] public static extern void native_view_clear_subviews(ulong self); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] + public static extern void native_view_end_updates([MarshalAs(UnmanagedType.I1)] bool redraw); + [DllImport(Libraries.NativeApi, CallingConvention = CallingConvention.Cdecl)] public static extern void native_view_focus(ulong self); diff --git a/bindings/csharp/src/NativeAPI/View.cs b/bindings/csharp/src/NativeAPI/View.cs index fd99fe16..00da751b 100644 --- a/bindings/csharp/src/NativeAPI/View.cs +++ b/bindings/csharp/src/NativeAPI/View.cs @@ -47,6 +47,7 @@ public sealed record Blurred(uint ViewId) : ViewEvent; public sealed record ButtonClicked(uint ViewId) : ViewEvent; public sealed record TextFieldChanged(uint ViewId, string? Text) : ViewEvent; public sealed record TextFieldSubmitted(uint ViewId) : ViewEvent; + public sealed record Updating(uint ViewId) : ViewEvent; internal static ViewEvent? FromRaw(in native_view_event_t raw) { @@ -57,6 +58,7 @@ public sealed record TextFieldSubmitted(uint ViewId) : ViewEvent; case 2: return new ButtonClicked(raw.view_id); case 3: return new TextFieldChanged(raw.view_id, Marshal.PtrToStringUTF8(raw.data.text_field_changed.text)); case 4: return new TextFieldSubmitted(raw.view_id); + case 5: return new Updating(raw.view_id); default: return null; } } @@ -129,6 +131,42 @@ public static ViewBackend GetDefaultBackend() return (ViewBackend)rawResult; } + public static void BeginUpdates() + { + Interop.native_view_begin_updates(); + } + + public static void EndUpdates(bool redraw) + { + Interop.native_view_end_updates(redraw); + } + + public static bool IsUpdating() + { + var rawResult = Interop.native_view_is_updating(); + return rawResult; + } + + public bool RequestUpdate() + { + var rawResult = Interop.native_view_request_update(NativeHandle); + return rawResult; + } + + public void CancelUpdate() + { + Interop.native_view_cancel_update(NativeHandle); + } + + public bool IsUpdatePending + { + get + { + var rawResult = Interop.native_view_is_update_pending(NativeHandle); + return rawResult; + } + } + public uint Id { get diff --git a/bindings/dart/cnativeapi/lib/src/bindings_generated.dart b/bindings/dart/cnativeapi/lib/src/bindings_generated.dart index c497db5c..44304d56 100644 --- a/bindings/dart/cnativeapi/lib/src/bindings_generated.dart +++ b/bindings/dart/cnativeapi/lib/src/bindings_generated.dart @@ -2562,9 +2562,15 @@ external int native_view_add_listener_async( @ffi.Native() external void native_view_add_subview(int view, int subview); +@ffi.Native() +external void native_view_begin_updates(); + @ffi.Native() external void native_view_blur(int view); +@ffi.Native() +external void native_view_cancel_update(int view); + @ffi.Native() external void native_view_clear_subviews(int view); @@ -2578,6 +2584,9 @@ external int native_view_create_with_native_view( ffi.Pointer native_view, ); +@ffi.Native() +external void native_view_end_updates(bool redraw); + @ffi.Native() external void native_view_focus(int view); @@ -2695,6 +2704,12 @@ external bool native_view_is_focused(int view); @ffi.Native() external bool native_view_is_supported(); +@ffi.Native() +external bool native_view_is_update_pending(int view); + +@ffi.Native() +external bool native_view_is_updating(); + @ffi.Native() external bool native_view_is_visible(int view); @@ -2716,6 +2731,9 @@ external bool native_view_remove_subview(int view, int subview); @ffi.Native() external bool native_view_remove_subview_at(int view, int index); +@ffi.Native() +external bool native_view_request_update(int view); + @ffi.Native( symbol: 'native_view_set_alignment', ) @@ -5868,7 +5886,8 @@ enum native_view_event_type_t { NATIVE_VIEW_EVENT_TYPE_BLURRED(1), NATIVE_VIEW_EVENT_TYPE_BUTTON_CLICKED(2), NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_CHANGED(3), - NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_SUBMITTED(4); + NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_SUBMITTED(4), + NATIVE_VIEW_EVENT_TYPE_UPDATING(5); final int value; const native_view_event_type_t(this.value); @@ -5879,6 +5898,7 @@ enum native_view_event_type_t { 2 => NATIVE_VIEW_EVENT_TYPE_BUTTON_CLICKED, 3 => NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_CHANGED, 4 => NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_SUBMITTED, + 5 => NATIVE_VIEW_EVENT_TYPE_UPDATING, _ => throw ArgumentError( 'Unknown value for native_view_event_type_t: $value', ), diff --git a/bindings/dart/nativeapi/CHANGELOG.md b/bindings/dart/nativeapi/CHANGELOG.md index 08fed733..119cd057 100644 --- a/bindings/dart/nativeapi/CHANGELOG.md +++ b/bindings/dart/nativeapi/CHANGELOG.md @@ -1,5 +1,9 @@ ## 0.6.0 +- Add cancellable `View.requestUpdate()` notifications. Windows coalesces publication on the owning UI thread and drains pending native paint after each update. + +- Add nested `View.beginUpdates()` / `View.endUpdates(redraw)` batches to coalesce layout. Windows also batches native moves and schedules geometry and visibility repaint after publication; self-rendering hosts can pass `false` to publish their own damage. Unchanged properties and absolute translations avoid redundant layout. + - **Breaking:** requires Flutter 3.50 / Dart 3.14. The experimental `runNativeApp()` in `package:nativeapi/standalone.dart` still depends on VM APIs that Dart 3.14 removed, so it cannot be compiled with this constraint until it is ported. - macOS: preserve a pending Flutter quit decision when AppKit acknowledges synchronous cancellation, so approving the later Dart response exits normally ([nativeapi-core#65](https://github.com/libnativeapi/nativeapi-core/issues/65)). - Linux: implement tray context menu popups and dismissal on X11, including double-click triggers. Document the native Wayland requirement to use host-rendered `Clicked` or `RightClicked` menus ([nativeapi-core#88](https://github.com/libnativeapi/nativeapi-core/issues/88)). diff --git a/bindings/dart/nativeapi/lib/src/view.dart b/bindings/dart/nativeapi/lib/src/view.dart index e885b841..db350a96 100644 --- a/bindings/dart/nativeapi/lib/src/view.dart +++ b/bindings/dart/nativeapi/lib/src/view.dart @@ -139,6 +139,10 @@ sealed class ViewEvent { .value) { return TextFieldSubmittedEvent(viewId: raw.view_id); } + if (raw.typeAsInt == + c.native_view_event_type_t.NATIVE_VIEW_EVENT_TYPE_UPDATING.value) { + return ViewUpdatingEvent(viewId: raw.view_id); + } return null; } } @@ -179,6 +183,13 @@ final class TextFieldSubmittedEvent extends ViewEvent { final ViewId viewId; } +final class ViewUpdatingEvent extends ViewEvent { + const ViewUpdatingEvent({required this.viewId}); + + @override + final ViewId viewId; +} + class View implements ffi.Finalizable { /// Adopts a handle returned by the C API and releases it when this /// object becomes unreachable. @@ -239,6 +250,30 @@ class View implements ffi.Finalizable { return ViewBackend.fromValue(raw.value); } + static void beginUpdates() { + c.native_view_begin_updates(); + } + + static void endUpdates(bool redraw) { + c.native_view_end_updates(redraw); + } + + static bool isUpdating() { + return c.native_view_is_updating(); + } + + bool requestUpdate() { + return c.native_view_request_update(nativeHandle); + } + + void cancelUpdate() { + c.native_view_cancel_update(nativeHandle); + } + + bool get isUpdatePending { + return c.native_view_is_update_pending(nativeHandle); + } + ViewId get id { return c.native_view_get_id(nativeHandle); } diff --git a/bindings/dart/nativeapi/lib/src/web/view.dart b/bindings/dart/nativeapi/lib/src/web/view.dart index 53ce8689..7ca672dd 100644 --- a/bindings/dart/nativeapi/lib/src/web/view.dart +++ b/bindings/dart/nativeapi/lib/src/web/view.dart @@ -121,6 +121,13 @@ final class TextFieldSubmittedEvent extends ViewEvent { final ViewId viewId; } +final class ViewUpdatingEvent extends ViewEvent { + const ViewUpdatingEvent({required this.viewId}); + + @override + final ViewId viewId; +} + class View { View.fromHandle(this.nativeHandle); View.borrowed(this.nativeHandle); @@ -139,6 +146,18 @@ class View { static ViewBackend getDefaultBackend() => unsupported(); + static void beginUpdates() => unsupported(); + + static void endUpdates(bool redraw) => unsupported(); + + static bool isUpdating() => unsupported(); + + bool requestUpdate() => unsupported(); + + void cancelUpdate() => unsupported(); + + bool get isUpdatePending => unsupported(); + ViewId get id => unsupported(); ViewBackend get backend => unsupported(); diff --git a/bindings/go/nativeapi.gen.go b/bindings/go/nativeapi.gen.go index f42ac483..6e3d4d2f 100644 --- a/bindings/go/nativeapi.gen.go +++ b/bindings/go/nativeapi.gen.go @@ -2374,6 +2374,7 @@ const ( ViewEventButtonClicked ViewEventType = 2 ViewEventTextFieldChanged ViewEventType = 3 ViewEventTextFieldSubmitted ViewEventType = 4 + ViewEventUpdating ViewEventType = 5 ) // ViewEvent copies an event payload. Handle fields are borrowed until the callback returns. @@ -2394,6 +2395,7 @@ func fromCViewEvent(raw *C.native_view_event_t) ViewEvent { case ViewEventTextFieldChanged: value.Text = C.GoString(C.go_native_view_event_t_text_field_changed_Text(raw)) case ViewEventTextFieldSubmitted: + case ViewEventUpdating: } return value } @@ -2480,6 +2482,43 @@ func ViewDefaultBackend() ViewBackend { return ViewBackend(result) } +// ViewBeginUpdates invokes the native BeginUpdates operation. +func ViewBeginUpdates() { + C.native_view_begin_updates() +} + +// ViewEndUpdates invokes the native EndUpdates operation. +func ViewEndUpdates(redraw bool) { + C.native_view_end_updates(C.bool(redraw)) +} + +// ViewIsUpdating invokes the native IsUpdating operation. +func ViewIsUpdating() bool { + result := C.native_view_is_updating() + return bool(result) +} + +// RequestUpdate invokes the native RequestUpdate operation. +// Failure wraps ErrOperationFailed; the native ABI provides no detailed cause. +func (v *View) RequestUpdate() error { + result := C.native_view_request_update(C.native_view_t(v.nativeHandleValue())) + if !bool(result) { + return nativeError("View.RequestUpdate") + } + return nil +} + +// CancelUpdate invokes the native CancelUpdate operation. +func (v *View) CancelUpdate() { + C.native_view_cancel_update(C.native_view_t(v.nativeHandleValue())) +} + +// IsUpdatePending invokes the native IsUpdatePending operation. +func (v *View) IsUpdatePending() bool { + result := C.native_view_is_update_pending(C.native_view_t(v.nativeHandleValue())) + return bool(result) +} + // ID invokes the native GetId operation. func (v *View) ID() ViewID { result := C.native_view_get_id(C.native_view_t(v.nativeHandleValue())) diff --git a/bindings/js/lib/view.ts b/bindings/js/lib/view.ts index 847b5eac..1253c05c 100644 --- a/bindings/js/lib/view.ts +++ b/bindings/js/lib/view.ts @@ -42,7 +42,8 @@ export type ViewEvent = | { type: "blurred"; viewId: ViewId } | { type: "buttonClicked"; viewId: ViewId } | { type: "textFieldChanged"; viewId: ViewId; text: string | null } - | { type: "textFieldSubmitted"; viewId: ViewId }; + | { type: "textFieldSubmitted"; viewId: ViewId } + | { type: "updating"; viewId: ViewId }; /** A native View, held through an owned handle. */ export class View extends NativeObject { @@ -77,6 +78,30 @@ export class View extends NativeObject { return native.native_view_get_default_backend(); } + static beginUpdates(): void { + native.native_view_begin_updates(); + } + + static endUpdates(redraw: boolean): void { + native.native_view_end_updates(redraw); + } + + static isUpdating(): boolean { + return native.native_view_is_updating(); + } + + requestUpdate(): boolean { + return native.native_view_request_update(this.nativeHandle); + } + + cancelUpdate(): void { + native.native_view_cancel_update(this.nativeHandle); + } + + get isUpdatePending(): boolean { + return native.native_view_is_update_pending(this.nativeHandle); + } + get id(): ViewId { return native.native_view_get_id(this.nativeHandle); } diff --git a/bindings/js/src/generated/types.h b/bindings/js/src/generated/types.h index e8a05b0a..c3c9d96d 100644 --- a/bindings/js/src/generated/types.h +++ b/bindings/js/src/generated/types.h @@ -503,6 +503,9 @@ inline Value ToValue(const native_view_event_t& event) { case NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_SUBMITTED: result.Set("type", Value::String("textFieldSubmitted")); break; + case NATIVE_VIEW_EVENT_TYPE_UPDATING: + result.Set("type", Value::String("updating")); + break; default: return Value::Null(); } diff --git a/bindings/js/src/generated/view.cc b/bindings/js/src/generated/view.cc index bf1ae3d1..afe9faa2 100644 --- a/bindings/js/src/generated/view.cc +++ b/bindings/js/src/generated/view.cc @@ -114,6 +114,88 @@ napi_value Js_native_view_get_default_backend(napi_env env, napi_callback_info i return Value::Number(static_cast(result)).ToJs(env); } +napi_value Js_native_view_begin_updates(napi_env env, napi_callback_info info) { + Args args(env, info); + if (!args.ok()) { + return nullptr; + } + Arena arena; + (void)arena; + OnMainThread([&] { return native_view_begin_updates(); }); + return Undefined(env); +} + +napi_value Js_native_view_end_updates(napi_env env, napi_callback_info info) { + Args args(env, info); + if (!args.ok()) { + return nullptr; + } + Arena arena; + (void)arena; + bool p0 = {}; + if (!GetBool(env, args[0], &p0)) { + return nullptr; + } + OnMainThread([&] { return native_view_end_updates(p0); }); + return Undefined(env); +} + +napi_value Js_native_view_is_updating(napi_env env, napi_callback_info info) { + Args args(env, info); + if (!args.ok()) { + return nullptr; + } + Arena arena; + (void)arena; + auto result = OnMainThread([&] { return native_view_is_updating(); }); + return Value::Bool(result).ToJs(env); +} + +napi_value Js_native_view_request_update(napi_env env, napi_callback_info info) { + Args args(env, info); + if (!args.ok()) { + return nullptr; + } + Arena arena; + (void)arena; + uint64_t self = 0; + if (!GetHandle(env, args[0], &self)) { + return nullptr; + } + auto result = OnMainThread([&] { return native_view_request_update(self); }); + return Value::Bool(result).ToJs(env); +} + +napi_value Js_native_view_cancel_update(napi_env env, napi_callback_info info) { + Args args(env, info); + if (!args.ok()) { + return nullptr; + } + Arena arena; + (void)arena; + uint64_t self = 0; + if (!GetHandle(env, args[0], &self)) { + return nullptr; + } + OnMainThread([&] { return native_view_cancel_update(self); }); + return Undefined(env); +} + +napi_value Js_native_view_is_update_pending(napi_env env, napi_callback_info info) { + Args args(env, info); + if (!args.ok()) { + return nullptr; + } + Arena arena; + (void)arena; + uint64_t self = 0; + if (!GetHandle(env, args[0], &self)) { + return nullptr; + } + auto result = OnMainThread([&] { return native_view_is_update_pending(self); }); + return Value::Bool(result).ToJs(env); +} + napi_value Js_native_view_get_id(napi_env env, napi_callback_info info) { Args args(env, info); if (!args.ok()) { @@ -1417,6 +1499,12 @@ void RegisterView(napi_env env, napi_value exports) { Export(env, exports, "native_view_is_backend_supported", Js_native_view_is_backend_supported); Export(env, exports, "native_view_set_default_backend", Js_native_view_set_default_backend); Export(env, exports, "native_view_get_default_backend", Js_native_view_get_default_backend); + Export(env, exports, "native_view_begin_updates", Js_native_view_begin_updates); + Export(env, exports, "native_view_end_updates", Js_native_view_end_updates); + Export(env, exports, "native_view_is_updating", Js_native_view_is_updating); + Export(env, exports, "native_view_request_update", Js_native_view_request_update); + Export(env, exports, "native_view_cancel_update", Js_native_view_cancel_update); + Export(env, exports, "native_view_is_update_pending", Js_native_view_is_update_pending); Export(env, exports, "native_view_get_id", Js_native_view_get_id); Export(env, exports, "native_view_get_backend", Js_native_view_get_backend); Export(env, exports, "native_view_add_subview", Js_native_view_add_subview); diff --git a/bindings/js/test/smoke.test.ts b/bindings/js/test/smoke.test.ts index c40a76d6..e5934580 100644 --- a/bindings/js/test/smoke.test.ts +++ b/bindings/js/test/smoke.test.ts @@ -3,7 +3,20 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { Color, NativeObject, Preferences, Shortcut, ShortcutManager, ShortcutScope } from "../lib/index.ts"; +import { Color, NativeObject, Preferences, Shortcut, ShortcutManager, ShortcutScope, View } from "../lib/index.ts"; + +test("nested view batches cross the C ABI", () => { + assert.equal(View.isUpdating(), false); + View.beginUpdates(); + try { + View.beginUpdates(); + View.endUpdates(false); + assert.equal(View.isUpdating(), true); + } finally { + View.endUpdates(true); + } + assert.equal(View.isUpdating(), false); +}); test("structs round-trip through the C ABI", () => { assert.deepEqual(Color.fromHex("#ff8000"), { r: 255, g: 128, b: 0, a: 255 }); diff --git a/bindings/python/nativeapi/__init__.py b/bindings/python/nativeapi/__init__.py index 4ad82967..964e779f 100644 --- a/bindings/python/nativeapi/__init__.py +++ b/bindings/python/nativeapi/__init__.py @@ -189,6 +189,7 @@ ViewFocusedEvent, ViewId, ViewLayout, + ViewUpdatingEvent, ) from .window import ( ResizeEdge, @@ -359,6 +360,7 @@ "ViewFocusedEvent", "ViewId", "ViewLayout", + "ViewUpdatingEvent", "VisualEffect", "Window", "WindowBlurredEvent", diff --git a/bindings/python/nativeapi/_capi.py b/bindings/python/nativeapi/_capi.py index d7f0a660..c44b4c81 100644 --- a/bindings/python/nativeapi/_capi.py +++ b/bindings/python/nativeapi/_capi.py @@ -1840,6 +1840,18 @@ class native_window_list_t(Structure): ], ) native_view_get_default_backend = function("native_view_get_default_backend", c_int, []) +native_view_begin_updates = function("native_view_begin_updates", None, []) +native_view_end_updates = function("native_view_end_updates", None, [c_bool]) +native_view_is_updating = function("native_view_is_updating", c_bool, []) +native_view_request_update = function("native_view_request_update", c_bool, [c_uint64]) +native_view_cancel_update = function("native_view_cancel_update", None, [c_uint64]) +native_view_is_update_pending = function( + "native_view_is_update_pending", + c_bool, + [ + c_uint64, + ], +) native_view_get_id = function("native_view_get_id", c_uint, [c_uint64]) native_view_get_backend = function("native_view_get_backend", c_int, [c_uint64]) native_view_add_subview = function( diff --git a/bindings/python/nativeapi/view.py b/bindings/python/nativeapi/view.py index f269279c..d5e1c3b9 100644 --- a/bindings/python/nativeapi/view.py +++ b/bindings/python/nativeapi/view.py @@ -63,6 +63,8 @@ def _from_c(raw: _C.native_view_event_t) -> ViewEvent | None: ) if raw.type == 4: return TextFieldSubmittedEvent(raw.view_id) + if raw.type == 5: + return ViewUpdatingEvent(raw.view_id) return None @@ -91,6 +93,11 @@ class TextFieldSubmittedEvent(ViewEvent): pass +@dataclass(frozen=True) +class ViewUpdatingEvent(ViewEvent): + pass + + class View(_rt.NativeObject): """Owned reference to a native View. @@ -134,6 +141,31 @@ def get_default_backend() -> ViewBackend: raw = _C.native_view_get_default_backend() return _rt.to_enum(ViewBackend, raw) + @staticmethod + def begin_updates() -> None: + _C.native_view_begin_updates() + + @staticmethod + def end_updates(redraw: bool) -> None: + _C.native_view_end_updates(redraw) + + @staticmethod + def is_updating() -> bool: + raw = _C.native_view_is_updating() + return raw + + def request_update(self) -> bool: + raw = _C.native_view_request_update(self._handle) + return raw + + def cancel_update(self) -> None: + _C.native_view_cancel_update(self._handle) + + @property + def is_update_pending(self) -> bool: + raw = _C.native_view_is_update_pending(self._handle) + return raw + @property def id(self) -> ViewId: raw = _C.native_view_get_id(self._handle) diff --git a/bindings/python/tests/test_smoke.py b/bindings/python/tests/test_smoke.py index 2af6b141..0a508ef1 100644 --- a/bindings/python/tests/test_smoke.py +++ b/bindings/python/tests/test_smoke.py @@ -26,6 +26,19 @@ def test_every_export_resolves(): assert getattr(nativeapi, name) is not None, name +def test_view_update_batches_cross_the_c_abi(): + view = nativeapi.View + assert not view.is_updating() + view.begin_updates() + try: + view.begin_updates() + view.end_updates(False) + assert view.is_updating() + finally: + view.end_updates(True) + assert not view.is_updating() + + def test_structs_round_trip_through_the_c_abi(): assert Color.from_hex("#ff8000") == Color(255, 128, 0, 255) assert Color.from_rgba(1, 2, 3, 4).to_rgba() == 0x01020304 diff --git a/bindings/rust/cnativeapi/src/bindings.rs b/bindings/rust/cnativeapi/src/bindings.rs index ac5d9acb..70b8237d 100644 --- a/bindings/rust/cnativeapi/src/bindings.rs +++ b/bindings/rust/cnativeapi/src/bindings.rs @@ -378,6 +378,7 @@ pub const NATIVE_VIEW_EVENT_TYPE_BLURRED: native_view_event_type_t = 1; pub const NATIVE_VIEW_EVENT_TYPE_BUTTON_CLICKED: native_view_event_type_t = 2; pub const NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_CHANGED: native_view_event_type_t = 3; pub const NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_SUBMITTED: native_view_event_type_t = 4; +pub const NATIVE_VIEW_EVENT_TYPE_UPDATING: native_view_event_type_t = 5; #[doc = " Which concrete ViewEvent arrived."] pub type native_view_event_type_t = ::std::os::raw::c_uint; #[doc = " One ViewEvent, tagged by its concrete type.\n\n Synchronous callbacks borrow this payload until they return. Async callbacks\n borrow it until event_delivery_complete. Copy anything needed after that."] @@ -457,6 +458,24 @@ unsafe extern "C" { unsafe extern "C" { pub fn native_view_get_default_backend() -> native_view_backend_t; } +unsafe extern "C" { + pub fn native_view_begin_updates(); +} +unsafe extern "C" { + pub fn native_view_end_updates(redraw: bool); +} +unsafe extern "C" { + pub fn native_view_is_updating() -> bool; +} +unsafe extern "C" { + pub fn native_view_request_update(view: native_view_t) -> bool; +} +unsafe extern "C" { + pub fn native_view_cancel_update(view: native_view_t); +} +unsafe extern "C" { + pub fn native_view_is_update_pending(view: native_view_t) -> bool; +} unsafe extern "C" { pub fn native_view_get_id(view: native_view_t) -> native_view_id_t; } diff --git a/bindings/rust/nativeapi/src/view.rs b/bindings/rust/nativeapi/src/view.rs index cbd9bc0e..1dfe126c 100644 --- a/bindings/rust/nativeapi/src/view.rs +++ b/bindings/rust/nativeapi/src/view.rs @@ -116,6 +116,7 @@ pub enum ViewEvent { ButtonClicked { view_id: ViewId }, TextFieldChanged { view_id: ViewId, text: Option }, TextFieldSubmitted { view_id: ViewId }, + Updating { view_id: ViewId }, } impl ViewEvent { @@ -126,6 +127,7 @@ impl ViewEvent { cnativeapi::NATIVE_VIEW_EVENT_TYPE_BUTTON_CLICKED => Self::ButtonClicked { view_id: raw.view_id }, cnativeapi::NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_CHANGED => Self::TextFieldChanged { view_id: raw.view_id, text: if raw.data.text_field_changed.text.is_null() { None } else { Some(CStr::from_ptr(raw.data.text_field_changed.text).to_string_lossy().into_owned()) } }, cnativeapi::NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_SUBMITTED => Self::TextFieldSubmitted { view_id: raw.view_id }, + cnativeapi::NATIVE_VIEW_EVENT_TYPE_UPDATING => Self::Updating { view_id: raw.view_id }, _ => return None, }) } @@ -199,6 +201,42 @@ impl View { } } + pub fn begin_updates() { + unsafe { + cnativeapi::native_view_begin_updates(); + } + } + + pub fn end_updates(redraw: bool) { + unsafe { + cnativeapi::native_view_end_updates(redraw); + } + } + + pub fn is_updating() -> bool { + unsafe { + cnativeapi::native_view_is_updating() + } + } + + pub fn request_update(&self) -> bool { + unsafe { + cnativeapi::native_view_request_update(self.handle) + } + } + + pub fn cancel_update(&self) { + unsafe { + cnativeapi::native_view_cancel_update(self.handle); + } + } + + pub fn is_update_pending(&self) -> bool { + unsafe { + cnativeapi::native_view_is_update_pending(self.handle) + } + } + pub fn id(&self) -> ViewId { unsafe { cnativeapi::native_view_get_id(self.handle) diff --git a/bindings/swift/Package.swift b/bindings/swift/Package.swift index 8ba3e8a3..07db7891 100644 --- a/bindings/swift/Package.swift +++ b/bindings/swift/Package.swift @@ -122,7 +122,8 @@ let package = Package( name: "NativeAPI", platforms: [.macOS(.v11)], products: [ - .library(name: "NativeAPI", targets: ["NativeAPI"]) + .library(name: "NativeAPI", targets: ["NativeAPI"]), + .library(name: "CNativeAPI", targets: ["CNativeAPI"]) ], targets: systemTargets + [ .target( diff --git a/bindings/swift/README.md b/bindings/swift/README.md index 6de2d1a0..bcb2c944 100644 --- a/bindings/swift/README.md +++ b/bindings/swift/README.md @@ -1,6 +1,6 @@ # nativeapi for Swift -Native desktop APIs for Swift on macOS, backed by the libnativeapi C ABI. +Native desktop APIs for Swift on macOS, Windows and Linux, backed by the libnativeapi C ABI. The generated API covers windows, views, menus, tray icons, displays, keyboard, dialogs, preferences, storage and the other APIs currently exposed by the C ABI. @@ -11,8 +11,8 @@ yet. ## Requirements -- macOS 11 or later (the binding is built and tested on macOS; the core also - supports Windows and Linux, where SwiftPM would need each platform's setup) +- macOS 11 or later, Windows with the official Swift toolchain and Visual + Studio C++ build tools, or Linux with GTK 3, X11 and XI development packages - Swift 5.9 or later (Xcode 15+); the package builds in Swift 5 language mode - The `core` submodule checked out: @@ -56,6 +56,21 @@ swift build swift test ``` +On Windows, enable Developer Mode for symlinks and prepare the source link +before building (also works when Git checked it out as a plain text file): + +```powershell +./scripts/prepare-windows.ps1 +swift build +swift test +``` + +The Windows target compiles the Win32 backend, without the optional WinUI 3 +layer. Core is compiled into the Swift executable, which links the Windows +system libraries. +Use a Swift version compatible with the installed MSVC headers. Swift 6.4.2 +has been used for the Windows source build. + ## API conventions - **Constructors and factories** are static, and return `nil` when the native diff --git a/bindings/swift/Sources/NativeAPI/View.swift b/bindings/swift/Sources/NativeAPI/View.swift index dffa72f7..1bfaf581 100644 --- a/bindings/swift/Sources/NativeAPI/View.swift +++ b/bindings/swift/Sources/NativeAPI/View.swift @@ -90,6 +90,7 @@ public enum ViewEvent { case buttonClicked(viewId: ViewId) case textFieldChanged(viewId: ViewId, text: String?) case textFieldSubmitted(viewId: ViewId) + case updating(viewId: ViewId) init?(raw: native_view_event_t) { switch raw.type { @@ -98,6 +99,7 @@ public enum ViewEvent { case NATIVE_VIEW_EVENT_TYPE_BUTTON_CLICKED: self = .buttonClicked(viewId: raw.view_id) case NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_CHANGED: self = .textFieldChanged(viewId: raw.view_id, text: raw.data.text_field_changed.text.map { String(cString: $0) }) case NATIVE_VIEW_EVENT_TYPE_TEXT_FIELD_SUBMITTED: self = .textFieldSubmitted(viewId: raw.view_id) + case NATIVE_VIEW_EVENT_TYPE_UPDATING: self = .updating(viewId: raw.view_id) default: return nil } } @@ -161,6 +163,30 @@ public class View { return ViewBackend(raw: native_view_get_default_backend()) } + public static func beginUpdates() -> Void { + native_view_begin_updates() + } + + public static func endUpdates(_ redraw: Bool) -> Void { + native_view_end_updates(redraw) + } + + public static func isUpdating() -> Bool { + return native_view_is_updating() + } + + public func requestUpdate() -> Bool { + return native_view_request_update(nativeHandle) + } + + public func cancelUpdate() -> Void { + native_view_cancel_update(nativeHandle) + } + + public var isUpdatePending: Bool { + return native_view_is_update_pending(nativeHandle) + } + public var id: ViewId { return native_view_get_id(nativeHandle) } diff --git a/bindings/swift/scripts/prepare-windows.ps1 b/bindings/swift/scripts/prepare-windows.ps1 new file mode 100644 index 00000000..257d73c3 --- /dev/null +++ b/bindings/swift/scripts/prepare-windows.ps1 @@ -0,0 +1,41 @@ +param() +$ErrorActionPreference = 'Stop' + +# Git can check a symlink out as a text file when core.symlinks is false. +# SwiftPM then silently discovers no core sources and fails at the umbrella +# header. Repair only this known link; never touch the core checkout itself. +$packageRoot = Split-Path -Parent $PSScriptRoot +$workspaceRoot = [IO.Path]::GetFullPath((Join-Path $packageRoot '../..')) +$coreRoot = Join-Path $workspaceRoot 'core' +$linkPath = Join-Path $packageRoot 'Sources/CNativeAPI/core' +if (!(Test-Path -LiteralPath (Join-Path $coreRoot 'include/nativeapi.h'))) { + throw "Initialize core first: git -C `"$workspaceRoot`" submodule update --init core" +} +$item = Get-Item -LiteralPath $linkPath -Force -ErrorAction SilentlyContinue +if ($item -and $item.LinkType) { + $targets = @($item.Target) + if ($targets.Count -ne 1) { throw "Unexpected core link targets: $($item.Target)" } + $target = [string]$targets[0] + $resolved = if ([IO.Path]::IsPathRooted($target)) { + [IO.Path]::GetFullPath($target) + } else { + [IO.Path]::GetFullPath((Join-Path (Split-Path $linkPath -Parent) $target)) + } + if ($resolved -ne $coreRoot) { throw "Unexpected core link target: $resolved" } + Write-Output 'NativeAPI Swift core link is ready.' + exit 0 +} +if ($item) { + if ($item.PSIsContainer -or (Get-Content -LiteralPath $linkPath -Raw).Trim() -ne '../../../../core') { + throw "Refusing to replace unexpected content at $linkPath" + } + Remove-Item -LiteralPath $linkPath +} +try { + New-Item -ItemType SymbolicLink -Path $linkPath -Target '../../../../core' | Out-Null +} catch { + # Restore Git's placeholder if the host does not allow symlink creation. + [IO.File]::WriteAllText($linkPath, '../../../../core') + throw 'Enable Windows Developer Mode (or symlink privileges), then run prepare-windows.ps1 again.' +} +Write-Output 'NativeAPI Swift core link is ready.' diff --git a/core b/core index 677c4c94..ab3e0147 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 677c4c946526853c71358ce602e7eeb91d4c40b3 +Subproject commit ab3e0147998b72c90e4e278c81afd5ca9b4527df diff --git a/examples/dart_view_example/lib/src/event_log.dart b/examples/dart_view_example/lib/src/event_log.dart index 4b06aceb..6496d675 100644 --- a/examples/dart_view_example/lib/src/event_log.dart +++ b/examples/dart_view_example/lib/src/event_log.dart @@ -65,6 +65,8 @@ final class EventLog { _add(source, 'focused'); case ViewBlurredEvent(): _add(source, 'blurred'); + case ViewUpdatingEvent(): + _add(source, 'updating'); } } diff --git a/specs/view.md b/specs/view.md index 3d168141..86d9351a 100644 --- a/specs/view.md +++ b/specs/view.md @@ -193,9 +193,26 @@ Window ──shared_ptr──▶ root View (包装窗口内容区) View 按各自首选(或固有)尺寸排开所需的大小——主轴首尾相接加间距,交叉轴取最大, 再加内边距;flex 子 View 也按自然尺寸计入。所以嵌套的行列不设 `SetPreferredSize()` 也不会塌成 0。Absolute 容器的固有尺寸是 0(子 View 自己定位)。 -- 布局是**同步的**:任何影响布局的 setter(增删子 View、`SetFrame`、`SetPreferredSize`、 - `SetFlex`、`SetVisible`、固有尺寸型控件的 `SetText`)都在返回前重排该容器及其祖先。 - 简单实现优先;发现性能问题再引入延迟到下一轮主循环的 dirty 标记。 +- 默认布局仍然同步。`View::BeginUpdates()` / `EndUpdates()` 是 UI 线程级、可嵌套的 + 显式批次,覆盖该线程上的所有 View(含游离和借用的原生视图);只在最外层结束时 + 重排 dirty 子树,祖先已 dirty 时合并后代请求。调用必须成对,批次内不运行事件循环。 + 这不是回滚事务:属性立即更新,原生几何可能在结束时才发布。 +- `RequestUpdate()` 在 UI 线程上请求一次异步 `ViewUpdatingEvent`,同一 View 的重复请求 + 合并。事件开始派发后才受理下一次交付,监听器可以请求下一次更新。`CancelUpdate()` 或 + 销毁 View 会取消尚未派发的请求。Windows 根据桌面刷新周期安排派发,并在发布后处理已 + 排队的重绘。实际派发仍受输入和主线程负载影响。 +- 相同属性不触发布局;Absolute 子 View 的纯平移不改变自身子布局或祖先固有尺寸, + 因而不重排整棵树;尺寸变化只重排该子树。Row / Column 的尺寸提示和内容变化仍 + 向根传递布局请求。批次内销毁或重挂的 View 不留下失效的布局请求。 +- Windows 的批次把同父 HWND 的平移交给 `DeferWindowPos`,尺寸变化立即应用供后续 + 嵌套布局和 hit region 使用;几何和可见性变化使用 `SWP_NOREDRAW`,结束时合并受损 + 区域并排队重绘,不强制同步 paint,也不用会改变可见性标志的 `WM_SETREDRAW`。 + 其他原生控件属性仍可立即生效。其他后端共用布局合并,绘制由各自原生调度器负责。 +- 自绘宿主在最外层使用 `EndUpdates(false)` 接管 Windows 几何 / 可见性变化的重绘 + 排队,避免「nativeapi 先 invalidate,宿主再 validate 后重画」的重复区域计算。 + 默认 `true` 保持普通原生控件自动重绘;内层调用不改变外层选择。 +- Windows 的逻辑坐标转像素在正负半像素使用相同的舍入方向,保证跨越零点的整数 + 像素平移不会多跳一像素;子 View 的位置始终相对原生父 View 计算。 - `SetVisible(false)` 的子 View 不占位(等价 Flutter 的 `Visibility` 而非 `Opacity`)。 - 根 View 的尺寸随窗口内容区变化(macOS `NSViewFrameDidChangeNotification`、Windows `WM_SIZE`、GTK `size-allocate`);变化后重排一次。 diff --git a/tools/codegen/bindings/src/python.rs b/tools/codegen/bindings/src/python.rs index 6addf689..3aee99da 100644 --- a/tools/codegen/bindings/src/python.rs +++ b/tools/codegen/bindings/src/python.rs @@ -579,7 +579,7 @@ fn render_header_functions( if lines.is_empty() { return; } - let path = header.path.to_string_lossy(); + let path = header.path.to_string_lossy().replace('\\', "/"); let name = path.rsplit("/src/").next().unwrap_or(&path); writeln!(out, "\n# {name}\n").unwrap(); for line in lines { @@ -833,7 +833,7 @@ fn public_module(api: &Api, header: &Header, origins: &TypeOrigins, prefix: &str } let mut out = String::from(BANNER); - let path = header.path.to_string_lossy(); + let path = header.path.to_string_lossy().replace('\\', "/"); let name = path.rsplit("/src/").next().unwrap_or(&path); writeln!(out, "\"\"\"Generated from {name}.\"\"\"\n").unwrap(); writeln!(out, "from __future__ import annotations\n").unwrap(); diff --git a/tools/gui/frame_probe/.gitignore b/tools/gui/frame_probe/.gitignore new file mode 100644 index 00000000..84c048a7 --- /dev/null +++ b/tools/gui/frame_probe/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/tools/gui/frame_probe/CMakeLists.txt b/tools/gui/frame_probe/CMakeLists.txt new file mode 100644 index 00000000..26d3df4a --- /dev/null +++ b/tools/gui/frame_probe/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 3.24) +project(nativeapi_frame_probe LANGUAGES CXX) +if(NOT WIN32) + message(FATAL_ERROR "Desktop duplication frame probe requires Windows") +endif() +add_executable(frame_probe frame_probe.cpp) +target_compile_features(frame_probe PRIVATE cxx_std_17) +target_compile_definitions(frame_probe PRIVATE UNICODE _UNICODE NOMINMAX) +target_link_libraries(frame_probe PRIVATE d3d11 dxgi dwmapi) diff --git a/tools/gui/frame_probe/README.md b/tools/gui/frame_probe/README.md new file mode 100644 index 00000000..6de39dee --- /dev/null +++ b/tools/gui/frame_probe/README.md @@ -0,0 +1,55 @@ +# Windows compositor frame probe + +Build with `cmake -S tools/gui/frame_probe -B tools/gui/frame_probe/build`, then +`cmake --build tools/gui/frame_probe/build --config Release`. + +Run `frame_probe.exe "exact test window title" output.jsonl 30` before starting +the test window. It waits up to 40 seconds for that window, binds to its monitor, +and observes composed desktop images through DXGI Desktop Duplication. The ROI +is the middle 30–65% of the client width and 15–80% of its height. The target must +be visible, stationary and unobscured. The tool never sends input, changes the +display mode, or saves screenshots. An access, rotation, occlusion or capture +failure is an error, not a zero-frame pass. + +When a producer records `frequency` and `samples` with `phase`, `start_qpc`, +`finish_qpc` and `cpu_ms`, join them with: + +```text +python tools/gui/frame_probe/analyze.py capture.jsonl producer.json report.json +``` + +For frame identity, a test-only producer can paint a sequence strip **after its +real WM_PAINT** and record the same nonzero `frame_id` in each sample. Paint 48 +black/white cells, each 3 physical pixels wide and 8 high, at ROI origin + (8, 8). +In least-significant-bit order encode `0xA55A`, the 16-bit sequence, then its +16-bit complement (white = 1). Use unique IDs within one run (at most 65535). +Include marker painting in `cpu_ms` and flush GDI before returning from paint. +The observer validates and decodes the strip independently from desktop pixels; +the analyzer reports the first observation of each producer ID, missing IDs, +intervals and update-to-composed-marker latency. Capture must continue briefly +after the final producer sample to observe its asynchronous presentation. +The matched-ID report also includes refresh-cycle counts and complete one-second +frame counts. Use these to check sustained cadence; an average near 60 Hz alone +does not establish smooth presentation. Missing producer IDs remain explicit. + +This marker is test instrumentation, not part of a production UI. Its cost and +the observer's CPU/readback load remain in the paced test. Observing a marker +proves that the corresponding paint reached the compositor; it does not prove +that every pixel was published atomically. Keep pixel correctness tests separate. + +Each record contains the desktop image's `LastPresentTime` QPC timestamp, capture +completion time, `AccumulatedFrames`, and a sampled RGB content hash. Pointer-only +updates are ignored. Compare **changed target hashes**, not all desktop updates, +against the test's steady-state QPC interval. Report both changed-frame intervals +and frames accumulated by the observer; accumulation can hide intermediate +frames and prevents a claim that every application frame was displayed. + +The metadata includes monitor refresh and DWM refresh. A 60 Hz producer on a +165 Hz monitor naturally alternates between display intervals of two or three +refreshes. A desktop capture observes composed output; it does not measure the +panel's scanout, remote-stream delivery, or input-to-photon latency. Hash changes +alone cannot distinguish a partially published frame from a complete one: pair +them with application timing records and pixel correctness tests. + +API semantics: [DXGI frame information](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_2/ns-dxgi1_2-dxgi_outdupl_frame_info), +[AcquireNextFrame](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgioutputduplication-acquirenextframe). diff --git a/tools/gui/frame_probe/analyze.py b/tools/gui/frame_probe/analyze.py new file mode 100644 index 00000000..f4a1eb4f --- /dev/null +++ b/tools/gui/frame_probe/analyze.py @@ -0,0 +1,183 @@ +"""Join compositor QPC samples with an application's paced frame records.""" + +import argparse +import collections +import itertools +import json +import math +import statistics +from pathlib import Path + + +def statistics_for(values): + values = sorted(values) + if not values: + return {"count": 0} + return { + "count": len(values), + "mean_ms": statistics.mean(values), + "p95_ms": values[math.ceil(len(values) * 0.95) - 1], + "p99_ms": values[math.ceil(len(values) * 0.99) - 1], + "max_ms": values[-1], + } + + +def analyze(capture, producer): + records = [json.loads(line) for line in Path(capture).read_text().splitlines()] + meta = records[0] + if records[-1].get("type") != "complete": + raise ValueError("Capture did not finish successfully") + app = json.loads(Path(producer).read_text(encoding="utf-8-sig")) + frequency = app["frequency"] + if frequency != meta["frequency"]: + raise ValueError("Capture and producer clocks disagree") + samples = [s for s in app["samples"] if s["phase"] == "steady"] + if len(samples) < 2: + raise ValueError("Need at least two steady producer samples") + start, end = samples[0]["start_qpc"], samples[-1]["finish_qpc"] + observations = [r for r in records if r.get("type") == "frame"] + if ( + not observations + or observations[0]["present_qpc"] > start + or observations[-1]["present_qpc"] < end + ): + raise ValueError("Capture does not cover the entire steady producer interval") + frames = [ + r + for r in records + if r.get("type") == "frame" and start <= r["present_qpc"] <= end + ] + changed = [r for r in frames if r["changed"]] + if len(changed) < 2: + raise ValueError("Need at least two changed composed frames") + intervals = [ + (b["present_qpc"] - a["present_qpc"]) * 1000 / frequency + for a, b in itertools.pairwise(changed) + ] + hashes = collections.Counter(r["hash"] for r in changed) + refresh_hz = ( + meta["dwm_refresh_numerator"] / meta["dwm_refresh_denominator"] + if meta["dwm_refresh_denominator"] + else meta["refresh_hz"] + ) + result = { + "capture": str(capture), + "producer": str(producer), + "metadata": meta, + "steady_seconds": (end - start) / frequency, + "target_hz": app["target_hz"], + "produced_samples": len(samples), + "changed_composed_frames": len(changed), + "changed_frame_rate_hz": ( + (len(changed) - 1) + * frequency + / (changed[-1]["present_qpc"] - changed[0]["present_qpc"]) + ), + "producer_rate_hz": (len(samples) - 1) + * frequency + / (samples[-1]["start_qpc"] - start), + "producer_cpu": statistics_for([s["cpu_ms"] for s in samples]), + "composed_frame_intervals": statistics_for(intervals), + "intervals_over_33_34_ms": sum(v > 33.34 for v in intervals), + "intervals_over_50_ms": sum(v > 50 for v in intervals), + "observer_accumulated_updates": sum( + max(0, r["accumulated"] - 1) for r in frames + ), + "observer_max_accumulated": max(r["accumulated"] for r in frames), + "display_cycle_histogram": dict( + sorted( + collections.Counter( + round(v * refresh_hz / 1000) for v in intervals + ).items() + ) + ), + "distinct_target_hashes": len(hashes), + "most_common_hashes": hashes.most_common(25), + "limitations": [ + "Composed desktop output, not panel scanout or remote stream delivery.", + "Hash changes are not frame IDs; partial publications can also change pixels.", + "Accumulated observer updates can hide intermediate composed images.", + "Producer runs at target_hz; output intervals are quantized to monitor refresh.", + ], + } + if samples[0].get("frame_id"): + source = {s["frame_id"]: s for s in samples} + if len(source) != len(samples): + raise ValueError("Producer frame IDs must be unique") + matched = {} + for record in records: + frame_id = record.get("frame_id", 0) + if ( + frame_id in source + and record["present_qpc"] >= source[frame_id]["start_qpc"] + ): + matched.setdefault(frame_id, record["present_qpc"]) + times = sorted(matched.values()) + result["matched_frame_ids"] = len(matched) + result["missing_producer_frame_count"] = len(source) - len(matched) + result["missing_producer_frame_ids"] = sorted(set(source) - set(matched)) + result["matched_frame_rate_hz"] = ( + ((len(times) - 1) * frequency / (times[-1] - times[0])) + if len(times) > 1 + else 0 + ) + result["matched_frame_intervals"] = statistics_for( + [(b - a) * 1000 / frequency for a, b in itertools.pairwise(times)] + ) + result["matched_display_cycle_histogram"] = dict( + sorted( + collections.Counter( + round((b - a) * refresh_hz / frequency) + for a, b in itertools.pairwise(times) + ).items() + ) + ) + # Count complete one-second windows; exclude the partial last window. + result["matched_frames_per_second"] = ( + [ + sum( + times[0] + second * frequency + <= t + < times[0] + (second + 1) * frequency + for t in times + ) + for second in range(int((times[-1] - times[0]) / frequency)) + ] + if times + else [] + ) + result["matched_intervals_over_33_34_ms"] = sum( + (b - a) * 1000 / frequency > 33.34 for a, b in itertools.pairwise(times) + ) + result["update_to_composed_marker"] = statistics_for( + [ + (time - source[frame_id]["start_qpc"]) * 1000 / frequency + for frame_id, time in matched.items() + ] + ) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("capture") + parser.add_argument("producer") + parser.add_argument("output") + args = parser.parse_args() + result = analyze(args.capture, args.producer) + Path(args.output).write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print( + json.dumps( + { + k: v + for k, v in result.items() + if k + not in ( + "most_common_hashes", + "limitations", + "missing_producer_frame_ids", + ) + }, + indent=2, + ) + ) diff --git a/tools/gui/frame_probe/frame_probe.cpp b/tools/gui/frame_probe/frame_probe.cpp new file mode 100644 index 00000000..65f86bf6 --- /dev/null +++ b/tools/gui/frame_probe/frame_probe.cpp @@ -0,0 +1,224 @@ +// Read-only compositor observation, scoped to a visible client-area rectangle. +// Usage: frame_probe "exact window title" output.jsonl seconds +// No screenshot files, global input, display-mode changes or injected code. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using Microsoft::WRL::ComPtr; + +static void Check(HRESULT value, const char *operation) { + if (FAILED(value)) { + std::cerr << operation << " HRESULT=0x" << std::hex << unsigned(value) + << '\n'; + throw std::runtime_error(operation); + } +} +static int64_t Now() { + LARGE_INTEGER time; + QueryPerformanceCounter(&time); + return time.QuadPart; +} + +int wmain(int argc, wchar_t **argv) { + if (argc != 4) { + std::cerr << "Usage: frame_probe title output.jsonl seconds\n"; + return 2; + } + SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); + try { + LARGE_INTEGER frequency; + QueryPerformanceFrequency(&frequency); + const auto waiting = Now(); + HWND target = nullptr; + while (!(target = FindWindowW(nullptr, argv[1]))) { + if (Now() - waiting > frequency.QuadPart * 40) + throw std::runtime_error("window not found"); + Sleep(20); + } + DWORD pid = 0; + GetWindowThreadProcessId(target, &pid); + RECT client; + GetClientRect(target, &client); + POINT origin{}; + ClientToScreen(target, &origin); + RECT roi{origin.x + client.right * 30 / 100, + origin.y + client.bottom * 15 / 100, + origin.x + client.right * 65 / 100, + origin.y + client.bottom * 80 / 100}; + const HMONITOR monitor = MonitorFromWindow(target, MONITOR_DEFAULTTONULL); + ComPtr factory; + Check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "CreateDXGIFactory1"); + ComPtr adapter; + ComPtr output; + DXGI_OUTPUT_DESC description{}; + for (UINT a = 0; !output; ++a) { + ComPtr next; + if (factory->EnumAdapters1(a, &next) == DXGI_ERROR_NOT_FOUND) + break; + for (UINT o = 0;; ++o) { + ComPtr candidate; + if (next->EnumOutputs(o, &candidate) == DXGI_ERROR_NOT_FOUND) + break; + Check(candidate->GetDesc(&description), "GetDesc"); + if (description.Monitor == monitor) { + adapter = next; + Check(candidate.As(&output), "IDXGIOutput1"); + break; + } + } + } + if (!output) + throw std::runtime_error("target monitor not found"); + if (description.Rotation != DXGI_MODE_ROTATION_IDENTITY) + throw std::runtime_error("rotated output requires a rotated capture ROI"); + if (roi.left < description.DesktopCoordinates.left || + roi.top < description.DesktopCoordinates.top || + roi.right > description.DesktopCoordinates.right || + roi.bottom > description.DesktopCoordinates.bottom) + throw std::runtime_error( + "capture ROI is not entirely on the target monitor"); + ComPtr device; + ComPtr context; + Check(D3D11CreateDevice(adapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, + nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, + &context), + "D3D11CreateDevice"); + ComPtr duplication; + Check(output->DuplicateOutput(device.Get(), &duplication), + "DuplicateOutput"); + D3D11_TEXTURE2D_DESC stage{}; + stage.Width = roi.right - roi.left; + stage.Height = roi.bottom - roi.top; + stage.MipLevels = stage.ArraySize = 1; + stage.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + stage.SampleDesc.Count = 1; + stage.Usage = D3D11_USAGE_STAGING; + stage.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + ComPtr readback; + Check(device->CreateTexture2D(&stage, nullptr, &readback), + "CreateTexture2D"); + D3D11_BOX box{UINT(roi.left - description.DesktopCoordinates.left), + UINT(roi.top - description.DesktopCoordinates.top), + 0, + UINT(roi.right - description.DesktopCoordinates.left), + UINT(roi.bottom - description.DesktopCoordinates.top), + 1}; + DEVMODEW mode{}; + mode.dmSize = sizeof(mode); + EnumDisplaySettingsW(description.DeviceName, ENUM_CURRENT_SETTINGS, &mode); + DWM_TIMING_INFO timing{}; + timing.cbSize = sizeof(timing); + const auto timingResult = DwmGetCompositionTimingInfo(nullptr, &timing); + std::ofstream log(argv[2]); + if (!log) + throw std::runtime_error("cannot write capture log"); + log << "{\"type\":\"metadata\",\"pid\":" << pid + << ",\"frequency\":" << frequency.QuadPart + << ",\"refresh_hz\":" << mode.dmDisplayFrequency + << ",\"dwm_refresh_numerator\":" + << (SUCCEEDED(timingResult) ? timing.rateRefresh.uiNumerator : 0) + << ",\"dwm_refresh_denominator\":" + << (SUCCEEDED(timingResult) ? timing.rateRefresh.uiDenominator : 0) + << ",\"roi\":[" << roi.left << ',' << roi.top << ',' << roi.right << ',' + << roi.bottom << "]}\n"; + log.flush(); + const auto start = Now(); + uint64_t previous = 0; + size_t changes = 0, frames = 0; + while (Now() - start < std::stod(argv[3]) * frequency.QuadPart && + IsWindow(target)) { + DXGI_OUTDUPL_FRAME_INFO frame{}; + ComPtr resource; + const auto result = duplication->AcquireNextFrame(100, &frame, &resource); + if (result == DXGI_ERROR_WAIT_TIMEOUT) + continue; + Check(result, "AcquireNextFrame"); + if (!frame.LastPresentTime.QuadPart) { + duplication->ReleaseFrame(); + continue; + } + POINT current{}; + ClientToScreen(target, ¤t); + if (!IsWindow(target) || !IsWindowVisible(target) || IsIconic(target)) { + duplication->ReleaseFrame(); + break; + } + if (current.x != origin.x || current.y != origin.y) + throw std::runtime_error("target moved during capture"); + RECT current_client{}; + GetClientRect(target, ¤t_client); + if (!EqualRect(&client, ¤t_client)) + throw std::runtime_error("target resized during capture"); + if (frame.ProtectedContentMaskedOut) + throw std::runtime_error("capture contains masked pixels"); + for (POINT point : + {POINT{roi.left, roi.top}, POINT{roi.right - 1, roi.bottom - 1}, + POINT{(roi.left + roi.right) / 2, (roi.top + roi.bottom) / 2}}) { + DWORD owner = 0; + GetWindowThreadProcessId(WindowFromPoint(point), &owner); + if (owner != pid) + throw std::runtime_error( + "capture ROI is occluded by another process"); + } + ComPtr texture; + Check(resource.As(&texture), "frame texture"); + context->CopySubresourceRegion(readback.Get(), 0, 0, 0, 0, texture.Get(), + 0, &box); + duplication->ReleaseFrame(); + D3D11_MAPPED_SUBRESOURCE pixels{}; + Check(context->Map(readback.Get(), 0, D3D11_MAP_READ, 0, &pixels), "Map"); + // Sample every fourth column, every row. Ignore alpha and hardware mouse + // updates; hash only the selected application's composed content pixels. + uint64_t hash = 14695981039346656037ull; + for (UINT y = 0; y < stage.Height; ++y) { + const auto *row = reinterpret_cast( + static_cast(pixels.pData) + y * pixels.RowPitch); + for (UINT x = 0; x < stage.Width; x += 4) { + hash ^= row[x] & 0xffffff; + hash *= 1099511628211ull; + } + } + uint64_t marker = 0; + if (stage.Width >= 152 && stage.Height >= 16) { + const auto *row = reinterpret_cast( + static_cast(pixels.pData) + 12 * pixels.RowPitch); + for (unsigned bit = 0; bit < 48; ++bit) { + const auto rgb = row[9 + bit * 3]; + if (((rgb >> 16) & 255) + ((rgb >> 8) & 255) + (rgb & 255) > 384) + marker |= uint64_t(1) << bit; + } + } + const unsigned sequence = unsigned((marker >> 16) & 0xffff); + const bool marker_valid = + (marker & 0xffff) == 0xA55A && + (sequence ^ unsigned((marker >> 32) & 0xffff)) == 0xffff; + context->Unmap(readback.Get(), 0); + ++frames; + log << "{\"type\":\"frame\",\"present_qpc\":" + << frame.LastPresentTime.QuadPart << ",\"captured_qpc\":" << Now() + << ",\"accumulated\":" << frame.AccumulatedFrames + << ",\"changed\":" << (hash != previous ? "true" : "false") + << ",\"frame_id\":" << (marker_valid ? sequence : 0) << ",\"hash\":\"" + << std::hex << hash << std::dec << "\"}\n"; + changes += hash != previous; + previous = hash; + } + log << "{\"type\":\"complete\",\"frames\":" << frames + << ",\"changes\":" << changes << "}\n"; + std::cout << "Captured " << frames << " desktop updates, " << changes + << " target content changes\n"; + return frames ? 0 : 1; + } catch (const std::exception &e) { + std::cerr << e.what() << '\n'; + return 1; + } +} diff --git a/website/content/api/view.json b/website/content/api/view.json index c111d64c..e02bd5c0 100644 --- a/website/content/api/view.json +++ b/website/content/api/view.json @@ -350,6 +350,282 @@ } } }, + { + "key": "View::BeginUpdates", + "kind": "static", + "doc": { + "summary": "Begins a nested batch of view updates on the current UI thread.", + "details": "All views on this thread participate, including detached and borrowed views. Layout is coalesced until the matching outermost EndUpdates(). Stored properties change immediately; native geometry may lag until the batch ends. Pair every call with EndUpdates() on the same thread, without pumping the event loop inside the batch. This is not a rollback transaction.", + "notes": [ + { + "kind": "note", + "text": "Platform availability:\n- macOS: Fully supported - Coalesces the shared view layout.\n- Windows: Fully supported - Also batches Win32 moves and defers geometry and visibility repaint; other control properties may update immediately. WinUI3 coalesces shared layout and uses its native rendering scheduler.\n- Linux: Fully supported - Coalesces shared layout; GTK schedules painting.\n- Android: Not applicable - Views are unsupported.\n- iOS: Not applicable - Views are unsupported.\n- OpenHarmony: Fully supported - Coalesces layout on the owning UI thread." + } + ] + }, + "signatures": { + "cpp": { + "name": "BeginUpdates", + "signature": "static void BeginUpdates()" + }, + "csharp": { + "name": "BeginUpdates", + "signature": "public static void BeginUpdates()" + }, + "dart": { + "name": "beginUpdates", + "signature": "static void beginUpdates()" + }, + "go": { + "name": "ViewBeginUpdates", + "signature": "func ViewBeginUpdates()" + }, + "js": { + "name": "beginUpdates", + "signature": "static beginUpdates(): void" + }, + "python": { + "name": "begin_updates", + "signature": "@staticmethod\ndef begin_updates() -> None:" + }, + "rust": { + "name": "begin_updates", + "signature": "pub fn begin_updates()" + }, + "swift": { + "name": "beginUpdates", + "signature": "static func beginUpdates() -> Void" + } + } + }, + { + "key": "View::EndUpdates", + "kind": "static", + "doc": { + "summary": "Ends a batch, applying pending layout at the outermost boundary.", + "details": "An unmatched call is ignored. Win32 repaint is scheduled, never forced synchronously, so callers can finish publishing their own drawing first.", + "params": [ + { + "name": "redraw", + "text": "Whether the outermost call requests Win32 geometry and visibility repaint. Pass false when a host renderer publishes its own damage. Inner calls do not change the outer call's choice. Other backends retain their native paint scheduling." + } + ], + "notes": [ + { + "kind": "see", + "text": "BeginUpdates() for platform availability and pairing requirements." + } + ] + }, + "signatures": { + "cpp": { + "name": "EndUpdates", + "signature": "static void EndUpdates(bool redraw)" + }, + "csharp": { + "name": "EndUpdates", + "signature": "public static void EndUpdates(bool redraw)" + }, + "dart": { + "name": "endUpdates", + "signature": "static void endUpdates(bool redraw)" + }, + "go": { + "name": "ViewEndUpdates", + "signature": "func ViewEndUpdates(redraw bool)" + }, + "js": { + "name": "endUpdates", + "signature": "static endUpdates(redraw: boolean): void" + }, + "python": { + "name": "end_updates", + "signature": "@staticmethod\ndef end_updates(redraw: bool) -> None:" + }, + "rust": { + "name": "end_updates", + "signature": "pub fn end_updates(redraw: bool)" + }, + "swift": { + "name": "endUpdates", + "signature": "static func endUpdates(_ redraw: Bool) -> Void" + } + } + }, + { + "key": "View::IsUpdating", + "kind": "static", + "doc": { + "summary": "Checks if this UI thread has an open view update batch.", + "returns": "true between BeginUpdates() and its matching EndUpdates()." + }, + "signatures": { + "cpp": { + "name": "IsUpdating", + "signature": "static bool IsUpdating()" + }, + "csharp": { + "name": "IsUpdating", + "signature": "public static bool IsUpdating()" + }, + "dart": { + "name": "isUpdating", + "signature": "static bool isUpdating()" + }, + "go": { + "name": "ViewIsUpdating", + "signature": "func ViewIsUpdating() bool" + }, + "js": { + "name": "isUpdating", + "signature": "static isUpdating(): boolean" + }, + "python": { + "name": "is_updating", + "signature": "@staticmethod\ndef is_updating() -> bool:" + }, + "rust": { + "name": "is_updating", + "signature": "pub fn is_updating() -> bool" + }, + "swift": { + "name": "isUpdating", + "signature": "static func isUpdating() -> Bool" + } + } + }, + { + "key": "View::RequestUpdate", + "kind": "method", + "doc": { + "summary": "Requests a coalesced asynchronous ViewUpdatingEvent.", + "details": "Call on the owning UI thread. The view must have shared ownership. This schedules state publication, not an animation or a continuous frame loop. Destruction or CancelUpdate cancels delivery. Listeners must not pump events.", + "returns": "false if unsupported, not shared-owned, or scheduling failed.", + "notes": [ + { + "kind": "note", + "text": "Platform availability:\n- macOS: Supported - Coalesced main-thread dispatch; AppKit owns painting.\n- Windows: Supported for Win32 - Coalesced per UI thread using the observed desktop refresh period (60 Hz fallback), followed by pending native paint. Input may defer delivery. This is not a vsync or frame-rate guarantee.\n- Linux: Supported - Coalesced main-thread dispatch; GTK owns painting.\n- Android: Not applicable - Views are unsupported; returns false.\n- iOS: Not applicable - Views are unsupported; returns false.\n- OpenHarmony: Supported - Coalesced dispatch through the initialized UI host." + } + ] + }, + "signatures": { + "cpp": { + "name": "RequestUpdate", + "signature": "bool RequestUpdate()" + }, + "csharp": { + "name": "RequestUpdate", + "signature": "public bool RequestUpdate()" + }, + "dart": { + "name": "requestUpdate", + "signature": "bool requestUpdate()" + }, + "go": { + "name": "RequestUpdate", + "signature": "func (v *View) RequestUpdate() error" + }, + "js": { + "name": "requestUpdate", + "signature": "requestUpdate(): boolean" + }, + "python": { + "name": "request_update", + "signature": "def request_update(self) -> bool:" + }, + "rust": { + "name": "request_update", + "signature": "pub fn request_update(&self) -> bool" + }, + "swift": { + "name": "requestUpdate", + "signature": "func requestUpdate() -> Bool" + } + } + }, + { + "key": "View::CancelUpdate", + "kind": "method", + "doc": { + "summary": "Cancels this view's pending update without running its listeners." + }, + "signatures": { + "cpp": { + "name": "CancelUpdate", + "signature": "void CancelUpdate()" + }, + "csharp": { + "name": "CancelUpdate", + "signature": "public void CancelUpdate()" + }, + "dart": { + "name": "cancelUpdate", + "signature": "void cancelUpdate()" + }, + "go": { + "name": "CancelUpdate", + "signature": "func (v *View) CancelUpdate()" + }, + "js": { + "name": "cancelUpdate", + "signature": "cancelUpdate(): void" + }, + "python": { + "name": "cancel_update", + "signature": "def cancel_update(self) -> None:" + }, + "rust": { + "name": "cancel_update", + "signature": "pub fn cancel_update(&self)" + }, + "swift": { + "name": "cancelUpdate", + "signature": "func cancelUpdate() -> Void" + } + } + }, + { + "key": "View::IsUpdatePending", + "kind": "method", + "doc": { + "summary": "Checks if a requested update is awaiting delivery.", + "returns": "true after a successful RequestUpdate until delivery or cancellation." + }, + "signatures": { + "cpp": { + "name": "IsUpdatePending", + "signature": "bool IsUpdatePending() const" + }, + "csharp": { + "name": "IsUpdatePending", + "signature": "public bool IsUpdatePending" + }, + "dart": { + "name": "isUpdatePending", + "signature": "bool get isUpdatePending" + }, + "go": { + "name": "IsUpdatePending", + "signature": "func (v *View) IsUpdatePending() bool" + }, + "js": { + "name": "isUpdatePending", + "signature": "get isUpdatePending(): boolean" + }, + "python": { + "name": "is_update_pending", + "signature": "@property\ndef is_update_pending(self) -> bool:" + }, + "rust": { + "name": "is_update_pending", + "signature": "pub fn is_update_pending(&self) -> bool" + }, + "swift": { + "name": "isUpdatePending", + "signature": "var isUpdatePending: Bool" + } + } + }, { "key": "View::GetId", "kind": "method", @@ -4672,6 +4948,48 @@ "signature": "case textFieldSubmitted(viewId: ViewId)" } } + }, + { + "key": "ViewUpdatingEvent", + "kind": "variant", + "doc": { + "summary": "A requested view update is ready to publish on the owning UI thread.", + "details": "Repeated RequestUpdate calls coalesce. Listeners publish their current state; a request made by a listener is delivered in a later update, never recursively." + }, + "signatures": { + "cpp": { + "name": "ViewUpdatingEvent", + "signature": "class ViewUpdatingEvent : public ViewEvent" + }, + "csharp": { + "name": "ViewEvent.Updating", + "signature": "public sealed record Updating(uint ViewId) : ViewEvent;" + }, + "dart": { + "name": "ViewUpdatingEvent", + "signature": "final class ViewUpdatingEvent extends ViewEvent" + }, + "go": { + "name": "ViewEventUpdating", + "signature": "const ViewEventUpdating ViewEventType = 5" + }, + "js": { + "name": "Extract", + "signature": "| { type: \"updating\"; viewId: ViewId }" + }, + "python": { + "name": "ViewUpdatingEvent", + "signature": "@dataclass(frozen=True)\nclass ViewUpdatingEvent(ViewEvent):" + }, + "rust": { + "name": "ViewEvent::Updating", + "signature": "Updating { view_id: ViewId }" + }, + "swift": { + "name": "updating", + "signature": "case updating(viewId: ViewId)" + } + } } ] },