diff --git a/bindings/dart/cnativeapi/CHANGELOG.md b/bindings/dart/cnativeapi/CHANGELOG.md index bc156f5c..62645347 100644 --- a/bindings/dart/cnativeapi/CHANGELOG.md +++ b/bindings/dart/cnativeapi/CHANGELOG.md @@ -1,3 +1,7 @@ +## Unreleased + +- Windows: resolve the current process window across Dart isolate threads and hidden startup windows, including after a Flutter hot restart ([#49](https://github.com/libnativeapi/nativeapi/issues/49)). + ## 0.6.1 - Windows: keep the owning window active while tracking a window-relative popup menu ([nativeapi-core#94](https://github.com/libnativeapi/nativeapi-core/pull/94)). diff --git a/bindings/dart/nativeapi/CHANGELOG.md b/bindings/dart/nativeapi/CHANGELOG.md index d8a3095c..411af955 100644 --- a/bindings/dart/nativeapi/CHANGELOG.md +++ b/bindings/dart/nativeapi/CHANGELOG.md @@ -1,3 +1,7 @@ +## Unreleased + +- Windows: resolve the current process window across Dart isolate threads and hidden startup windows, including after a Flutter hot restart ([#49](https://github.com/libnativeapi/nativeapi/issues/49)). + ## 0.6.1 - Windows: keep the owning window active while tracking a window-relative popup menu ([nativeapi-core#94](https://github.com/libnativeapi/nativeapi-core/pull/94)). diff --git a/bindings/dart/nativeapi_flutter/CHANGELOG.md b/bindings/dart/nativeapi_flutter/CHANGELOG.md index 427f7456..f3de51a5 100644 --- a/bindings/dart/nativeapi_flutter/CHANGELOG.md +++ b/bindings/dart/nativeapi_flutter/CHANGELOG.md @@ -1,3 +1,7 @@ +## Unreleased + +- Windows: keep `WindowManager.instance.getCurrent()` available after Flutter hot restart when the new isolate runs on a different thread ([#49](https://github.com/libnativeapi/nativeapi/issues/49)). + ## 0.6.1 - Windows: keep the owning window active while tracking a window-relative popup menu ([nativeapi-core#94](https://github.com/libnativeapi/nativeapi-core/pull/94)). diff --git a/tools/gui/README.md b/tools/gui/README.md index 9f318468..9c0fef84 100644 --- a/tools/gui/README.md +++ b/tools/gui/README.md @@ -10,6 +10,7 @@ runner) lives in [`.agents/skills/`](../../.agents/skills); read | Script | Example | Platform | Covers | | --- | --- | --- | --- | +| `flutter_hot_restart_test.py` / `window_hot_restart_flutter.dart` | `flutter_window_example` with its stock runner (#49) | Windows | No input: startup and three actual Flutter hot restarts retain the same non-null current window, HWND and ID; the restarted isolate cancels a native close, then approves closing and exits. Run `python3 tools/gui/flutter_hot_restart_test.py --host windows-laptop`, or omit `--host` on Windows. Requires Flutter/fastforge and a logged-on desktop. | | `window_shadow_visual_flutter.dart` / `build_shadow_visual_flutter.py` | Flutter host and core `window_shadow_visual_linux_test` (#594) | Linux Wayland / XWayland | No input: actual RGB/RGBA visuals, transparent shadow pixels, content dimensions, input regions, shadow toggles, maximize/restore and repeated hide/show. See [visual results and commands](window_shadow_visual_verification.md) and [size regression verification](window_shadow_size_verification.md). | | `window_minimum_restore_flutter.dart` / `build_minimum_restore_flutter.py` | stock Flutter runner and core `window_minimum_restore_linux_test` (#35) | Linux Wayland / XWayland | No input: hidden-window minimum-size restoration, three maximize/restore cycles, minimum/maximum enforcement and host size-request preservation. Private KWin, Breeze and verified 125% output scaling; see [results and commands](window_minimum_restore_verification.md). | | `verify_owned_file_dialog_windows.ps1` | core cross-thread HWND and COM dialog tests (#29) | Windows | No input: deterministic cross-thread registration stall, deferred property notifications and destruction cleanup, real owned/unowned save/open dialogs with automatic cancellation, preserved modality and existing window regressions. See [results and commands](owned_file_dialog_verification.md). | diff --git a/tools/gui/flutter_hot_restart_test.py b/tools/gui/flutter_hot_restart_test.py new file mode 100644 index 00000000..72ffc6de --- /dev/null +++ b/tools/gui/flutter_hot_restart_test.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Exercise Windows GetCurrent across actual Flutter hot restarts, then close. + +Run locally with --host windows-laptop (fastforge forwards the VM service), or +on Windows without --host. No synthetic mouse or keyboard input is sent. +The app uses flutter_window_example's unmodified runner and local bindings. +""" +import argparse +import json +from pathlib import Path +import queue +import re +import subprocess +import threading +import time +import urllib.parse +import urllib.request +import urllib.error + +ROOT = Path(__file__).resolve().parents[2] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--host') + parser.add_argument('--restarts', type=int, default=3) + parser.add_argument('--timeout', type=int, default=900) + args = parser.parse_args() + command = (['fastforge', '--no-version-check', 'run', '--host', args.host, '-p', 'windows'] + if args.host else ['flutter', '--no-version-check', 'run', '-d', 'windows']) + command += ['-t', '../../tools/gui/window_hot_restart_flutter.dart'] + process = subprocess.Popen(command, cwd=ROOT / 'examples/flutter_window_example', + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, bufsize=1) + lines = queue.Queue() + + def read_output(): + for line in process.stdout: + lines.put(line) + lines.put(None) + + threading.Thread(target=read_output, daemon=True).start() + reports = [] + service = None + restart_ready = False + close_sent = False + close_observed = False + + def rpc(method, **parameters): + # fastforge prints a URL just before its SSH port forward starts. + for attempt in range(50): + try: + with urllib.request.urlopen(service + 'getVM', timeout=10) as response: + vm = json.load(response) + break + except urllib.error.URLError: + if attempt == 49: + raise + time.sleep(.2) + isolate = next(i['id'] for i in vm['result']['isolates'] if i['name'] == 'main') + query = urllib.parse.urlencode({'isolateId': isolate, **parameters}) + with urllib.request.urlopen(service + method + '?' + query, timeout=10) as response: + result = json.load(response) + assert 'error' not in result, result + return result['result'] + + deadline = time.monotonic() + args.timeout + try: + while time.monotonic() < deadline: + try: + line = lines.get(timeout=1) + except queue.Empty: + line = '' + if line is None: + break + print(line, end='', flush=True) + match = re.search(r'(http://(?:127\.0\.0\.1|localhost):\d+/[^\s]*)', line) + if match and ('VM Service' in line or 'VM service' in line): + service = match[1].rstrip('/') + '/' + # Do not send the next command before flutter run finishes attaching + # or restarting, even if the new isolate has already printed main(). + if 'key commands' in line or 'Restarted application in' in line: + restart_ready = True + if service and restart_ready: + report = rpc('ext.nativeapi.hotRestartState') + assert report['id'] and report['hwnd'], f'GetCurrent returned null: {report}' + if reports: + assert all(report[k] == reports[0][k] for k in ('pid', 'id', 'hwnd')), report + assert report['generation'] != reports[-1]['generation'], 'main() did not restart' + reports.append(report) + print('CHECK', json.dumps(report), flush=True) + restart_ready = False + if len(reports) <= args.restarts: + process.stdin.write('R') + process.stdin.flush() + else: + assert rpc('ext.nativeapi.closeForTest')['requested'] + close_sent = True + deadline = min(deadline, time.monotonic() + 30) + if close_sent and not close_observed: + state = rpc('ext.nativeapi.hotRestartState') + if state['closeCount']: + assert state['closeCount'] == 1, state + close_observed = True + assert rpc('ext.nativeapi.closeForTest', allow='true')['requested'] + assert len(reports) == args.restarts + 1, f'Expected startup and {args.restarts} restarts: {reports}' + assert close_sent and close_observed, 'The restarted isolate did not receive and approve native close' + code = process.wait(timeout=15) + assert code == 0, f'Flutter run exited with {code}' + print(f'PASS startup, {args.restarts} hot restarts with stable HWND/id, vetoed close and clean exit') + finally: + if process.poll() is None: + try: + process.stdin.write('q') + process.stdin.flush() + process.wait(timeout=15) + except (BrokenPipeError, subprocess.TimeoutExpired): + process.terminate() + process.wait(timeout=10) + + +if __name__ == '__main__': + main() diff --git a/tools/gui/window_hot_restart_flutter.dart b/tools/gui/window_hot_restart_flutter.dart new file mode 100644 index 00000000..58eecb5c --- /dev/null +++ b/tools/gui/window_hot_restart_flutter.dart @@ -0,0 +1,69 @@ +// Target for flutter_hot_restart_test.py. Run in flutter_window_example so its +// unmodified Windows runner exercises the same lifecycle as a generated app. +import 'dart:async'; +import 'dart:convert'; +import 'dart:developer'; +import 'dart:io'; + +import 'package:flutter/widgets.dart'; +import 'package:nativeapi/nativeapi.dart' as native; + +void main() { + WidgetsFlutterBinding.ensureInitialized(); + final window = native.WindowManager.instance.getCurrent(); + final generation = DateTime.now().microsecondsSinceEpoch; + var closeCount = 0; + var allowClose = false; + registerExtension('ext.nativeapi.hotRestartState', (_, _) async { + return ServiceExtensionResponse.result( + jsonEncode({ + 'pid': pid, + 'id': window?.id, + 'hwnd': window?.nativeObject.address, + 'generation': generation, + 'closeCount': closeCount, + }), + ); + }); + stdout.writeln( + 'HOT_RESTART_REPORT ${jsonEncode({'pid': pid, 'id': window?.id, 'hwnd': window?.nativeObject.address})}', + ); + if (window != null) { + window + ..title = 'NativeAPI hot restart regression' + ..titleBarStyle = native.TitleBarStyle.hidden + ..minimumSize = const native.Size(width: 800, height: 600) + ..show() + ..focus(); + window.addListener((event) { + if (event is native.WindowCloseRequestedEvent) { + closeCount++; + if (!allowClose) event.request.cancel(); + stdout.writeln('HOT_RESTART_CLOSE ${window.id}'); + } + }); + } + registerExtension('ext.nativeapi.closeForTest', (_, parameters) async { + allowClose = parameters['allow'] == 'true'; + // Let the RPC return before the Flutter engine shuts down. + Timer(const Duration(milliseconds: 500), () => window?.close()); + return ServiceExtensionResponse.result( + jsonEncode({'requested': window != null}), + ); + }); + runApp( + Directionality( + textDirection: TextDirection.ltr, + child: ColoredBox( + color: const Color(0xFF244865), + child: Center( + child: Text( + window == null + ? 'FAIL: current window is null' + : 'Hot restart ready', + ), + ), + ), + ), + ); +} diff --git a/tools/gui/window_hot_restart_verification.md b/tools/gui/window_hot_restart_verification.md new file mode 100644 index 00000000..6e62d311 --- /dev/null +++ b/tools/gui/window_hot_restart_verification.md @@ -0,0 +1,22 @@ +# Windows hot restart (#49) + +Run `python3 tools/gui/flutter_hot_restart_test.py --host windows-laptop` from the +workspace root. The test uses the stock `flutter_window_example` Windows runner, +the local bindings and core, and sends no synthetic mouse or keyboard input. + +Verified on the Windows x64 `windows-laptop` host with Flutter 3.50.0 / Dart 3.14.0 +and core `9307412`: + +- Startup and three actual hot restarts returned the same non-null window ID and + HWND in the same process. A new generation timestamp confirms `main()` ran again. +- The restarted isolate received and cancelled a native close request; the window + remained available through the VM service with exactly one close notification. +- A second, allowed native close shut down the Flutter engine and the attached + runner exited successfully. + +The implementation fix is already on main in core `7b2e366`: `GetCurrent()` finds +the process's foreground, last-focused, visible or hidden startup window when the +calling Dart thread has no active window. The published cnativeapi 0.6.1 source +only queries `GetActiveWindow()`. This test and the Unreleased changelog entries +cover that existing fix; this PR does not change the core API or publish a release. +Flutter 3.50.1 and manual caption-button clicks were not tested in this run.