Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions bindings/dart/cnativeapi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
244 changes: 237 additions & 7 deletions bindings/dart/cnativeapi/hook/build.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ void main(List<String> 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/');

Expand All @@ -46,19 +47,26 @@ void main(List<String> 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 = <String>[];
final defines = <String, String?>{};
final libraries = <String>[];
final libraryDirectories = <String>[];
var frameworks = <String>[];
_WinUI3Paths? winui3Paths;
switch (targetOS) {
case OS.macOS:
flags.addAll(_objectiveCpp);
Expand Down Expand Up @@ -126,6 +134,21 @@ void main(List<String> 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) {
Expand All @@ -145,8 +168,12 @@ void main(List<String> 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 <experimental/coroutine>,
// which MSVC 14.52+ (VS 18) rejects with STL1011; C++20 selects standard
// <coroutine>.
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
Expand All @@ -163,6 +190,22 @@ void main(List<String> 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,
),
);
}
});
}

Expand Down Expand Up @@ -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<String> _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<String> _skippedPlatforms(BuildInput input) {
Expand Down Expand Up @@ -262,7 +492,7 @@ Future<List<String>> _pkgConfig(List<String> 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}',
);
}
Expand Down
Loading
Loading