diff --git a/bindings/dart/cnativeapi/CHANGELOG.md b/bindings/dart/cnativeapi/CHANGELOG.md index 62645347..32c7f4b6 100644 --- a/bindings/dart/cnativeapi/CHANGELOG.md +++ b/bindings/dart/cnativeapi/CHANGELOG.md @@ -1,6 +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)). +- Windows 11: suppress the DWM border for explicit frameless windows when they gain or lose focus; restore normal frame rendering when frameless mode is disabled ([#50](https://github.com/libnativeapi/nativeapi/issues/50)). ## 0.6.1 diff --git a/bindings/dart/nativeapi/CHANGELOG.md b/bindings/dart/nativeapi/CHANGELOG.md index 411af955..5d2ffd0b 100644 --- a/bindings/dart/nativeapi/CHANGELOG.md +++ b/bindings/dart/nativeapi/CHANGELOG.md @@ -1,6 +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)). +- Windows 11: suppress the DWM border for explicit frameless windows when they gain or lose focus; restore normal frame rendering when frameless mode is disabled ([#50](https://github.com/libnativeapi/nativeapi/issues/50)). ## 0.6.1 diff --git a/bindings/dart/nativeapi_flutter/CHANGELOG.md b/bindings/dart/nativeapi_flutter/CHANGELOG.md index f3de51a5..a11abd74 100644 --- a/bindings/dart/nativeapi_flutter/CHANGELOG.md +++ b/bindings/dart/nativeapi_flutter/CHANGELOG.md @@ -1,6 +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)). +- Windows 11: keep explicit frameless Flutter windows free of the DWM border across focus changes ([#50](https://github.com/libnativeapi/nativeapi/issues/50)). ## 0.6.1 diff --git a/tools/gui/README.md b/tools/gui/README.md index 9c0fef84..fe18c1c8 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_frameless_focus_test.ps1` / `window_frameless_focus_flutter.dart` | `flutter_window_example` stock runner (#50) | Windows 11 | No input: three focus cycles between owned windows, actual edge pixels, full-frame client geometry, DWM non-client state and restoration of normal framing (33 checks). See [commands and results](window_frameless_focus_verification.md). | | `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). | diff --git a/tools/gui/flutter_frameless_focus_test.ps1 b/tools/gui/flutter_frameless_focus_test.ps1 new file mode 100644 index 00000000..0dba9cd2 --- /dev/null +++ b/tools/gui/flutter_frameless_focus_test.ps1 @@ -0,0 +1,53 @@ +# Run #50 in the logged-on Windows 11 desktop, without synthetic input. +# Build flutter_window_example with -t ../../tools/gui/window_frameless_focus_flutter.dart first. +param([switch]$DesktopSession, [string]$RunDirectory) +$ErrorActionPreference = 'Stop' +$workspace = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +if (-not $DesktopSession) { + if (-not (Get-Process explorer -ErrorAction SilentlyContinue | Where-Object {$_.SessionId -ne 0})) { + throw 'No logged-on Windows desktop' + } + $RunDirectory = Join-Path $workspace ('core\build\frameless-focus-' + [Guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Force $RunDirectory | Out-Null + $taskName = 'NativeAPI-FramelessFocus-' + [Guid]::NewGuid().ToString('N') + $arguments = '-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "' + $PSCommandPath + '" -DesktopSession -RunDirectory "' + $RunDirectory + '"' + $action = New-ScheduledTaskAction -Execute powershell.exe -Argument $arguments + $principal = New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value) -LogonType Interactive -RunLevel Limited + try { + Register-ScheduledTask -TaskName $taskName -Action $action -Principal $principal -Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::FromMinutes(2)) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries) | Out-Null + Start-ScheduledTask -TaskName $taskName + $deadline = (Get-Date).AddSeconds(110) + while (-not (Test-Path "$RunDirectory\result.json") -and (Get-Date) -lt $deadline) { Start-Sleep -Milliseconds 250 } + if (-not (Test-Path "$RunDirectory\result.json")) { throw "No result: $RunDirectory" } + Get-Content "$RunDirectory\stdout.log" + Get-Content "$RunDirectory\stderr.log" + $result = Get-Content "$RunDirectory\result.json" -Raw | ConvertFrom-Json + $result | ConvertTo-Json + exit ([int]$result.exitCode) + } finally { + Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue + Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue + } +} + +$result = @{exitCode = 1; session = (Get-Process -Id $PID).SessionId; directory = $RunDirectory} +$app = $null +try { + if ($result.session -eq 0) { throw 'This test requires an interactive desktop session' } + $bundle = Join-Path $workspace 'examples\flutter_window_example\build\windows\x64\runner\Debug' + $app = Start-Process (Join-Path $bundle 'window_example.exe') -WorkingDirectory $bundle -PassThru -RedirectStandardOutput "$RunDirectory\stdout.log" -RedirectStandardError "$RunDirectory\stderr.log" + $app.Handle | Out-Null + if (-not $app.WaitForExit(45000)) { throw 'Fixture timed out' } + if ($app.ExitCode -ne 0) { throw "Fixture exited with $($app.ExitCode)" } + $line = Get-Content "$RunDirectory\stdout.log" | Where-Object {$_ -like 'FRAMELESS_RESULT *'} | Select-Object -Last 1 + if (-not $line) { throw 'Missing FRAMELESS_RESULT' } + $report = $line.Substring('FRAMELESS_RESULT '.Length) | ConvertFrom-Json + if ($report.passed -ne 33 -or @($report.failures).Count -ne 0) { throw ($report | ConvertTo-Json) } + $result.passed = $report.passed + $result.exitCode = 0 +} catch { + $result.error = $_.Exception.Message +} finally { + if ($app -and -not $app.HasExited) { Stop-Process -Id $app.Id } + $result | ConvertTo-Json | Out-File "$RunDirectory\result.json" -Encoding utf8 +} diff --git a/tools/gui/window_frameless_focus_flutter.dart b/tools/gui/window_frameless_focus_flutter.dart new file mode 100644 index 00000000..2a2c8337 --- /dev/null +++ b/tools/gui/window_frameless_focus_flutter.dart @@ -0,0 +1,199 @@ +// Self-driving Windows 11 regression for #50. No mouse or keyboard input. +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; +import 'package:flutter/widgets.dart'; +import 'package:nativeapi/nativeapi.dart' as native; + +final _attribute = DynamicLibrary.open('dwmapi.dll') + .lookupFunction< + Int32 Function(Pointer, Uint32, Pointer, Uint32), + int Function(Pointer, int, Pointer, int) + >('DwmGetWindowAttribute'); + +int attribute(native.Window window, int attribute) { + final value = calloc(); + try { + final result = _attribute( + window.nativeObject, + attribute, + value.cast(), + sizeOf(), + ); + if (result != 0) + throw StateError('DwmGetWindowAttribute($attribute): $result'); + return value.value; + } finally { + calloc.free(value); + } +} + +final class _Rect extends Struct { + @Int32() + external int left; + @Int32() + external int top; + @Int32() + external int right; + @Int32() + external int bottom; +} + +final _user32 = DynamicLibrary.open('user32.dll'); +final _windowRect = _user32 + .lookupFunction< + Int32 Function(Pointer, Pointer<_Rect>), + int Function(Pointer, Pointer<_Rect>) + >('GetWindowRect'); +final _clientRect = _user32 + .lookupFunction< + Int32 Function(Pointer, Pointer<_Rect>), + int Function(Pointer, Pointer<_Rect>) + >('GetClientRect'); +final _getDC = _user32 + .lookupFunction< + Pointer Function(Pointer), + Pointer Function(Pointer) + >('GetDC'); +final _releaseDC = _user32 + .lookupFunction< + Int32 Function(Pointer, Pointer), + int Function(Pointer, Pointer) + >('ReleaseDC'); +final _getPixel = DynamicLibrary.open('gdi32.dll') + .lookupFunction< + Uint32 Function(Pointer, Int32, Int32), + int Function(Pointer, int, int) + >('GetPixel'); + +List framePixels(native.Window window) { + final rect = calloc<_Rect>(); + final dc = _getDC(nullptr); + try { + if (_windowRect(window.nativeObject, rect) == 0 || dc == nullptr) + throw StateError('Cannot measure the test window'); + final r = rect.ref; + final x = (r.left + r.right) ~/ 2; + final y = (r.top + r.bottom) ~/ 2; + return [ + _getPixel(dc, x, r.top), + _getPixel(dc, r.right - 1, y), + _getPixel(dc, x, r.bottom - 1), + _getPixel(dc, r.left, y), + ]; + } finally { + _releaseDC(nullptr, dc); + calloc.free(rect); + } +} + +bool clientFillsFrame(native.Window window) { + final outer = calloc<_Rect>(); + final client = calloc<_Rect>(); + try { + if (_windowRect(window.nativeObject, outer) == 0 || + _clientRect(window.nativeObject, client) == 0) + return false; + return outer.ref.right - outer.ref.left == client.ref.right && + outer.ref.bottom - outer.ref.top == client.ref.bottom; + } finally { + calloc.free(outer); + calloc.free(client); + } +} + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + final window = native.WindowManager.instance.getCurrent(); + if (window == null) throw StateError('No Flutter host window'); + window + ..title = 'NativeAPI frameless focus regression' + ..backgroundColor = const native.Color(a: 255, r: 0, g: 0, b: 0) + ..titleBarStyle = native.TitleBarStyle.hidden + ..minimumSize = const native.Size(width: 800, height: 600); + if (!window.setFrameless(true)) throw StateError('SetFrameless failed'); + // Let the native close complete after the FFI call returns to Dart. + window.addListener((_) {}); + window.show(); + runApp( + const Directionality( + textDirection: TextDirection.ltr, + child: ColoredBox( + color: Color(0xFF000000), + child: Center(child: Text('Frameless focus regression')), + ), + ), + ); + await WidgetsBinding.instance.endOfFrame; + final anchor = native.Window.create()! + ..title = 'NativeAPI focus anchor' + ..bounds = native.Rectangle( + x: window.bounds.x + 100, + y: window.bounds.y + 100, + width: 250, + height: 150, + ) + ..show(); + var passed = 0; + final failures = []; + void check(bool ok, String label) { + stdout.writeln('${ok ? "PASS" : "FAIL"} $label'); + if (ok) { + passed++; + } else { + failures.add(label); + } + } + + void checkFrame(String phase) { + check(window.isFrameless, '$phase remains frameless'); + // DWMWA_NCRENDERING_ENABLED is readable. DWMWA_BORDER_COLOR is set-only, + // so inspect the actual desktop pixels at the midpoints of all four edges. + check( + attribute(window, 1) == 0, + '$phase DWM non-client rendering is disabled', + ); + check(clientFillsFrame(window), '$phase client fills the whole frame'); + final pixels = framePixels(window); + check( + pixels.every((color) => color == 0), + '$phase edges stay black: $pixels', + ); + } + + try { + for (var cycle = 1; cycle <= 3; cycle++) { + anchor.focus(); + await Future.delayed(const Duration(milliseconds: 400)); + check( + anchor.isFocused && !window.isFocused, + 'cycle $cycle focuses the owned anchor', + ); + checkFrame('inactive $cycle'); + window.focus(); + await Future.delayed(const Duration(milliseconds: 400)); + check( + window.isFocused && !anchor.isFocused, + 'cycle $cycle focuses the Flutter host', + ); + checkFrame('active $cycle'); + } + window.setFrameless(false); + await Future.delayed(const Duration(milliseconds: 300)); + check(!window.isFrameless, 'normal frame is restored'); + check(attribute(window, 1) != 0, 'normal DWM frame is restored'); + check(!clientFillsFrame(window), 'normal non-client frame is restored'); + } catch (error, stack) { + failures.add('$error'); + stderr.writeln('$error\n$stack'); + } finally { + anchor.close(); + stdout.writeln( + 'FRAMELESS_RESULT ${jsonEncode({'passed': passed, 'failures': failures})}', + ); + window.close(); + } +} diff --git a/tools/gui/window_frameless_focus_verification.md b/tools/gui/window_frameless_focus_verification.md new file mode 100644 index 00000000..239981a3 --- /dev/null +++ b/tools/gui/window_frameless_focus_verification.md @@ -0,0 +1,31 @@ +# Windows frameless focus (#50) + +Build on the Windows host from `examples/flutter_window_example`: + +```sh +fastforge --no-version-check host exec windows-laptop -- flutter build windows --debug --target ../../tools/gui/window_frameless_focus_flutter.dart +``` + +Run from the workspace root: + +```sh +fastforge --no-version-check host exec windows-laptop --no-sync -- powershell -NoProfile -ExecutionPolicy Bypass -File tools/gui/flutter_frameless_focus_test.ps1 +``` + +Verified on `windows-laptop`, Windows 11 x64 build 26300, Flutter 3.50.0 / +Dart 3.14.0, core `9307412`: **33 checks passed**, process exit code 0. +The scenario sends no synthetic input. It switches native focus between two +owned windows three times and asserts both focus states, frameless state, +disabled DWM non-client rendering, matching native client/outer dimensions, and +black screen pixels at the midpoints of all four edges. It then restores and +checks the normal frame. Results/logs remain under `core/build/frameless-focus-*` +on the host. The anchor stays inside the host's content, away from those samples. + +Core `29c0b9b` already suppresses Windows 11's DWM border for explicit frameless +windows; published cnativeapi 0.6.1 does not include that suppression. This PR +adds coverage and Unreleased notes for the existing implementation fix. +`DWMWA_BORDER_COLOR` is a set-only attribute according to the +[Microsoft documentation](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute), +so the test uses actual desktop pixels instead of attempting to read it back. +It checks settled focus states, not every intermediate animation frame; physical +clicks, Flutter 3.50.1 and other Windows builds were not tested in this run.