Repository navigation
Description
[Windows] 逐步构建/投递 Moved/Resized 事件拖慢窗口线程,导致无边框边缘拖拽"内容追边框" / Per-resize-step Moved/Resized event construction + delivery on the window thread make frameless edge-drag visibly lag behind the frame (content "trails" the border)
本 issue 提供中英双语:中文在前,英文原文在后(
---分隔)。
Bilingual issue: Chinese first, then the original English text below the separator.
中文版
概述
在 Windows 上,注册了 nativeapi 窗口监听器时,交互式拖拽窗口边缘会出现明显的内容追边框(橡皮筋效应):边框跟着鼠标走,而 Flutter 内容晚几帧才到达。在 sizing 模态循环期间,矩形每变化一步都会产生一条 WM_WINDOWPOSCHANGED;每一步里,nativeapi 的几何子类(geometry subclass)对比快照、查询矩形和 DPI(GetSize())、构造一个 WindowMoved/Resized 事件,并通过 NativeCallable + delivery_is_active/delivery_complete 握手投递给 Dart——这一切都发生在窗口线程上,每秒执行数百次。Dart 侧的帧耗时指标看起来健康(我们的 Debug 采集中 rasterP50 ≈ 1.4 ms,而帧管线 span 的 P50 约为 13–16 ms——这里看的是形态,不是绝对值),说明瓶颈在平台线程的调度延迟,而不是渲染负载。
在 Release 保真度下做 A/B 开关(同一二进制、单变量探针,见下文)显示:回归的绝大部分可归因于逐步事件路径,而仅包一层 Window wrapper 时也有一小块可测量的残留。我们在源码和实测中都确认:minimumSize / titleBarStyle 这两个 setter 的处理函数会在应用窗口上安装通用的 WindowMessageDispatcher(整体替换 GWLP_WNDPROC),即使监听器数量为零——因此每条消息都要走一遍 mutex/vector/sort 路径,普通无边框应用也会被收税(见根因第 4 条和量化小节)。
机器相关但在我们的笔记本上保持一致:脚本化的左边缘负载(1500 步一像素的 SetWindowPos)产生了恰好 1500 个 WindowMovedEvent + 1500 个 WindowResizedEvent——每一步 WM_WINDOWPOSCHANGED 构造并投递两个事件,零合并,并使窗口线程每步的 wall time 在裸 Flutter 窗口约 10–13 ms 的基础上增加约 1.3–1.8 ms(约 10–15%)。方法与细节见下文"量化复现"。
环境
- nativeapi / cnativeapi / nativeapi_flutter:0.5.10(pub.dev,截至 2026-11-10 为最新发布版)
- nativeapi-core
mainHEAD 上的window_manager_windows.cpp与 0.5.10 pub 包逐字节一致(我们做过 diff)——下文所有内容也是当前上游行为;两个版本的行号通用。 - Flutter 3.47.6 stable(Windows x64),Dart 3.13
- Windows 11(Build 26300),单 GPU(RTX 4060 Laptop,直连面板)
- 应用:无边框窗口(
titleBarStyle = hidden),普通 Flutter UI
我们如何隔离问题(同一 Release 二进制上的 A/B)
我们构建了一个应用,并在运行时逐项开关 nativeapi 的使用:
| 配置 | 边缘拖拽手感 |
|---|---|
| 完整 nativeapi 使用(注册监听器、隐藏标题栏、设置最小尺寸) | 明显追边框 |
跳过 hideTitleBar()(绕过 frame/命中测试链,监听器仍在) |
仍然追边框 |
不设置 minimumSize |
仍然追边框 |
包装了窗口,但从未调用 addListener() |
接近正常,有轻微残留 |
| 完全不创建 nativeapi Window wrapper(纯 Win32 + Flutter) | 流畅 |
| 旧技术栈(window_manager 0.5.x + bitsdojo,无 nativeapi) | 流畅 |
因此,成本的大部分跟随"事件注册与投递";较小的残留跟随 wrapper 自身的逐消息链(几何子类 + 标题栏/命中测试处理函数)——凡是 wrapper 存在的行都有这部分。
量化复现(独立探针应用,同一二进制,环境变量切换档位)
由于无法可复现地脚本化真实鼠标拖拽,我们驱动拖拽所使用的同一条消息路径:一个独立进程对窗口左边缘发出 SetWindowPos 一像素振荡(x+1/w−1,然后 x−1/w+1)。每一步都会穿过 sizing 消息路径(WM_WINDOWPOSCHANGED),且每次调用都会阻塞到窗口线程处理完毕——因此每步 wall time 就是窗口线程的工作时间。探针应用是一个普通的 flutter create Windows 应用,通过 Window.createWithNativeWindow 绑定 runner 的 HWND;各档位由运行时环境变量切换:
| 档位 | 监听器 | titleBarStyle=hidden |
minimumSize |
含义 |
|---|---|---|---|---|
| B | — | — | — | 裸 Flutter 窗口(基线) |
| A | ✔ | — | — | 仅几何事件链 |
| C | ✔ | ✔ | ✔ | 我们修复前的应用形态 |
| D | — | ✔ | ✔ | 我们修复后的应用形态(事件已退订) |
结果(Release,RTX 4060 笔记本,每档每轮 1500 步,轮次交错;热漂移使后段轮次整体变慢,因此差值按约 ±0.5 ms 计):
- 每步事件数——零合并。 A/C 档记录到 1500 步左边缘拖拽产生
moved = 1500和resized = 1500:每一步WM_WINDOWPOSCHANGED恰好构造并投递两个事件到 Dart(左/右边缘拖拽同时改变位置和尺寸,因此OnWindowChanged的两个分支都会触发)。负载期间持续约 165 事件/秒;某一轮里 3000 个中有 8 个被跳过,说明投递既非无损也无合并。这与代码一致:moved(:834-835)和resized(:837-839)是独立的if,且OnWindowEvent(:892-901)对每个事件重新查询注册表 +GetSize()/GetPosition()。 - 每步窗口线程税。 同轮配对差值:
A−B ≈ +1.3 … +1.8 ms/步,基线B ≈ 9.6 … 13.8 ms/步(约 10–15%);C−B ≈ +1.7 … +2.4。事件链本身占了大头,与主观阶梯表一致。 - 附带发现(行为类,可能是有意为之): 对一个已经可见的窗口设置
titleBarStyle = TitleBarStyle.hidden会清除WS_VISIBLE——窗口保留几何,但IsWindowVisible返回 false,直到我们再次调用show()。我们的应用只是因为遵循"先隐藏 → 改样式 → 再 show"的顺序才躲过了这个问题。
探针应用 + 驱动脚本总共约 150 行;如有需要我们乐意附上或贴出。
根因指针(cnativeapi-0.5.10)
- 几何事件在每一步拖拽中都在窗口线程上构建并投递——边缘拖拽每步两个。
window_manager_windows.cpp:203-217——WindowGeometryProc(由WatchWindowGeometry通过SetWindowSubclass安装,:222-224)拦截WM_WINDOWPOSCHANGED,先调用原过程,然后OnWindowChanged(:778-841)对比快照(:769-775,GetWindowRect+IsIconic+IsZoomed),并独立触发moved(:834-835)和resized(:837-839)——边缘拖拽同时改变 x 和宽度,所以每步两者都触发(实测:1500 步恰好产生 1500+1500 个事件,零合并)。
每个事件还额外通过 C++ getter 重新查询几何(OnWindowEvent,window_manager_windows.cpp:862-906→ 注册表查找 +window->GetSize()/GetPosition()= 矩形 + DPI 计算),构造一个WindowMoved/WindowResized,并通过带native_event_delivery_is_active/native_event_delivery_complete握手的NativeCallable投递(bindings/dart/nativeapi/lib/src/callbacks.dart,deliverEvent;DispatchWindowEvent:1199-1202)。在边缘拖拽期间,WM_WINDOWPOSCHANGED以鼠标采样率到达——每秒数百次这样的构建+跨语言投递,而这条线程同时还必须让 sizing 模态循环和WM_SIZE → MoveWindow(child) → engine present链继续运行。 - 你们自己的代码就记录着这种失败模式。
window_manager_windows.cpp:143-148解释了为什么几何上报采用子类(subclass)而不是EVENT_OBJECT_LOCATIONCHANGEWinEvent 钩子:跨上下文(out-of-context)的 WinEvent"会在线程下一次读取消息时被投递——正好在 Flutter 的 resize 中间,而 Flutter resize 在等待新尺寸的一帧时会泵消息……而从那里被调用的监听器(Dart 监听器是同步的)让每一个 resize 步骤都迟到了。"子类把投递点移到了一个确定的位置;它并没有减少每步的工作本身。 - 遮挡(occlusion)有合并,但 Moved/Resized 没有。
window_manager_windows.cpp:511,546-547——遮挡路径会启动一个 100 ms 定时器,理由是"这些事件是一阵一阵来的(拖拽会让窗口一秒动几十次)"。WindowMoved/WindowResized没有等价的节流:边缘拖拽实测每一步WM_WINDOWPOSCHANGED恰好两个事件。 - 已确认:通用 dispatcher 会被安装到普通应用窗口上——由标准 setter 安装,即使监听器数量为零。
WindowMessageDispatcher::RegisterHandler(hwnd, …)(window_message_dispatcher.cpp:34-52)调用InstallHook(hwnd)(:163-186),也就是SetWindowLongPtr(GWLP_WNDPROC, DispatchWindowProc)替换——而调用者是日常功能:最小/最大尺寸处理函数(window_windows.cpp:1560-1568,WM_GETMINMAXINFO)、always-on-bottom(:1659-1667)、标题栏/命中测试处理函数(:~1700)。因此仅minimumSize/titleBarStyle就让应用窗口的每条消息都走一遍逐消息的mutex快照 + 两次哈希查找 +std::vector分配 +std::sort路径(window_message_dispatcher.cpp:96-161),包括拖拽期间的高频非客户区消息(WM_NCHITTEST、WM_MOUSEMOVE、WM_SIZING)。我们的无监听器 D 档相比基线仍多花约 +1–2 ms/步,这是在 item 1 事件链税(A 档)之外的部分;item 1 占主导,但两者都需要修才能真正消除差距。
最小复现
一个 Flutter Windows 应用:
final window = na.WindowManager.instance.getCurrent()!; // 或包装 runner 的 HWND
final id = window.addListener((e) { /* no-op */ }); // 保持监听器注册
// 无边框:
window.titleBarStyle = na.TitleBarStyle.hidden;然后以中等、稳定的速度水平拖拽窗口边缘,再与删掉 addListener 一行(或在拖拽前 removeListener)的情况对比。差异可以通过边框与内容的边界很容易看出来;当窗口内是静态高对比布局时最明显(任何内容滞后都会一目了然)。
如果你想要无需人工拖拽的量化采集:上文"量化复现"小节脚本化了同一条消息路径(从第二进程发出 SetWindowPos 左边缘振荡)并统计产生的 Dart 侧事件;我们还建议用 QueryPerformanceCounter 对 WindowGeometryProc 中 WM_WINDOWPOSCHANGED 的处理(入口到返回)以及 Dart 投递握手计时,在一个 10 s 负载上做直方图,对比注册监听器与不注册。
修复建议(任选其一或更好的想法)
- 合并/节流 Moved/Resized 投递——你们对遮挡事件已经这么做了:在突发事件上启动定时器,并始终在
WM_ENTERSIZEMOVE/WM_EXITSIZEMOVE会话边沿发出最新几何。大多数应用需要的是会话边沿 + 节流后的流,而不是每条WM_WINDOWPOSCHANGED一个事件。 - 省掉每个事件额外的 getter 往返——快照里已经持有新的
WINDOWPOS;尺寸/位置可以直接从它推导,而不是重新查询矩形 + DPI。 - Dispatcher 快路径(如果它被安装到应用窗口上——见开放问题 4):提供消息类别白名单或
anyHandlerCares位图,让不关心的消息直接到达原过程,绕过逐消息的 mutex/vector/sort;考虑用SetWindowSubclass取代GWLP_WNDPROC替换。 - 记录几何订阅的逐窗口成本,让宿主应用能决定自己注册什么。
关联
- nativeapi-core #78("Verify: events, input and icon reports from …")——这是一份 Windows 事件路径报告,带有复现结构,正好是该 issue 所要求的形态。
- 同一用户的早期报告:libnativeapi/nativeapi [Windows] Caption drag region (SetPropW) freezes during modal SIZEMOVE loop when the UI isolate runs on a separate thread; WinEvent-based events still require the platform thread #18(caption 拖拽区域在 SIZEMOVE 模态循环中冻结;已由 0.5.3 的"事件在拥有窗口的线程上投递"修复)——本报告针对的正是那次修复所产生的投递路径的每步成本。
- 历史症状亲属:libnativeapi/nativeapi [Windows] Window resize lags behind the pointer starting with nativeapi 0.2.5 #17("从 0.2.5 起 resize 落后于指针")——当前
SetWindowSubclass设计正源自那次修复(见根因第 2 条引用的代码注释);本 issue 报告的残留正是那笔交易的另一半。 - 构建探针时还遇到(独立问题,你们的未发布树中已修复——0.5.10 仍没有):事件结构体变成 tree-shake 不可达时,AOT
gen_snapshot报"Class with illegal cid: native_window_event_t"——[vm] Looking up pragma on empty classes without entry-point pragma causes illegal cid ingen_snapshotdart-lang/sdk#50540 workaround,CHANGELOG Unreleased / 你们的 Issue compiling for IOS and Android #26,感谢。 - 状态核查(2026-11-10):0.5.10 是最新发布版;nativeapi-core
mainHEAD 仍包含上述确切行为(文件逐字节一致),两个 CHANGELOG 的 Unreleased 中都没有相关条目。
English original
Summary
On Windows, with nativeapi window listeners registered, an interactive edge-resize shows
clear content trailing behind the window frame (rubber-banding): the frame follows the
mouse while the Flutter content arrives frames late. During the sizing modal loop, every
rectangle step produces a WM_WINDOWPOSCHANGED; per step, nativeapi's geometry subclass
diffs a snapshot, queries rect + DPI (GetSize()), constructs a WindowMoved/Resized
event and delivers it to Dart through the NativeCallable +
delivery_is_active/delivery_complete handshake — all on the window thread, hundreds of
times per second. Dart-side frame timings stay healthy (in our Debug captures
rasterP50 ≈ 1.4 ms while frame pipeline span P50 ≈ 13–16 ms — shape, not absolutes),
pointing at platform-thread scheduling latency rather than rendering load.
A/B toggles at Release fidelity (same binary, single-variable probes below) attribute the
bulk of the regression to the per-step event path, with a measurable residual while merely
wrapped. We confirmed in code and in measurement that minimumSize / titleBarStyle
setter handlers install the generic WindowMessageDispatcher (full GWLP_WNDPROC swap)
on the app window even with zero listeners — so the per-message mutex/vector/sort path
taxes every message of a plain frameless app too (see root-cause item 4 and the
quantified section).
Machine-specific but consistent on our laptop: a scripted left-edge load of 1500 one-pixel
SetWindowPos steps produced exactly 1500 WindowMovedEvents + 1500
WindowResizedEvents — two constructed-and-delivered events per WM_WINDOWPOSCHANGED,
zero coalescing, and raised per-step window-thread wall time by ~1.3–1.8 ms on top of a
~10–13 ms bare-Flutter-window step (~10–15 %). Details and method in "Quantified
reproduction" below.
Environment
- nativeapi / cnativeapi / nativeapi_flutter: 0.5.10 (pub.dev; latest published as of
2026-11-10) window_manager_windows.cppon nativeapi-coremainHEAD is byte-for-byte identical
to the 0.5.10 pub package (we diffed it) — everything below is also current-upstream;
line numbers are shared between the two.- Flutter 3.47.6 stable (Windows x64), Dart 3.13
- Windows 11 (Build 26300), single GPU (RTX 4060 Laptop, direct panel)
- App: frameless window (
titleBarStyle = hidden), plain Flutter UI
How we isolated it (A/B on the same Release binary)
We built one app and toggled individual parts of our nativeapi usage at runtime:
| Configuration | Edge-drag feel |
|---|---|
| Full nativeapi usage (listener registered, hidden title bar, min size) | clearly trails |
hideTitleBar() skipped (frame/hit-test chain bypassed, listener still on) |
still trails |
minimumSize not set |
still trails |
Window wrapped, but addListener() never called |
nearly fine, faint residual |
| nativeapi Window wrapper not created at all (plain Win32 + Flutter) | smooth |
| Previous stack (window_manager 0.5.x + bitsdojo, no nativeapi) | smooth |
So the bulk of the cost tracks event registration and delivery; a smaller residual tracks the
wrapper's own per-message chains (geometry subclass + title-bar/hit-test handlers), present in
every row where the wrapper existed.
Quantified reproduction (standalone probe app, same binary, env-toggled arms)
Because we cannot script a real mouse-drag reproducibly, we drive the same message path a
drag uses: a separate process issues SetWindowPos one-pixel oscillations on the window's
left edge (x+1/w−1 then x−1/w+1). Every step crosses the sizing message path
(WM_WINDOWPOSCHANGED) and each call blocks until the window thread has finished handling
it — so wall-time-per-step is window-thread work time. The probe app is a plain
flutter create Windows app that binds its runner HWND via
Window.createWithNativeWindow; arms are runtime env toggles:
| Arm | Listener | titleBarStyle=hidden |
minimumSize |
meaning |
|---|---|---|---|---|
| B | — | — | — | bare Flutter window (baseline) |
| A | ✔ | — | — | geometry event chain only |
| C | ✔ | ✔ | ✔ | our pre-fix app shape |
| D | — | ✔ | ✔ | our post-fix app shape (events unsubscribed) |
Results (Release, RTX 4060 laptop, 1500 steps/arm/round, rounds interleaved; thermal drift
made late rounds uniformly slower, so treat deltas as ~±0.5 ms):
- Event count per step — zero coalescing. Arm A/C runs recorded
moved = 1500andresized = 1500for 1500 left-edge steps: exactly two
constructed + Dart-delivered events perWM_WINDOWPOSCHANGED(a left/right-edge drag
mutates position and size, so both branches ofOnWindowChangedfire). Sustained
~165 events/s during the load; in one run 8 of 3000 were skipped, so delivery is neither
lossless nor coalesced. This matches the code:moved(:834-835) andresized
(:837-839) are independentifs, andOnWindowEvent(:892-901) re-queries the registryGetSize()/GetPosition()per event.
- Per-step window-thread tax. Paired same-round deltas:
A−B ≈ +1.3 … +1.8 ms/step
on top of aB ≈ 9.6 … 13.8 ms/stepbare baseline (~10–15 %);C−B ≈ +1.7 … +2.4.
The event chain alone accounts for most of it, consistent with the subjective ladder. - Side finding (behavioral, maybe intended): applying
titleBarStyle = TitleBarStyle.hiddento an already-visible window cleared
WS_VISIBLE— the window kept its geometry butIsWindowVisiblereturned false until we
calledshow()again. Our app dodged this only because it follows the
hide → set-style → show order.
Probe app + driver are tiny (~150 lines total); happy to attach or post them if useful.
Root-cause pointers (cnativeapi-0.5.10)
- Geometry events are built and delivered per drag step, on the window thread —
two per step on an edge drag.
window_manager_windows.cpp:203-217—WindowGeometryProc(installed via
SetWindowSubclassbyWatchWindowGeometry, :222-224) interceptsWM_WINDOWPOSCHANGED,
calls the original procedure first, thenOnWindowChanged(:778-841) diffs a snapshot
(:769-775,GetWindowRect+IsIconic+IsZoomed) and firesmoved(:834-835) and
resized(:837-839) independently — an edge drag changes both x and width, so both
fire per step (measured: exactly 1500+1500 events for 1500 steps, zero coalescing).
Each event additionally re-queries geometry through the C++ getters
(OnWindowEvent,window_manager_windows.cpp:862-906→ registry lookup +
window->GetSize()/GetPosition()= rect + DPI math), constructs a
WindowMoved/WindowResized, and delivers it viaNativeCallablewith the
native_event_delivery_is_active/native_event_delivery_completehandshake
(bindings/dart/nativeapi/lib/src/callbacks.dart,deliverEvent;
DispatchWindowEvent:1199-1202). During an edge drag,WM_WINDOWPOSCHANGEDarrives at
mouse-sampling rate — hundreds of these builds+crossings per second on the thread that
must also keep the sizing modal loop and theWM_SIZE → MoveWindow(child) → engine presentchain moving. - Your own code documents this failure mode.
window_manager_windows.cpp:143-148explains why geometry reporting is a subclass rather
than anEVENT_OBJECT_LOCATIONCHANGEWinEvent hook: out-of-context WinEvents "are
delivered whenever [the thread] next reads a message — in the middle of Flutter's resize,
which pumps messages while it waits for a frame of the new size … and the listeners called
from there (Dart ones synchronously) made every resize step late." The subclass moves
the delivery point to a well-defined place; it does not reduce the per-step work itself. - Coalescing exists for occlusion, but not for Moved/Resized.
window_manager_windows.cpp:511,546-547— the occlusion path arms a 100 ms timer
because "the events come in bursts (a drag moves a window dozens of times a second)".
WindowMoved/WindowResizedhave no equivalent throttle: measured exactly two events
perWM_WINDOWPOSCHANGEDon an edge drag. - Confirmed: the generic dispatcher is installed on plain app windows — by the
standard setters, even with zero listeners.
WindowMessageDispatcher::RegisterHandler(hwnd, …)
(window_message_dispatcher.cpp:34-52) callsInstallHook(hwnd)(:163-186), a
SetWindowLongPtr(GWLP_WNDPROC, DispatchWindowProc)swap — and the callers are everyday
features: the min/max-size handler (window_windows.cpp:1560-1568,WM_GETMINMAXINFO),
always-on-bottom (:1659-1667), and the title-bar/hit-test handler (:~1700). So
minimumSize/titleBarStylealone put every message of the app window through the
per-messagemutexsnapshot + two hash lookups +std::vectoralloc +std::sortpath
(window_message_dispatcher.cpp:96-161), including the high-rate non-client messages of
a drag (WM_NCHITTEST,WM_MOUSEMOVE,WM_SIZING). Our no-listener arm D still cost
~+1–2 ms/step over baseline, in addition to the item-1 event-chain tax (arm A); item 1
dominates, but both need fixing to fully close the gap.
Minimal reproduction
A Flutter Windows app with:
final window = na.WindowManager.instance.getCurrent()!; // or wrap the runner HWND
final id = window.addListener((e) { /* no-op */ }); // keep listener registered
// frameless:
window.titleBarStyle = na.TitleBarStyle.hidden;Then drag a window edge horizontally at a moderate, steady pace and compare with the
addListener line removed (or removeListener before dragging). The difference is easy to
see with the frame vs. content boundary; it is most visible while the window contains a
static high-contrast layout (so any content lag is obvious).
If you want quantitative capture without a human drag: the "Quantified reproduction"
section above scripts the same message path (SetWindowPos left-edge oscillation from a
second process) and counts the resulting Dart-side events; we also suggest timing
WM_WINDOWPOSCHANGED handling in WindowGeometryProc (entry to return) and the Dart
delivery handshake with QueryPerformanceCounter, histogrammed over one 10 s load,
listener-registered vs. not.
Suggested fixes (any of, or better ideas)
- Coalesce/throttle Moved/Resized delivery — you already do exactly this for occlusion:
arm a timer on burst events, and always emit atWM_ENTERSIZEMOVE/WM_EXITSIZEMOVE
session edges with latest geometry. Most apps need session edges + a throttled stream,
not one event perWM_WINDOWPOSCHANGED. - Skip the extra getter round-trips per event — the snapshot already holds the new
WINDOWPOS; size/position could be derived from it instead of re-querying rect + DPI. - Dispatcher fast path (if it is installed on app windows — open question 4): a
message-class whitelist oranyHandlerCaresbitmap so non-consumable messages reach the
original procedure without the per-message mutex/vector/sort; considerSetWindowSubclass
instead of theGWLP_WNDPROCswap. - Document the per-window cost of geometry subscriptions so host apps can decide what they
register.
Related
- nativeapi-core #78 ("Verify: events, input and icon reports from …") — this is a Windows
event-path report with a repro structure, in exactly the shape that issue asks for. - Earlier report from the same user: libnativeapi/nativeapi [Windows] Caption drag region (SetPropW) freezes during modal SIZEMOVE loop when the UI isolate runs on a separate thread; WinEvent-based events still require the platform thread #18 (caption-drag region
freezing during the modal SIZEMOVE loop; fixed by 0.5.3 "events are delivered on the
thread that owns the windows") — this new report is about the per-step cost of the
delivery path that fix produced. - Historical symptom sibling: libnativeapi/nativeapi [Windows] Window resize lags behind the pointer starting with nativeapi 0.2.5 #17 ("resize lags behind the
pointer starting with 0.2.5") — the currentSetWindowSubclassdesign was born from
that fix (see the code comment quoted in root-cause item 2); the residual this issue
reports is the other half of that trade. - Also hit while building probes (separate, already fixed in your unreleased tree — still
absent from 0.5.10): AOTgen_snapshot"Class with illegal cid: native_window_event_t"
when event struct becomes tree-shake-unreachable — [vm] Looking up pragma on empty classes without entry-point pragma causes illegal cid ingen_snapshotdart-lang/sdk#50540 workaround,
CHANGELOG Unreleased / your Issue compiling for IOS and Android #26, thanks for that. - Status check (2026-11-10): 0.5.10 is the latest published; nativeapi-core
mainHEAD
still contains the exact behavior above (byte-identical file), no related entry in either
CHANGELOG's Unreleased.
Activity
TATboy210 commentedon Nov 13, 2026
中文版
Follow-up:修复后形态 vs 旧窗口层基线的对照量化(应用侧零监听 + 命令通道化)
感谢上方的确认。在等待上游修复期间,我们按本 issue 的结论在应用侧做了规避:完全弃用
addListener(几何变化检测改走 Flutter 引擎的WidgetsBindingObserver.didChangeMetrics,nativeapi 仅保留为命令通道:show/maximize/minimize/minimumSize 等)。这里补一份修复后形态与我们上一代窗口栈(bitsdojo_window 0.1.6 + window_manager 0.5.2,v0.0.10.1)的同机同 Flutter 对照数据,希望能帮助上游区分"监听器路径成本"(已确认)与"wrapper 无条件每消息成本"(残留嫌疑,即根因第 4 条)。环境:RTX 4060 Laptop 单卡直驱 2560×1440@150%,Windows build 26300,Flutter 3.47.9 stable,两代均锁 Skia 渲染、UI 独立线程。激励协议两边完全一致(自研驱动,3 轮 × 每轮:左右边缘真实 SendInput 拖拽 6s+6s / 标题栏移动 / 1200 步 ±1px
SetWindowPosresize 振荡 / 600 步 move 振荡 / 4× 最大化-还原循环)。帧指标用应用内置的resize_frame_metrics(SchedulerBinding.addTimingsCallback会话采集,schema 两代同源)。结果 1 —— 窗口线程每步工时(Release AOT,跨进程
SetWindowPos阻塞 QPC 计时,n=3600/配置):零监听形态下窗口线程 resize 路径比旧窗口栈还快 ~30%(Debug 口径 23.9 vs 40.4ms,方向一致)。move 路径两边无差异(≈2ms)——印证差价确实集中在 resize 消息路径。监听器弃用后,逐步事件构建/投递的税负在应用侧已消除。
结果 2 —— Flutter 帧管线 span(Debug 产物口径,maximize/restore 循环场景,跨 3 轮 24 会话取中位):
raster 成本统计上相同(同 Skia 同 GPU),但零监听形态的帧管线 span 仍是基线的 4.0 倍、jank 比例 3.2 倍:
totalSpan − build − raster ≈ 11.3ms/帧的等待(基线同口径仅 ≈0.7ms)。这与主 issue 描述的"Dart 帧数字健康而管线 span 虚高"形态一致,且在我们此前的 Release 探针阶梯中,同引擎完全摘除 nativeapi wrapper 后该等待基本消失(≈基线)——指向 wrapper 安装的子类链/dispatcher 每消息固定成本(根因第 4 条),而非事件投递路径。对修复方向的建议排序(基于新数据微调):
SetWindowSubclass)的价值上升:对已经退订事件、只用命令通道的应用,这是残留 4× 管线 span 差距的唯一可解释来源;Window.createWithNativeWindow包装 + 退订全部监听的形态,帧管线仍带可测成本——如果 dispatcher/子类链能在"零注册 handler"时完全不安装或完全短路,命令通道形态应当能回到基线水平。附带取证(可能对其他用户有价值):旧窗口栈里 window_manager 0.5.2 的
resize事件仅在WM_SIZING中发射(window_manager_plugin.cpp:227-232);当 bitsdojo 的BDW_CUSTOM_FRAME接管拖拽路径后该消息不再到达 Dart,帧指标会话静默失效——排查基线数据时踩过的坑,供参考。完整测试报告(含协议、全部原始数据清单、局限性声明)可应要求提供;上方摘要已覆盖全部关键数字。
English
Follow-up: post-mitigation form vs our previous window stack — quantified A/B (app-side zero-listener + command-channel-only)
Thanks for the confirmation above. While waiting on an upstream fix we adopted the mitigation this issue implies: we stopped using
addListenerentirely (geometry change detection now rides Flutter's engineWidgetsBindingObserver.didChangeMetrics; nativeapi remains only as a command channel — show/maximize/minimize/minimumSize etc.). Below is a same-machine, same-Flutter comparison of that mitigated form against our previous window stack (bitsdojo_window 0.1.6 + window_manager 0.5.2, tag v0.0.10.1), hoping it helps separate the listener-path cost (confirmed) from the wrapper's unconditional per-message cost (the remaining suspect — root cause #4).Environment: RTX 4060 Laptop, single GPU driving 2560×1440 @150%, Windows build 26300, Flutter 3.47.9 stable; both generations locked to Skia and separate UI thread. Identical stimulus protocol on both sides (custom driver, 3 trials × per trial: real SendInput edge drags L/R 6s+6s, title-bar move, 1200-step ±1px
SetWindowPosresize oscillation, 600-step move oscillation, 4× maximize/restore cycles). Frame metrics from the app's built-inresize_frame_metrics(SchedulerBinding.addTimingsCallback, per-session; schema identical across generations).Result 1 — window-thread per-step work (Release AOT, cross-process
SetWindowPosblocking time via QPC, n=3600/config):With listeners gone, the resize path is ~30% faster than even the old window stack (Debug builds: 23.9 vs 40.4ms, same direction). The move path shows no difference (≈2ms) — confirming the delta is specific to the resize message path. The per-step event construction/delivery tax is gone on our side.
Result 2 — Flutter frame pipeline span (Debug-build metrics, maximize/restore-cycle sessions, median over 24 sessions / 3 trials):
Raster cost is statistically identical (same Skia, same GPU), yet the mitigated form's pipeline span is still 4.0× the baseline with 3.2× the jank ratio:
totalSpan − build − raster ≈ 11.3ms/frameof waiting (baseline: ≈0.7ms by the same arithmetic). This matches the "healthy Dart frame numbers, inflated pipeline span" signature in the main issue — and in our earlier Release probe ladder, removing the nativeapi wrapper entirely on the same engine made that waiting vanish (≈baseline) — pointing at the wrapper's subclass/dispatcher per-message fixed cost (root cause #4), not the event delivery path.Suggested re-prioritization of the fix directions, based on this data:
SetWindowSubclass): for apps that have unsubscribed from events and use only the command channel, it is the only remaining explanation for the residual 4× pipeline-span gap;Window.createWithNativeWindowwrapping plus all listeners unsubscribed, the frame pipeline still carries measurable cost — if the dispatcher/subclass chain could avoid installing entirely (or short-circuit completely) when zero handlers are registered, the command-channel form should return to baseline.Side forensics that may help other users: in the old stack, window_manager 0.5.2 emits its
resizeevent only fromWM_SIZING(window_manager_plugin.cpp:227-232); once bitsdojo'sBDW_CUSTOM_FRAMEtakes over the drag path that message never reaches Dart, and frame-metric sessions silently stop firing — a pitfall we hit while baselining, recorded here for the next person.Full test report (protocol, raw-data inventory, limitations): see attached summary above; raw CSVs/screenshots available on request.
TATboy210 commentedon Nov 13, 2026
中文版
Follow-up 2:完整测试报告 + 两项补充(2026-11-13)
上一轮摘要(#issuecomment-6845966847)结尾写了「完整测试报告可应要求提供」,这里直接附上。另外补充两项此后才确认的信息。
补充 1 —— 版本状态
nativeapi/cnativeapi0.6.0 已于 2026-11-12 发布;其 CHANGELOG 没有与本 issue 相关的条目。main于 2026-11-13 复核:下述实现仍在(文件与 0.5.10 行为一致),issue 仍 open。补充 2 —— 零监听形态下,C++ 侧仍逐消息工作(源码级;修正上一轮的措辞)
上一轮我们说「监听器弃用后,逐步事件构建/投递的税负在应用侧已消除」。更准确的说法是:只消除了 Dart 侧的回调税;C++ 侧的几何观察管线仍然每步运行。这也解释了我们此前 G12 探针(仅退订监听)残留的「一丢丢卡」,以及本报告 §5.1 的 4× 管线 span 差。
以 cnativeapi 0.5.10 与 nativeapi-core
main(2026-11-13 两处逐行核对)为准:window_manager_windows.cpp:719(InstallObservation的EnumWindows)WatchWindowGeometry(hwnd)→SetWindowSubclass(WindowGeometryProc)WindowManager构造(如getCurrent())即安装window_manager_windows.cpp:204-217WM_WINDOWPOSCHANGED:DefSubclassProc→WithObserver(recursive_mutex)→OnWindowChangedwindow_manager_windows.cpp:769-775, 778-841IsReportableWindow(IsWindow/GetAncestor/GetPropW/GetWindowLongPtr/IsWindowVisible)+TakeSnapshot(IsIconic/IsZoomed/GetWindowRect)+ 矩形 diffwindow_manager_windows.cpp:862-906→:892-901WindowResizedEvent(window->GetSize())/WindowMovedEvent(window->GetPosition())(注册表查找 + rect + DPI 计算)event_emitter.h:306-321(Emit)lock(listeners_mutex_)+ResolveListenersLocked生成 vector 快照,再遍历(零监听时循环为空)window_close_dispatch.cpp:229-240(EmitObservedWindowEvent)unordered_map查找结论:对「已退订事件、只用命令通道」的应用,每步
WM_WINDOWPOSCHANGED的固定成本 = 子类拦截(含原过程转发)+ 观察者锁 + 快照 diff(4 个 Win32 查询)+ 事件构造(GetSize/GetPosition+ DPI)+Emit的锁/分配 + 观察者分发查找。唯一被跳过的是 DartNativeCallable边界与回调执行。可操作的修复(若认可):
EventEmitter::HasListeners<WindowMovedEvent>()/HasListeners<WindowResizedEvent>()已经存在,可在零几何监听时:① 不安装WindowGeometryProc(或使其直接DefSubclassProc返回);② 在OnWindowChanged/OnWindowEvent入口短路,不构造事件。这样命令通道形态应能回到纯 Flutter 窗口的管线水平。完整测试报告
nativeapi 0.5.10 Windows 窗口层卡顿量化测试 —— 以 v0.0.10.1(bitsdojo_window + window_manager 0.5.2)为基线的对照采集
1. 测试环境
resize_frame_metrics仅在 Debug/Profile 采集;同产物相对比较口径,Debug 绝对值含 JIT 虚高)2. 配置矩阵
SIMPLER_PLAYER_FORCE_SKIA=1)基线由公开 tag v0.0.10.1 重建(ae3b2158,与远程 tag 逐字节一致)。唯一基线改动:
lib/main.dart放开 debug 级日志(LoggerPackageSink.minLevel = LogLevel.debug,不影响窗口/渲染行为)。3. 激励协议(三配置完全一致)
每配置 3 轮 × 每轮 6 阶段(自研驱动,SendInput/QPC):
SetWindowPos右缘 ±1px × 1200 步(QPC 逐步计时 = 窗口线程每步工时)帧指标:应用内置
resize_frame_metrics(schemaVersion 1,SchedulerBinding.addTimingsCallback)——build/raster/totalSpan 的 P50/P95/P99/max、jank60Ratio(totalSpan > 16.667ms 帧占比)、heavyRasterCount(raster > 8ms)。两代指标代码同源,schema 一致(B 缺 heavyRasterCount 归因字段,属后续新增,不影响对比)。4. 结果
4.1 帧时序(跨轮会话中位数,单位 µs)
maximize_cycle(对称场景,无拖拽模态循环干扰,区分度最高)
drag_edge(真实边缘拖拽,会话帧)
resize_osc(编程式连续 resize,会话帧)
* B1/B2 无 osc 会话的原因见 §5.4——基线会话检测源(window_manager resize 事件)对编程式 resize 不触发,属基线采集链限制,非数据缺失。振荡期窗口线程步时由 CSV 直接覆盖(§4.2)。
4.2 窗口线程每步工时(跨进程 SetWindowPos 阻塞时长,QPC,n=3600/1800)
Release(AOT,跨进程纯外部测量,与 app 内部日志无关——两口径独立验证)
Debug(同激励,JIT 口径)
Release 口径 A 比 B1 快 30%(12.5 vs 17.9ms),Debug 口径快 41%——方向一致,结论稳固。
4.3 独立复现(A,单会话抽查)
同一应用内 Marionette 会话:sessionId=2,566 帧,jank60Ratio=0.479,totalSpanP50=15620µs——与 3 轮 trials 一致(重现稳定)。
5. 核心发现
5.1 修复后仍存「内容呈现延迟」指纹:totalSpan 与 build+raster 的巨大缺口
5.2 窗口线程步进与帧管线的「卡顿维度分离」
5.3 渲染后端变量确认(B2 vs B1)
Impeller(出厂默认)在全部拖拽指标上劣于 Skia(drag_edge rasterP95 36.6ms vs 21.3ms,jank60 0.671 vs 0.448),与历史 A/B 数据一致。基线对比必须锁 Skia 才公平——本报告 B1 即此口径。
5.4 基线侧取证附记:v0.0.10.1 的 resize 事件链缺陷
window_manager 0.5.2 仅在
WM_SIZING发射 "resize" 事件(window_manager_plugin.cpp:227-232),而 bitsdojoBDW_CUSTOM_FRAME接管拖拽路径后该消息不再到达 Dart 层——基线内置的 resize_frame_metrics 会话在真实拖拽下静默失效(仅 maximize/unmaximize 可开 session,已实证)。这解释了此前一轮基线「无日志」的原因,也是本报告中「基线为何缺 resize_osc 会话」的佐证。5.5 Release 探针阶梯(同一引擎,逐项摘除 nativeapi 能力,主观拖感)
minimumSize处理器hideTitleBar帧链(NCCALCSIZE/NCHITTEST/子窗拦截)阶梯形状:主成本来自事件观察管线(G12 大头消失),残余来自
createWithNativeWindow包装自身的无条件拦截层(G12 → G7 的差)。与本报告 §5.1 的 4× 管线 span 残差互相印证;结合「补充 2」的源码核对,该残差可以定位到零监听下仍常驻的几何观察管线,而不必假设 dispatcher 一定落在应用窗口上。6. 对 issue 的建议措辞要点
addListener(几何检测改引擎 metrics + 命令通道化)后,窗口线程 resize 每步成本 Release 口径 17.9ms(bitsdojo+wm 基线)→ 12.5ms(-30%,Debug 口径 -41%,双口径一致),且快于旧窗口层组合。WM_ENTERSIZEMOVE/WM_EXITSIZEMOVE会话边沿必发(惠及仍订阅几何事件的应用);WINDOWPOS,免每步重新GetSize()/GetPosition()往返;WindowGeometryProc、不构造几何事件;dispatcher 侧同理提供消息白名单/SetWindowSubclass;7. 证据可得性
原始数据可按需提供(不含密钥、账号、仓库历史等敏感内容),包括:
resize_frame_metricsJSON 原文)8. 局限性如实声明
English
Follow-up 2: full test report + two additions (2026-11-13)
Our previous summary (#issuecomment-6845966847) said the full report was available on request. Here it is. Two additions below reflect what we confirmed after posting that summary.
Addition 1 — version status
nativeapi/cnativeapi0.6.0 shipped 2026-11-12; its CHANGELOG contains nothing related to this issue.main, checked 2026-11-13, still contains the same implementation (behaviour identical to 0.5.10). The issue remains open.Addition 2 — with zero listeners, the C++ side still runs per message (source-level; corrects our earlier wording)
Last time we wrote "the per-step event construction/delivery tax is gone on our side". More precisely: only the Dart-side callback tax is gone; the C++ geometry-observation pipeline still runs on every step. This explains both the residual "a tiny bit of lag" in our earlier G12 probe (listener registration disabled) and the 4× pipeline-span gap in §5.1 of the report.
Verified line by line against cnativeapi 0.5.10 and nativeapi-core
main(2026-11-13):window_manager_windows.cpp:719(EnumWindowsinInstallObservation)WatchWindowGeometry(hwnd)→SetWindowSubclass(WindowGeometryProc)WindowManageris constructed (e.g.getCurrent()), even if no listener is ever addedwindow_manager_windows.cpp:204-217WM_WINDOWPOSCHANGED:DefSubclassProc→WithObserver(recursive_mutex) →OnWindowChangedwindow_manager_windows.cpp:769-775, 778-841IsReportableWindow(IsWindow/GetAncestor/GetPropW/GetWindowLongPtr/IsWindowVisible) +TakeSnapshot(IsIconic/IsZoomed/GetWindowRect) + rect diffwindow_manager_windows.cpp:862-906→:892-901WindowResizedEvent(window->GetSize())/WindowMovedEvent(window->GetPosition())(registry lookup + rect + DPI math)event_emitter.h:306-321(Emit)listeners_mutex_, allocates a listener snapshot vector, then iterates (empty loop when zero listeners)window_close_dispatch.cpp:229-240(EmitObservedWindowEvent)unordered_maplookup per dispatchNet: for an app that has unsubscribed from events and uses only the command channel, each
WM_WINDOWPOSCHANGEDstill costs: subclass interception (+ original-proc forwarding) + observer lock + snapshot diff (4 Win32 queries) + event construction (GetSize/GetPosition+ DPI) +Emitlock/allocation + observer-dispatch lookup. The only thing skipped is the DartNativeCallablecrossing and the callback itself.Suggested actionable fix:
EventEmitter::HasListeners<WindowMovedEvent>()/HasListeners<WindowResizedEvent>()already exist. When no geometry listener is registered, ① do not installWindowGeometryProc(or make it a plainDefSubclassProcpass-through), and ② short-circuit at the entry ofOnWindowChanged/OnWindowEventso no event is constructed. The command-channel form should then return to a plain-Flutter-window pipeline level.Full report (summary of the Chinese original)
Environment: RTX 4060 Laptop, single GPU, 2560×1440 @150%, Windows 10.0.26300, Flutter 3.47.9 stable, both generations locked to Skia and separate UI thread. Window layer A = nativeapi/cnativeapi 0.5.10 (zero listeners + command channel only), B1/B2 = bitsdojo_window 0.1.6 + window_manager 0.5.2 (B1 Skia, B2 Impeller as a render-backend control). A = mpv_kit engine, B1/B2 = media_kit 1.2.6 (limitation noted below).
Stimulus, identical for all configs: 3 trials × 6 phases — real
SendInputedge drags left/right (6 s out + 6 s back), title-bar move drag, 1200-step ±1pxSetWindowPosresize oscillation, 600-step move oscillation, 4× maximize/restore cycles. Frame metrics from the app's built-inresize_frame_metrics(SchedulerBinding.addTimingsCallback).Frame timing (Debug builds; session medians, µs)
maximize_cycle:
drag_edge (real edge drags):
resize_osc (programmatic; A only — the baseline's session detector never fires on programmatic resize, see below): A n=3, rasterP50 5355, rasterP95 15642, totalSpan P50 15557, jank60 0.468.
Window-thread per-step work (cross-process
SetWindowPos, QPC, n=3600 resize / 1800 move)Findings
totalSpan − build − raster ≈ 11.3 ms/frameof waiting (B1 ≈0.7 ms). Real drags show the same direction with smaller amplitude (+16% totalSpan P50, jank 0.539 vs 0.448).resizeevent only fromWM_SIZING(window_manager_plugin.cpp:227-232); once bitsdojo'sBDW_CUSTOM_FRAMEtakes over the drag path, that message never reaches Dart and frame-metric sessions silently stop firing — the reason the baseline has no resize_osc sessions.minimumSizehandler off) = still trails; G11 (onlyhideTitleBarframe chain off) = still trails; G12 (only listener registration off) = a tiny bit of lag, the bulk is gone; G7 (nativeapi wrapper fully removed) = essentially smooth (≈baseline); F (v0.0.12 old stack) = smooth. Combined with Addition 2, the G12 residual is explained by the always-on geometry observation pipeline, without requiring the assumption that the dispatcher necessarily lands on the app window.Limitations (as stated in the Chinese original): frame timings are Debug-build only; A and B1 differ in media engine (mpv_kit vs media_kit), so the nativeapi attribution rests on the same-engine G7/G12 ladder rather than a directly controlled variable; real-drag session counts are small (A=10, B1=12); background desktop load existed during trials (medians over 3 trials); Release builds intentionally collect no frame metrics.
Raw data: 109 session metric rows, per-trial app logs with raw
resize_frame_metricsJSON, Release per-step CSVs, per-trial stimulus timelines, 105 OS-level drag screenshots (A 53 / B1 52), in-app screenshots, and the collector/aggregator/driver scripts — available on request. No credentials, account data or repository history are included.Merge pull request #42 from libnativeapi/fix/issue-30