diff --git a/bindings/dart/cnativeapi/README.md b/bindings/dart/cnativeapi/README.md index ac8e348..fd7abd4 100644 --- a/bindings/dart/cnativeapi/README.md +++ b/bindings/dart/cnativeapi/README.md @@ -27,6 +27,19 @@ hooks: The names are `android`, `ios`, `linux`, `macos` and `windows`. On a skipped platform, importing the package works, but calling into nativeapi throws an `ArgumentError`, so guard those calls with a platform check. +### Enabling the WinUI 3 backend on Windows + +On Windows, the build hook compiles the Win32 backend by default. An app can opt in to `nativeapi-core`'s WinUI 3 backend (`ContentDialog` message dialogs, `MenuFlyout` menus, WinUI 3 views, `AppWindow` title-bar colors and `AppNotifications`) in its `pubspec.yaml` (or the pub workspace root's): + +```yaml +hooks: + user_defines: + cnativeapi: + winui3: true +``` + +When enabled on Windows, the hook restores the pinned Windows App SDK 1.6, C++/WinRT and WebView2 NuGet packages once into its shared build directory, generates the C++/WinRT projections, compiles core with `NATIVEAPI_ENABLE_WINUI3`, and bundles `Microsoft.WindowsAppRuntime.Bootstrap.dll` beside the executable. Target machines must have the [Windows App Runtime 1.6](https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/downloads-archive) installed, and the host executable should declare `PerMonitorV2` DPI awareness in its manifest (enabled by default in Flutter's Windows runner). On other platforms this setting is ignored. + ## Usage ```dart diff --git a/bindings/dart/cnativeapi/hook/build.dart b/bindings/dart/cnativeapi/hook/build.dart index 698069a..5177b31 100644 --- a/bindings/dart/cnativeapi/hook/build.dart +++ b/bindings/dart/cnativeapi/hook/build.dart @@ -21,6 +21,7 @@ void main(List args) async { if (_skippedPlatforms(input).contains(targetOS.name)) { return; } + final winui3 = _winui3Enabled(input) && targetOS == OS.windows; final core = _locateCore(input.packageRoot); final src = core.resolve('src/'); @@ -46,19 +47,26 @@ void main(List args) async { ..._list(src, 'foundation/', '.cpp'), ..._list(src, 'capi/', '.cpp'), ..._list(src, 'platform/$platformDir/', apple ? '.mm' : '.cpp').where( - // The WinUI 3 backend is opt-in in core's CMake build and needs the - // Windows App SDK; the Win32 implementations stand in for it. - (path) => !RegExp( - r'(menu_winui3|message_dialog_winui3|window_winui3|winui3_runtime|view_winui3)_windows\.cpp$', - ).hasMatch(path), + winui3 + ? (path) => + !RegExp(r'(^|[\\/])message_dialog_windows\.cpp$') + .hasMatch(path) + : + // The WinUI 3 backend is opt-in in core's CMake build and needs + // the Windows App SDK; the Win32 implementations stand in for it. + (path) => !RegExp( + r'(menu_winui3|message_dialog_winui3|window_winui3|winui3_runtime|view_winui3)_windows\.cpp$', + ).hasMatch(path), ), shim.resolve(shimSource).toFilePath(), ]; final flags = []; + final defines = {}; final libraries = []; final libraryDirectories = []; var frameworks = []; + _WinUI3Paths? winui3Paths; switch (targetOS) { case OS.macOS: flags.addAll(_objectiveCpp); @@ -126,6 +134,21 @@ void main(List args) async { 'version', 'gdi32', ]); + if (winui3) { + winui3Paths = await _prepareWinUI3(input, output, core); + // Pass generated C++/WinRT and Windows App SDK include directories + // via /I flags rather than CBuilder.includes so CBuilder does not + // enumerate 1,500+ generated headers into HookOutput.dependencies. + // RestoreWinUI3.ps1 (with pinned SHA-256 hashes) is tracked instead. + flags.addAll([ + '/MP', + '/bigobj', + '/I${winui3Paths.projectionDir}', + '/I${winui3Paths.includeDir}', + ]); + defines.addAll({'NATIVEAPI_ENABLE_WINUI3': null, 'NOMINMAX': null}); + libraries.add('windowsapp'); + } } if (targetOS == OS.linux || targetOS == OS.android) { @@ -145,8 +168,12 @@ void main(List args) async { libraries: libraries, libraryDirectories: libraryDirectories, flags: flags, + defines: defines, language: Language.cpp, - std: 'c++17', + // Under C++17, C++/WinRT's winrt/base.h includes , + // which MSVC 14.52+ (VS 18) rejects with STL1011; C++20 selects standard + // . + std: winui3 ? 'c++20' : 'c++17', // MSVC's /Os is only a size preference, unlike Clang/GCC's -Os. Keep // the existing /O2 optimization on Windows. optimizationLevel: targetOS == OS.windows @@ -163,6 +190,22 @@ void main(List args) async { ..level = Level.ALL ..onRecord.listen((record) => print(record.message)), ); + + if (winui3Paths != null && + input.config.code.linkModePreference != LinkModePreference.static) { + final stagedBootstrap = input.outputDirectory.resolve( + 'Microsoft.WindowsAppRuntime.Bootstrap.dll', + ); + winui3Paths.bootstrapDll.copySync(File.fromUri(stagedBootstrap).path); + output.assets.code.add( + CodeAsset( + package: input.packageName, + name: 'Microsoft.WindowsAppRuntime.Bootstrap.dll', + linkMode: DynamicLoadingBundled(), + file: stagedBootstrap, + ), + ); + } }); } @@ -210,6 +253,193 @@ String _linuxBackend(BuildInput input) { ); } +/// Whether to build the optional Windows WinUI 3 backend (`false` by default), +/// from `hooks.user_defines.cnativeapi.winui3` in the app's pubspec. +bool _winui3Enabled(BuildInput input) { + final value = input.userDefines['winui3']; + if (value == null) { + return false; + } + if (value is bool) { + return value; + } + throw FormatException( + 'hooks.user_defines.cnativeapi.winui3 must be a boolean; got $value', + ); +} + +final class _WinUI3Paths { + const _WinUI3Paths({ + required this.includeDir, + required this.projectionDir, + required this.bootstrapDll, + }); + + final String includeDir; + final String projectionDir; + final File bootstrapDll; +} + +/// Restores the pinned Windows App SDK 1.6, C++/WinRT and WebView2 NuGet +/// packages into [BuildInput.outputDirectoryShared] and generates the C++/WinRT +/// projection headers (matching `core/cmake/WinUI3.cmake`). +Future<_WinUI3Paths> _prepareWinUI3( + BuildInput input, + BuildOutputBuilder output, + Uri core, +) async { + final arch = switch (input.config.code.targetArchitecture) { + Architecture.x64 => 'x64', + Architecture.arm64 => 'arm64', + Architecture.ia32 => 'x86', + final other => throw UnsupportedError( + 'WinUI 3 backend does not support target architecture $other', + ), + }; + + final restoreScript = core.resolve('cmake/RestoreWinUI3.ps1'); + final restoreScriptFile = File.fromUri(restoreScript); + if (!restoreScriptFile.existsSync()) { + throw StateError( + 'WinUI 3 restore script not found at ${restoreScriptFile.path}', + ); + } + output.dependencies.add(restoreScript); + final scriptSignature = restoreScriptFile.readAsStringSync(); + + // Keep directory names short inside outputDirectoryShared so deep C++/WinRT + // header names stay well below Windows MAX_PATH. + final packagesDir = input.outputDirectoryShared.resolve('w3pkg/'); + final projectionDir = input.outputDirectoryShared.resolve('w3proj/'); + final stampFile = File.fromUri( + input.outputDirectoryShared.resolve('w3.stamp'), + ); + final includeDir = packagesDir.resolve('winappsdk/include/'); + final versionHeader = File.fromUri( + includeDir.resolve('WindowsAppSDK-VersionInfo.h'), + ); + final cppwinrtExe = File.fromUri( + packagesDir.resolve('cppwinrt/bin/cppwinrt.exe'), + ); + final webview2Winmd = File.fromUri( + packagesDir.resolve('webview2/lib/Microsoft.Web.WebView2.Core.winmd'), + ); + final projectionBaseHeader = File.fromUri( + projectionDir.resolve('winrt/base.h'), + ); + final bootstrapDll = File.fromUri( + packagesDir.resolve( + 'winappsdk/runtimes/win-$arch/native/Microsoft.WindowsAppRuntime.Bootstrap.dll', + ), + ); + + final upToDate = + stampFile.existsSync() && + stampFile.readAsStringSync() == scriptSignature && + versionHeader.existsSync() && + cppwinrtExe.existsSync() && + webview2Winmd.existsSync() && + projectionBaseHeader.existsSync() && + bootstrapDll.existsSync(); + + if (!upToDate) { + final shell = await _findPowerShell(); + final restore = await Process.run( + shell, + [ + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Bypass', + '-Command', + r"$env:PSModulePath = Join-Path $PSHOME 'Modules'; " + r'Import-Module Microsoft.PowerShell.Utility, Microsoft.PowerShell.Archive; ' + r"$ProgressPreference = 'SilentlyContinue'; " + r'& $env:NATIVEAPI_RESTORE_SCRIPT ' + r'-Destination $env:NATIVEAPI_RESTORE_DEST', + ], + environment: { + // Clear any inherited PSModulePath from a different PowerShell edition + // (e.g. pwsh 7 -> powershell 5.1 on CI) so built-in modules load cleanly. + 'PSModulePath': '', + 'NATIVEAPI_RESTORE_SCRIPT': restoreScriptFile.path, + 'NATIVEAPI_RESTORE_DEST': _stripTrailingSlash(packagesDir.toFilePath()), + }, + ); + if (restore.exitCode != 0) { + throw StateError( + 'RestoreWinUI3.ps1 failed (exit ${restore.exitCode}):\n' + '${restore.stdout}\n${restore.stderr}', + ); + } + + if (!versionHeader.existsSync() || + !RegExp(r'WINDOWSAPPSDK_RELEASE_MAJORMINOR[ \t]+0x00010006') + .hasMatch(versionHeader.readAsStringSync())) { + throw StateError( + 'The WinUI 3 backend currently supports Windows App SDK 1.6 packages', + ); + } + + Directory.fromUri(projectionDir).createSync(recursive: true); + final projection = await Process.run(cppwinrtExe.path, [ + '-input', + 'sdk', + '-input', + _stripTrailingSlash( + packagesDir.resolve('winappsdk/lib/uap10.0/').toFilePath(), + ), + '-input', + _stripTrailingSlash( + packagesDir.resolve('winappsdk/lib/uap10.0.17763/').toFilePath(), + ), + '-input', + webview2Winmd.path, + '-output', + _stripTrailingSlash(projectionDir.toFilePath()), + ]); + if (projection.exitCode != 0) { + throw StateError( + 'cppwinrt.exe failed (exit ${projection.exitCode}):\n' + '${projection.stdout}\n${projection.stderr}', + ); + } + stampFile.writeAsStringSync(scriptSignature); + } + + if (!bootstrapDll.existsSync()) { + throw StateError( + 'Microsoft.WindowsAppRuntime.Bootstrap.dll not found at ' + '${bootstrapDll.path}', + ); + } + + return _WinUI3Paths( + includeDir: _stripTrailingSlash(includeDir.toFilePath()), + projectionDir: _stripTrailingSlash(projectionDir.toFilePath()), + bootstrapDll: bootstrapDll, + ); +} + +String _stripTrailingSlash(String path) => + path.replaceFirst(RegExp(r'[\\/]+$'), ''); + +Future _findPowerShell() async { + try { + final probe = await Process.run( + 'pwsh.exe', + ['-NoProfile', '-NonInteractive', '-Command', 'exit 0'], + environment: const {'PSModulePath': ''}, + ); + if (probe.exitCode == 0) { + return 'pwsh.exe'; + } + } on ProcessException { + // Fall back to Windows PowerShell 5.1 built into Windows. + } + return 'powershell.exe'; +} + /// The platforms the app builds without the native library, from /// `hooks.user_defines.cnativeapi.skip_platforms` in its pubspec. Set _skippedPlatforms(BuildInput input) { @@ -262,7 +492,7 @@ Future> _pkgConfig(List args) async { final result = await Process.run('pkg-config', args); if (result.exitCode != 0) { throw StateError( - 'pkg-config ${args.join(' ')} failed; install the GTK 3, X11 and Xi ' + 'pkg-config ${args.join(' ')} failed; install the GTK, X11 and Xi ' 'development packages.\n${result.stderr}', ); } diff --git a/bindings/dart/cnativeapi/test/build_hook_test.dart b/bindings/dart/cnativeapi/test/build_hook_test.dart index 9c2d688..fd66de1 100644 --- a/bindings/dart/cnativeapi/test/build_hook_test.dart +++ b/bindings/dart/cnativeapi/test/build_hook_test.dart @@ -1,25 +1,40 @@ +import 'dart:ffi' as ffi; +import 'dart:io'; + import 'package:code_assets/code_assets.dart'; import 'package:hooks/hooks.dart'; import 'package:test/test.dart'; import '../hook/build.dart' as hook; -/// Runs the build hook for [targetOS], with [skipPlatforms] as the app's -/// `skip_platforms`, and returns the native libraries it built. -Future> build(OS targetOS, {Object? skipPlatforms}) async { +/// Runs the build hook for [targetOS], with optional `user_defines`, and +/// returns the native libraries it built. +Future> build( + OS targetOS, { + Object? skipPlatforms, + Object? winui3, + void Function(BuildInput, BuildOutput)? inspect, +}) async { + final defines = { + if (skipPlatforms != null) 'skip_platforms': skipPlatforms, + if (winui3 != null) 'winui3': winui3, + }; late List libraries; await testCodeBuildHook( mainMethod: hook.main, targetOS: targetOS, - userDefines: skipPlatforms == null + userDefines: defines.isEmpty ? null : PackageUserDefines( workspacePubspec: PackageUserDefinesSource( - defines: {'skip_platforms': skipPlatforms}, + defines: defines, basePath: Uri.file('/'), ), ), - check: (input, output) => libraries = output.assets.code.toList(), + check: (input, output) { + libraries = output.assets.code.toList(); + inspect?.call(input, output); + }, ); return libraries; } @@ -75,4 +90,100 @@ void main() { }); } }); + + group('winui3', () { + for (final flag in [false, true]) { + test('accepts boolean $flag on non-Windows platforms', () async { + await expectLater( + build(OS.fuchsia, winui3: flag), + throwsUnsupportedError, + ); + }); + } + + for (final invalid in [ + 'true', + 'false', + 1, + [true], + {}, + ]) { + test('rejects non-boolean $invalid, naming the setting', () async { + await expectLater( + build(OS.fuchsia, winui3: invalid), + throwsA( + isFormatException.having( + (e) => e.message, + 'message', + contains('hooks.user_defines.cnativeapi.winui3'), + ), + ), + ); + }); + } + + test( + 'compiles WinUI 3 backend and bundles Windows App Runtime bootstrap DLL', + () async { + await build( + OS.windows, + winui3: true, + inspect: (input, output) { + final assets = output.assets.code; + expect( + assets.map((a) => a.id), + containsAll([ + 'package:cnativeapi/cnativeapi.dart', + 'package:cnativeapi/Microsoft.WindowsAppRuntime.Bootstrap.dll', + ]), + ); + + final mainAsset = assets.firstWhere( + (a) => a.id == 'package:cnativeapi/cnativeapi.dart', + ); + final bootstrapAsset = assets.firstWhere( + (a) => a.id == 'package:cnativeapi/Microsoft.WindowsAppRuntime.Bootstrap.dll', + ); + expect(File.fromUri(mainAsset.file!).existsSync(), isTrue); + expect(File.fromUri(bootstrapAsset.file!).existsSync(), isTrue); + expect( + File.fromUri(bootstrapAsset.file!).lengthSync(), + greaterThan(0), + ); + + final dylib = ffi.DynamicLibrary.open(mainAsset.file!.toFilePath()); + try { + final isExtendedDialogSupported = dylib + .lookupFunction( + 'native_message_dialog_is_extended_supported', + ); + final isNotificationSupported = dylib + .lookupFunction( + 'native_notification_manager_is_supported', + ); + final isMenuBackendSupported = dylib + .lookupFunction< + ffi.Bool Function(ffi.UnsignedInt), + bool Function(int) + >('native_menu_is_backend_supported'); + final isViewBackendSupported = dylib + .lookupFunction< + ffi.Bool Function(ffi.UnsignedInt), + bool Function(int) + >('native_view_is_backend_supported'); + + expect(isExtendedDialogSupported(), isTrue); + expect(isNotificationSupported(), isTrue); + expect(isMenuBackendSupported(1), isTrue); + expect(isViewBackendSupported(1), isTrue); + } finally { + dylib.close(); + } + }, + ); + }, + testOn: 'windows', + timeout: const Timeout(Duration(minutes: 5)), + ); + }); }