A cross platform Audiobookshelf client for Android and iOS
Dart
Play audio, transcribe and save logs on Windows, ask for the server at sign-in, add an installer and stop the reader crashing
Barnabas86d68b4deb38
diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.ymlindex 7a44c6f9..92c1d316 100644--- a/.github/workflows/windows-build.yml+++ b/.github/workflows/windows-build.yml@@ -1,9 +1,10 @@name: Windows Desktop Build# Builds the Windows desktop app from whichever branch the run is started on-# and uploads the runner folder as a workflow artifact. Nothing is signed and-# nothing goes to a release: download the zip from the run page, unpack it-# anywhere and start absorb.exe.+# and packs it into an installer (windows/installer/absorb.iss). Nothing is+# signed and nothing goes to a release: download the artifact from the run+# page and run the setup exe inside it. It installs per-user, adds a Start+# menu entry and an uninstaller, and updates an existing install in place.on:workflow_dispatch:@@ -31,12 +32,14 @@ jobs:shell: bashrun: |full=$(grep -E '^version:' pubspec.yaml | sed -E 's/^version:[[:space:]]*//' | tr -d '\r')- echo "name=absorb-${full/+/-}-windows" >> "$GITHUB_OUTPUT"+ echo "name=absorb-${full/+/-}-windows-setup" >> "$GITHUB_OUTPUT"+ # Inno wants a numeric version: 1.11.1+286 -> 1.11.1.286+ echo "numeric=${full/+/.}" >> "$GITHUB_OUTPUT"- name: Buildrun: flutter build windows --release- # The runner folder needs the VC++ runtime next to the exe on machines+ # The installed app needs the VC++ runtime next to the exe on machines# that never installed the redistributable.- name: Add the VC++ runtime DLLsshell: pwsh@@ -50,9 +53,20 @@ jobs:}Get-ChildItem $out | Select-Object Name, Length+ - name: Build the installer+ shell: pwsh+ run: |+ choco install innosetup -y --no-progress+ & "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" `+ "/DAppVersion=${{ steps.version.outputs.numeric }}" `+ "/DOutputBase=${{ steps.version.outputs.name }}" `+ windows\installer\absorb.iss+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+ Get-ChildItem build\installer | Select-Object Name, Length+- uses: actions/upload-artifact@v4with:name: ${{ steps.version.outputs.name }}- path: build/windows/x64/runner/Release+ path: build/installer/${{ steps.version.outputs.name }}.exeif-no-files-found: errorretention-days: 14diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex 69a9db41..b11e7867 100644--- a/lib/providers/auth_provider.dart+++ b/lib/providers/auth_provider.dart@@ -562,7 +562,7 @@ class AuthProvider extends ChangeNotifier {);}_serverReachable = reachable;- if (AppPlatform.lacksPhonePlugins && !reachable) {+ if (AppPlatform.isWeb && !reachable) {_accessToken = null;_refreshToken = null;_isLegacyToken = false;diff --git a/lib/screens/chapter_editor_screen.dart b/lib/screens/chapter_editor_screen.dartindex d4b7a7f7..972d7c85 100644--- a/lib/screens/chapter_editor_screen.dart+++ b/lib/screens/chapter_editor_screen.dart@@ -1358,9 +1358,10 @@ class _ChapterEditBodyState extends State<ChapterEditBody>final trackIndex = _tracks.indexOf(track);final offset = (track['startOffset'] as num?)?.toDouble() ?? 0;final trackDur = (track['duration'] as num?)?.toDouble() ?? 0;- // Android's decoder opens a stream URL itself. Apple's only reads local- // files, so on iOS a streamed book gets the window's bytes pulled down- // and rewrapped first.+ // Android's decoder opens a stream URL itself. Apple's and Windows' read+ // local files (Windows' could open a URL, but not with our auth header),+ // so there a streamed book gets the window's bytes pulled down and+ // rewrapped first.final String source;RemoteTrack? remote;if (downloaded && trackIndex >= 0 && trackIndex < localPaths.length) {@@ -1369,7 +1370,7 @@ class _ChapterEditBodyState extends State<ChapterEditBody>final contentUrl = track['contentUrl'] as String?;if (contentUrl == null) return;source = api.buildTrackUrl(contentUrl);- if (Platform.isIOS) {+ if (Platform.isIOS || Platform.isWindows) {remote = RemoteTrack(url: source,headers: api.mediaHeaders,@@ -1862,6 +1863,7 @@ class _FindStartSheetState extends State<_FindStartSheet> {},);} on TranscriptionException catch (e) {+ debugPrint('[ChapterFind] ${e.kind.name}: ${e.detail}');if (!mounted) return;final l = AppLocalizations.of(context)!;setState(() {diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dartindex 383da666..8395f93d 100644--- a/lib/screens/login_screen.dart+++ b/lib/screens/login_screen.dart@@ -102,7 +102,7 @@ class _LoginScreenState extends State<LoginScreen>if (!mounted) return;final auth = context.read<AuthProvider>();final account = widget.prefillAccount;- if (AppPlatform.lacksPhonePlugins) {+ if (AppPlatform.isWeb) {final serverUrl = serverUrlFromWebOrigin(Uri.base);if (serverUrl != null) {_setInitialHeaders(account?.customHeaders ?? auth.customHeaders);@@ -129,7 +129,7 @@ class _LoginScreenState extends State<LoginScreen>}void _prefillLogin(String serverUrl, String username) {- final resolvedServerUrl = AppPlatform.lacksPhonePlugins+ final resolvedServerUrl = AppPlatform.isWeb? serverUrlFromWebOrigin(Uri.base) ?? serverUrl: serverUrl;final uri = Uri.tryParse(resolvedServerUrl);@@ -164,7 +164,7 @@ class _LoginScreenState extends State<LoginScreen>final info = await PackageInfo.fromPlatform();if (mounted) setState(() => _appVersion = 'v${info.version}');} catch (_) {}- if (!AppPlatform.lacksPhonePlugins) {+ if (!AppPlatform.isWeb) {try {final trust = await PlayerSettings.getTrustAllCerts();if (mounted) setState(() => _trustAllCerts = trust);@@ -189,7 +189,7 @@ class _LoginScreenState extends State<LoginScreen>String _lastValidatedServer = '';String get _resolvedServerUrl {- if (AppPlatform.lacksPhonePlugins) {+ if (AppPlatform.isWeb) {return serverUrlFromWebOrigin(Uri.base) ?? '';}@@ -548,7 +548,7 @@ class _LoginScreenState extends State<LoginScreen>Padding(padding: const EdgeInsets.only(left: 4, bottom: 16),child: Text(- AppPlatform.lacksPhonePlugins ? l.loginSignIn : l.loginConnectToServer,+ AppPlatform.isWeb ? l.loginSignIn : l.loginConnectToServer,style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.7),fontWeight: FontWeight.w500,@@ -557,7 +557,7 @@ class _LoginScreenState extends State<LoginScreen>),// Server URL- if (!AppPlatform.lacksPhonePlugins) _buildInputField(+ if (!AppPlatform.isWeb) _buildInputField(controller: _serverController,label: l.loginServerAddress,hint: l.loginServerHint,@@ -736,7 +736,7 @@ class _LoginScreenState extends State<LoginScreen>),),),- if (!AppPlatform.lacksPhonePlugins) ...[+ if (!AppPlatform.isWeb) ...[const SizedBox(height: 8),const Divider(height: 1),const SizedBox(height: 4),diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex ff97942f..c1b1c0e7 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -5,6 +5,7 @@ import 'package:flutter/services.dart';import '_audio_player.dart';import 'package:audio_service/audio_service.dart';import 'package:audio_session/audio_session.dart';+import 'package:just_audio_media_kit/just_audio_media_kit.dart';import 'package:shared_preferences/shared_preferences.dart';import 'api_service.dart';import 'download_service.dart';@@ -44,8 +45,8 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {// platforms (ExoPlayer via setDefaultRequestProperties, AVPlayer via// AVURLAssetHTTPHeaderFieldsKey). The proxy doubles the packet count.useProxyForRequestHeaders: false,- audioLoadConfiguration: const AudioLoadConfiguration(- androidLoadControl: AndroidLoadControl(+ audioLoadConfiguration: AudioLoadConfiguration(+ androidLoadControl: const AndroidLoadControl(bufferForPlaybackDuration: Duration(seconds: 2),bufferForPlaybackAfterRebufferDuration: Duration(seconds: 5),targetBufferBytes: 5 * 1024 * 1024, // 5 MB buffer@@ -56,8 +57,11 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {// resolves instantly; in background after a fresh asset load, iOS never// grants that guarantee, so the new track stays state=buffering at// pos=0.0 forever even with hundreds of seconds buffered (GH #244).+ // Apple only: elsewhere leaving the default skips the call, which the+ // Windows engine doesn't implement and failed every load on.darwinLoadControl: DarwinLoadControl(- automaticallyWaitsToMinimizeStalling: false,+ automaticallyWaitsToMinimizeStalling:+ !(AppPlatform.isIOS || AppPlatform.isMacOS),),),);@@ -2816,27 +2820,35 @@ class AudioPlayerService extends ChangeNotifier {try {final fwdSkip = await PlayerSettings.getForwardSkip();final backSkip = await PlayerSettings.getBackSkip();- _handler = await AudioService.init<AudioPlayerHandler>(- builder: () => AudioPlayerHandler(),- config: AudioServiceConfig(- androidNotificationChannelId: 'com.audiobookshelf.app.channel.audio',- androidNotificationChannelName: 'Absorb',- // Keep foreground service alive when paused — prevents Android from- // killing audio after notification interruptions on locked screen.- androidStopForegroundOnPause: false,- androidNotificationIcon: 'drawable/ic_notification',- fastForwardInterval: Duration(seconds: fwdSkip),- rewindInterval: Duration(seconds: backSkip),- androidBrowsableRootExtras: {- AndroidContentStyle.supportedKey: true,- AndroidContentStyle.browsableHintKey:- AndroidContentStyle.categoryListItemHintValue,- AndroidContentStyle.playableHintKey:- AndroidContentStyle.gridItemHintValue,- 'android.media.browse.SEARCH_SUPPORTED': true,- },- ),- );+ // Windows has no audio_service or just_audio implementation: without+ // this AudioService.init threw, no player existed, and play spun+ // forever. media_kit plays the audio; the handler runs standalone.+ if (AppPlatform.isWindows) {+ JustAudioMediaKit.ensureInitialized(windows: true, linux: false);+ _handler = AudioPlayerHandler();+ } else {+ _handler = await AudioService.init<AudioPlayerHandler>(+ builder: () => AudioPlayerHandler(),+ config: AudioServiceConfig(+ androidNotificationChannelId: 'com.audiobookshelf.app.channel.audio',+ androidNotificationChannelName: 'Absorb',+ // Keep foreground service alive when paused — prevents Android from+ // killing audio after notification interruptions on locked screen.+ androidStopForegroundOnPause: false,+ androidNotificationIcon: 'drawable/ic_notification',+ fastForwardInterval: Duration(seconds: fwdSkip),+ rewindInterval: Duration(seconds: backSkip),+ androidBrowsableRootExtras: {+ AndroidContentStyle.supportedKey: true,+ AndroidContentStyle.browsableHintKey:+ AndroidContentStyle.categoryListItemHintValue,+ AndroidContentStyle.playableHintKey:+ AndroidContentStyle.gridItemHintValue,+ 'android.media.browse.SEARCH_SUPPORTED': true,+ },+ ),+ );+ }// Bind service so handler routes play/pause through service (for auto-rewind)_handler!.bindService(_instance);_instance._audioServiceErrorSub ??= AudioService.asyncError.listen(@@ -3506,7 +3518,10 @@ class AudioPlayerService extends ChangeNotifier {_playFromUi = fromUi;if (_handler == null) {debugPrint('[Player] Handler not yet initialized, waiting…');- await _initCompleter.future;+ // If startup never got as far as init, this would wait forever and the+ // play button would spin with no error.+ await _initCompleter.future+ .timeout(const Duration(seconds: 15), onTimeout: () {});}if (_handler == null) {debugPrint('[Player] Handler init failed, cannot play');diff --git a/lib/services/log_service.dart b/lib/services/log_service.dartindex ae204e05..24153657 100644--- a/lib/services/log_service.dart+++ b/lib/services/log_service.dart@@ -356,6 +356,19 @@ class LogService {return;}+ // Windows' share flyout has no "save to file", so desktop saves instead.+ if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {+ final logFile = _logFile;+ final logs = logFile != null && await logFile.exists()+ ? await logFile.readAsString()+ : '';+ final content = logs.isNotEmpty+ ? '${_sanitizeUrls(logs)}\n=== Report Info ===\n$info'+ : '=== Absorb Log Report ===\n$info\n(No log data found - is logging enabled?)\n';+ await downloadTextFile(fileName: 'absorb_logs.txt', content: content);+ return;+ }+final hasFile =_logFile != null &&await _logFile!.exists() &&diff --git a/lib/services/server_log_export_service.dart b/lib/services/server_log_export_service.dartindex 98318769..a24b41b4 100644--- a/lib/services/server_log_export_service.dart+++ b/lib/services/server_log_export_service.dart@@ -14,7 +14,10 @@ class ServerLogExportService {required String content,Rect? sharePositionOrigin,}) async {- if (kIsWeb) {+ if (kIsWeb ||+ defaultTargetPlatform == TargetPlatform.windows ||+ defaultTargetPlatform == TargetPlatform.macOS ||+ defaultTargetPlatform == TargetPlatform.linux) {await downloadTextFile(fileName: fileName, content: content);return;}diff --git a/lib/utils/text_file_download.dart b/lib/utils/text_file_download.dartindex 6772213c..31ec60a1 100644--- a/lib/utils/text_file_download.dart+++ b/lib/utils/text_file_download.dart@@ -1,2 +1,2 @@-export 'text_file_download_stub.dart'+export 'text_file_download_io.dart'if (dart.library.js_interop) 'text_file_download_web.dart';diff --git a/lib/utils/text_file_download_io.dart b/lib/utils/text_file_download_io.dartnew file mode 100644index 00000000..34fa5f2a--- /dev/null+++ b/lib/utils/text_file_download_io.dart@@ -0,0 +1,19 @@+import 'dart:io';++import 'package:file_picker/file_picker.dart';++/// Desktop: ask where to save and write it there. The share sheet the phones+/// use has no "save to file" on Windows. A cancelled dialog saves nothing.+Future<void> downloadTextFile({+ required String fileName,+ required String content,+}) async {+ final dot = fileName.lastIndexOf('.');+ final path = await FilePicker.platform.saveFile(+ fileName: fileName,+ type: dot > 0 ? FileType.custom : FileType.any,+ allowedExtensions: dot > 0 ? [fileName.substring(dot + 1)] : null,+ );+ if (path == null) return;+ await File(path).writeAsString(content);+}diff --git a/lib/utils/text_file_download_stub.dart b/lib/utils/text_file_download_stub.dartdeleted file mode 100644index b036d443..00000000--- a/lib/utils/text_file_download_stub.dart+++ /dev/null@@ -1,4 +0,0 @@-Future<void> downloadTextFile({- required String fileName,- required String content,-}) => throw UnsupportedError('Text file downloads are only available on web.');diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dartindex a3c255e8..f6c12043 100644--- a/lib/widgets/library_grid_tiles.dart+++ b/lib/widgets/library_grid_tiles.dart@@ -94,13 +94,16 @@ class _GridBookTileState extends State<GridBookTile> {!lib.isOffline &&isDesktopWorkspace(context) &&(context.watch<AuthProvider?>()?.canUpdateMetadata ?? false);- // Desktop hover actions only; selection is drawn by the tile itself.+ // Desktop hover actions. Once select mode is on the tile draws its own+ // check, so the hover circle is only the way in: clicking it starts+ // select mode with this book picked, like the home rows.return HoverCoverActions(onMenu: (!widget.selectionMode && itemId.isNotEmpty && !lib.isPodcastLibrary)? () => showQuickActionsSheet(context, itemId, initialItem: widget.item): null,editItemId: canEdit && !widget.selectionMode ? itemId : null,selectionMode: widget.selectionMode,+ onSelectionToggle: widget.selectionMode ? null : widget.onSelectionToggle,child: GestureDetector(// opaque so taps on the blank space below the title (the tile's tall// aspect ratio leaves a gap when the Column children stop short)diff --git a/lib/widgets/scroll_reveal.dart b/lib/widgets/scroll_reveal.dartindex 88ce0016..9bc0d7d1 100644--- a/lib/widgets/scroll_reveal.dart+++ b/lib/widgets/scroll_reveal.dart@@ -59,7 +59,10 @@ class ScrollRevealDriver {void resetToShown() {_snapController.stop();notifier.value = 1.0;- _lastOffset = _attached?.offset ?? 0.0;+ // Desktop disables the driver during the first build, before the list has+ // attached to the controller; reading offset then threw.+ final c = _attached;+ _lastOffset = c != null && c.hasClients ? c.offset : 0.0;_lastDir = 0;}diff --git a/packages/flutter_inappwebview_windows/CHANGELOG.md b/packages/flutter_inappwebview_windows/CHANGELOG.mdnew file mode 100644index 00000000..dd1cc41a--- /dev/null+++ b/packages/flutter_inappwebview_windows/CHANGELOG.md@@ -0,0 +1,52 @@+## 0.6.0++- Updated code to support multiple flutter windows++## 0.5.0+2++- Fixed `InAppWebViewController.callAsyncJavaScript` not working with JSON objects++## 0.5.0+1++- Fixed `onLoadResourceWithCustomScheme` WebView event called every time++## 0.5.0++- Implemented `shouldInterceptRequest`, `onLoadResourceWithCustomScheme` WebView events+- Updated flutter_inappwebview_platform_interface version to ^1.3.0++## 0.4.1++- Implemented `incognito` for `InAppWebViewSettings`++## 0.4.0++- Updated `shouldOverrideUrlLoading` implementation using the Chrome DevTools Protocol API Fetch.requestPaused event+- Updated flutter_inappwebview_platform_interface version to ^1.2.0++## 0.3.0+1++- Removed unwanted debug log++## 0.3.0++- Implemented `pause`, `resume`, `getCertificate` methods for `InAppWebViewController`+- Implemented `onPermissionRequest` WebView event++## 0.2.0+1++- Fixed `InAppWebViewController.evaluateJavascript` not working with JSON objects+- Fixed `InAppWebViewManager::METHOD_CHANNEL_NAME` c++ value+- Fixed `InAppWebViewController.takeScreenshot` to behave consistently with the other platforms++## 0.2.0++- Added support for keeping alive InAppWebView widgets+- Added onProgressChanged, onCreateWindow, onCloseWindow support+- Updated Microsoft.Web.WebView2 SDK version from `1.0.2210.55` to `1.0.2792.45`+- Updated pubspec.yaml+- Fixed `CookieManager.setCookie`++## 0.1.0++- Initial releasediff --git a/packages/flutter_inappwebview_windows/LICENSE b/packages/flutter_inappwebview_windows/LICENSEnew file mode 100644index 00000000..6ccd8da4--- /dev/null+++ b/packages/flutter_inappwebview_windows/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2023 Lorenzo Pichilli++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/flutter_inappwebview_windows/README.md b/packages/flutter_inappwebview_windows/README.mdnew file mode 100644index 00000000..127910a6--- /dev/null+++ b/packages/flutter_inappwebview_windows/README.md@@ -0,0 +1,13 @@+# flutter\_inappwebview\_windows++The Windows WebView2 implementation of [`flutter_inappwebview`](https://pub.dev/packages/flutter_inappwebview).++## Usage++This package is [endorsed](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin),+which means you can simply use `flutter_inappwebview`+normally. This package will be automatically included in your app when you do,+so you do not need to add it to your `pubspec.yaml`.++However, if you `import` this package to use any of its APIs directly, you+should add it to your `pubspec.yaml` as usual.\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/analysis_options.yaml b/packages/flutter_inappwebview_windows/analysis_options.yamlnew file mode 100644index 00000000..84964c30--- /dev/null+++ b/packages/flutter_inappwebview_windows/analysis_options.yaml@@ -0,0 +1,15 @@+include: package:flutter_lints/flutter.yaml++linter:+ rules:+ constant_identifier_names: ignore+ deprecated_member_use_from_same_package: ignore++# Additional information about this file can be found at+# https://dart.dev/guides/language/analysis-options+analyzer:+ errors:+ deprecated_member_use: ignore+ deprecated_member_use_from_same_package: ignore+ unnecessary_cast: ignore+ unnecessary_import: ignorediff --git a/packages/flutter_inappwebview_windows/lib/flutter_inappwebview_windows.dart b/packages/flutter_inappwebview_windows/lib/flutter_inappwebview_windows.dartnew file mode 100644index 00000000..4cd071c6--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/flutter_inappwebview_windows.dart@@ -0,0 +1,3 @@+library flutter_inappwebview_windows;++export 'src/main.dart';diff --git a/packages/flutter_inappwebview_windows/lib/src/cookie_manager.dart b/packages/flutter_inappwebview_windows/lib/src/cookie_manager.dartnew file mode 100644index 00000000..1da14b0b--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/cookie_manager.dart@@ -0,0 +1,238 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';++import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++import 'webview_environment/webview_environment.dart';++/// Object specifying creation parameters for creating a [WindowsCookieManager].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformCookieManagerCreationParams] for+/// more information.+@immutable+class WindowsCookieManagerCreationParams+ extends PlatformCookieManagerCreationParams {+ /// Creates a new [WindowsCookieManagerCreationParams] instance.+ const WindowsCookieManagerCreationParams({this.webViewEnvironment});++ /// Creates a [WindowsCookieManagerCreationParams] instance based on [PlatformCookieManagerCreationParams].+ factory WindowsCookieManagerCreationParams.fromPlatformCookieManagerCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformCookieManagerCreationParams params) {+ return WindowsCookieManagerCreationParams(+ webViewEnvironment:+ params.webViewEnvironment as WindowsWebViewEnvironment?);+ }++ @override+ final WindowsWebViewEnvironment? webViewEnvironment;+}++///{@macro flutter_inappwebview_platform_interface.PlatformCookieManager}+class WindowsCookieManager extends PlatformCookieManager+ with ChannelController {+ /// Creates a new [WindowsCookieManager].+ WindowsCookieManager(PlatformCookieManagerCreationParams params)+ : super.implementation(+ params is WindowsCookieManagerCreationParams+ ? params+ : WindowsCookieManagerCreationParams+ .fromPlatformCookieManagerCreationParams(params),+ ) {+ channel = const MethodChannel(+ 'com.pichillilorenzo/flutter_inappwebview_cookiemanager');+ handler = handleMethod;+ initMethodCallHandler();+ }++ static WindowsCookieManager? _instance;++ ///Gets the [WindowsCookieManager] shared instance.+ static WindowsCookieManager instance(+ {WindowsWebViewEnvironment? webViewEnvironment}) {+ if (webViewEnvironment == null) {+ if (_instance == null) {+ _instance = _init();+ }+ return _instance!;+ } else {+ return WindowsCookieManager(WindowsCookieManagerCreationParams(+ webViewEnvironment: webViewEnvironment));+ }+ }++ static WindowsCookieManager _init() {+ _instance = WindowsCookieManager(WindowsCookieManagerCreationParams());+ return _instance!;+ }++ Future<dynamic> _handleMethod(MethodCall call) async {}++ @override+ Future<bool> setCookie(+ {required WebUri url,+ required String name,+ required String value,+ String path = "/",+ String? domain,+ int? expiresDate,+ int? maxAge,+ bool? isSecure,+ bool? isHttpOnly,+ HTTPCookieSameSitePolicy? sameSite,+ @Deprecated("Use webViewController instead")+ PlatformInAppWebViewController? iosBelow11WebViewController,+ PlatformInAppWebViewController? webViewController}) async {+ assert(url.toString().isNotEmpty);+ assert(name.isNotEmpty);+ assert(value.isNotEmpty);+ assert(path.isNotEmpty);++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('url', () => url.toString());+ args.putIfAbsent('name', () => name);+ args.putIfAbsent('value', () => value);+ args.putIfAbsent('domain', () => domain);+ args.putIfAbsent('path', () => path);+ args.putIfAbsent('expiresDate', () => expiresDate);+ args.putIfAbsent('maxAge', () => maxAge);+ args.putIfAbsent('isSecure', () => isSecure);+ args.putIfAbsent('isHttpOnly', () => isHttpOnly);+ args.putIfAbsent('sameSite', () => sameSite?.toNativeValue());+ args.putIfAbsent(+ 'webViewEnvironmentId', () => params.webViewEnvironment?.id);++ return await channel?.invokeMethod<bool>('setCookie', args) ?? false;+ }++ @override+ Future<List<Cookie>> getCookies(+ {required WebUri url,+ @Deprecated("Use webViewController instead")+ PlatformInAppWebViewController? iosBelow11WebViewController,+ PlatformInAppWebViewController? webViewController}) async {+ assert(url.toString().isNotEmpty);++ List<Cookie> cookies = [];++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('url', () => url.toString());+ args.putIfAbsent(+ 'webViewEnvironmentId', () => params.webViewEnvironment?.id);+ List<dynamic> cookieListMap =+ await channel?.invokeMethod<List>('getCookies', args) ?? [];+ cookieListMap = cookieListMap.cast<Map<dynamic, dynamic>>();++ cookieListMap.forEach((cookieMap) {+ cookies.add(Cookie(+ name: cookieMap["name"],+ value: cookieMap["value"],+ expiresDate: cookieMap["expiresDate"],+ isSessionOnly: cookieMap["isSessionOnly"],+ domain: cookieMap["domain"],+ sameSite:+ HTTPCookieSameSitePolicy.fromNativeValue(cookieMap["sameSite"]),+ isSecure: cookieMap["isSecure"],+ isHttpOnly: cookieMap["isHttpOnly"],+ path: cookieMap["path"]));+ });+ return cookies;+ }++ @override+ Future<Cookie?> getCookie(+ {required WebUri url,+ required String name,+ @Deprecated("Use webViewController instead")+ PlatformInAppWebViewController? iosBelow11WebViewController,+ PlatformInAppWebViewController? webViewController}) async {+ assert(url.toString().isNotEmpty);+ assert(name.isNotEmpty);++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('url', () => url.toString());+ args.putIfAbsent(+ 'webViewEnvironmentId', () => params.webViewEnvironment?.id);+ List<dynamic> cookies =+ await channel?.invokeMethod<List>('getCookies', args) ?? [];+ cookies = cookies.cast<Map<dynamic, dynamic>>();+ for (var i = 0; i < cookies.length; i++) {+ cookies[i] = cookies[i].cast<String, dynamic>();+ if (cookies[i]["name"] == name)+ return Cookie(+ name: cookies[i]["name"],+ value: cookies[i]["value"],+ expiresDate: cookies[i]["expiresDate"],+ isSessionOnly: cookies[i]["isSessionOnly"],+ domain: cookies[i]["domain"],+ sameSite: HTTPCookieSameSitePolicy.fromNativeValue(+ cookies[i]["sameSite"]),+ isSecure: cookies[i]["isSecure"],+ isHttpOnly: cookies[i]["isHttpOnly"],+ path: cookies[i]["path"]);+ }+ return null;+ }++ @override+ Future<bool> deleteCookie(+ {required WebUri url,+ required String name,+ String path = "/",+ String? domain,+ @Deprecated("Use webViewController instead")+ PlatformInAppWebViewController? iosBelow11WebViewController,+ PlatformInAppWebViewController? webViewController}) async {+ assert(url.toString().isNotEmpty);+ assert(name.isNotEmpty);++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('url', () => url.toString());+ args.putIfAbsent('name', () => name);+ args.putIfAbsent('domain', () => domain);+ args.putIfAbsent('path', () => path);+ args.putIfAbsent(+ 'webViewEnvironmentId', () => params.webViewEnvironment?.id);+ return await channel?.invokeMethod<bool>('deleteCookie', args) ?? false;+ }++ @override+ Future<bool> deleteCookies(+ {required WebUri url,+ String path = "/",+ String? domain,+ @Deprecated("Use webViewController instead")+ PlatformInAppWebViewController? iosBelow11WebViewController,+ PlatformInAppWebViewController? webViewController}) async {+ assert(url.toString().isNotEmpty);++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('url', () => url.toString());+ args.putIfAbsent('domain', () => domain);+ args.putIfAbsent('path', () => path);+ args.putIfAbsent(+ 'webViewEnvironmentId', () => params.webViewEnvironment?.id);+ return await channel?.invokeMethod<bool>('deleteCookies', args) ?? false;+ }++ @override+ Future<bool> deleteAllCookies() async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent(+ 'webViewEnvironmentId', () => params.webViewEnvironment?.id);+ return await channel?.invokeMethod<bool>('deleteAllCookies', args) ?? false;+ }++ @override+ void dispose() {+ // empty+ }+}++extension InternalCookieManager on WindowsCookieManager {+ get handleMethod => _handleMethod;+}diff --git a/packages/flutter_inappwebview_windows/lib/src/find_interaction/find_interaction_controller.dart b/packages/flutter_inappwebview_windows/lib/src/find_interaction/find_interaction_controller.dartnew file mode 100644index 00000000..a3e59f43--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/find_interaction/find_interaction_controller.dart@@ -0,0 +1,125 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++/// Object specifying creation parameters for creating a [WindowsFindInteractionController].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformFindInteractionControllerCreationParams] for+/// more information.+@immutable+class WindowsFindInteractionControllerCreationParams+ extends PlatformFindInteractionControllerCreationParams {+ /// Creates a new [WindowsFindInteractionControllerCreationParams] instance.+ const WindowsFindInteractionControllerCreationParams(+ {super.onFindResultReceived});++ /// Creates a [WindowsFindInteractionControllerCreationParams] instance based on [PlatformFindInteractionControllerCreationParams].+ factory WindowsFindInteractionControllerCreationParams.fromPlatformFindInteractionControllerCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformFindInteractionControllerCreationParams params) {+ return WindowsFindInteractionControllerCreationParams(+ onFindResultReceived: params.onFindResultReceived);+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController}+class WindowsFindInteractionController extends PlatformFindInteractionController+ with ChannelController {+ /// Constructs a [WindowsFindInteractionController].+ WindowsFindInteractionController(+ PlatformFindInteractionControllerCreationParams params)+ : super.implementation(+ params is WindowsFindInteractionControllerCreationParams+ ? params+ : WindowsFindInteractionControllerCreationParams+ .fromPlatformFindInteractionControllerCreationParams(params),+ );++ _debugLog(String method, dynamic args) {+ debugLog(+ className: this.runtimeType.toString(),+ debugLoggingSettings:+ PlatformFindInteractionController.debugLoggingSettings,+ method: method,+ args: args);+ }++ Future<dynamic> _handleMethod(MethodCall call) async {+ _debugLog(call.method, call.arguments);++ switch (call.method) {+ case "onFindResultReceived":+ if (onFindResultReceived != null) {+ int activeMatchOrdinal = call.arguments["activeMatchOrdinal"];+ int numberOfMatches = call.arguments["numberOfMatches"];+ bool isDoneCounting = call.arguments["isDoneCounting"];+ onFindResultReceived!(+ this, activeMatchOrdinal, numberOfMatches, isDoneCounting);+ }+ break;+ default:+ throw UnimplementedError("Unimplemented ${call.method} method");+ }+ return null;+ }++ ///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.findAll}+ Future<void> findAll({String? find}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('find', () => find);+ await channel?.invokeMethod('findAll', args);+ }++ ///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.findNext}+ Future<void> findNext({bool forward = true}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('forward', () => forward);+ await channel?.invokeMethod('findNext', args);+ }++ ///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.clearMatches}+ Future<void> clearMatches() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('clearMatches', args);+ }++ ///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.setSearchText}+ Future<void> setSearchText(String? searchText) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('searchText', () => searchText);+ await channel?.invokeMethod('setSearchText', args);+ }++ ///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.getSearchText}+ Future<String?> getSearchText() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<String?>('getSearchText', args);+ }++ ///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.getActiveFindSession}+ Future<FindSession?> getActiveFindSession() async {+ Map<String, dynamic> args = <String, dynamic>{};+ Map<String, dynamic>? result =+ (await channel?.invokeMethod('getActiveFindSession', args))+ ?.cast<String, dynamic>();+ return FindSession.fromMap(result);+ }++ ///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.dispose}+ @override+ void dispose({bool isKeepAlive = false}) {+ disposeChannel(removeMethodCallHandler: !isKeepAlive);+ }+}++extension InternalFindInteractionController+ on WindowsFindInteractionController {+ void init(dynamic id) {+ channel = MethodChannel(+ 'com.pichillilorenzo/flutter_inappwebview_find_interaction_$id');+ handler = _handleMethod;+ initMethodCallHandler();+ }+}diff --git a/packages/flutter_inappwebview_windows/lib/src/find_interaction/main.dart b/packages/flutter_inappwebview_windows/lib/src/find_interaction/main.dartnew file mode 100644index 00000000..a7adaacf--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/find_interaction/main.dart@@ -0,0 +1,2 @@+export 'find_interaction_controller.dart'+ hide InternalFindInteractionController;diff --git a/packages/flutter_inappwebview_windows/lib/src/http_auth_credentials_database.dart b/packages/flutter_inappwebview_windows/lib/src/http_auth_credentials_database.dartnew file mode 100644index 00000000..38b169e8--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/http_auth_credentials_database.dart@@ -0,0 +1,155 @@+import 'dart:async';+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++/// Object specifying creation parameters for creating a [WindowsHttpAuthCredentialDatabase].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformHttpAuthCredentialDatabaseCreationParams] for+/// more information.+@immutable+class WindowsHttpAuthCredentialDatabaseCreationParams+ extends PlatformHttpAuthCredentialDatabaseCreationParams {+ /// Creates a new [WindowsHttpAuthCredentialDatabaseCreationParams] instance.+ const WindowsHttpAuthCredentialDatabaseCreationParams(+ // This parameter prevents breaking changes later.+ // ignore: avoid_unused_constructor_parameters+ PlatformHttpAuthCredentialDatabaseCreationParams params,+ ) : super();++ /// Creates a [WindowsHttpAuthCredentialDatabaseCreationParams] instance based on [PlatformHttpAuthCredentialDatabaseCreationParams].+ factory WindowsHttpAuthCredentialDatabaseCreationParams.fromPlatformHttpAuthCredentialDatabaseCreationParams(+ PlatformHttpAuthCredentialDatabaseCreationParams params) {+ return WindowsHttpAuthCredentialDatabaseCreationParams(params);+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformHttpAuthCredentialDatabase}+class WindowsHttpAuthCredentialDatabase+ extends PlatformHttpAuthCredentialDatabase with ChannelController {+ /// Creates a new [WindowsHttpAuthCredentialDatabase].+ WindowsHttpAuthCredentialDatabase(+ PlatformHttpAuthCredentialDatabaseCreationParams params)+ : super.implementation(+ params is WindowsHttpAuthCredentialDatabaseCreationParams+ ? params+ : WindowsHttpAuthCredentialDatabaseCreationParams+ .fromPlatformHttpAuthCredentialDatabaseCreationParams(params),+ ) {+ channel = const MethodChannel(+ 'com.pichillilorenzo/flutter_inappwebview_credential_database');+ handler = handleMethod;+ initMethodCallHandler();+ }++ static WindowsHttpAuthCredentialDatabase? _instance;++ ///Gets the database shared instance.+ static WindowsHttpAuthCredentialDatabase instance() {+ return (_instance != null) ? _instance! : _init();+ }++ static WindowsHttpAuthCredentialDatabase _init() {+ _instance = WindowsHttpAuthCredentialDatabase(+ WindowsHttpAuthCredentialDatabaseCreationParams(+ const PlatformHttpAuthCredentialDatabaseCreationParams()));+ return _instance!;+ }++ Future<dynamic> _handleMethod(MethodCall call) async {}++ @override+ Future<List<URLProtectionSpaceHttpAuthCredentials>>+ getAllAuthCredentials() async {+ Map<String, dynamic> args = <String, dynamic>{};+ List<dynamic> allCredentials =+ await channel?.invokeMethod<List>('getAllAuthCredentials', args) ?? [];++ List<URLProtectionSpaceHttpAuthCredentials> result = [];++ for (Map<dynamic, dynamic> map in allCredentials) {+ var element = URLProtectionSpaceHttpAuthCredentials.fromMap(+ map.cast<String, dynamic>());+ if (element != null) {+ result.add(element);+ }+ }+ return result;+ }++ @override+ Future<List<URLCredential>> getHttpAuthCredentials(+ {required URLProtectionSpace protectionSpace}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("host", () => protectionSpace.host);+ args.putIfAbsent("protocol", () => protectionSpace.protocol);+ args.putIfAbsent("realm", () => protectionSpace.realm);+ args.putIfAbsent("port", () => protectionSpace.port);+ List<dynamic> credentialList =+ await channel?.invokeMethod<List>('getHttpAuthCredentials', args) ?? [];+ List<URLCredential> credentials = [];+ for (Map<dynamic, dynamic> map in credentialList) {+ var credential = URLCredential.fromMap(map.cast<String, dynamic>());+ if (credential != null) {+ credentials.add(credential);+ }+ }+ return credentials;+ }++ @override+ Future<void> setHttpAuthCredential(+ {required URLProtectionSpace protectionSpace,+ required URLCredential credential}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("host", () => protectionSpace.host);+ args.putIfAbsent("protocol", () => protectionSpace.protocol);+ args.putIfAbsent("realm", () => protectionSpace.realm);+ args.putIfAbsent("port", () => protectionSpace.port);+ args.putIfAbsent("username", () => credential.username);+ args.putIfAbsent("password", () => credential.password);+ await channel?.invokeMethod('setHttpAuthCredential', args);+ }++ @override+ Future<void> removeHttpAuthCredential(+ {required URLProtectionSpace protectionSpace,+ required URLCredential credential}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("host", () => protectionSpace.host);+ args.putIfAbsent("protocol", () => protectionSpace.protocol);+ args.putIfAbsent("realm", () => protectionSpace.realm);+ args.putIfAbsent("port", () => protectionSpace.port);+ args.putIfAbsent("username", () => credential.username);+ args.putIfAbsent("password", () => credential.password);+ await channel?.invokeMethod('removeHttpAuthCredential', args);+ }++ @override+ Future<void> removeHttpAuthCredentials(+ {required URLProtectionSpace protectionSpace}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("host", () => protectionSpace.host);+ args.putIfAbsent("protocol", () => protectionSpace.protocol);+ args.putIfAbsent("realm", () => protectionSpace.realm);+ args.putIfAbsent("port", () => protectionSpace.port);+ await channel?.invokeMethod('removeHttpAuthCredentials', args);+ }++ @override+ Future<void> clearAllAuthCredentials() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('clearAllAuthCredentials', args);+ }++ @override+ void dispose() {+ // empty+ }+}++extension InternalHttpAuthCredentialDatabase+ on WindowsHttpAuthCredentialDatabase {+ get handleMethod => _handleMethod;+}diff --git a/packages/flutter_inappwebview_windows/lib/src/in_app_browser/in_app_browser.dart b/packages/flutter_inappwebview_windows/lib/src/in_app_browser/in_app_browser.dartnew file mode 100644index 00000000..07f51385--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/in_app_browser/in_app_browser.dart@@ -0,0 +1,382 @@+import 'dart:async';+import 'dart:collection';++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++import '../find_interaction/find_interaction_controller.dart';+import '../in_app_webview/in_app_webview_controller.dart';+import '../webview_environment/webview_environment.dart';++/// Object specifying creation parameters for creating a [WindowsInAppBrowser].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformInAppBrowserCreationParams] for+/// more information.+class WindowsInAppBrowserCreationParams+ extends PlatformInAppBrowserCreationParams {+ /// Creates a new [WindowsInAppBrowserCreationParams] instance.+ WindowsInAppBrowserCreationParams(+ {super.contextMenu,+ super.pullToRefreshController,+ this.findInteractionController,+ super.initialUserScripts,+ super.windowId,+ this.webViewEnvironment});++ /// Creates a [WindowsInAppBrowserCreationParams] instance based on [PlatformInAppBrowserCreationParams].+ factory WindowsInAppBrowserCreationParams.fromPlatformInAppBrowserCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformInAppBrowserCreationParams params) {+ return WindowsInAppBrowserCreationParams(+ contextMenu: params.contextMenu,+ pullToRefreshController: params.pullToRefreshController,+ findInteractionController: params.findInteractionController+ as WindowsFindInteractionController?,+ initialUserScripts: params.initialUserScripts,+ windowId: params.windowId,+ webViewEnvironment:+ params.webViewEnvironment as WindowsWebViewEnvironment?);+ }++ @override+ final WindowsFindInteractionController? findInteractionController;++ @override+ final WindowsWebViewEnvironment? webViewEnvironment;+}++///{@macro flutter_inappwebview_platform_interface.PlatformInAppBrowser}+class WindowsInAppBrowser extends PlatformInAppBrowser with ChannelController {+ @override+ final String id = IdGenerator.generate();++ /// Constructs a [WindowsInAppBrowser].+ WindowsInAppBrowser(PlatformInAppBrowserCreationParams params)+ : super.implementation(+ params is WindowsInAppBrowserCreationParams+ ? params+ : WindowsInAppBrowserCreationParams+ .fromPlatformInAppBrowserCreationParams(params),+ ) {+ _contextMenu = params.contextMenu;+ }++ static final WindowsInAppBrowser _staticValue =+ WindowsInAppBrowser(WindowsInAppBrowserCreationParams());++ /// Provide static access.+ factory WindowsInAppBrowser.static() {+ return _staticValue;+ }++ WindowsInAppBrowserCreationParams get _windowsParams =>+ params as WindowsInAppBrowserCreationParams;++ static const MethodChannel _staticChannel =+ const MethodChannel('com.pichillilorenzo/flutter_inappbrowser');++ ContextMenu? _contextMenu;++ @override+ ContextMenu? get contextMenu => _contextMenu;++ Map<int, InAppBrowserMenuItem> _menuItems = HashMap();+ bool _isOpened = false;+ WindowsInAppWebViewController? _webViewController;++ @override+ WindowsInAppWebViewController? get webViewController {+ return _isOpened ? _webViewController : null;+ }++ _init() {+ channel = MethodChannel('com.pichillilorenzo/flutter_inappbrowser_$id');+ handler = _handleMethod;+ initMethodCallHandler();++ _webViewController = WindowsInAppWebViewController.fromInAppBrowser(+ WindowsInAppWebViewControllerCreationParams(id: id),+ channel!,+ this,+ this.initialUserScripts);+ _windowsParams.findInteractionController?.init(id);+ }++ _debugLog(String method, dynamic args) {+ debugLog(+ className: this.runtimeType.toString(),+ id: id,+ debugLoggingSettings: PlatformInAppBrowser.debugLoggingSettings,+ method: method,+ args: args);+ }++ Future<dynamic> _handleMethod(MethodCall call) async {+ switch (call.method) {+ case "onBrowserCreated":+ _debugLog(call.method, call.arguments);+ eventHandler?.onBrowserCreated();+ break;+ case "onMenuItemClicked":+ _debugLog(call.method, call.arguments);+ int id = call.arguments["id"].toInt();+ if (this._menuItems[id] != null) {+ if (this._menuItems[id]?.onClick != null) {+ this._menuItems[id]?.onClick!();+ }+ }+ break;+ case "onMainWindowWillClose":+ _debugLog(call.method, call.arguments);+ eventHandler?.onMainWindowWillClose();+ break;+ case "onExit":+ _debugLog(call.method, call.arguments);+ _isOpened = false;+ final onExit = eventHandler?.onExit;+ dispose();+ onExit?.call();+ break;+ default:+ return _webViewController?.handleMethod(call);+ }+ }++ Map<String, dynamic> _prepareOpenRequest(+ {@Deprecated('Use settings instead') InAppBrowserClassOptions? options,+ InAppBrowserClassSettings? settings}) {+ assert(!_isOpened, 'The browser is already opened.');+ _isOpened = true;+ _init();++ var initialSettings = settings?.toMap() ??+ options?.toMap() ??+ InAppBrowserClassSettings().toMap();++ Map<String, dynamic> pullToRefreshSettings =+ pullToRefreshController?.settings.toMap() ??+ pullToRefreshController?.options.toMap() ??+ PullToRefreshSettings(enabled: false).toMap();++ List<Map<String, dynamic>> menuItemList = [];+ _menuItems.forEach((key, value) {+ menuItemList.add(value.toMap());+ });++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('id', () => id);+ args.putIfAbsent('settings', () => initialSettings);+ args.putIfAbsent('contextMenu', () => contextMenu?.toMap() ?? {});+ args.putIfAbsent('windowId', () => windowId);+ args.putIfAbsent('initialUserScripts',+ () => initialUserScripts?.map((e) => e.toMap()).toList() ?? []);+ args.putIfAbsent('pullToRefreshSettings', () => pullToRefreshSettings);+ args.putIfAbsent('menuItems', () => menuItemList);+ args.putIfAbsent(+ 'webViewEnvironmentId', () => _windowsParams.webViewEnvironment?.id);+ return args;+ }++ @override+ Future<void> openUrlRequest(+ {required URLRequest urlRequest,+ // ignore: deprecated_member_use_from_same_package+ @Deprecated('Use settings instead') InAppBrowserClassOptions? options,+ InAppBrowserClassSettings? settings}) async {+ assert(urlRequest.url != null && urlRequest.url.toString().isNotEmpty);++ Map<String, dynamic> args =+ _prepareOpenRequest(options: options, settings: settings);+ args.putIfAbsent('urlRequest', () => urlRequest.toMap());+ await _staticChannel.invokeMethod('open', args);+ }++ @override+ Future<void> openFile(+ {required String assetFilePath,+ // ignore: deprecated_member_use_from_same_package+ @Deprecated('Use settings instead') InAppBrowserClassOptions? options,+ InAppBrowserClassSettings? settings}) async {+ assert(assetFilePath.isNotEmpty);++ Map<String, dynamic> args =+ _prepareOpenRequest(options: options, settings: settings);+ args.putIfAbsent('assetFilePath', () => assetFilePath);+ await _staticChannel.invokeMethod('open', args);+ }++ @override+ Future<void> openData(+ {required String data,+ String mimeType = "text/html",+ String encoding = "utf8",+ WebUri? baseUrl,+ @Deprecated("Use historyUrl instead") Uri? androidHistoryUrl,+ WebUri? historyUrl,+ // ignore: deprecated_member_use_from_same_package+ @Deprecated('Use settings instead') InAppBrowserClassOptions? options,+ InAppBrowserClassSettings? settings}) async {+ Map<String, dynamic> args =+ _prepareOpenRequest(options: options, settings: settings);+ args.putIfAbsent('data', () => data);+ args.putIfAbsent('mimeType', () => mimeType);+ args.putIfAbsent('encoding', () => encoding);+ args.putIfAbsent('baseUrl', () => baseUrl?.toString() ?? "about:blank");+ args.putIfAbsent('historyUrl',+ () => (historyUrl ?? androidHistoryUrl)?.toString() ?? "about:blank");+ await _staticChannel.invokeMethod('open', args);+ }++ @override+ Future<void> openWithSystemBrowser({required WebUri url}) async {+ assert(url.toString().isNotEmpty);++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('url', () => url.toString());+ return await _staticChannel.invokeMethod('openWithSystemBrowser', args);+ }++ @override+ void addMenuItem(InAppBrowserMenuItem menuItem) {+ _menuItems[menuItem.id] = menuItem;+ }++ @override+ void addMenuItems(List<InAppBrowserMenuItem> menuItems) {+ menuItems.forEach((menuItem) {+ _menuItems[menuItem.id] = menuItem;+ });+ }++ @override+ bool removeMenuItem(InAppBrowserMenuItem menuItem) {+ return _menuItems.remove(menuItem.id) != null;+ }++ @override+ void removeMenuItems(List<InAppBrowserMenuItem> menuItems) {+ for (final menuItem in menuItems) {+ removeMenuItem(menuItem);+ }+ }++ @override+ void removeAllMenuItem() {+ _menuItems.clear();+ }++ @override+ bool hasMenuItem(InAppBrowserMenuItem menuItem) {+ return _menuItems.containsKey(menuItem.id);+ }++ @override+ Future<void> show() async {+ assert(_isOpened, 'The browser is not opened.');++ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('show', args);+ }++ @override+ Future<void> hide() async {+ assert(_isOpened, 'The browser is not opened.');++ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('hide', args);+ }++ @override+ Future<void> close() async {+ assert(_isOpened, 'The browser is not opened.');++ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('close', args);+ }++ @override+ Future<bool> isHidden() async {+ assert(_isOpened, 'The browser is not opened.');++ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<bool>('isHidden', args) ?? false;+ }++ @override+ @Deprecated('Use setSettings instead')+ Future<void> setOptions({required InAppBrowserClassOptions options}) async {+ assert(_isOpened, 'The browser is not opened.');++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('settings', () => options.toMap());+ await channel?.invokeMethod('setSettings', args);+ }++ @override+ @Deprecated('Use getSettings instead')+ Future<InAppBrowserClassOptions?> getOptions() async {+ assert(_isOpened, 'The browser is not opened.');+ Map<String, dynamic> args = <String, dynamic>{};++ Map<dynamic, dynamic>? options =+ await channel?.invokeMethod('getSettings', args);+ if (options != null) {+ options = options.cast<String, dynamic>();+ return InAppBrowserClassOptions.fromMap(options as Map<String, dynamic>);+ }++ return null;+ }++ @override+ Future<void> setSettings(+ {required InAppBrowserClassSettings settings}) async {+ assert(_isOpened, 'The browser is not opened.');++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('settings', () => settings.toMap());+ await channel?.invokeMethod('setSettings', args);+ }++ @override+ Future<InAppBrowserClassSettings?> getSettings() async {+ assert(_isOpened, 'The browser is not opened.');++ Map<String, dynamic> args = <String, dynamic>{};++ Map<dynamic, dynamic>? settings =+ await channel?.invokeMethod('getSettings', args);+ if (settings != null) {+ settings = settings.cast<String, dynamic>();+ return InAppBrowserClassSettings.fromMap(+ settings as Map<String, dynamic>);+ }++ return null;+ }++ @override+ bool isOpened() {+ return this._isOpened;+ }++ @override+ @mustCallSuper+ void dispose() {+ super.dispose();+ disposeChannel();+ _webViewController?.dispose();+ _webViewController = null;+ pullToRefreshController?.dispose();+ findInteractionController?.dispose();+ }+}++extension InternalInAppBrowser on WindowsInAppBrowser {+ void setContextMenu(ContextMenu? contextMenu) {+ _contextMenu = contextMenu;+ }+}diff --git a/packages/flutter_inappwebview_windows/lib/src/in_app_browser/main.dart b/packages/flutter_inappwebview_windows/lib/src/in_app_browser/main.dartnew file mode 100644index 00000000..e11eb8b1--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/in_app_browser/main.dart@@ -0,0 +1 @@+export 'in_app_browser.dart' hide InternalInAppBrowser;diff --git a/packages/flutter_inappwebview_windows/lib/src/in_app_webview/_static_channel.dart b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/_static_channel.dartnew file mode 100644index 00000000..beb7de70--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/_static_channel.dart@@ -0,0 +1,4 @@+import 'package:flutter/services.dart';++const IN_APP_WEBVIEW_STATIC_CHANNEL =+ MethodChannel('com.pichillilorenzo/flutter_inappwebview_manager');diff --git a/packages/flutter_inappwebview_windows/lib/src/in_app_webview/custom_platform_view.dart b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/custom_platform_view.dartnew file mode 100644index 00000000..d4594ca5--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/custom_platform_view.dart@@ -0,0 +1,439 @@+import 'package:flutter/services.dart';+import 'dart:async';+import 'dart:ui';++import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter/widgets.dart';+import '_static_channel.dart';++const Map<String, SystemMouseCursor> _cursors = {+ 'none': SystemMouseCursors.none,+ 'basic': SystemMouseCursors.basic,+ 'click': SystemMouseCursors.click,+ 'forbidden': SystemMouseCursors.forbidden,+ 'wait': SystemMouseCursors.wait,+ 'progress': SystemMouseCursors.progress,+ 'contextMenu': SystemMouseCursors.contextMenu,+ 'help': SystemMouseCursors.help,+ 'text': SystemMouseCursors.text,+ 'verticalText': SystemMouseCursors.verticalText,+ 'cell': SystemMouseCursors.cell,+ 'precise': SystemMouseCursors.precise,+ 'move': SystemMouseCursors.move,+ 'grab': SystemMouseCursors.grab,+ 'grabbing': SystemMouseCursors.grabbing,+ 'noDrop': SystemMouseCursors.noDrop,+ 'alias': SystemMouseCursors.alias,+ 'copy': SystemMouseCursors.copy,+ 'disappearing': SystemMouseCursors.disappearing,+ 'allScroll': SystemMouseCursors.allScroll,+ 'resizeLeftRight': SystemMouseCursors.resizeLeftRight,+ 'resizeUpDown': SystemMouseCursors.resizeUpDown,+ 'resizeUpLeftDownRight': SystemMouseCursors.resizeUpLeftDownRight,+ 'resizeUpRightDownLeft': SystemMouseCursors.resizeUpRightDownLeft,+ 'resizeUp': SystemMouseCursors.resizeUp,+ 'resizeDown': SystemMouseCursors.resizeDown,+ 'resizeLeft': SystemMouseCursors.resizeLeft,+ 'resizeRight': SystemMouseCursors.resizeRight,+ 'resizeUpLeft': SystemMouseCursors.resizeUpLeft,+ 'resizeUpRight': SystemMouseCursors.resizeUpRight,+ 'resizeDownLeft': SystemMouseCursors.resizeDownLeft,+ 'resizeDownRight': SystemMouseCursors.resizeDownRight,+ 'resizeColumn': SystemMouseCursors.resizeColumn,+ 'resizeRow': SystemMouseCursors.resizeRow,+ 'zoomIn': SystemMouseCursors.zoomIn,+ 'zoomOut': SystemMouseCursors.zoomOut,+};++SystemMouseCursor _getCursorByName(String name) =>+ _cursors[name] ?? SystemMouseCursors.basic;++/// Pointer button type+// Order must match InAppWebViewPointerEventKind (see in_app_webview.h)+enum PointerButton { none, primary, secondary, tertiary }++/// Pointer Event kind+// Order must match InAppWebViewPointerEventKind (see in_app_webview.h)+enum InAppWebViewPointerEventKind { activate, down, enter, leave, up, update }++/// Attempts to translate a button constant such as [kPrimaryMouseButton]+/// to a [PointerButton]+PointerButton _getButton(int value) {+ switch (value) {+ case kPrimaryMouseButton:+ return PointerButton.primary;+ case kSecondaryMouseButton:+ return PointerButton.secondary;+ case kTertiaryButton:+ return PointerButton.tertiary;+ default:+ return PointerButton.none;+ }+}++const MethodChannel _pluginChannel = IN_APP_WEBVIEW_STATIC_CHANNEL;++class CustomFlutterViewControllerValue {+ const CustomFlutterViewControllerValue({+ required this.isInitialized,+ });++ final bool isInitialized;++ CustomFlutterViewControllerValue copyWith({+ bool? isInitialized,+ }) {+ return CustomFlutterViewControllerValue(+ isInitialized: isInitialized ?? this.isInitialized,+ );+ }++ CustomFlutterViewControllerValue.uninitialized()+ : this(+ isInitialized: false,+ );+}++/// Controls a WebView and provides streams for various change events.+class CustomPlatformViewController+ extends ValueNotifier<CustomFlutterViewControllerValue> {+ Completer<void> _creatingCompleter = Completer<void>();+ int _textureId = 0;+ bool _isDisposed = false;++ Future<void> get ready => _creatingCompleter.future;++ late MethodChannel _methodChannel;+ late EventChannel _eventChannel;+ StreamSubscription? _eventStreamSubscription;++ final StreamController<SystemMouseCursor> _cursorStreamController =+ StreamController<SystemMouseCursor>.broadcast();++ /// A stream reflecting the current cursor style.+ Stream<SystemMouseCursor> get _cursor => _cursorStreamController.stream;++ CustomPlatformViewController()+ : super(CustomFlutterViewControllerValue.uninitialized());++ /// Initializes the underlying platform view.+ Future<void> initialize(+ {Function(int id)? onPlatformViewCreated, dynamic arguments}) async {+ if (_isDisposed) {+ return;+ }+ _textureId = (await _pluginChannel.invokeMethod<int>(+ 'createInAppWebView', arguments))!;++ _methodChannel =+ MethodChannel('com.pichillilorenzo/custom_platform_view_$_textureId');+ _eventChannel = EventChannel(+ 'com.pichillilorenzo/custom_platform_view_${_textureId}_events');+ _eventStreamSubscription =+ _eventChannel.receiveBroadcastStream().listen((event) {+ final map = event as Map<dynamic, dynamic>;+ switch (map['type']) {+ case 'cursorChanged':+ _cursorStreamController.add(_getCursorByName(map['value']));+ break;+ }+ });++ _methodChannel.setMethodCallHandler((call) {+ throw MissingPluginException('Unknown method ${call.method}');+ });++ value = value.copyWith(isInitialized: true);++ _creatingCompleter.complete();++ onPlatformViewCreated?.call(_textureId);+ }++ @override+ Future<void> dispose() async {+ await _creatingCompleter.future;+ if (!_isDisposed) {+ _isDisposed = true;+ await _eventStreamSubscription?.cancel();+ await _pluginChannel.invokeMethod('dispose', {"id": _textureId});+ }+ super.dispose();+ }++ /// Limits the number of frames per second to the given value.+ Future<void> setFpsLimit([int? maxFps = 0]) async {+ if (_isDisposed) {+ return;+ }+ assert(value.isInitialized);+ return _methodChannel.invokeMethod('setFpsLimit', maxFps);+ }++ /// Sends a Pointer (Touch) update+ Future<void> _setPointerUpdate(InAppWebViewPointerEventKind kind, int pointer,+ Offset position, double size, double pressure) async {+ if (_isDisposed) {+ return;+ }+ assert(value.isInitialized);+ return _methodChannel.invokeMethod('setPointerUpdate',+ [pointer, kind.index, position.dx, position.dy, size, pressure]);+ }++ /// Moves the virtual cursor to [position].+ Future<void> _setCursorPos(Offset position) async {+ if (_isDisposed) {+ return;+ }+ assert(value.isInitialized);+ return _methodChannel+ .invokeMethod('setCursorPos', [position.dx, position.dy]);+ }++ /// Indicates whether the specified [button] is currently down.+ Future<void> _setPointerButtonState(PointerButton button, bool isDown) async {+ if (_isDisposed) {+ return;+ }+ assert(value.isInitialized);+ return _methodChannel.invokeMethod('setPointerButton',+ <String, dynamic>{'button': button.index, 'isDown': isDown});+ }++ /// Sets the horizontal and vertical scroll delta.+ Future<void> _setScrollDelta(double dx, double dy) async {+ if (_isDisposed) {+ return;+ }+ assert(value.isInitialized);+ return _methodChannel.invokeMethod('setScrollDelta', [dx, dy]);+ }++ /// Sets the surface size to the provided [size].+ Future<void> _setSize(Size size, double scaleFactor) async {+ if (_isDisposed) {+ return;+ }+ assert(value.isInitialized);+ return _methodChannel+ .invokeMethod('setSize', [size.width, size.height, scaleFactor]);+ }++ /// Sets the surface size to the provided [size].+ Future<void> _setPosition(Offset position, double scaleFactor) async {+ if (_isDisposed) {+ return;+ }+ assert(value.isInitialized);+ return _methodChannel+ .invokeMethod('setPosition', [position.dx, position.dy, scaleFactor]);+ }+}++class CustomPlatformView extends StatefulWidget {+ /// An optional scale factor. Defaults to [FlutterView.devicePixelRatio] for+ /// rendering in native resolution.+ /// Setting this to 1.0 will disable high-DPI support.+ /// This should only be needed to mimic old behavior before high-DPI support+ /// was available.+ final double? scaleFactor;++ /// The [FilterQuality] used for scaling the texture's contents.+ /// Defaults to [FilterQuality.none] as this renders in native resolution+ /// unless specifying a [scaleFactor].+ final FilterQuality filterQuality;++ final dynamic creationParams;++ final Function(int id)? onPlatformViewCreated;++ const CustomPlatformView(+ {this.creationParams,+ this.onPlatformViewCreated,+ this.scaleFactor,+ this.filterQuality = FilterQuality.none});++ @override+ _CustomPlatformViewState createState() => _CustomPlatformViewState();+}++class _CustomPlatformViewState extends State<CustomPlatformView> {+ final GlobalKey _key = GlobalKey();+ final _downButtons = <int, PointerButton>{};++ PointerDeviceKind _pointerKind = PointerDeviceKind.unknown;++ MouseCursor _cursor = SystemMouseCursors.basic;++ final _controller = CustomPlatformViewController();+ final _focusNode = FocusNode();++ StreamSubscription? _cursorSubscription;++ @override+ void initState() {+ super.initState();++ _controller.initialize(+ onPlatformViewCreated: (id) {+ widget.onPlatformViewCreated?.call(id);+ setState(() {});+ },+ arguments: widget.creationParams);++ // Report initial surface size and widget position+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _reportSurfaceSize();+ _reportWidgetPosition();+ });++ _cursorSubscription = _controller._cursor.listen((cursor) {+ setState(() {+ _cursor = cursor;+ });+ });+ }++ @override+ Widget build(BuildContext context) {+ return Focus(+ autofocus: true,+ focusNode: _focusNode,+ canRequestFocus: true,+ debugLabel: "flutter_inappwebview_windows_custom_platform_view",+ onFocusChange: (focused) {},+ child: SizedBox.expand(key: _key, child: _buildInner()),+ );+ }++ Widget _buildInner() {+ return NotificationListener<SizeChangedLayoutNotification>(+ onNotification: (notification) {+ _reportSurfaceSize();+ _reportWidgetPosition();+ return true;+ },+ child: SizeChangedLayoutNotifier(+ child: _controller.value.isInitialized+ ? Listener(+ onPointerHover: (ev) {+ // ev.kind is for whatever reason not set to touch+ // even on touch input+ if (_pointerKind == PointerDeviceKind.touch) {+ // Ignoring hover events on touch for now+ return;+ }+ _controller._setCursorPos(ev.localPosition);+ },+ onPointerDown: (ev) {+ _reportSurfaceSize();+ _reportWidgetPosition();++ if (!_focusNode.hasFocus) {+ _focusNode.requestFocus();+ Future.delayed(const Duration(milliseconds: 50), () {+ if (!_focusNode.hasFocus) {+ _focusNode.requestFocus();+ }+ });+ }++ _pointerKind = ev.kind;+ if (ev.kind == PointerDeviceKind.touch) {+ _controller._setPointerUpdate(+ InAppWebViewPointerEventKind.down,+ ev.pointer,+ ev.localPosition,+ ev.size,+ ev.pressure);+ return;+ }+ final button = _getButton(ev.buttons);+ _downButtons[ev.pointer] = button;+ _controller._setPointerButtonState(button, true);+ },+ onPointerUp: (ev) {+ _pointerKind = ev.kind;+ if (ev.kind == PointerDeviceKind.touch) {+ _controller._setPointerUpdate(+ InAppWebViewPointerEventKind.up,+ ev.pointer,+ ev.localPosition,+ ev.size,+ ev.pressure);+ return;+ }+ final button = _downButtons.remove(ev.pointer);+ if (button != null) {+ _controller._setPointerButtonState(button, false);+ }+ },+ onPointerCancel: (ev) {+ _pointerKind = ev.kind;+ final button = _downButtons.remove(ev.pointer);+ if (button != null) {+ _controller._setPointerButtonState(button, false);+ }+ },+ onPointerMove: (ev) {+ _pointerKind = ev.kind;+ if (ev.kind == PointerDeviceKind.touch) {+ _controller._setPointerUpdate(+ InAppWebViewPointerEventKind.update,+ ev.pointer,+ ev.localPosition,+ ev.size,+ ev.pressure);+ } else {+ _controller._setCursorPos(ev.localPosition);+ }+ },+ onPointerSignal: (signal) {+ if (signal is PointerScrollEvent) {+ _controller._setScrollDelta(+ -signal.scrollDelta.dx, -signal.scrollDelta.dy);+ }+ },+ onPointerPanZoomUpdate: (ev) {+ _controller._setScrollDelta(+ ev.panDelta.dx, ev.panDelta.dy);+ },+ child: MouseRegion(+ cursor: _cursor,+ child: Texture(+ textureId: _controller._textureId,+ filterQuality: widget.filterQuality,+ )),+ )+ : const SizedBox()));+ }++ void _reportSurfaceSize() async {+ final box = _key.currentContext?.findRenderObject() as RenderBox?;+ if (box != null) {+ await _controller.ready;+ unawaited(_controller._setSize(+ box.size, widget.scaleFactor ?? window.devicePixelRatio));+ }+ }++ void _reportWidgetPosition() async {+ final box = _key.currentContext?.findRenderObject() as RenderBox?;+ if (box != null) {+ await _controller.ready;+ final position = box.localToGlobal(Offset.zero);+ unawaited(_controller._setPosition(+ position, widget.scaleFactor ?? window.devicePixelRatio));+ }+ }++ @override+ void dispose() {+ super.dispose();+ _cursorSubscription?.cancel();+ _controller.dispose();+ _focusNode.dispose();+ }+}diff --git a/packages/flutter_inappwebview_windows/lib/src/in_app_webview/headless_in_app_webview.dart b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/headless_in_app_webview.dartnew file mode 100644index 00000000..b46a2355--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/headless_in_app_webview.dart@@ -0,0 +1,448 @@+import 'dart:ui';++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';+import '../find_interaction/find_interaction_controller.dart';+import '../webview_environment/webview_environment.dart';+import 'in_app_webview_controller.dart';++/// Object specifying creation parameters for creating a [WindowsHeadlessInAppWebView].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformHeadlessInAppWebViewCreationParams] for+/// more information.+@immutable+class WindowsHeadlessInAppWebViewCreationParams+ extends PlatformHeadlessInAppWebViewCreationParams {+ /// Creates a new [WindowsHeadlessInAppWebViewCreationParams] instance.+ WindowsHeadlessInAppWebViewCreationParams(+ {super.controllerFromPlatform,+ super.initialSize,+ this.webViewEnvironment,+ super.windowId,+ super.onWebViewCreated,+ super.onLoadStart,+ super.onLoadStop,+ @Deprecated('Use onReceivedError instead') super.onLoadError,+ super.onReceivedError,+ @Deprecated("Use onReceivedHttpError instead") super.onLoadHttpError,+ super.onReceivedHttpError,+ super.onProgressChanged,+ super.onConsoleMessage,+ super.shouldOverrideUrlLoading,+ super.onLoadResource,+ super.onScrollChanged,+ @Deprecated('Use onDownloadStartRequest instead') super.onDownloadStart,+ super.onDownloadStartRequest,+ @Deprecated('Use onLoadResourceWithCustomScheme instead')+ super.onLoadResourceCustomScheme,+ super.onLoadResourceWithCustomScheme,+ super.onCreateWindow,+ super.onCloseWindow,+ super.onJsAlert,+ super.onJsConfirm,+ super.onJsPrompt,+ super.onReceivedHttpAuthRequest,+ super.onReceivedServerTrustAuthRequest,+ super.onReceivedClientCertRequest,+ @Deprecated('Use FindInteractionController.onFindResultReceived instead')+ super.onFindResultReceived,+ super.shouldInterceptAjaxRequest,+ super.onAjaxReadyStateChange,+ super.onAjaxProgress,+ super.shouldInterceptFetchRequest,+ super.onUpdateVisitedHistory,+ @Deprecated("Use onPrintRequest instead") super.onPrint,+ super.onPrintRequest,+ super.onLongPressHitTestResult,+ super.onEnterFullscreen,+ super.onExitFullscreen,+ super.onPageCommitVisible,+ super.onTitleChanged,+ super.onWindowFocus,+ super.onWindowBlur,+ super.onOverScrolled,+ super.onZoomScaleChanged,+ @Deprecated('Use onSafeBrowsingHit instead')+ super.androidOnSafeBrowsingHit,+ super.onSafeBrowsingHit,+ @Deprecated('Use onPermissionRequest instead')+ super.androidOnPermissionRequest,+ super.onPermissionRequest,+ @Deprecated('Use onGeolocationPermissionsShowPrompt instead')+ super.androidOnGeolocationPermissionsShowPrompt,+ super.onGeolocationPermissionsShowPrompt,+ @Deprecated('Use onGeolocationPermissionsHidePrompt instead')+ super.androidOnGeolocationPermissionsHidePrompt,+ super.onGeolocationPermissionsHidePrompt,+ @Deprecated('Use shouldInterceptRequest instead')+ super.androidShouldInterceptRequest,+ super.shouldInterceptRequest,+ @Deprecated('Use onRenderProcessGone instead')+ super.androidOnRenderProcessGone,+ super.onRenderProcessGone,+ @Deprecated('Use onRenderProcessResponsive instead')+ super.androidOnRenderProcessResponsive,+ super.onRenderProcessResponsive,+ @Deprecated('Use onRenderProcessUnresponsive instead')+ super.androidOnRenderProcessUnresponsive,+ super.onRenderProcessUnresponsive,+ @Deprecated('Use onFormResubmission instead')+ super.androidOnFormResubmission,+ super.onFormResubmission,+ @Deprecated('Use onZoomScaleChanged instead') super.androidOnScaleChanged,+ @Deprecated('Use onReceivedIcon instead') super.androidOnReceivedIcon,+ super.onReceivedIcon,+ @Deprecated('Use onReceivedTouchIconUrl instead')+ super.androidOnReceivedTouchIconUrl,+ super.onReceivedTouchIconUrl,+ @Deprecated('Use onJsBeforeUnload instead') super.androidOnJsBeforeUnload,+ super.onJsBeforeUnload,+ @Deprecated('Use onReceivedLoginRequest instead')+ super.androidOnReceivedLoginRequest,+ super.onReceivedLoginRequest,+ super.onPermissionRequestCanceled,+ super.onRequestFocus,+ @Deprecated('Use onWebContentProcessDidTerminate instead')+ super.iosOnWebContentProcessDidTerminate,+ super.onWebContentProcessDidTerminate,+ @Deprecated(+ 'Use onDidReceiveServerRedirectForProvisionalNavigation instead')+ super.iosOnDidReceiveServerRedirectForProvisionalNavigation,+ super.onDidReceiveServerRedirectForProvisionalNavigation,+ @Deprecated('Use onNavigationResponse instead')+ super.iosOnNavigationResponse,+ super.onNavigationResponse,+ @Deprecated('Use shouldAllowDeprecatedTLS instead')+ super.iosShouldAllowDeprecatedTLS,+ super.shouldAllowDeprecatedTLS,+ super.onCameraCaptureStateChanged,+ super.onMicrophoneCaptureStateChanged,+ super.onContentSizeChanged,+ super.initialUrlRequest,+ super.initialFile,+ super.initialData,+ @Deprecated('Use initialSettings instead') super.initialOptions,+ super.initialSettings,+ super.contextMenu,+ super.initialUserScripts,+ super.pullToRefreshController,+ this.findInteractionController});++ /// Creates a [WindowsHeadlessInAppWebViewCreationParams] instance based on [PlatformHeadlessInAppWebViewCreationParams].+ WindowsHeadlessInAppWebViewCreationParams.fromPlatformHeadlessInAppWebViewCreationParams(+ PlatformHeadlessInAppWebViewCreationParams params)+ : this(+ controllerFromPlatform: params.controllerFromPlatform,+ webViewEnvironment:+ params.webViewEnvironment as WindowsWebViewEnvironment?,+ initialSize: params.initialSize,+ windowId: params.windowId,+ onWebViewCreated: params.onWebViewCreated,+ onLoadStart: params.onLoadStart,+ onLoadStop: params.onLoadStop,+ onLoadError: params.onLoadError,+ onReceivedError: params.onReceivedError,+ onLoadHttpError: params.onLoadHttpError,+ onReceivedHttpError: params.onReceivedHttpError,+ onProgressChanged: params.onProgressChanged,+ onConsoleMessage: params.onConsoleMessage,+ shouldOverrideUrlLoading: params.shouldOverrideUrlLoading,+ onLoadResource: params.onLoadResource,+ onScrollChanged: params.onScrollChanged,+ onDownloadStart: params.onDownloadStart,+ onDownloadStartRequest: params.onDownloadStartRequest,+ onLoadResourceCustomScheme: params.onLoadResourceCustomScheme,+ onLoadResourceWithCustomScheme:+ params.onLoadResourceWithCustomScheme,+ onCreateWindow: params.onCreateWindow,+ onCloseWindow: params.onCloseWindow,+ onJsAlert: params.onJsAlert,+ onJsConfirm: params.onJsConfirm,+ onJsPrompt: params.onJsPrompt,+ onReceivedHttpAuthRequest: params.onReceivedHttpAuthRequest,+ onReceivedServerTrustAuthRequest:+ params.onReceivedServerTrustAuthRequest,+ onReceivedClientCertRequest: params.onReceivedClientCertRequest,+ onFindResultReceived: params.onFindResultReceived,+ shouldInterceptAjaxRequest: params.shouldInterceptAjaxRequest,+ onAjaxReadyStateChange: params.onAjaxReadyStateChange,+ onAjaxProgress: params.onAjaxProgress,+ shouldInterceptFetchRequest: params.shouldInterceptFetchRequest,+ onUpdateVisitedHistory: params.onUpdateVisitedHistory,+ onPrint: params.onPrint,+ onPrintRequest: params.onPrintRequest,+ onLongPressHitTestResult: params.onLongPressHitTestResult,+ onEnterFullscreen: params.onEnterFullscreen,+ onExitFullscreen: params.onExitFullscreen,+ onPageCommitVisible: params.onPageCommitVisible,+ onTitleChanged: params.onTitleChanged,+ onWindowFocus: params.onWindowFocus,+ onWindowBlur: params.onWindowBlur,+ onOverScrolled: params.onOverScrolled,+ onZoomScaleChanged: params.onZoomScaleChanged,+ androidOnSafeBrowsingHit: params.androidOnSafeBrowsingHit,+ onSafeBrowsingHit: params.onSafeBrowsingHit,+ androidOnPermissionRequest: params.androidOnPermissionRequest,+ onPermissionRequest: params.onPermissionRequest,+ androidOnGeolocationPermissionsShowPrompt:+ params.androidOnGeolocationPermissionsShowPrompt,+ onGeolocationPermissionsShowPrompt:+ params.onGeolocationPermissionsShowPrompt,+ androidOnGeolocationPermissionsHidePrompt:+ params.androidOnGeolocationPermissionsHidePrompt,+ onGeolocationPermissionsHidePrompt:+ params.onGeolocationPermissionsHidePrompt,+ androidShouldInterceptRequest: params.androidShouldInterceptRequest,+ shouldInterceptRequest: params.shouldInterceptRequest,+ androidOnRenderProcessGone: params.androidOnRenderProcessGone,+ onRenderProcessGone: params.onRenderProcessGone,+ androidOnRenderProcessResponsive:+ params.androidOnRenderProcessResponsive,+ onRenderProcessResponsive: params.onRenderProcessResponsive,+ androidOnRenderProcessUnresponsive:+ params.androidOnRenderProcessUnresponsive,+ onRenderProcessUnresponsive: params.onRenderProcessUnresponsive,+ androidOnFormResubmission: params.androidOnFormResubmission,+ onFormResubmission: params.onFormResubmission,+ androidOnScaleChanged: params.androidOnScaleChanged,+ androidOnReceivedIcon: params.androidOnReceivedIcon,+ onReceivedIcon: params.onReceivedIcon,+ androidOnReceivedTouchIconUrl: params.androidOnReceivedTouchIconUrl,+ onReceivedTouchIconUrl: params.onReceivedTouchIconUrl,+ androidOnJsBeforeUnload: params.androidOnJsBeforeUnload,+ onJsBeforeUnload: params.onJsBeforeUnload,+ androidOnReceivedLoginRequest: params.androidOnReceivedLoginRequest,+ onReceivedLoginRequest: params.onReceivedLoginRequest,+ onPermissionRequestCanceled: params.onPermissionRequestCanceled,+ onRequestFocus: params.onRequestFocus,+ iosOnWebContentProcessDidTerminate:+ params.iosOnWebContentProcessDidTerminate,+ onWebContentProcessDidTerminate:+ params.onWebContentProcessDidTerminate,+ iosOnDidReceiveServerRedirectForProvisionalNavigation:+ params.iosOnDidReceiveServerRedirectForProvisionalNavigation,+ onDidReceiveServerRedirectForProvisionalNavigation:+ params.onDidReceiveServerRedirectForProvisionalNavigation,+ iosOnNavigationResponse: params.iosOnNavigationResponse,+ onNavigationResponse: params.onNavigationResponse,+ iosShouldAllowDeprecatedTLS: params.iosShouldAllowDeprecatedTLS,+ shouldAllowDeprecatedTLS: params.shouldAllowDeprecatedTLS,+ onCameraCaptureStateChanged: params.onCameraCaptureStateChanged,+ onMicrophoneCaptureStateChanged:+ params.onMicrophoneCaptureStateChanged,+ onContentSizeChanged: params.onContentSizeChanged,+ initialUrlRequest: params.initialUrlRequest,+ initialFile: params.initialFile,+ initialData: params.initialData,+ initialOptions: params.initialOptions,+ initialSettings: params.initialSettings,+ contextMenu: params.contextMenu,+ initialUserScripts: params.initialUserScripts,+ pullToRefreshController: params.pullToRefreshController,+ findInteractionController: params.findInteractionController+ as WindowsFindInteractionController?);++ @override+ final WindowsFindInteractionController? findInteractionController;++ @override+ final WindowsWebViewEnvironment? webViewEnvironment;+}++///{@macro flutter_inappwebview_platform_interface.PlatformHeadlessInAppWebView}+class WindowsHeadlessInAppWebView extends PlatformHeadlessInAppWebView+ with ChannelController {+ @override+ late final String id;++ bool _started = false;+ bool _running = false;++ static const MethodChannel _sharedChannel =+ const MethodChannel('com.pichillilorenzo/flutter_headless_inappwebview');++ WindowsInAppWebViewController? _webViewController;++ /// Constructs a [WindowsHeadlessInAppWebView].+ WindowsHeadlessInAppWebView(PlatformHeadlessInAppWebViewCreationParams params)+ : super.implementation(+ params is WindowsHeadlessInAppWebViewCreationParams+ ? params+ : WindowsHeadlessInAppWebViewCreationParams+ .fromPlatformHeadlessInAppWebViewCreationParams(params),+ ) {+ id = IdGenerator.generate();+ }++ @override+ WindowsInAppWebViewController? get webViewController => _webViewController;++ dynamic _controllerFromPlatform;++ WindowsHeadlessInAppWebViewCreationParams get _windowsParams =>+ params as WindowsHeadlessInAppWebViewCreationParams;++ _init() {+ _webViewController = WindowsInAppWebViewController(+ WindowsInAppWebViewControllerCreationParams(+ id: id, webviewParams: params),+ );+ _controllerFromPlatform =+ params.controllerFromPlatform?.call(_webViewController!) ??+ _webViewController!;+ _windowsParams.findInteractionController?.init(id);+ channel =+ MethodChannel('com.pichillilorenzo/flutter_headless_inappwebview_$id');+ handler = _handleMethod;+ initMethodCallHandler();+ }++ Future<dynamic> _handleMethod(MethodCall call) async {+ switch (call.method) {+ case "onWebViewCreated":+ if (params.onWebViewCreated != null && _webViewController != null) {+ params.onWebViewCreated!(_controllerFromPlatform);+ }+ break;+ default:+ throw UnimplementedError("Unimplemented ${call.method} method");+ }+ return null;+ }++ Future<void> run() async {+ if (_started) {+ return;+ }+ _started = true;+ _init();++ final initialSettings = params.initialSettings ?? InAppWebViewSettings();+ _inferInitialSettings(initialSettings);++ Map<String, dynamic> settingsMap =+ (params.initialSettings != null ? initialSettings.toMap() : null) ??+ params.initialOptions?.toMap() ??+ initialSettings.toMap();++ Map<String, dynamic> pullToRefreshSettings =+ _windowsParams.pullToRefreshController?.params.settings.toMap() ??+ _windowsParams.pullToRefreshController?.params.options.toMap() ??+ PullToRefreshSettings(enabled: false).toMap();++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('id', () => id);+ args.putIfAbsent(+ 'params',+ () => <String, dynamic>{+ 'initialUrlRequest': params.initialUrlRequest?.toMap(),+ 'initialFile': params.initialFile,+ 'initialData': params.initialData?.toMap(),+ 'initialSettings': settingsMap,+ 'contextMenu': params.contextMenu?.toMap() ?? {},+ 'windowId': params.windowId,+ 'initialUserScripts':+ params.initialUserScripts?.map((e) => e.toMap()).toList() ??+ [],+ 'pullToRefreshSettings': pullToRefreshSettings,+ 'initialSize': params.initialSize.toMap(),+ 'webViewEnvironmentId': params.webViewEnvironment?.id,+ });+ try {+ await _sharedChannel.invokeMethod('run', args);+ _running = true;+ } catch (e) {+ _running = false;+ _started = false;+ throw e;+ }+ }++ void _inferInitialSettings(InAppWebViewSettings settings) {+ if (params.shouldOverrideUrlLoading != null &&+ settings.useShouldOverrideUrlLoading == null) {+ settings.useShouldOverrideUrlLoading = true;+ }+ if (params.onLoadResource != null && settings.useOnLoadResource == null) {+ settings.useOnLoadResource = true;+ }+ if (params.onDownloadStartRequest != null &&+ settings.useOnDownloadStart == null) {+ settings.useOnDownloadStart = true;+ }+ if (params.shouldInterceptAjaxRequest != null &&+ settings.useShouldInterceptAjaxRequest == null) {+ settings.useShouldInterceptAjaxRequest = true;+ }+ if (params.shouldInterceptFetchRequest != null &&+ settings.useShouldInterceptFetchRequest == null) {+ settings.useShouldInterceptFetchRequest = true;+ }+ if (params.shouldInterceptRequest != null &&+ settings.useShouldInterceptRequest == null) {+ settings.useShouldInterceptRequest = true;+ }+ if (params.onRenderProcessGone != null &&+ settings.useOnRenderProcessGone == null) {+ settings.useOnRenderProcessGone = true;+ }+ if (params.onNavigationResponse != null &&+ settings.useOnNavigationResponse == null) {+ settings.useOnNavigationResponse = true;+ }+ }++ @override+ bool isRunning() {+ return _running;+ }++ @override+ Future<void> setSize(Size size) async {+ if (!_running) {+ return;+ }++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('size', () => size.toMap());+ await channel?.invokeMethod('setSize', args);+ }++ @override+ Future<Size?> getSize() async {+ if (!_running) {+ return null;+ }++ Map<String, dynamic> args = <String, dynamic>{};+ Map<String, dynamic> sizeMap =+ (await channel?.invokeMethod('getSize', args))?.cast<String, dynamic>();+ return MapSize.fromMap(sizeMap);+ }++ @override+ Future<void> dispose() async {+ if (!_running) {+ return;+ }+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('dispose', args);+ disposeChannel();+ _started = false;+ _running = false;+ _webViewController?.dispose();+ _webViewController = null;+ _controllerFromPlatform = null;+ _windowsParams.pullToRefreshController?.dispose();+ _windowsParams.findInteractionController?.dispose();+ }+}++extension InternalHeadlessInAppWebView on WindowsHeadlessInAppWebView {+ Future<void> internalDispose() async {+ _started = false;+ _running = false;+ }+}diff --git a/packages/flutter_inappwebview_windows/lib/src/in_app_webview/in_app_webview.dart b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/in_app_webview.dartnew file mode 100644index 00000000..0b2c515d--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/in_app_webview.dart@@ -0,0 +1,412 @@+import 'package:flutter/material.dart';+import 'package:flutter/widgets.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';+import '../webview_environment/webview_environment.dart';+import 'headless_in_app_webview.dart';++import '../find_interaction/find_interaction_controller.dart';+import 'in_app_webview_controller.dart';++import 'custom_platform_view.dart';++/// Object specifying creation parameters for creating a [PlatformInAppWebViewWidget].+///+/// Platform specific implementations can add additional fields by extending+/// this class.+class WindowsInAppWebViewWidgetCreationParams+ extends PlatformInAppWebViewWidgetCreationParams {+ WindowsInAppWebViewWidgetCreationParams(+ {super.controllerFromPlatform,+ super.key,+ super.layoutDirection,+ super.gestureRecognizers,+ super.headlessWebView,+ super.keepAlive,+ super.preventGestureDelay,+ super.windowId,+ this.webViewEnvironment,+ super.onWebViewCreated,+ super.onLoadStart,+ super.onLoadStop,+ @Deprecated('Use onReceivedError instead') super.onLoadError,+ super.onReceivedError,+ @Deprecated("Use onReceivedHttpError instead") super.onLoadHttpError,+ super.onReceivedHttpError,+ super.onProgressChanged,+ super.onConsoleMessage,+ super.shouldOverrideUrlLoading,+ super.onLoadResource,+ super.onScrollChanged,+ @Deprecated('Use onDownloadStartRequest instead') super.onDownloadStart,+ super.onDownloadStartRequest,+ @Deprecated('Use onLoadResourceWithCustomScheme instead')+ super.onLoadResourceCustomScheme,+ super.onLoadResourceWithCustomScheme,+ super.onCreateWindow,+ super.onCloseWindow,+ super.onJsAlert,+ super.onJsConfirm,+ super.onJsPrompt,+ super.onReceivedHttpAuthRequest,+ super.onReceivedServerTrustAuthRequest,+ super.onReceivedClientCertRequest,+ @Deprecated('Use FindInteractionController.onFindResultReceived instead')+ super.onFindResultReceived,+ super.shouldInterceptAjaxRequest,+ super.onAjaxReadyStateChange,+ super.onAjaxProgress,+ super.shouldInterceptFetchRequest,+ super.onUpdateVisitedHistory,+ @Deprecated("Use onPrintRequest instead") super.onPrint,+ super.onPrintRequest,+ super.onLongPressHitTestResult,+ super.onEnterFullscreen,+ super.onExitFullscreen,+ super.onPageCommitVisible,+ super.onTitleChanged,+ super.onWindowFocus,+ super.onWindowBlur,+ super.onOverScrolled,+ super.onZoomScaleChanged,+ @Deprecated('Use onSafeBrowsingHit instead')+ super.androidOnSafeBrowsingHit,+ super.onSafeBrowsingHit,+ @Deprecated('Use onPermissionRequest instead')+ super.androidOnPermissionRequest,+ super.onPermissionRequest,+ @Deprecated('Use onGeolocationPermissionsShowPrompt instead')+ super.androidOnGeolocationPermissionsShowPrompt,+ super.onGeolocationPermissionsShowPrompt,+ @Deprecated('Use onGeolocationPermissionsHidePrompt instead')+ super.androidOnGeolocationPermissionsHidePrompt,+ super.onGeolocationPermissionsHidePrompt,+ @Deprecated('Use shouldInterceptRequest instead')+ super.androidShouldInterceptRequest,+ super.shouldInterceptRequest,+ @Deprecated('Use onRenderProcessGone instead')+ super.androidOnRenderProcessGone,+ super.onRenderProcessGone,+ @Deprecated('Use onRenderProcessResponsive instead')+ super.androidOnRenderProcessResponsive,+ super.onRenderProcessResponsive,+ @Deprecated('Use onRenderProcessUnresponsive instead')+ super.androidOnRenderProcessUnresponsive,+ super.onRenderProcessUnresponsive,+ @Deprecated('Use onFormResubmission instead')+ super.androidOnFormResubmission,+ super.onFormResubmission,+ @Deprecated('Use onZoomScaleChanged instead') super.androidOnScaleChanged,+ @Deprecated('Use onReceivedIcon instead') super.androidOnReceivedIcon,+ super.onReceivedIcon,+ @Deprecated('Use onReceivedTouchIconUrl instead')+ super.androidOnReceivedTouchIconUrl,+ super.onReceivedTouchIconUrl,+ @Deprecated('Use onJsBeforeUnload instead') super.androidOnJsBeforeUnload,+ super.onJsBeforeUnload,+ @Deprecated('Use onReceivedLoginRequest instead')+ super.androidOnReceivedLoginRequest,+ super.onReceivedLoginRequest,+ super.onPermissionRequestCanceled,+ super.onRequestFocus,+ @Deprecated('Use onWebContentProcessDidTerminate instead')+ super.iosOnWebContentProcessDidTerminate,+ super.onWebContentProcessDidTerminate,+ @Deprecated(+ 'Use onDidReceiveServerRedirectForProvisionalNavigation instead')+ super.iosOnDidReceiveServerRedirectForProvisionalNavigation,+ super.onDidReceiveServerRedirectForProvisionalNavigation,+ @Deprecated('Use onNavigationResponse instead')+ super.iosOnNavigationResponse,+ super.onNavigationResponse,+ @Deprecated('Use shouldAllowDeprecatedTLS instead')+ super.iosShouldAllowDeprecatedTLS,+ super.shouldAllowDeprecatedTLS,+ super.onCameraCaptureStateChanged,+ super.onMicrophoneCaptureStateChanged,+ super.onContentSizeChanged,+ super.initialUrlRequest,+ super.initialFile,+ super.initialData,+ @Deprecated('Use initialSettings instead') super.initialOptions,+ super.initialSettings,+ super.contextMenu,+ super.initialUserScripts,+ super.pullToRefreshController,+ this.findInteractionController});++ /// Constructs a [WindowsInAppWebViewWidgetCreationParams] using a+ /// [PlatformInAppWebViewWidgetCreationParams].+ WindowsInAppWebViewWidgetCreationParams.fromPlatformInAppWebViewWidgetCreationParams(+ PlatformInAppWebViewWidgetCreationParams params)+ : this(+ controllerFromPlatform: params.controllerFromPlatform,+ key: params.key,+ layoutDirection: params.layoutDirection,+ gestureRecognizers: params.gestureRecognizers,+ headlessWebView: params.headlessWebView,+ keepAlive: params.keepAlive,+ preventGestureDelay: params.preventGestureDelay,+ windowId: params.windowId,+ webViewEnvironment:+ params.webViewEnvironment as WindowsWebViewEnvironment?,+ onWebViewCreated: params.onWebViewCreated,+ onLoadStart: params.onLoadStart,+ onLoadStop: params.onLoadStop,+ onLoadError: params.onLoadError,+ onReceivedError: params.onReceivedError,+ onLoadHttpError: params.onLoadHttpError,+ onReceivedHttpError: params.onReceivedHttpError,+ onProgressChanged: params.onProgressChanged,+ onConsoleMessage: params.onConsoleMessage,+ shouldOverrideUrlLoading: params.shouldOverrideUrlLoading,+ onLoadResource: params.onLoadResource,+ onScrollChanged: params.onScrollChanged,+ onDownloadStart: params.onDownloadStart,+ onDownloadStartRequest: params.onDownloadStartRequest,+ onLoadResourceCustomScheme: params.onLoadResourceCustomScheme,+ onLoadResourceWithCustomScheme:+ params.onLoadResourceWithCustomScheme,+ onCreateWindow: params.onCreateWindow,+ onCloseWindow: params.onCloseWindow,+ onJsAlert: params.onJsAlert,+ onJsConfirm: params.onJsConfirm,+ onJsPrompt: params.onJsPrompt,+ onReceivedHttpAuthRequest: params.onReceivedHttpAuthRequest,+ onReceivedServerTrustAuthRequest:+ params.onReceivedServerTrustAuthRequest,+ onReceivedClientCertRequest: params.onReceivedClientCertRequest,+ onFindResultReceived: params.onFindResultReceived,+ shouldInterceptAjaxRequest: params.shouldInterceptAjaxRequest,+ onAjaxReadyStateChange: params.onAjaxReadyStateChange,+ onAjaxProgress: params.onAjaxProgress,+ shouldInterceptFetchRequest: params.shouldInterceptFetchRequest,+ onUpdateVisitedHistory: params.onUpdateVisitedHistory,+ onPrint: params.onPrint,+ onPrintRequest: params.onPrintRequest,+ onLongPressHitTestResult: params.onLongPressHitTestResult,+ onEnterFullscreen: params.onEnterFullscreen,+ onExitFullscreen: params.onExitFullscreen,+ onPageCommitVisible: params.onPageCommitVisible,+ onTitleChanged: params.onTitleChanged,+ onWindowFocus: params.onWindowFocus,+ onWindowBlur: params.onWindowBlur,+ onOverScrolled: params.onOverScrolled,+ onZoomScaleChanged: params.onZoomScaleChanged,+ androidOnSafeBrowsingHit: params.androidOnSafeBrowsingHit,+ onSafeBrowsingHit: params.onSafeBrowsingHit,+ androidOnPermissionRequest: params.androidOnPermissionRequest,+ onPermissionRequest: params.onPermissionRequest,+ androidOnGeolocationPermissionsShowPrompt:+ params.androidOnGeolocationPermissionsShowPrompt,+ onGeolocationPermissionsShowPrompt:+ params.onGeolocationPermissionsShowPrompt,+ androidOnGeolocationPermissionsHidePrompt:+ params.androidOnGeolocationPermissionsHidePrompt,+ onGeolocationPermissionsHidePrompt:+ params.onGeolocationPermissionsHidePrompt,+ androidShouldInterceptRequest: params.androidShouldInterceptRequest,+ shouldInterceptRequest: params.shouldInterceptRequest,+ androidOnRenderProcessGone: params.androidOnRenderProcessGone,+ onRenderProcessGone: params.onRenderProcessGone,+ androidOnRenderProcessResponsive:+ params.androidOnRenderProcessResponsive,+ onRenderProcessResponsive: params.onRenderProcessResponsive,+ androidOnRenderProcessUnresponsive:+ params.androidOnRenderProcessUnresponsive,+ onRenderProcessUnresponsive: params.onRenderProcessUnresponsive,+ androidOnFormResubmission: params.androidOnFormResubmission,+ onFormResubmission: params.onFormResubmission,+ androidOnScaleChanged: params.androidOnScaleChanged,+ androidOnReceivedIcon: params.androidOnReceivedIcon,+ onReceivedIcon: params.onReceivedIcon,+ androidOnReceivedTouchIconUrl: params.androidOnReceivedTouchIconUrl,+ onReceivedTouchIconUrl: params.onReceivedTouchIconUrl,+ androidOnJsBeforeUnload: params.androidOnJsBeforeUnload,+ onJsBeforeUnload: params.onJsBeforeUnload,+ androidOnReceivedLoginRequest: params.androidOnReceivedLoginRequest,+ onReceivedLoginRequest: params.onReceivedLoginRequest,+ onPermissionRequestCanceled: params.onPermissionRequestCanceled,+ onRequestFocus: params.onRequestFocus,+ iosOnWebContentProcessDidTerminate:+ params.iosOnWebContentProcessDidTerminate,+ onWebContentProcessDidTerminate:+ params.onWebContentProcessDidTerminate,+ iosOnDidReceiveServerRedirectForProvisionalNavigation:+ params.iosOnDidReceiveServerRedirectForProvisionalNavigation,+ onDidReceiveServerRedirectForProvisionalNavigation:+ params.onDidReceiveServerRedirectForProvisionalNavigation,+ iosOnNavigationResponse: params.iosOnNavigationResponse,+ onNavigationResponse: params.onNavigationResponse,+ iosShouldAllowDeprecatedTLS: params.iosShouldAllowDeprecatedTLS,+ shouldAllowDeprecatedTLS: params.shouldAllowDeprecatedTLS,+ onCameraCaptureStateChanged: params.onCameraCaptureStateChanged,+ onMicrophoneCaptureStateChanged:+ params.onMicrophoneCaptureStateChanged,+ onContentSizeChanged: params.onContentSizeChanged,+ initialUrlRequest: params.initialUrlRequest,+ initialFile: params.initialFile,+ initialData: params.initialData,+ initialOptions: params.initialOptions,+ initialSettings: params.initialSettings,+ contextMenu: params.contextMenu,+ initialUserScripts: params.initialUserScripts,+ pullToRefreshController: params.pullToRefreshController,+ findInteractionController: params.findInteractionController+ as WindowsFindInteractionController?);++ @override+ final WindowsFindInteractionController? findInteractionController;++ @override+ final WindowsWebViewEnvironment? webViewEnvironment;+}++///{@macro flutter_inappwebview_platform_interface.PlatformInAppWebViewWidget}+class WindowsInAppWebViewWidget extends PlatformInAppWebViewWidget {+ /// Constructs a [WindowsInAppWebViewWidget].+ ///+ ///{@macro flutter_inappwebview_platform_interface.PlatformInAppWebViewWidget}+ WindowsInAppWebViewWidget(PlatformInAppWebViewWidgetCreationParams params)+ : super.implementation(+ params is WindowsInAppWebViewWidgetCreationParams+ ? params+ : WindowsInAppWebViewWidgetCreationParams+ .fromPlatformInAppWebViewWidgetCreationParams(params),+ );++ WindowsInAppWebViewWidgetCreationParams get _windowsParams =>+ params as WindowsInAppWebViewWidgetCreationParams;++ WindowsInAppWebViewController? _controller;++ WindowsHeadlessInAppWebView? get _windowsHeadlessInAppWebView =>+ params.headlessWebView as WindowsHeadlessInAppWebView?;++ @override+ Widget build(BuildContext context) {+ final initialSettings = params.initialSettings ?? InAppWebViewSettings();+ _inferInitialSettings(initialSettings);++ Map<String, dynamic> settingsMap =+ (params.initialSettings != null ? initialSettings.toMap() : null) ??+ // ignore: deprecated_member_use_from_same_package+ params.initialOptions?.toMap() ??+ initialSettings.toMap();++ Map<String, dynamic> pullToRefreshSettings =+ params.pullToRefreshController?.params.settings.toMap() ??+ // ignore: deprecated_member_use_from_same_package+ params.pullToRefreshController?.params.options.toMap() ??+ PullToRefreshSettings(enabled: false).toMap();++ if ((params.headlessWebView?.isRunning() ?? false) &&+ params.keepAlive != null) {+ final headlessId = params.headlessWebView?.id;+ if (headlessId != null) {+ // force keep alive id to match headless webview id+ params.keepAlive?.id = headlessId;+ }+ }++ return CustomPlatformView(+ onPlatformViewCreated: _onPlatformViewCreated,+ creationParams: <String, dynamic>{+ 'initialUrlRequest': params.initialUrlRequest?.toMap(),+ 'initialFile': params.initialFile,+ 'initialData': params.initialData?.toMap(),+ 'initialSettings': settingsMap,+ 'contextMenu': params.contextMenu?.toMap() ?? {},+ 'windowId': params.windowId,+ 'headlessWebViewId': params.headlessWebView?.isRunning() ?? false+ ? params.headlessWebView?.id+ : null,+ 'initialUserScripts':+ params.initialUserScripts?.map((e) => e.toMap()).toList() ?? [],+ 'keepAliveId': params.keepAlive?.id,+ 'webViewEnvironmentId': params.webViewEnvironment?.id,+ },+ );+ }++ void _onPlatformViewCreated(int id) {+ dynamic viewId = id;+ if (params.headlessWebView?.isRunning() ?? false) {+ viewId = params.headlessWebView?.id;+ }+ viewId = params.keepAlive?.id ?? viewId ?? id;+ _windowsHeadlessInAppWebView?.internalDispose();+ _controller = WindowsInAppWebViewController(+ PlatformInAppWebViewControllerCreationParams(+ id: viewId, webviewParams: params));+ _windowsParams.findInteractionController?.init(viewId);+ debugLog(+ className: runtimeType.toString(),+ id: viewId?.toString(),+ debugLoggingSettings:+ PlatformInAppWebViewController.debugLoggingSettings,+ method: "onWebViewCreated",+ args: []);+ if (params.onWebViewCreated != null) {+ params.onWebViewCreated!(+ params.controllerFromPlatform?.call(_controller!) ?? _controller!);+ }+ }++ void _inferInitialSettings(InAppWebViewSettings settings) {+ if (params.shouldOverrideUrlLoading != null &&+ settings.useShouldOverrideUrlLoading == null) {+ settings.useShouldOverrideUrlLoading = true;+ }+ if (params.onLoadResource != null && settings.useOnLoadResource == null) {+ settings.useOnLoadResource = true;+ }+ if (params.onDownloadStartRequest != null &&+ settings.useOnDownloadStart == null) {+ settings.useOnDownloadStart = true;+ }+ if ((params.shouldInterceptAjaxRequest != null ||+ params.onAjaxProgress != null ||+ params.onAjaxReadyStateChange != null) &&+ settings.useShouldInterceptAjaxRequest == null) {+ settings.useShouldInterceptAjaxRequest = true;+ }+ if (params.shouldInterceptFetchRequest != null &&+ settings.useShouldInterceptFetchRequest == null) {+ settings.useShouldInterceptFetchRequest = true;+ }+ if (params.shouldInterceptRequest != null &&+ settings.useShouldInterceptRequest == null) {+ settings.useShouldInterceptRequest = true;+ }+ if (params.onRenderProcessGone != null &&+ settings.useOnRenderProcessGone == null) {+ settings.useOnRenderProcessGone = true;+ }+ if (params.onNavigationResponse != null &&+ settings.useOnNavigationResponse == null) {+ settings.useOnNavigationResponse = true;+ }+ }++ @override+ void dispose() {+ dynamic viewId = _controller?.getViewId();+ debugLog(+ className: runtimeType.toString(),+ id: viewId?.toString(),+ debugLoggingSettings:+ PlatformInAppWebViewController.debugLoggingSettings,+ method: "dispose",+ args: []);+ final isKeepAlive = params.keepAlive != null;+ _controller?.dispose(isKeepAlive: isKeepAlive);+ _controller = null;+ params.findInteractionController?.dispose(isKeepAlive: isKeepAlive);+ }++ @override+ T controllerFromPlatform<T>(PlatformInAppWebViewController controller) {+ // unused+ throw UnimplementedError();+ }+}diff --git a/packages/flutter_inappwebview_windows/lib/src/in_app_webview/in_app_webview_controller.dart b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/in_app_webview_controller.dartnew file mode 100644index 00000000..8f1ab3ff--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/in_app_webview_controller.dart@@ -0,0 +1,2775 @@+import 'dart:io';+import 'dart:collection';+import 'dart:convert';+import 'dart:core';+import 'dart:developer' as developer;+import 'dart:typed_data';+import 'dart:ui';++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++import '../web_message/main.dart';++import '../in_app_browser/in_app_browser.dart';+import '../web_storage/web_storage.dart';++import 'headless_in_app_webview.dart';+import '_static_channel.dart';++import '../print_job/main.dart';++///List of forbidden names for JavaScript handlers.+// ignore: non_constant_identifier_names+final _JAVASCRIPT_HANDLER_FORBIDDEN_NAMES = UnmodifiableListView<String>([+ "onLoadResource",+ "shouldInterceptAjaxRequest",+ "onAjaxReadyStateChange",+ "onAjaxProgress",+ "shouldInterceptFetchRequest",+ "onPrintRequest",+ "onWindowFocus",+ "onWindowBlur",+ "callAsyncJavaScript",+ "evaluateJavaScriptWithContentWorld"+]);++/// Object specifying creation parameters for creating a [WindowsInAppWebViewController].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformInAppWebViewControllerCreationParams] for+/// more information.+@immutable+class WindowsInAppWebViewControllerCreationParams+ extends PlatformInAppWebViewControllerCreationParams {+ /// Creates a new [WindowsInAppWebViewControllerCreationParams] instance.+ const WindowsInAppWebViewControllerCreationParams(+ {required super.id, super.webviewParams});++ /// Creates a [WindowsInAppWebViewControllerCreationParams] instance based on [PlatformInAppWebViewControllerCreationParams].+ factory WindowsInAppWebViewControllerCreationParams.fromPlatformInAppWebViewControllerCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformInAppWebViewControllerCreationParams params) {+ return WindowsInAppWebViewControllerCreationParams(+ id: params.id, webviewParams: params.webviewParams);+ }+}++///Controls a WebView, such as an [InAppWebView] widget instance, a [WindowsHeadlessInAppWebView] instance or [WindowsInAppBrowser] WebView instance.+///+///If you are using the [InAppWebView] widget, an [InAppWebViewController] instance can be obtained by setting the [InAppWebView.onWebViewCreated]+///callback. Instead, if you are using an [WindowsInAppBrowser] instance, you can get it through the [WindowsInAppBrowser.webViewController] attribute.+class WindowsInAppWebViewController extends PlatformInAppWebViewController+ with ChannelController {+ static final MethodChannel _staticChannel = IN_APP_WEBVIEW_STATIC_CHANNEL;++ // List of properties to be saved and restored for keep alive feature+ Map<String, JavaScriptHandlerCallback> _javaScriptHandlersMap =+ HashMap<String, JavaScriptHandlerCallback>();+ Map<UserScriptInjectionTime, List<UserScript>> _userScripts = {+ UserScriptInjectionTime.AT_DOCUMENT_START: <UserScript>[],+ UserScriptInjectionTime.AT_DOCUMENT_END: <UserScript>[]+ };+ Set<String> _webMessageListenerObjNames = Set();+ Map<String, ScriptHtmlTagAttributes> _injectedScriptsFromURL = {};+ Set<WindowsWebMessageChannel> _webMessageChannels = Set();+ Set<WindowsWebMessageListener> _webMessageListeners = Set();+ Map<String, Function(dynamic data)> _devToolsProtocolEventListenerMap =+ HashMap();++ // static map that contains the properties to be saved and restored for keep alive feature+ static final Map<InAppWebViewKeepAlive, InAppWebViewControllerKeepAliveProps?>+ _keepAliveMap = {};++ WindowsInAppBrowser? _inAppBrowser;++ PlatformInAppBrowserEvents? get _inAppBrowserEventHandler =>+ _inAppBrowser?.eventHandler;++ dynamic _controllerFromPlatform;++ @override+ late WindowsWebStorage webStorage;++ WindowsInAppWebViewController(+ PlatformInAppWebViewControllerCreationParams params)+ : super.implementation(params+ is WindowsInAppWebViewControllerCreationParams+ ? params+ : WindowsInAppWebViewControllerCreationParams+ .fromPlatformInAppWebViewControllerCreationParams(params)) {+ channel = MethodChannel('com.pichillilorenzo/flutter_inappwebview_$id');+ handler = handleMethod;+ initMethodCallHandler();++ final initialUserScripts = webviewParams?.initialUserScripts;+ if (initialUserScripts != null) {+ for (final userScript in initialUserScripts) {+ if (userScript.injectionTime ==+ UserScriptInjectionTime.AT_DOCUMENT_START) {+ this+ ._userScripts[UserScriptInjectionTime.AT_DOCUMENT_START]+ ?.add(userScript);+ } else {+ this+ ._userScripts[UserScriptInjectionTime.AT_DOCUMENT_END]+ ?.add(userScript);+ }+ }+ }++ this._init(params);+ }++ static final WindowsInAppWebViewController _staticValue =+ WindowsInAppWebViewController(+ WindowsInAppWebViewControllerCreationParams(id: null));++ factory WindowsInAppWebViewController.static() {+ return _staticValue;+ }++ WindowsInAppWebViewController.fromInAppBrowser(+ PlatformInAppWebViewControllerCreationParams params,+ MethodChannel channel,+ WindowsInAppBrowser inAppBrowser,+ UnmodifiableListView<UserScript>? initialUserScripts)+ : super.implementation(+ params is WindowsInAppWebViewControllerCreationParams+ ? params+ : WindowsInAppWebViewControllerCreationParams+ .fromPlatformInAppWebViewControllerCreationParams(params)) {+ this.channel = channel;+ this._inAppBrowser = inAppBrowser;++ if (initialUserScripts != null) {+ for (final userScript in initialUserScripts) {+ if (userScript.injectionTime ==+ UserScriptInjectionTime.AT_DOCUMENT_START) {+ this+ ._userScripts[UserScriptInjectionTime.AT_DOCUMENT_START]+ ?.add(userScript);+ } else {+ this+ ._userScripts[UserScriptInjectionTime.AT_DOCUMENT_END]+ ?.add(userScript);+ }+ }+ }+ this._init(params);+ }++ void _init(PlatformInAppWebViewControllerCreationParams params) {+ _controllerFromPlatform =+ params.webviewParams?.controllerFromPlatform?.call(this) ?? this;++ webStorage = WindowsWebStorage(WindowsWebStorageCreationParams(+ localStorage: WindowsLocalStorage.defaultStorage(controller: this),+ sessionStorage:+ WindowsSessionStorage.defaultStorage(controller: this)));++ if (params.webviewParams is PlatformInAppWebViewWidgetCreationParams) {+ final keepAlive =+ (params.webviewParams as PlatformInAppWebViewWidgetCreationParams)+ .keepAlive;+ if (keepAlive != null) {+ InAppWebViewControllerKeepAliveProps? props = _keepAliveMap[keepAlive];+ if (props == null) {+ // save controller properties to restore it later+ _keepAliveMap[keepAlive] = InAppWebViewControllerKeepAliveProps(+ injectedScriptsFromURL: _injectedScriptsFromURL,+ javaScriptHandlersMap: _javaScriptHandlersMap,+ userScripts: _userScripts,+ webMessageListenerObjNames: _webMessageListenerObjNames,+ webMessageChannels: _webMessageChannels,+ webMessageListeners: _webMessageListeners,+ devToolsProtocolEventListenerMap:+ _devToolsProtocolEventListenerMap);+ } else {+ // restore controller properties+ _injectedScriptsFromURL = props.injectedScriptsFromURL;+ _javaScriptHandlersMap = props.javaScriptHandlersMap;+ _userScripts = props.userScripts;+ _webMessageListenerObjNames = props.webMessageListenerObjNames;+ _webMessageChannels =+ props.webMessageChannels as Set<WindowsWebMessageChannel>;+ _webMessageListeners =+ props.webMessageListeners as Set<WindowsWebMessageListener>;+ _devToolsProtocolEventListenerMap =+ props.devToolsProtocolEventListenerMap;+ }+ }+ }+ }++ _debugLog(String method, dynamic args) {+ debugLog(+ className: this.runtimeType.toString(),+ name: _inAppBrowser == null+ ? "WebView"+ : _inAppBrowser.runtimeType.toString(),+ id: (getViewId() ?? _inAppBrowser?.id).toString(),+ debugLoggingSettings:+ PlatformInAppWebViewController.debugLoggingSettings,+ method: method,+ args: args);+ }++ Future<dynamic> _handleMethod(MethodCall call) async {+ if (PlatformInAppWebViewController.debugLoggingSettings.enabled &&+ call.method != "onCallJsHandler") {+ _debugLog(call.method, call.arguments);+ }++ switch (call.method) {+ case "onLoadStart":+ _injectedScriptsFromURL.clear();+ if ((webviewParams != null && webviewParams!.onLoadStart != null) ||+ _inAppBrowserEventHandler != null) {+ String? url = call.arguments["url"];+ WebUri? uri = url != null ? WebUri(url) : null;+ if (webviewParams != null && webviewParams!.onLoadStart != null)+ webviewParams!.onLoadStart!(_controllerFromPlatform, uri);+ else+ _inAppBrowserEventHandler!.onLoadStart(uri);+ }+ break;+ case "onLoadStop":+ if ((webviewParams != null && webviewParams!.onLoadStop != null) ||+ _inAppBrowserEventHandler != null) {+ String? url = call.arguments["url"];+ WebUri? uri = url != null ? WebUri(url) : null;+ if (webviewParams != null && webviewParams!.onLoadStop != null)+ webviewParams!.onLoadStop!(_controllerFromPlatform, uri);+ else+ _inAppBrowserEventHandler!.onLoadStop(uri);+ }+ break;+ case "onReceivedError":+ if ((webviewParams != null &&+ (webviewParams!.onReceivedError != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.onLoadError != null)) ||+ _inAppBrowserEventHandler != null) {+ WebResourceRequest request = WebResourceRequest.fromMap(+ call.arguments["request"].cast<String, dynamic>())!;+ WebResourceError error = WebResourceError.fromMap(+ call.arguments["error"].cast<String, dynamic>())!;+ var isForMainFrame = request.isForMainFrame ?? false;++ if (webviewParams != null) {+ if (webviewParams!.onReceivedError != null)+ webviewParams!.onReceivedError!(+ _controllerFromPlatform, request, error);+ else if (isForMainFrame) {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.onLoadError!(_controllerFromPlatform, request.url,+ error.type.toNativeValue() ?? -1, error.description);+ }+ } else {+ if (isForMainFrame) {+ _inAppBrowserEventHandler!.onLoadError(request.url,+ error.type.toNativeValue() ?? -1, error.description);+ }+ _inAppBrowserEventHandler!.onReceivedError(request, error);+ }+ }+ break;+ case "onReceivedHttpError":+ if ((webviewParams != null &&+ (webviewParams!.onReceivedHttpError != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.onLoadHttpError != null)) ||+ _inAppBrowserEventHandler != null) {+ WebResourceRequest request = WebResourceRequest.fromMap(+ call.arguments["request"].cast<String, dynamic>())!;+ WebResourceResponse errorResponse = WebResourceResponse.fromMap(+ call.arguments["errorResponse"].cast<String, dynamic>())!;+ var isForMainFrame = request.isForMainFrame ?? false;++ if (webviewParams != null) {+ if (webviewParams!.onReceivedHttpError != null)+ webviewParams!.onReceivedHttpError!(+ _controllerFromPlatform, request, errorResponse);+ else if (isForMainFrame) {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.onLoadHttpError!(+ _controllerFromPlatform,+ request.url,+ errorResponse.statusCode ?? -1,+ errorResponse.reasonPhrase ?? '');+ }+ } else {+ if (isForMainFrame) {+ _inAppBrowserEventHandler!.onLoadHttpError(+ request.url,+ errorResponse.statusCode ?? -1,+ errorResponse.reasonPhrase ?? '');+ }+ _inAppBrowserEventHandler!+ .onReceivedHttpError(request, errorResponse);+ }+ }+ break;+ case "onProgressChanged":+ if ((webviewParams != null &&+ webviewParams!.onProgressChanged != null) ||+ _inAppBrowserEventHandler != null) {+ int progress = call.arguments["progress"];+ if (webviewParams != null && webviewParams!.onProgressChanged != null)+ webviewParams!.onProgressChanged!(+ _controllerFromPlatform, progress);+ else+ _inAppBrowserEventHandler!.onProgressChanged(progress);+ }+ break;+ case "shouldOverrideUrlLoading":+ if ((webviewParams != null &&+ webviewParams!.shouldOverrideUrlLoading != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ NavigationAction navigationAction =+ NavigationAction.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.shouldOverrideUrlLoading != null)+ return (await webviewParams!.shouldOverrideUrlLoading!(+ _controllerFromPlatform, navigationAction))+ ?.toNativeValue();+ return (await _inAppBrowserEventHandler!+ .shouldOverrideUrlLoading(navigationAction))+ ?.toNativeValue();+ }+ break;+ case "onConsoleMessage":+ if ((webviewParams != null &&+ webviewParams!.onConsoleMessage != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ ConsoleMessage consoleMessage = ConsoleMessage.fromMap(arguments)!;+ if (webviewParams != null && webviewParams!.onConsoleMessage != null)+ webviewParams!.onConsoleMessage!(+ _controllerFromPlatform, consoleMessage);+ else+ _inAppBrowserEventHandler!.onConsoleMessage(consoleMessage);+ }+ break;+ case "onScrollChanged":+ if ((webviewParams != null && webviewParams!.onScrollChanged != null) ||+ _inAppBrowserEventHandler != null) {+ int x = call.arguments["x"];+ int y = call.arguments["y"];+ if (webviewParams != null && webviewParams!.onScrollChanged != null)+ webviewParams!.onScrollChanged!(_controllerFromPlatform, x, y);+ else+ _inAppBrowserEventHandler!.onScrollChanged(x, y);+ }+ break;+ case "onDownloadStartRequest":+ if ((webviewParams != null &&+ // ignore: deprecated_member_use_from_same_package+ (webviewParams!.onDownloadStart != null ||+ webviewParams!.onDownloadStartRequest != null)) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ DownloadStartRequest downloadStartRequest =+ DownloadStartRequest.fromMap(arguments)!;++ if (webviewParams != null) {+ if (webviewParams!.onDownloadStartRequest != null)+ webviewParams!.onDownloadStartRequest!(+ _controllerFromPlatform, downloadStartRequest);+ else {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.onDownloadStart!(+ _controllerFromPlatform, downloadStartRequest.url);+ }+ } else {+ // ignore: deprecated_member_use_from_same_package+ _inAppBrowserEventHandler!+ .onDownloadStart(downloadStartRequest.url);+ _inAppBrowserEventHandler!+ .onDownloadStartRequest(downloadStartRequest);+ }+ }+ break;+ case "onLoadResourceWithCustomScheme":+ if ((webviewParams != null &&+ (webviewParams!.onLoadResourceWithCustomScheme != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.onLoadResourceCustomScheme != null)) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> requestMap =+ call.arguments["request"].cast<String, dynamic>();+ WebResourceRequest request = WebResourceRequest.fromMap(requestMap)!;++ if (webviewParams != null) {+ if (webviewParams!.onLoadResourceWithCustomScheme != null)+ return (await webviewParams!.onLoadResourceWithCustomScheme!(+ _controllerFromPlatform, request))+ ?.toMap();+ else {+ return (await params+ .webviewParams!+ // ignore: deprecated_member_use_from_same_package+ .onLoadResourceCustomScheme!(+ _controllerFromPlatform, request.url))+ ?.toMap();+ }+ } else {+ return ((await _inAppBrowserEventHandler!+ .onLoadResourceWithCustomScheme(request)) ??+ (await _inAppBrowserEventHandler!+ .onLoadResourceCustomScheme(request.url)))+ ?.toMap();+ }+ }+ break;+ case "onCreateWindow":+ if ((webviewParams != null && webviewParams!.onCreateWindow != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ CreateWindowAction createWindowAction =+ CreateWindowAction.fromMap(arguments)!;++ if (webviewParams != null && webviewParams!.onCreateWindow != null)+ return await webviewParams!.onCreateWindow!(+ _controllerFromPlatform, createWindowAction);+ else+ return await _inAppBrowserEventHandler!+ .onCreateWindow(createWindowAction);+ }+ break;+ case "onCloseWindow":+ if (webviewParams != null && webviewParams!.onCloseWindow != null)+ webviewParams!.onCloseWindow!(_controllerFromPlatform);+ else if (_inAppBrowserEventHandler != null)+ _inAppBrowserEventHandler!.onCloseWindow();+ break;+ case "onTitleChanged":+ if ((webviewParams != null && webviewParams!.onTitleChanged != null) ||+ _inAppBrowserEventHandler != null) {+ String? title = call.arguments["title"];+ if (webviewParams != null && webviewParams!.onTitleChanged != null)+ webviewParams!.onTitleChanged!(_controllerFromPlatform, title);+ else+ _inAppBrowserEventHandler!.onTitleChanged(title);+ }+ break;+ case "onGeolocationPermissionsShowPrompt":+ if ((webviewParams != null &&+ (webviewParams!.onGeolocationPermissionsShowPrompt != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnGeolocationPermissionsShowPrompt !=+ null)) ||+ _inAppBrowserEventHandler != null) {+ String origin = call.arguments["origin"];++ if (webviewParams != null) {+ if (webviewParams!.onGeolocationPermissionsShowPrompt != null)+ return (await webviewParams!.onGeolocationPermissionsShowPrompt!(+ _controllerFromPlatform, origin))+ ?.toMap();+ else {+ return (await params+ .webviewParams!+ // ignore: deprecated_member_use_from_same_package+ .androidOnGeolocationPermissionsShowPrompt!(+ _controllerFromPlatform, origin))+ ?.toMap();+ }+ } else {+ return ((await _inAppBrowserEventHandler!+ .onGeolocationPermissionsShowPrompt(origin)) ??+ (await _inAppBrowserEventHandler!+ .androidOnGeolocationPermissionsShowPrompt(origin)))+ ?.toMap();+ }+ }+ break;+ case "onGeolocationPermissionsHidePrompt":+ if (webviewParams != null &&+ (webviewParams!.onGeolocationPermissionsHidePrompt != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnGeolocationPermissionsHidePrompt !=+ null)) {+ if (webviewParams!.onGeolocationPermissionsHidePrompt != null)+ webviewParams!+ .onGeolocationPermissionsHidePrompt!(_controllerFromPlatform);+ else {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnGeolocationPermissionsHidePrompt!(+ _controllerFromPlatform);+ }+ } else if (_inAppBrowserEventHandler != null) {+ _inAppBrowserEventHandler!.onGeolocationPermissionsHidePrompt();+ // ignore: deprecated_member_use_from_same_package+ _inAppBrowserEventHandler!+ .androidOnGeolocationPermissionsHidePrompt();+ }+ break;+ case "shouldInterceptRequest":+ if ((webviewParams != null &&+ (webviewParams!.shouldInterceptRequest != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidShouldInterceptRequest != null)) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ WebResourceRequest request = WebResourceRequest.fromMap(arguments)!;++ if (webviewParams != null) {+ if (webviewParams!.shouldInterceptRequest != null)+ return (await webviewParams!.shouldInterceptRequest!(+ _controllerFromPlatform, request))+ ?.toMap();+ else {+ // ignore: deprecated_member_use_from_same_package+ return (await webviewParams!.androidShouldInterceptRequest!(+ _controllerFromPlatform, request))+ ?.toMap();+ }+ } else {+ return ((await _inAppBrowserEventHandler!+ .shouldInterceptRequest(request)) ??+ (await _inAppBrowserEventHandler!+ .androidShouldInterceptRequest(request)))+ ?.toMap();+ }+ }+ break;+ case "onRenderProcessUnresponsive":+ if ((webviewParams != null &&+ (webviewParams!.onRenderProcessUnresponsive != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnRenderProcessUnresponsive !=+ null)) ||+ _inAppBrowserEventHandler != null) {+ String? url = call.arguments["url"];+ WebUri? uri = url != null ? WebUri(url) : null;++ if (webviewParams != null) {+ if (webviewParams!.onRenderProcessUnresponsive != null)+ return (await webviewParams!.onRenderProcessUnresponsive!(+ _controllerFromPlatform, uri))+ ?.toNativeValue();+ else {+ // ignore: deprecated_member_use_from_same_package+ return (await webviewParams!.androidOnRenderProcessUnresponsive!(+ _controllerFromPlatform, uri))+ ?.toNativeValue();+ }+ } else {+ return ((await _inAppBrowserEventHandler!+ .onRenderProcessUnresponsive(uri)) ??+ (await _inAppBrowserEventHandler!+ .androidOnRenderProcessUnresponsive(uri)))+ ?.toNativeValue();+ }+ }+ break;+ case "onRenderProcessResponsive":+ if ((webviewParams != null &&+ (webviewParams!.onRenderProcessResponsive != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnRenderProcessResponsive != null)) ||+ _inAppBrowserEventHandler != null) {+ String? url = call.arguments["url"];+ WebUri? uri = url != null ? WebUri(url) : null;++ if (webviewParams != null) {+ if (webviewParams!.onRenderProcessResponsive != null)+ return (await webviewParams!.onRenderProcessResponsive!(+ _controllerFromPlatform, uri))+ ?.toNativeValue();+ else {+ // ignore: deprecated_member_use_from_same_package+ return (await webviewParams!.androidOnRenderProcessResponsive!(+ _controllerFromPlatform, uri))+ ?.toNativeValue();+ }+ } else {+ return ((await _inAppBrowserEventHandler!+ .onRenderProcessResponsive(uri)) ??+ (await _inAppBrowserEventHandler!+ .androidOnRenderProcessResponsive(uri)))+ ?.toNativeValue();+ }+ }+ break;+ case "onRenderProcessGone":+ if ((webviewParams != null &&+ (webviewParams!.onRenderProcessGone != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnRenderProcessGone != null)) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ RenderProcessGoneDetail detail =+ RenderProcessGoneDetail.fromMap(arguments)!;++ if (webviewParams != null) {+ if (webviewParams!.onRenderProcessGone != null)+ webviewParams!.onRenderProcessGone!(+ _controllerFromPlatform, detail);+ else {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnRenderProcessGone!(+ _controllerFromPlatform, detail);+ }+ } else if (_inAppBrowserEventHandler != null) {+ _inAppBrowserEventHandler!.onRenderProcessGone(detail);+ // ignore: deprecated_member_use_from_same_package+ _inAppBrowserEventHandler!.androidOnRenderProcessGone(detail);+ }+ }+ break;+ case "onFormResubmission":+ if ((webviewParams != null &&+ (webviewParams!.onFormResubmission != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnFormResubmission != null)) ||+ _inAppBrowserEventHandler != null) {+ String? url = call.arguments["url"];+ WebUri? uri = url != null ? WebUri(url) : null;++ if (webviewParams != null) {+ if (webviewParams!.onFormResubmission != null)+ return (await webviewParams!.onFormResubmission!(+ _controllerFromPlatform, uri))+ ?.toNativeValue();+ else {+ // ignore: deprecated_member_use_from_same_package+ return (await webviewParams!.androidOnFormResubmission!(+ _controllerFromPlatform, uri))+ ?.toNativeValue();+ }+ } else {+ return ((await _inAppBrowserEventHandler!+ .onFormResubmission(uri)) ??+ // ignore: deprecated_member_use_from_same_package+ (await _inAppBrowserEventHandler!+ .androidOnFormResubmission(uri)))+ ?.toNativeValue();+ }+ }+ break;+ case "onZoomScaleChanged":+ if ((webviewParams != null &&+ // ignore: deprecated_member_use_from_same_package+ (webviewParams!.androidOnScaleChanged != null ||+ webviewParams!.onZoomScaleChanged != null)) ||+ _inAppBrowserEventHandler != null) {+ double oldScale = call.arguments["oldScale"];+ double newScale = call.arguments["newScale"];++ if (webviewParams != null) {+ if (webviewParams!.onZoomScaleChanged != null)+ webviewParams!.onZoomScaleChanged!(+ _controllerFromPlatform, oldScale, newScale);+ else {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnScaleChanged!(+ _controllerFromPlatform, oldScale, newScale);+ }+ } else {+ _inAppBrowserEventHandler!.onZoomScaleChanged(oldScale, newScale);+ // ignore: deprecated_member_use_from_same_package+ _inAppBrowserEventHandler!+ .androidOnScaleChanged(oldScale, newScale);+ }+ }+ break;+ case "onReceivedIcon":+ if ((webviewParams != null &&+ (webviewParams!.onReceivedIcon != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnReceivedIcon != null)) ||+ _inAppBrowserEventHandler != null) {+ Uint8List icon =+ Uint8List.fromList(call.arguments["icon"].cast<int>());++ if (webviewParams != null) {+ if (webviewParams!.onReceivedIcon != null)+ webviewParams!.onReceivedIcon!(_controllerFromPlatform, icon);+ else {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnReceivedIcon!(+ _controllerFromPlatform, icon);+ }+ } else {+ _inAppBrowserEventHandler!.onReceivedIcon(icon);+ // ignore: deprecated_member_use_from_same_package+ _inAppBrowserEventHandler!.androidOnReceivedIcon(icon);+ }+ }+ break;+ case "onReceivedTouchIconUrl":+ if ((webviewParams != null &&+ (webviewParams!.onReceivedTouchIconUrl != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnReceivedTouchIconUrl != null)) ||+ _inAppBrowserEventHandler != null) {+ String url = call.arguments["url"];+ bool precomposed = call.arguments["precomposed"];+ WebUri uri = WebUri(url);++ if (webviewParams != null) {+ if (webviewParams!.onReceivedTouchIconUrl != null)+ webviewParams!.onReceivedTouchIconUrl!(+ _controllerFromPlatform, uri, precomposed);+ else {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnReceivedTouchIconUrl!(+ _controllerFromPlatform, uri, precomposed);+ }+ } else {+ _inAppBrowserEventHandler!.onReceivedTouchIconUrl(uri, precomposed);+ // ignore: deprecated_member_use_from_same_package+ _inAppBrowserEventHandler!+ .androidOnReceivedTouchIconUrl(uri, precomposed);+ }+ }+ break;+ case "onJsAlert":+ if ((webviewParams != null && webviewParams!.onJsAlert != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ JsAlertRequest jsAlertRequest = JsAlertRequest.fromMap(arguments)!;++ if (webviewParams != null && webviewParams!.onJsAlert != null)+ return (await webviewParams!.onJsAlert!(+ _controllerFromPlatform, jsAlertRequest))+ ?.toMap();+ else+ return (await _inAppBrowserEventHandler!.onJsAlert(jsAlertRequest))+ ?.toMap();+ }+ break;+ case "onJsConfirm":+ if ((webviewParams != null && webviewParams!.onJsConfirm != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ JsConfirmRequest jsConfirmRequest =+ JsConfirmRequest.fromMap(arguments)!;++ if (webviewParams != null && webviewParams!.onJsConfirm != null)+ return (await webviewParams!.onJsConfirm!(+ _controllerFromPlatform, jsConfirmRequest))+ ?.toMap();+ else+ return (await _inAppBrowserEventHandler!+ .onJsConfirm(jsConfirmRequest))+ ?.toMap();+ }+ break;+ case "onJsPrompt":+ if ((webviewParams != null && webviewParams!.onJsPrompt != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ JsPromptRequest jsPromptRequest = JsPromptRequest.fromMap(arguments)!;++ if (webviewParams != null && webviewParams!.onJsPrompt != null)+ return (await webviewParams!.onJsPrompt!(+ _controllerFromPlatform, jsPromptRequest))+ ?.toMap();+ else+ return (await _inAppBrowserEventHandler!+ .onJsPrompt(jsPromptRequest))+ ?.toMap();+ }+ break;+ case "onJsBeforeUnload":+ if ((webviewParams != null &&+ (webviewParams!.onJsBeforeUnload != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnJsBeforeUnload != null)) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ JsBeforeUnloadRequest jsBeforeUnloadRequest =+ JsBeforeUnloadRequest.fromMap(arguments)!;++ if (webviewParams != null) {+ if (webviewParams!.onJsBeforeUnload != null)+ return (await webviewParams!.onJsBeforeUnload!(+ _controllerFromPlatform, jsBeforeUnloadRequest))+ ?.toMap();+ else {+ // ignore: deprecated_member_use_from_same_package+ return (await webviewParams!.androidOnJsBeforeUnload!(+ _controllerFromPlatform, jsBeforeUnloadRequest))+ ?.toMap();+ }+ } else {+ return ((await _inAppBrowserEventHandler!+ .onJsBeforeUnload(jsBeforeUnloadRequest)) ??+ (await _inAppBrowserEventHandler!+ .androidOnJsBeforeUnload(jsBeforeUnloadRequest)))+ ?.toMap();+ }+ }+ break;+ case "onSafeBrowsingHit":+ if ((webviewParams != null &&+ (webviewParams!.onSafeBrowsingHit != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnSafeBrowsingHit != null)) ||+ _inAppBrowserEventHandler != null) {+ String url = call.arguments["url"];+ SafeBrowsingThreat? threatType =+ SafeBrowsingThreat.fromNativeValue(call.arguments["threatType"]);+ WebUri uri = WebUri(url);++ if (webviewParams != null) {+ if (webviewParams!.onSafeBrowsingHit != null)+ return (await webviewParams!.onSafeBrowsingHit!(+ _controllerFromPlatform, uri, threatType))+ ?.toMap();+ else {+ // ignore: deprecated_member_use_from_same_package+ return (await webviewParams!.androidOnSafeBrowsingHit!(+ _controllerFromPlatform, uri, threatType))+ ?.toMap();+ }+ } else {+ return ((await _inAppBrowserEventHandler!+ .onSafeBrowsingHit(uri, threatType)) ??+ (await _inAppBrowserEventHandler!+ .androidOnSafeBrowsingHit(uri, threatType)))+ ?.toMap();+ }+ }+ break;+ case "onReceivedLoginRequest":+ if ((webviewParams != null &&+ (webviewParams!.onReceivedLoginRequest != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnReceivedLoginRequest != null)) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ LoginRequest loginRequest = LoginRequest.fromMap(arguments)!;++ if (webviewParams != null) {+ if (webviewParams!.onReceivedLoginRequest != null)+ webviewParams!.onReceivedLoginRequest!(+ _controllerFromPlatform, loginRequest);+ else {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnReceivedLoginRequest!(+ _controllerFromPlatform, loginRequest);+ }+ } else {+ _inAppBrowserEventHandler!.onReceivedLoginRequest(loginRequest);+ // ignore: deprecated_member_use_from_same_package+ _inAppBrowserEventHandler!+ .androidOnReceivedLoginRequest(loginRequest);+ }+ }+ break;+ case "onPermissionRequestCanceled":+ if ((webviewParams != null &&+ webviewParams!.onPermissionRequestCanceled != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ PermissionRequest permissionRequest =+ PermissionRequest.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.onPermissionRequestCanceled != null)+ webviewParams!.onPermissionRequestCanceled!(+ _controllerFromPlatform, permissionRequest);+ else+ _inAppBrowserEventHandler!+ .onPermissionRequestCanceled(permissionRequest);+ }+ break;+ case "onRequestFocus":+ if ((webviewParams != null && webviewParams!.onRequestFocus != null) ||+ _inAppBrowserEventHandler != null) {+ if (webviewParams != null && webviewParams!.onRequestFocus != null)+ webviewParams!.onRequestFocus!(_controllerFromPlatform);+ else+ _inAppBrowserEventHandler!.onRequestFocus();+ }+ break;+ case "onReceivedHttpAuthRequest":+ if ((webviewParams != null &&+ webviewParams!.onReceivedHttpAuthRequest != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ HttpAuthenticationChallenge challenge =+ HttpAuthenticationChallenge.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.onReceivedHttpAuthRequest != null)+ return (await webviewParams!.onReceivedHttpAuthRequest!(+ _controllerFromPlatform, challenge))+ ?.toMap();+ else+ return (await _inAppBrowserEventHandler!+ .onReceivedHttpAuthRequest(challenge))+ ?.toMap();+ }+ break;+ case "onReceivedServerTrustAuthRequest":+ if ((webviewParams != null &&+ webviewParams!.onReceivedServerTrustAuthRequest != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ ServerTrustChallenge challenge =+ ServerTrustChallenge.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.onReceivedServerTrustAuthRequest != null)+ return (await webviewParams!.onReceivedServerTrustAuthRequest!(+ _controllerFromPlatform, challenge))+ ?.toMap();+ else+ return (await _inAppBrowserEventHandler!+ .onReceivedServerTrustAuthRequest(challenge))+ ?.toMap();+ }+ break;+ case "onReceivedClientCertRequest":+ if ((webviewParams != null &&+ webviewParams!.onReceivedClientCertRequest != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ ClientCertChallenge challenge =+ ClientCertChallenge.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.onReceivedClientCertRequest != null)+ return (await webviewParams!.onReceivedClientCertRequest!(+ _controllerFromPlatform, challenge))+ ?.toMap();+ else+ return (await _inAppBrowserEventHandler!+ .onReceivedClientCertRequest(challenge))+ ?.toMap();+ }+ break;+ case "onFindResultReceived":+ if ((webviewParams != null &&+ (webviewParams!.onFindResultReceived != null ||+ (webviewParams!.findInteractionController != null &&+ webviewParams!.findInteractionController!.params+ .onFindResultReceived !=+ null))) ||+ _inAppBrowserEventHandler != null) {+ int activeMatchOrdinal = call.arguments["activeMatchOrdinal"];+ int numberOfMatches = call.arguments["numberOfMatches"];+ bool isDoneCounting = call.arguments["isDoneCounting"];+ if (webviewParams != null) {+ if (webviewParams!.findInteractionController != null &&+ webviewParams!.findInteractionController!.params+ .onFindResultReceived !=+ null)+ webviewParams!+ .findInteractionController!.params.onFindResultReceived!(+ webviewParams!.findInteractionController!,+ activeMatchOrdinal,+ numberOfMatches,+ isDoneCounting);+ else+ webviewParams!.onFindResultReceived!(_controllerFromPlatform,+ activeMatchOrdinal, numberOfMatches, isDoneCounting);+ } else {+ if (_inAppBrowser!.findInteractionController != null &&+ _inAppBrowser!+ .findInteractionController!.onFindResultReceived !=+ null)+ _inAppBrowser!.findInteractionController!.onFindResultReceived!(+ webviewParams!.findInteractionController!,+ activeMatchOrdinal,+ numberOfMatches,+ isDoneCounting);+ else+ _inAppBrowserEventHandler!.onFindResultReceived(+ activeMatchOrdinal, numberOfMatches, isDoneCounting);+ }+ }+ break;+ case "onPermissionRequest":+ if ((webviewParams != null &&+ (webviewParams!.onPermissionRequest != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.androidOnPermissionRequest != null)) ||+ _inAppBrowserEventHandler != null) {+ String origin = call.arguments["origin"];+ List<String> resources = call.arguments["resources"].cast<String>();++ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ PermissionRequest permissionRequest =+ PermissionRequest.fromMap(arguments)!;++ if (webviewParams != null) {+ if (webviewParams!.onPermissionRequest != null)+ return (await webviewParams!.onPermissionRequest!(+ _controllerFromPlatform, permissionRequest))+ ?.toMap();+ else {+ return (await webviewParams!.androidOnPermissionRequest!(+ _controllerFromPlatform, origin, resources))+ ?.toMap();+ }+ } else {+ return (await _inAppBrowserEventHandler!+ .onPermissionRequest(permissionRequest))+ ?.toMap() ??+ (await _inAppBrowserEventHandler!+ .androidOnPermissionRequest(origin, resources))+ ?.toMap();+ }+ }+ break;+ case "onUpdateVisitedHistory":+ if ((webviewParams != null &&+ webviewParams!.onUpdateVisitedHistory != null) ||+ _inAppBrowserEventHandler != null) {+ String? url = call.arguments["url"];+ bool? isReload = call.arguments["isReload"];+ WebUri? uri = url != null ? WebUri(url) : null;+ if (webviewParams != null &&+ webviewParams!.onUpdateVisitedHistory != null)+ webviewParams!.onUpdateVisitedHistory!(+ _controllerFromPlatform, uri, isReload);+ else+ _inAppBrowserEventHandler!.onUpdateVisitedHistory(uri, isReload);+ }+ break;+ case "onWebContentProcessDidTerminate":+ if (webviewParams != null &&+ (webviewParams!.onWebContentProcessDidTerminate != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.iosOnWebContentProcessDidTerminate != null)) {+ if (webviewParams!.onWebContentProcessDidTerminate != null)+ webviewParams!+ .onWebContentProcessDidTerminate!(_controllerFromPlatform);+ else {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!+ .iosOnWebContentProcessDidTerminate!(_controllerFromPlatform);+ }+ } else if (_inAppBrowserEventHandler != null) {+ _inAppBrowserEventHandler!.onWebContentProcessDidTerminate();+ // ignore: deprecated_member_use_from_same_package+ _inAppBrowserEventHandler!.iosOnWebContentProcessDidTerminate();+ }+ break;+ case "onPageCommitVisible":+ if ((webviewParams != null &&+ webviewParams!.onPageCommitVisible != null) ||+ _inAppBrowserEventHandler != null) {+ String? url = call.arguments["url"];+ WebUri? uri = url != null ? WebUri(url) : null;+ if (webviewParams != null &&+ webviewParams!.onPageCommitVisible != null)+ webviewParams!.onPageCommitVisible!(_controllerFromPlatform, uri);+ else+ _inAppBrowserEventHandler!.onPageCommitVisible(uri);+ }+ break;+ case "onDidReceiveServerRedirectForProvisionalNavigation":+ if (webviewParams != null &&+ (webviewParams!+ .onDidReceiveServerRedirectForProvisionalNavigation !=+ null ||+ params+ .webviewParams!+ // ignore: deprecated_member_use_from_same_package+ .iosOnDidReceiveServerRedirectForProvisionalNavigation !=+ null)) {+ if (webviewParams!+ .onDidReceiveServerRedirectForProvisionalNavigation !=+ null)+ webviewParams!.onDidReceiveServerRedirectForProvisionalNavigation!(+ _controllerFromPlatform);+ else {+ params+ .webviewParams!+ // ignore: deprecated_member_use_from_same_package+ .iosOnDidReceiveServerRedirectForProvisionalNavigation!(+ _controllerFromPlatform);+ }+ } else if (_inAppBrowserEventHandler != null) {+ _inAppBrowserEventHandler!+ .onDidReceiveServerRedirectForProvisionalNavigation();+ _inAppBrowserEventHandler!+ .iosOnDidReceiveServerRedirectForProvisionalNavigation();+ }+ break;+ case "onNavigationResponse":+ if ((webviewParams != null &&+ (webviewParams!.onNavigationResponse != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.iosOnNavigationResponse != null)) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ // ignore: deprecated_member_use_from_same_package+ IOSWKNavigationResponse iosOnNavigationResponse =+ // ignore: deprecated_member_use_from_same_package+ IOSWKNavigationResponse.fromMap(arguments)!;++ NavigationResponse navigationResponse =+ NavigationResponse.fromMap(arguments)!;++ if (webviewParams != null) {+ if (webviewParams!.onNavigationResponse != null)+ return (await webviewParams!.onNavigationResponse!(+ _controllerFromPlatform, navigationResponse))+ ?.toNativeValue();+ else {+ // ignore: deprecated_member_use_from_same_package+ return (await webviewParams!.iosOnNavigationResponse!(+ _controllerFromPlatform, iosOnNavigationResponse))+ ?.toNativeValue();+ }+ } else {+ return (await _inAppBrowserEventHandler!+ .onNavigationResponse(navigationResponse))+ ?.toNativeValue() ??+ (await _inAppBrowserEventHandler!+ .iosOnNavigationResponse(iosOnNavigationResponse))+ ?.toNativeValue();+ }+ }+ break;+ case "shouldAllowDeprecatedTLS":+ if ((webviewParams != null &&+ (webviewParams!.shouldAllowDeprecatedTLS != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.iosShouldAllowDeprecatedTLS != null)) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ URLAuthenticationChallenge challenge =+ URLAuthenticationChallenge.fromMap(arguments)!;++ if (webviewParams != null) {+ if (webviewParams!.shouldAllowDeprecatedTLS != null)+ return (await webviewParams!.shouldAllowDeprecatedTLS!(+ _controllerFromPlatform, challenge))+ ?.toNativeValue();+ else {+ // ignore: deprecated_member_use_from_same_package+ return (await webviewParams!.iosShouldAllowDeprecatedTLS!(+ _controllerFromPlatform, challenge))+ ?.toNativeValue();+ }+ } else {+ return (await _inAppBrowserEventHandler!+ .shouldAllowDeprecatedTLS(challenge))+ ?.toNativeValue() ??+ // ignore: deprecated_member_use_from_same_package+ (await _inAppBrowserEventHandler!+ .iosShouldAllowDeprecatedTLS(challenge))+ ?.toNativeValue();+ }+ }+ break;+ case "onLongPressHitTestResult":+ if ((webviewParams != null &&+ webviewParams!.onLongPressHitTestResult != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ InAppWebViewHitTestResult hitTestResult =+ InAppWebViewHitTestResult.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.onLongPressHitTestResult != null)+ webviewParams!.onLongPressHitTestResult!(+ _controllerFromPlatform, hitTestResult);+ else+ _inAppBrowserEventHandler!.onLongPressHitTestResult(hitTestResult);+ }+ break;+ case "onCreateContextMenu":+ ContextMenu? contextMenu;+ if (webviewParams != null && webviewParams!.contextMenu != null) {+ contextMenu = webviewParams!.contextMenu;+ } else if (_inAppBrowserEventHandler != null &&+ _inAppBrowser!.contextMenu != null) {+ contextMenu = _inAppBrowser!.contextMenu;+ }++ if (contextMenu != null && contextMenu.onCreateContextMenu != null) {+ Map<String, dynamic> arguments =+ call.arguments.cast<String, dynamic>();+ InAppWebViewHitTestResult hitTestResult =+ InAppWebViewHitTestResult.fromMap(arguments)!;++ contextMenu.onCreateContextMenu!(hitTestResult);+ }+ break;+ case "onHideContextMenu":+ ContextMenu? contextMenu;+ if (webviewParams != null && webviewParams!.contextMenu != null) {+ contextMenu = webviewParams!.contextMenu;+ } else if (_inAppBrowserEventHandler != null &&+ _inAppBrowser!.contextMenu != null) {+ contextMenu = _inAppBrowser!.contextMenu;+ }++ if (contextMenu != null && contextMenu.onHideContextMenu != null) {+ contextMenu.onHideContextMenu!();+ }+ break;+ case "onContextMenuActionItemClicked":+ ContextMenu? contextMenu;+ if (webviewParams != null && webviewParams!.contextMenu != null) {+ contextMenu = webviewParams!.contextMenu;+ } else if (_inAppBrowserEventHandler != null &&+ _inAppBrowser!.contextMenu != null) {+ contextMenu = _inAppBrowser!.contextMenu;+ }++ if (contextMenu != null) {+ int? androidId = call.arguments["androidId"];+ String? iosId = call.arguments["iosId"];+ dynamic id = call.arguments["id"];+ String title = call.arguments["title"];++ ContextMenuItem menuItemClicked = ContextMenuItem(+ id: id,+ // ignore: deprecated_member_use_from_same_package+ androidId: androidId,+ // ignore: deprecated_member_use_from_same_package+ iosId: iosId,+ title: title,+ action: null);++ for (var menuItem in contextMenu.menuItems) {+ if (menuItem.id == id) {+ menuItemClicked = menuItem;+ if (menuItem.action != null) {+ menuItem.action!();+ }+ break;+ }+ }++ if (contextMenu.onContextMenuActionItemClicked != null) {+ contextMenu.onContextMenuActionItemClicked!(menuItemClicked);+ }+ }+ break;+ case "onEnterFullscreen":+ if (webviewParams != null && webviewParams!.onEnterFullscreen != null)+ webviewParams!.onEnterFullscreen!(_controllerFromPlatform);+ else if (_inAppBrowserEventHandler != null)+ _inAppBrowserEventHandler!.onEnterFullscreen();+ break;+ case "onExitFullscreen":+ if (webviewParams != null && webviewParams!.onExitFullscreen != null)+ webviewParams!.onExitFullscreen!(_controllerFromPlatform);+ else if (_inAppBrowserEventHandler != null)+ _inAppBrowserEventHandler!.onExitFullscreen();+ break;+ case "onOverScrolled":+ if ((webviewParams != null && webviewParams!.onOverScrolled != null) ||+ _inAppBrowserEventHandler != null) {+ int x = call.arguments["x"];+ int y = call.arguments["y"];+ bool clampedX = call.arguments["clampedX"];+ bool clampedY = call.arguments["clampedY"];++ if (webviewParams != null && webviewParams!.onOverScrolled != null)+ webviewParams!.onOverScrolled!(+ _controllerFromPlatform, x, y, clampedX, clampedY);+ else+ _inAppBrowserEventHandler!.onOverScrolled(x, y, clampedX, clampedY);+ }+ break;+ case "onWindowFocus":+ if (webviewParams != null && webviewParams!.onWindowFocus != null)+ webviewParams!.onWindowFocus!(_controllerFromPlatform);+ else if (_inAppBrowserEventHandler != null)+ _inAppBrowserEventHandler!.onWindowFocus();+ break;+ case "onWindowBlur":+ if (webviewParams != null && webviewParams!.onWindowBlur != null)+ webviewParams!.onWindowBlur!(_controllerFromPlatform);+ else if (_inAppBrowserEventHandler != null)+ _inAppBrowserEventHandler!.onWindowBlur();+ break;+ case "onPrintRequest":+ if ((webviewParams != null &&+ (webviewParams!.onPrintRequest != null ||+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.onPrint != null)) ||+ _inAppBrowserEventHandler != null) {+ String? url = call.arguments["url"];+ String? printJobId = call.arguments["printJobId"];+ WebUri? uri = url != null ? WebUri(url) : null;+ WindowsPrintJobController? printJob = printJobId != null+ ? WindowsPrintJobController(+ WindowsPrintJobControllerCreationParams(id: printJobId))+ : null;++ if (webviewParams != null) {+ if (webviewParams!.onPrintRequest != null)+ return await webviewParams!.onPrintRequest!(+ _controllerFromPlatform, uri, printJob);+ else {+ // ignore: deprecated_member_use_from_same_package+ webviewParams!.onPrint!(_controllerFromPlatform, uri);+ return false;+ }+ } else {+ // ignore: deprecated_member_use_from_same_package+ _inAppBrowserEventHandler!.onPrint(uri);+ return await _inAppBrowserEventHandler!+ .onPrintRequest(uri, printJob);+ }+ }+ break;+ case "onInjectedScriptLoaded":+ String id = call.arguments[0];+ var onLoadCallback = _injectedScriptsFromURL[id]?.onLoad;+ if ((webviewParams != null || _inAppBrowserEventHandler != null) &&+ onLoadCallback != null) {+ onLoadCallback();+ }+ break;+ case "onInjectedScriptError":+ String id = call.arguments[0];+ var onErrorCallback = _injectedScriptsFromURL[id]?.onError;+ if ((webviewParams != null || _inAppBrowserEventHandler != null) &&+ onErrorCallback != null) {+ onErrorCallback();+ }+ break;+ case "onCameraCaptureStateChanged":+ if ((webviewParams != null &&+ webviewParams!.onCameraCaptureStateChanged != null) ||+ _inAppBrowserEventHandler != null) {+ var oldState =+ MediaCaptureState.fromNativeValue(call.arguments["oldState"]);+ var newState =+ MediaCaptureState.fromNativeValue(call.arguments["newState"]);++ if (webviewParams != null &&+ webviewParams!.onCameraCaptureStateChanged != null)+ webviewParams!.onCameraCaptureStateChanged!(+ _controllerFromPlatform, oldState, newState);+ else+ _inAppBrowserEventHandler!+ .onCameraCaptureStateChanged(oldState, newState);+ }+ break;+ case "onMicrophoneCaptureStateChanged":+ if ((webviewParams != null &&+ webviewParams!.onMicrophoneCaptureStateChanged != null) ||+ _inAppBrowserEventHandler != null) {+ var oldState =+ MediaCaptureState.fromNativeValue(call.arguments["oldState"]);+ var newState =+ MediaCaptureState.fromNativeValue(call.arguments["newState"]);++ if (webviewParams != null &&+ webviewParams!.onMicrophoneCaptureStateChanged != null)+ webviewParams!.onMicrophoneCaptureStateChanged!(+ _controllerFromPlatform, oldState, newState);+ else+ _inAppBrowserEventHandler!+ .onMicrophoneCaptureStateChanged(oldState, newState);+ }+ break;+ case "onContentSizeChanged":+ if ((webviewParams != null &&+ webviewParams!.onContentSizeChanged != null) ||+ _inAppBrowserEventHandler != null) {+ var oldContentSize = MapSize.fromMap(+ call.arguments["oldContentSize"]?.cast<String, dynamic>())!;+ var newContentSize = MapSize.fromMap(+ call.arguments["newContentSize"]?.cast<String, dynamic>())!;++ if (webviewParams != null &&+ webviewParams!.onContentSizeChanged != null)+ webviewParams!.onContentSizeChanged!(+ _controllerFromPlatform, oldContentSize, newContentSize);+ else+ _inAppBrowserEventHandler!+ .onContentSizeChanged(oldContentSize, newContentSize);+ }+ break;+ case "onDevToolsProtocolEventReceived":+ String eventName = call.arguments["eventName"];+ dynamic data = call.arguments["data"] != null+ ? jsonDecode(call.arguments["data"])+ : null;++ if (this._devToolsProtocolEventListenerMap.containsKey(eventName)) {+ this._devToolsProtocolEventListenerMap[eventName]!.call(data);+ }+ break;+ case "onCallJsHandler":+ String handlerName = call.arguments["handlerName"];+ // decode args to json+ List<dynamic> args = jsonDecode(call.arguments["args"]);++ _debugLog(handlerName, args);++ switch (handlerName) {+ case "onLoadResource":+ if ((webviewParams != null &&+ webviewParams!.onLoadResource != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments = args[0].cast<String, dynamic>();+ arguments["startTime"] = arguments["startTime"] is int+ ? arguments["startTime"].toDouble()+ : arguments["startTime"];+ arguments["duration"] = arguments["duration"] is int+ ? arguments["duration"].toDouble()+ : arguments["duration"];++ var response = LoadedResource.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.onLoadResource != null)+ webviewParams!.onLoadResource!(+ _controllerFromPlatform, response);+ else+ _inAppBrowserEventHandler!.onLoadResource(response);+ }+ return null;+ case "shouldInterceptAjaxRequest":+ if ((webviewParams != null &&+ webviewParams!.shouldInterceptAjaxRequest != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments = args[0].cast<String, dynamic>();+ AjaxRequest request = AjaxRequest.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.shouldInterceptAjaxRequest != null)+ return jsonEncode(+ await params.webviewParams!.shouldInterceptAjaxRequest!(+ _controllerFromPlatform, request));+ else+ return jsonEncode(await _inAppBrowserEventHandler!+ .shouldInterceptAjaxRequest(request));+ }+ return null;+ case "onAjaxReadyStateChange":+ if ((webviewParams != null &&+ webviewParams!.onAjaxReadyStateChange != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments = args[0].cast<String, dynamic>();+ AjaxRequest request = AjaxRequest.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.onAjaxReadyStateChange != null)+ return (await webviewParams!.onAjaxReadyStateChange!(+ _controllerFromPlatform, request))+ ?.toNativeValue();+ else+ return (await _inAppBrowserEventHandler!+ .onAjaxReadyStateChange(request))+ ?.toNativeValue();+ }+ return null;+ case "onAjaxProgress":+ if ((webviewParams != null &&+ webviewParams!.onAjaxProgress != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments = args[0].cast<String, dynamic>();+ AjaxRequest request = AjaxRequest.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.onAjaxProgress != null)+ return (await webviewParams!.onAjaxProgress!(+ _controllerFromPlatform, request))+ ?.toNativeValue();+ else+ return (await _inAppBrowserEventHandler!+ .onAjaxProgress(request))+ ?.toNativeValue();+ }+ return null;+ case "shouldInterceptFetchRequest":+ if ((webviewParams != null &&+ webviewParams!.shouldInterceptFetchRequest != null) ||+ _inAppBrowserEventHandler != null) {+ Map<String, dynamic> arguments = args[0].cast<String, dynamic>();+ FetchRequest request = FetchRequest.fromMap(arguments)!;++ if (webviewParams != null &&+ webviewParams!.shouldInterceptFetchRequest != null)+ return jsonEncode(+ await webviewParams!.shouldInterceptFetchRequest!(+ _controllerFromPlatform, request));+ else+ return jsonEncode(await _inAppBrowserEventHandler!+ .shouldInterceptFetchRequest(request));+ }+ return null;+ case "onWindowFocus":+ if (webviewParams != null && webviewParams!.onWindowFocus != null)+ webviewParams!.onWindowFocus!(_controllerFromPlatform);+ else if (_inAppBrowserEventHandler != null)+ _inAppBrowserEventHandler!.onWindowFocus();+ return null;+ case "onWindowBlur":+ if (webviewParams != null && webviewParams!.onWindowBlur != null)+ webviewParams!.onWindowBlur!(_controllerFromPlatform);+ else if (_inAppBrowserEventHandler != null)+ _inAppBrowserEventHandler!.onWindowBlur();+ return null;+ case "onInjectedScriptLoaded":+ String id = args[0];+ var onLoadCallback = _injectedScriptsFromURL[id]?.onLoad;+ if ((webviewParams != null || _inAppBrowserEventHandler != null) &&+ onLoadCallback != null) {+ onLoadCallback();+ }+ return null;+ case "onInjectedScriptError":+ String id = args[0];+ var onErrorCallback = _injectedScriptsFromURL[id]?.onError;+ if ((webviewParams != null || _inAppBrowserEventHandler != null) &&+ onErrorCallback != null) {+ onErrorCallback();+ }+ return null;+ }++ if (_javaScriptHandlersMap.containsKey(handlerName)) {+ // convert result to json+ try {+ return jsonEncode(await _javaScriptHandlersMap[handlerName]!(args));+ } catch (error, stacktrace) {+ developer.log(error.toString() + '\n' + stacktrace.toString(),+ name: 'JavaScript Handler "$handlerName"');+ throw Exception(error.toString().replaceFirst('Exception: ', ''));+ }+ }+ break;+ default:+ throw UnimplementedError("Unimplemented ${call.method} method");+ }+ return null;+ }++ @override+ Future<WebUri?> getUrl() async {+ Map<String, dynamic> args = <String, dynamic>{};+ String? url = await channel?.invokeMethod<String?>('getUrl', args);+ return url != null ? WebUri(url) : null;+ }++ @override+ Future<String?> getTitle() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<String?>('getTitle', args);+ }++ @override+ Future<int?> getProgress() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<int?>('getProgress', args);+ }++ @override+ Future<String?> getHtml() async {+ String? html;++ InAppWebViewSettings? settings = await getSettings();+ if (settings != null && settings.javaScriptEnabled == true) {+ html = await evaluateJavascript(+ source: "window.document.getElementsByTagName('html')[0].outerHTML;");+ if (html != null && html.isNotEmpty) return html;+ }++ var webviewUrl = await getUrl();+ if (webviewUrl == null) {+ return html;+ }++ if (webviewUrl.isScheme("file")) {+ var assetPathSplit = webviewUrl.toString().split("/flutter_assets/");+ var assetPath = assetPathSplit[assetPathSplit.length - 1];+ try {+ var bytes = await rootBundle.load(assetPath);+ html = utf8.decode(bytes.buffer.asUint8List());+ } catch (e) {}+ } else {+ try {+ HttpClient client = HttpClient();+ var htmlRequest = await client.getUrl(webviewUrl);+ html =+ await (await htmlRequest.close()).transform(Utf8Decoder()).join();+ } catch (e) {+ developer.log(e.toString(), name: this.runtimeType.toString());+ }+ }++ return html;+ }++ @override+ Future<List<Favicon>> getFavicons() async {+ List<Favicon> favicons = [];++ var webviewUrl = await getUrl();++ if (webviewUrl == null) {+ return favicons;+ }++ String? manifestUrl;++ var html = await getHtml();+ if (html == null || html.isEmpty) {+ return favicons;+ }+ var assetPathBase;++ if (webviewUrl.isScheme("file")) {+ var assetPathSplit = webviewUrl.toString().split("/flutter_assets/");+ assetPathBase = assetPathSplit[0] + "/flutter_assets/";+ }++ InAppWebViewSettings? settings = await getSettings();+ if (settings != null && settings.javaScriptEnabled == true) {+ List<Map<dynamic, dynamic>> links = (await evaluateJavascript(source: """+(function() {+ var linkNodes = document.head.getElementsByTagName("link");+ var links = [];+ for (var i = 0; i < linkNodes.length; i++) {+ var linkNode = linkNodes[i];+ if (linkNode.rel === 'manifest') {+ links.push(+ {+ rel: linkNode.rel,+ href: linkNode.href,+ sizes: null+ }+ );+ } else if (linkNode.rel != null && linkNode.rel.indexOf('icon') >= 0) {+ links.push(+ {+ rel: linkNode.rel,+ href: linkNode.href,+ sizes: linkNode.sizes != null && linkNode.sizes.value != "" ? linkNode.sizes.value : null+ }+ );+ }+ }+ return links;+})();+"""))?.cast<Map<dynamic, dynamic>>() ?? [];+ for (var link in links) {+ if (link["rel"] == "manifest") {+ manifestUrl = link["href"];+ if (!_isUrlAbsolute(manifestUrl!)) {+ if (manifestUrl.startsWith("/")) {+ manifestUrl = manifestUrl.substring(1);+ }+ manifestUrl = ((assetPathBase == null)+ ? webviewUrl.scheme + "://" + webviewUrl.host + "/"+ : assetPathBase) ++ manifestUrl;+ }+ continue;+ }+ favicons.addAll(_createFavicons(webviewUrl, assetPathBase, link["href"],+ link["rel"], link["sizes"], false));+ }+ }++ // try to get /favicon.ico+ try {+ HttpClient client = HttpClient();+ var faviconUrl =+ webviewUrl.scheme + "://" + webviewUrl.host + "/favicon.ico";+ var faviconUri = WebUri(faviconUrl);+ var headRequest = await client.headUrl(faviconUri);+ var headResponse = await headRequest.close();+ if (headResponse.statusCode == 200) {+ favicons.add(Favicon(url: faviconUri, rel: "shortcut icon"));+ }+ } catch (e) {+ developer.log("/favicon.ico file not found: " + e.toString(),+ name: runtimeType.toString());+ }++ // try to get the manifest file+ HttpClientRequest? manifestRequest;+ HttpClientResponse? manifestResponse;+ bool manifestFound = false;+ if (manifestUrl == null) {+ manifestUrl =+ webviewUrl.scheme + "://" + webviewUrl.host + "/manifest.json";+ }+ try {+ HttpClient client = HttpClient();+ manifestRequest = await client.getUrl(Uri.parse(manifestUrl));+ manifestResponse = await manifestRequest.close();+ manifestFound = manifestResponse.statusCode == 200 &&+ manifestResponse.headers.contentType?.mimeType == "application/json";+ } catch (e) {+ developer.log("Manifest file not found: " + e.toString(),+ name: this.runtimeType.toString());+ }++ if (manifestFound) {+ try {+ Map<String, dynamic> manifest = json+ .decode(await manifestResponse!.transform(Utf8Decoder()).join());+ if (manifest.containsKey("icons")) {+ for (Map<String, dynamic> icon in manifest["icons"]) {+ favicons.addAll(_createFavicons(webviewUrl, assetPathBase,+ icon["src"], icon["rel"], icon["sizes"], true));+ }+ }+ } catch (e) {+ developer.log(+ "Cannot get favicons from Manifest file. It might not have a valid format: " ++ e.toString(),+ error: e,+ name: runtimeType.toString());+ }+ }++ return favicons;+ }++ bool _isUrlAbsolute(String url) {+ return url.startsWith("http://") || url.startsWith("https://");+ }++ List<Favicon> _createFavicons(WebUri url, String? assetPathBase,+ String urlIcon, String? rel, String? sizes, bool isManifest) {+ List<Favicon> favicons = [];++ List<String> urlSplit = urlIcon.split("/");+ if (!_isUrlAbsolute(urlIcon)) {+ if (urlIcon.startsWith("/")) {+ urlIcon = urlIcon.substring(1);+ }+ urlIcon = ((assetPathBase == null)+ ? url.scheme + "://" + url.host + "/"+ : assetPathBase) ++ urlIcon;+ }+ if (isManifest) {+ rel = (sizes != null)+ ? urlSplit[urlSplit.length - 1]+ .replaceFirst("-" + sizes, "")+ .split(" ")[0]+ .split(".")[0]+ : null;+ }+ if (sizes != null && sizes.isNotEmpty && sizes != "any") {+ List<String> sizesSplit = sizes.split(" ");+ for (String size in sizesSplit) {+ int width = int.parse(size.split("x")[0]);+ int height = int.parse(size.split("x")[1]);+ favicons.add(Favicon(+ url: WebUri(urlIcon), rel: rel, width: width, height: height));+ }+ } else {+ favicons.add(+ Favicon(url: WebUri(urlIcon), rel: rel, width: null, height: null));+ }++ return favicons;+ }++ @override+ Future<void> loadUrl(+ {required URLRequest urlRequest,+ @Deprecated('Use allowingReadAccessTo instead')+ Uri? iosAllowingReadAccessTo,+ WebUri? allowingReadAccessTo}) async {+ assert(urlRequest.url != null && urlRequest.url.toString().isNotEmpty);+ assert(+ allowingReadAccessTo == null || allowingReadAccessTo.isScheme("file"));+ assert(iosAllowingReadAccessTo == null ||+ iosAllowingReadAccessTo.isScheme("file"));++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('urlRequest', () => urlRequest.toMap());+ args.putIfAbsent(+ 'allowingReadAccessTo',+ () =>+ allowingReadAccessTo?.toString() ??+ iosAllowingReadAccessTo?.toString());+ await channel?.invokeMethod('loadUrl', args);+ }++ @override+ Future<void> postUrl(+ {required WebUri url, required Uint8List postData}) async {+ assert(url.toString().isNotEmpty);+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('url', () => url.toString());+ args.putIfAbsent('postData', () => postData);+ await channel?.invokeMethod('postUrl', args);+ }++ @override+ Future<void> loadData(+ {required String data,+ String mimeType = "text/html",+ String encoding = "utf8",+ WebUri? baseUrl,+ @Deprecated('Use historyUrl instead') Uri? androidHistoryUrl,+ WebUri? historyUrl,+ @Deprecated('Use allowingReadAccessTo instead')+ Uri? iosAllowingReadAccessTo,+ WebUri? allowingReadAccessTo}) async {+ assert(+ allowingReadAccessTo == null || allowingReadAccessTo.isScheme("file"));+ assert(iosAllowingReadAccessTo == null ||+ iosAllowingReadAccessTo.isScheme("file"));++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('data', () => data);+ args.putIfAbsent('mimeType', () => mimeType);+ args.putIfAbsent('encoding', () => encoding);+ args.putIfAbsent('baseUrl', () => baseUrl?.toString() ?? "about:blank");+ args.putIfAbsent(+ 'historyUrl',+ () =>+ historyUrl?.toString() ??+ androidHistoryUrl?.toString() ??+ "about:blank");+ args.putIfAbsent(+ 'allowingReadAccessTo',+ () =>+ allowingReadAccessTo?.toString() ??+ iosAllowingReadAccessTo?.toString());+ await channel?.invokeMethod('loadData', args);+ }++ @override+ Future<void> loadFile({required String assetFilePath}) async {+ assert(assetFilePath.isNotEmpty);+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('assetFilePath', () => assetFilePath);+ await channel?.invokeMethod('loadFile', args);+ }++ @override+ Future<void> reload() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('reload', args);+ }++ @override+ Future<void> goBack() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('goBack', args);+ }++ @override+ Future<bool> canGoBack() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<bool>('canGoBack', args) ?? false;+ }++ @override+ Future<void> goForward() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('goForward', args);+ }++ @override+ Future<bool> canGoForward() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<bool>('canGoForward', args) ?? false;+ }++ @override+ Future<void> goBackOrForward({required int steps}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('steps', () => steps);+ await channel?.invokeMethod('goBackOrForward', args);+ }++ @override+ Future<bool> canGoBackOrForward({required int steps}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('steps', () => steps);+ return await channel?.invokeMethod<bool>('canGoBackOrForward', args) ??+ false;+ }++ @override+ Future<void> goTo({required WebHistoryItem historyItem}) async {+ var steps = historyItem.offset;+ if (steps != null) {+ await goBackOrForward(steps: steps);+ }+ }++ @override+ Future<bool> isLoading() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<bool>('isLoading', args) ?? false;+ }++ @override+ Future<void> stopLoading() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('stopLoading', args);+ }++ @override+ Future<dynamic> evaluateJavascript(+ {required String source, ContentWorld? contentWorld}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('source', () => source);+ args.putIfAbsent('contentWorld', () => contentWorld?.toMap());+ var data = await channel?.invokeMethod('evaluateJavascript', args);+ if (data != null) {+ try {+ // try to json decode the data coming from JavaScript+ // otherwise return it as it is.+ data = json.decode(data);+ } catch (e) {}+ }+ return data;+ }++ @override+ Future<void> injectJavascriptFileFromUrl(+ {required WebUri urlFile,+ ScriptHtmlTagAttributes? scriptHtmlTagAttributes}) async {+ assert(urlFile.toString().isNotEmpty);+ var id = scriptHtmlTagAttributes?.id;+ if (scriptHtmlTagAttributes != null && id != null) {+ _injectedScriptsFromURL[id] = scriptHtmlTagAttributes;+ }+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('urlFile', () => urlFile.toString());+ args.putIfAbsent(+ 'scriptHtmlTagAttributes', () => scriptHtmlTagAttributes?.toMap());+ await channel?.invokeMethod('injectJavascriptFileFromUrl', args);+ }++ @override+ Future<dynamic> injectJavascriptFileFromAsset(+ {required String assetFilePath}) async {+ String source = await rootBundle.loadString(assetFilePath);+ return await evaluateJavascript(source: source);+ }++ @override+ Future<void> injectCSSCode({required String source}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('source', () => source);+ await channel?.invokeMethod('injectCSSCode', args);+ }++ @override+ Future<void> injectCSSFileFromUrl(+ {required WebUri urlFile,+ CSSLinkHtmlTagAttributes? cssLinkHtmlTagAttributes}) async {+ assert(urlFile.toString().isNotEmpty);+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('urlFile', () => urlFile.toString());+ args.putIfAbsent(+ 'cssLinkHtmlTagAttributes', () => cssLinkHtmlTagAttributes?.toMap());+ await channel?.invokeMethod('injectCSSFileFromUrl', args);+ }++ @override+ Future<void> injectCSSFileFromAsset({required String assetFilePath}) async {+ String source = await rootBundle.loadString(assetFilePath);+ await injectCSSCode(source: source);+ }++ @override+ void addJavaScriptHandler(+ {required String handlerName,+ required JavaScriptHandlerCallback callback}) {+ assert(!_JAVASCRIPT_HANDLER_FORBIDDEN_NAMES.contains(handlerName),+ '"$handlerName" is a forbidden name!');+ this._javaScriptHandlersMap[handlerName] = (callback);+ }++ @override+ JavaScriptHandlerCallback? removeJavaScriptHandler(+ {required String handlerName}) {+ return this._javaScriptHandlersMap.remove(handlerName);+ }++ @override+ bool hasJavaScriptHandler({required String handlerName}) {+ return this._javaScriptHandlersMap.containsKey(handlerName);+ }++ @override+ Future<Uint8List?> takeScreenshot(+ {ScreenshotConfiguration? screenshotConfiguration}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent(+ 'screenshotConfiguration', () => screenshotConfiguration?.toMap());+ final base64 = await channel?.invokeMethod<String?>('takeScreenshot', args);+ return base64 != null ? base64Decode(base64) : null;+ }++ @override+ @Deprecated('Use setSettings instead')+ Future<void> setOptions({required InAppWebViewGroupOptions options}) async {+ InAppWebViewSettings settings =+ InAppWebViewSettings.fromMap(options.toMap()) ?? InAppWebViewSettings();+ await setSettings(settings: settings);+ }++ @override+ @Deprecated('Use getSettings instead')+ Future<InAppWebViewGroupOptions?> getOptions() async {+ InAppWebViewSettings? settings = await getSettings();++ Map<dynamic, dynamic>? options = settings?.toMap();+ if (options != null) {+ options = options.cast<String, dynamic>();+ return InAppWebViewGroupOptions.fromMap(options as Map<String, dynamic>);+ }++ return null;+ }++ @override+ Future<void> setSettings({required InAppWebViewSettings settings}) async {+ Map<String, dynamic> args = <String, dynamic>{};++ args.putIfAbsent('settings', () => settings.toMap());+ await channel?.invokeMethod('setSettings', args);+ }++ @override+ Future<InAppWebViewSettings?> getSettings() async {+ Map<String, dynamic> args = <String, dynamic>{};++ Map<dynamic, dynamic>? settings =+ await channel?.invokeMethod('getSettings', args);+ if (settings != null) {+ settings = settings.cast<String, dynamic>();+ return InAppWebViewSettings.fromMap(settings as Map<String, dynamic>);+ }++ return null;+ }++ @override+ Future<WebHistory?> getCopyBackForwardList() async {+ Map<String, dynamic> args = <String, dynamic>{};+ Map<String, dynamic>? result =+ (await channel?.invokeMethod('getCopyBackForwardList', args))+ ?.cast<String, dynamic>();+ return WebHistory.fromMap(result);+ }++ @override+ @Deprecated("Use InAppWebViewController.clearAllCache instead")+ Future<void> clearCache() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('clearCache', args);+ }++ @override+ @Deprecated("Use FindInteractionController.findAll instead")+ Future<void> findAllAsync({required String find}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('find', () => find);+ await channel?.invokeMethod('findAll', args);+ }++ @override+ @Deprecated("Use FindInteractionController.findNext instead")+ Future<void> findNext({required bool forward}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('forward', () => forward);+ await channel?.invokeMethod('findNext', args);+ }++ @override+ @Deprecated("Use FindInteractionController.clearMatches instead")+ Future<void> clearMatches() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('clearMatches', args);+ }++ @override+ @Deprecated("Use tRexRunnerHtml instead")+ Future<String> getTRexRunnerHtml() async {+ return await tRexRunnerHtml;+ }++ @override+ @Deprecated("Use tRexRunnerCss instead")+ Future<String> getTRexRunnerCss() async {+ return await tRexRunnerCss;+ }++ @override+ Future<void> scrollTo(+ {required int x, required int y, bool animated = false}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('x', () => x);+ args.putIfAbsent('y', () => y);+ args.putIfAbsent('animated', () => animated);+ await channel?.invokeMethod('scrollTo', args);+ }++ @override+ Future<void> scrollBy(+ {required int x, required int y, bool animated = false}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('x', () => x);+ args.putIfAbsent('y', () => y);+ args.putIfAbsent('animated', () => animated);+ await channel?.invokeMethod('scrollBy', args);+ }++ @override+ Future<void> pauseTimers() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('pauseTimers', args);+ }++ @override+ Future<void> resumeTimers() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('resumeTimers', args);+ }++ @override+ Future<WindowsPrintJobController?> printCurrentPage(+ {PrintJobSettings? settings}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("settings", () => settings?.toMap());+ String? jobId =+ await channel?.invokeMethod<String?>('printCurrentPage', args);+ if (jobId != null) {+ return WindowsPrintJobController(+ PlatformPrintJobControllerCreationParams(id: jobId));+ }+ return null;+ }++ @override+ Future<int?> getContentHeight() async {+ Map<String, dynamic> args = <String, dynamic>{};+ var height = await channel?.invokeMethod('getContentHeight', args);+ if (height == null || height == 0) {+ // try to use javascript+ var scrollHeight = await evaluateJavascript(+ source: "document.documentElement.scrollHeight;");+ if (scrollHeight != null && scrollHeight is num) {+ height = scrollHeight.toInt();+ }+ }+ return height;+ }++ @override+ Future<int?> getContentWidth() async {+ Map<String, dynamic> args = <String, dynamic>{};+ var height = await channel?.invokeMethod('getContentWidth', args);+ if (height == null || height == 0) {+ // try to use javascript+ var scrollHeight = await evaluateJavascript(+ source: "document.documentElement.scrollWidth;");+ if (scrollHeight != null && scrollHeight is num) {+ height = scrollHeight.toInt();+ }+ }+ return height;+ }++ @override+ Future<void> zoomBy(+ {required double zoomFactor,+ @Deprecated('Use animated instead') bool? iosAnimated,+ bool animated = false}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('zoomFactor', () => zoomFactor);+ args.putIfAbsent('animated', () => iosAnimated ?? animated);+ return await channel?.invokeMethod('zoomBy', args);+ }++ @override+ Future<WebUri?> getOriginalUrl() async {+ Map<String, dynamic> args = <String, dynamic>{};+ String? url = await channel?.invokeMethod<String?>('getOriginalUrl', args);+ return url != null ? WebUri(url) : null;+ }++ @override+ @Deprecated('Use getZoomScale instead')+ Future<double?> getScale() async {+ return await getZoomScale();+ }++ @override+ Future<String?> getSelectedText() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<String?>('getSelectedText', args);+ }++ @override+ Future<List<MetaTag>> getMetaTags() async {+ List<MetaTag> metaTags = [];++ List<Map<dynamic, dynamic>>? metaTagList =+ (await evaluateJavascript(source: """+(function() {+ var metaTags = [];+ var metaTagNodes = document.head.getElementsByTagName('meta');+ for (var i = 0; i < metaTagNodes.length; i++) {+ var metaTagNode = metaTagNodes[i];++ var otherAttributes = metaTagNode.getAttributeNames();+ var nameIndex = otherAttributes.indexOf("name");+ if (nameIndex !== -1) otherAttributes.splice(nameIndex, 1);+ var contentIndex = otherAttributes.indexOf("content");+ if (contentIndex !== -1) otherAttributes.splice(contentIndex, 1);++ var attrs = [];+ for (var j = 0; j < otherAttributes.length; j++) {+ var otherAttribute = otherAttributes[j];+ attrs.push(+ {+ name: otherAttribute,+ value: metaTagNode.getAttribute(otherAttribute)+ }+ );+ }++ metaTags.push(+ {+ name: metaTagNode.name,+ content: metaTagNode.content,+ attrs: attrs+ }+ );+ }+ return metaTags;+})();+ """))?.cast<Map<dynamic, dynamic>>();++ if (metaTagList == null) {+ return metaTags;+ }++ for (var metaTag in metaTagList) {+ var attrs = <MetaTagAttribute>[];++ for (var metaTagAttr in metaTag["attrs"]) {+ attrs.add(MetaTagAttribute(+ name: metaTagAttr["name"], value: metaTagAttr["value"]));+ }++ metaTags.add(MetaTag(+ name: metaTag["name"], content: metaTag["content"], attrs: attrs));+ }++ return metaTags;+ }++ @override+ Future<Color?> getMetaThemeColor() async {+ Color? themeColor;++ try {+ Map<String, dynamic> args = <String, dynamic>{};+ themeColor = UtilColor.fromStringRepresentation(+ await channel?.invokeMethod('getMetaThemeColor', args));+ return themeColor;+ } catch (e) {+ // not implemented+ }++ // try using javascript+ var metaTags = await getMetaTags();+ MetaTag? metaTagThemeColor;++ for (var metaTag in metaTags) {+ if (metaTag.name == "theme-color") {+ metaTagThemeColor = metaTag;+ break;+ }+ }++ if (metaTagThemeColor == null) {+ return null;+ }++ var colorValue = metaTagThemeColor.content;++ themeColor = colorValue != null+ ? UtilColor.fromStringRepresentation(colorValue)+ : null;++ return themeColor;+ }++ @override+ Future<int?> getScrollX() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<int?>('getScrollX', args);+ }++ @override+ Future<int?> getScrollY() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<int?>('getScrollY', args);+ }++ @override+ Future<SslCertificate?> getCertificate() async {+ Map<String, dynamic> args = <String, dynamic>{};+ Map<String, dynamic>? sslCertificateMap =+ (await channel?.invokeMethod('getCertificate', args))+ ?.cast<String, dynamic>();+ if (sslCertificateMap != null &&+ sslCertificateMap['x509Certificate'] != null) {+ sslCertificateMap['x509Certificate'] =+ base64Decode(sslCertificateMap['x509Certificate']);+ }+ return SslCertificate.fromMap(sslCertificateMap);+ }++ @override+ Future<void> addUserScript({required UserScript userScript}) async {+ assert(webviewParams?.windowId == null);++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('userScript', () => userScript.toMap());+ if (!(_userScripts[userScript.injectionTime]?.contains(userScript) ??+ false)) {+ _userScripts[userScript.injectionTime]?.add(userScript);+ await channel?.invokeMethod('addUserScript', args);+ }+ }++ @override+ Future<void> addUserScripts({required List<UserScript> userScripts}) async {+ assert(webviewParams?.windowId == null);++ for (var i = 0; i < userScripts.length; i++) {+ await addUserScript(userScript: userScripts[i]);+ }+ }++ @override+ Future<bool> removeUserScript({required UserScript userScript}) async {+ assert(webviewParams?.windowId == null);++ var index = _userScripts[userScript.injectionTime]?.indexOf(userScript);+ if (index == null || index == -1) {+ return false;+ }++ _userScripts[userScript.injectionTime]?.remove(userScript);+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('userScript', () => userScript.toMap());+ args.putIfAbsent('index', () => index);+ await channel?.invokeMethod('removeUserScript', args);++ return true;+ }++ @override+ Future<void> removeUserScriptsByGroupName({required String groupName}) async {+ assert(webviewParams?.windowId == null);++ final List<UserScript> userScriptsAtDocumentStart = List.from(+ _userScripts[UserScriptInjectionTime.AT_DOCUMENT_START] ?? []);+ for (final userScript in userScriptsAtDocumentStart) {+ if (userScript.groupName == groupName) {+ _userScripts[userScript.injectionTime]?.remove(userScript);+ }+ }++ final List<UserScript> userScriptsAtDocumentEnd =+ List.from(_userScripts[UserScriptInjectionTime.AT_DOCUMENT_END] ?? []);+ for (final userScript in userScriptsAtDocumentEnd) {+ if (userScript.groupName == groupName) {+ _userScripts[userScript.injectionTime]?.remove(userScript);+ }+ }++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('groupName', () => groupName);+ await channel?.invokeMethod('removeUserScriptsByGroupName', args);+ }++ @override+ Future<void> removeUserScripts(+ {required List<UserScript> userScripts}) async {+ assert(webviewParams?.windowId == null);++ for (final userScript in userScripts) {+ await removeUserScript(userScript: userScript);+ }+ }++ @override+ Future<void> removeAllUserScripts() async {+ assert(webviewParams?.windowId == null);++ _userScripts[UserScriptInjectionTime.AT_DOCUMENT_START]?.clear();+ _userScripts[UserScriptInjectionTime.AT_DOCUMENT_END]?.clear();++ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('removeAllUserScripts', args);+ }++ @override+ bool hasUserScript({required UserScript userScript}) {+ return _userScripts[userScript.injectionTime]?.contains(userScript) ??+ false;+ }++ @override+ Future<CallAsyncJavaScriptResult?> callAsyncJavaScript(+ {required String functionBody,+ Map<String, dynamic> arguments = const <String, dynamic>{},+ ContentWorld? contentWorld}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('functionBody', () => functionBody);+ args.putIfAbsent('arguments', () => jsonEncode(arguments));+ args.putIfAbsent('contentWorld', () => contentWorld?.toMap());+ var data = await channel?.invokeMethod('callAsyncJavaScript', args);+ if (data == null) {+ return null;+ }+ data = json.decode(data);+ return CallAsyncJavaScriptResult(+ value: data["value"], error: data["error"]);+ }++ @override+ Future<String?> saveWebArchive(+ {required String filePath, bool autoname = false}) async {+ if (!autoname) {+ assert(+ filePath.endsWith("." + WebArchiveFormat.WEBARCHIVE.toNativeValue()));+ }++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("filePath", () => filePath);+ args.putIfAbsent("autoname", () => autoname);+ return await channel?.invokeMethod<String?>('saveWebArchive', args);+ }++ @override+ Future<bool> isSecureContext() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<bool>('isSecureContext', args) ?? false;+ }++ @override+ Future<WindowsWebMessageChannel?> createWebMessageChannel() async {+ Map<String, dynamic> args = <String, dynamic>{};+ Map<String, dynamic>? result =+ (await channel?.invokeMethod('createWebMessageChannel', args))+ ?.cast<String, dynamic>();+ final webMessageChannel = WindowsWebMessageChannel.static().fromMap(result);+ if (webMessageChannel != null) {+ _webMessageChannels.add(webMessageChannel);+ }+ return webMessageChannel;+ }++ @override+ Future<void> postWebMessage(+ {required WebMessage message, WebUri? targetOrigin}) async {+ if (targetOrigin == null) {+ targetOrigin = WebUri('');+ }+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('message', () => message.toMap());+ args.putIfAbsent('targetOrigin', () => targetOrigin.toString());+ await channel?.invokeMethod('postWebMessage', args);+ }++ @override+ Future<void> addWebMessageListener(+ PlatformWebMessageListener webMessageListener) async {+ assert(!_webMessageListeners.contains(webMessageListener),+ "${webMessageListener} was already added.");+ assert(+ !_webMessageListenerObjNames+ .contains(webMessageListener.params.jsObjectName),+ "jsObjectName ${webMessageListener.params.jsObjectName} was already added.");+ _webMessageListeners.add(webMessageListener as WindowsWebMessageListener);+ _webMessageListenerObjNames.add(webMessageListener.params.jsObjectName);++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('webMessageListener', () => webMessageListener.toMap());+ await channel?.invokeMethod('addWebMessageListener', args);+ }++ @override+ bool hasWebMessageListener(PlatformWebMessageListener webMessageListener) {+ return _webMessageListeners.contains(webMessageListener) ||+ _webMessageListenerObjNames+ .contains(webMessageListener.params.jsObjectName);+ }++ @override+ Future<bool> canScrollVertically() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<bool>('canScrollVertically', args) ??+ false;+ }++ @override+ Future<bool> canScrollHorizontally() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<bool>('canScrollHorizontally', args) ??+ false;+ }++ @override+ Future<void> reloadFromOrigin() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('reloadFromOrigin', args);+ }++ @override+ Future<Uint8List?> createPdf(+ {@Deprecated("Use pdfConfiguration instead")+ // ignore: deprecated_member_use_from_same_package+ IOSWKPDFConfiguration? iosWKPdfConfiguration,+ PDFConfiguration? pdfConfiguration}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('pdfConfiguration',+ () => pdfConfiguration?.toMap() ?? iosWKPdfConfiguration?.toMap());+ return await channel?.invokeMethod<Uint8List?>('createPdf', args);+ }++ @override+ Future<Uint8List?> createWebArchiveData() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod('createWebArchiveData', args);+ }++ @override+ Future<bool> hasOnlySecureContent() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<bool>('hasOnlySecureContent', args) ??+ false;+ }++ @override+ Future<void> pauseAllMediaPlayback() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod('pauseAllMediaPlayback', args);+ }++ @override+ Future<void> setAllMediaPlaybackSuspended({required bool suspended}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("suspended", () => suspended);+ return await channel?.invokeMethod('setAllMediaPlaybackSuspended', args);+ }++ @override+ Future<void> closeAllMediaPresentations() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod('closeAllMediaPresentations', args);+ }++ @override+ Future<MediaPlaybackState?> requestMediaPlaybackState() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return MediaPlaybackState.fromNativeValue(+ await channel?.invokeMethod('requestMediaPlaybackState', args));+ }++ @override+ Future<bool> isInFullscreen() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await channel?.invokeMethod<bool>('isInFullscreen', args) ?? false;+ }++ @override+ Future<MediaCaptureState?> getCameraCaptureState() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return MediaCaptureState.fromNativeValue(+ await channel?.invokeMethod('getCameraCaptureState', args));+ }++ @override+ Future<void> setCameraCaptureState({required MediaCaptureState state}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('state', () => state.toNativeValue());+ await channel?.invokeMethod('setCameraCaptureState', args);+ }++ @override+ Future<MediaCaptureState?> getMicrophoneCaptureState() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return MediaCaptureState.fromNativeValue(+ await channel?.invokeMethod('getMicrophoneCaptureState', args));+ }++ @override+ Future<void> setMicrophoneCaptureState(+ {required MediaCaptureState state}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('state', () => state.toNativeValue());+ await channel?.invokeMethod('setMicrophoneCaptureState', args);+ }++ @override+ Future<void> loadSimulatedRequest(+ {required URLRequest urlRequest,+ required Uint8List data,+ URLResponse? urlResponse}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('urlRequest', () => urlRequest.toMap());+ args.putIfAbsent('data', () => data);+ args.putIfAbsent('urlResponse', () => urlResponse?.toMap());+ await channel?.invokeMethod('loadSimulatedRequest', args);+ }++ @override+ Future<void> openDevTools() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('openDevTools', args);+ }++ @override+ Future<dynamic> callDevToolsProtocolMethod(+ {required String methodName, Map<String, dynamic>? parameters}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('methodName', () => methodName);+ args.putIfAbsent('parametersAsJson',+ () => parameters != null ? jsonEncode(parameters) : null);+ final result =+ await channel?.invokeMethod<String>('callDevToolsProtocolMethod', args);+ if (result != null) {+ return jsonDecode(result);+ }+ return null;+ }++ @override+ Future<void> addDevToolsProtocolEventListener(+ {required String eventName,+ required Function(dynamic data) callback}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('eventName', () => eventName);+ await channel?.invokeMethod('addDevToolsProtocolEventListener', args);+ this._devToolsProtocolEventListenerMap[eventName] = callback;+ }++ @override+ Future<void> removeDevToolsProtocolEventListener(+ {required String eventName}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('eventName', () => eventName);+ await channel?.invokeMethod('removeDevToolsProtocolEventListener', args);+ this._devToolsProtocolEventListenerMap.remove(eventName);+ }++ @override+ Future<void> pause() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('pause', args);+ }++ @override+ Future<void> resume() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('resume', args);+ }++ @override+ Future<String> getDefaultUserAgent() async {+ Map<String, dynamic> args = <String, dynamic>{};+ return await _staticChannel.invokeMethod<String>(+ 'getDefaultUserAgent', args) ??+ '';+ }++ @override+ Future<bool> handlesURLScheme(String urlScheme) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('urlScheme', () => urlScheme);+ return await _staticChannel.invokeMethod('handlesURLScheme', args);+ }++ @override+ Future<void> disposeKeepAlive(InAppWebViewKeepAlive keepAlive) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('keepAliveId', () => keepAlive.id);+ await _staticChannel.invokeMethod('disposeKeepAlive', args);+ _keepAliveMap[keepAlive] = null;+ }++ @override+ Future<void> clearAllCache({bool includeDiskFiles = true}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('includeDiskFiles', () => includeDiskFiles);+ await _staticChannel.invokeMethod('clearAllCache', args);+ }++ @override+ Future<String> get tRexRunnerHtml async => await rootBundle.loadString(+ 'packages/flutter_inappwebview/assets/t_rex_runner/t-rex.html');++ @override+ Future<String> get tRexRunnerCss async => await rootBundle.loadString(+ 'packages/flutter_inappwebview/assets/t_rex_runner/t-rex.css');++ @override+ dynamic getViewId() {+ return id;+ }++ @override+ void dispose({bool isKeepAlive = false}) {+ disposeChannel(removeMethodCallHandler: !isKeepAlive);+ _inAppBrowser = null;+ webStorage.dispose();+ if (!isKeepAlive) {+ _controllerFromPlatform = null;+ _javaScriptHandlersMap.clear();+ _userScripts.clear();+ _webMessageListenerObjNames.clear();+ _injectedScriptsFromURL.clear();+ for (final webMessageChannel in _webMessageChannels) {+ webMessageChannel.dispose();+ }+ _webMessageChannels.clear();+ for (final webMessageListener in _webMessageListeners) {+ webMessageListener.dispose();+ }+ _webMessageListeners.clear();+ _devToolsProtocolEventListenerMap.clear();+ }+ }+}++extension InternalInAppWebViewController on WindowsInAppWebViewController {+ get handleMethod => _handleMethod;+}diff --git a/packages/flutter_inappwebview_windows/lib/src/in_app_webview/main.dart b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/main.dartnew file mode 100644index 00000000..b83b0611--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/in_app_webview/main.dart@@ -0,0 +1,3 @@+export 'in_app_webview_controller.dart' hide InternalInAppWebViewController;+export 'in_app_webview.dart';+export 'headless_in_app_webview.dart' hide InternalHeadlessInAppWebView;diff --git a/packages/flutter_inappwebview_windows/lib/src/inappwebview_platform.dart b/packages/flutter_inappwebview_windows/lib/src/inappwebview_platform.dartnew file mode 100644index 00000000..b3ac0564--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/inappwebview_platform.dart@@ -0,0 +1,143 @@+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++import 'cookie_manager.dart';+import 'in_app_browser/in_app_browser.dart';+import 'in_app_webview/in_app_webview.dart';+import 'in_app_webview/in_app_webview_controller.dart';+import 'in_app_webview/headless_in_app_webview.dart';+import 'webview_environment/webview_environment.dart';+import 'web_storage/web_storage.dart';++/// Implementation of [InAppWebViewPlatform] using the WebKit API.+class WindowsInAppWebViewPlatform extends InAppWebViewPlatform {+ /// Registers this class as the default instance of [InAppWebViewPlatform].+ static void registerWith() {+ InAppWebViewPlatform.instance = WindowsInAppWebViewPlatform();+ }++ /// Creates a new [WindowsCookieManager].+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [CookieManager] in `flutter_inappwebview` instead.+ @override+ WindowsCookieManager createPlatformCookieManager(+ PlatformCookieManagerCreationParams params,+ ) {+ return WindowsCookieManager(params);+ }++ /// Creates a new [WindowsInAppWebViewController].+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [InAppWebViewController] in `flutter_inappwebview` instead.+ @override+ WindowsInAppWebViewController createPlatformInAppWebViewController(+ PlatformInAppWebViewControllerCreationParams params,+ ) {+ return WindowsInAppWebViewController(params);+ }++ /// Creates a new empty [WindowsInAppWebViewController] to access static methods.+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [InAppWebViewController] in `flutter_inappwebview` instead.+ @override+ WindowsInAppWebViewController createPlatformInAppWebViewControllerStatic() {+ return WindowsInAppWebViewController.static();+ }++ /// Creates a new [WindowsInAppWebViewWidget].+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [InAppWebView] in `flutter_inappwebview` instead.+ @override+ WindowsInAppWebViewWidget createPlatformInAppWebViewWidget(+ PlatformInAppWebViewWidgetCreationParams params,+ ) {+ return WindowsInAppWebViewWidget(params);+ }++ /// Creates a new [WindowsInAppBrowser].+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [InAppBrowser] in `flutter_inappwebview` instead.+ @override+ WindowsInAppBrowser createPlatformInAppBrowser(+ PlatformInAppBrowserCreationParams params,+ ) {+ return WindowsInAppBrowser(params);+ }++ /// Creates a new empty [WindowsInAppBrowser] to access static methods.+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [InAppBrowser] in `flutter_inappwebview` instead.+ @override+ WindowsInAppBrowser createPlatformInAppBrowserStatic() {+ return WindowsInAppBrowser.static();+ }++ /// Creates a new [WindowsHeadlessInAppWebView].+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [HeadlessInAppWebView] in `flutter_inappwebview` instead.+ @override+ WindowsHeadlessInAppWebView createPlatformHeadlessInAppWebView(+ PlatformHeadlessInAppWebViewCreationParams params,+ ) {+ return WindowsHeadlessInAppWebView(params);+ }++ /// Creates a new [WindowsWebViewEnvironment].+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [WebViewEnvironment] in `flutter_inappwebview` instead.+ @override+ WindowsWebViewEnvironment createPlatformWebViewEnvironment(+ PlatformWebViewEnvironmentCreationParams params,+ ) {+ return WindowsWebViewEnvironment(params);+ }++ /// Creates a new empty [WindowsWebViewEnvironment] to access static methods.+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [WebViewEnvironment] in `flutter_inappwebview` instead.+ @override+ WindowsWebViewEnvironment createPlatformWebViewEnvironmentStatic() {+ return WindowsWebViewEnvironment.static();+ }++ /// Creates a new [WindowsWebStorage].+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [WebStorage] in `flutter_inappwebview` instead.+ @override+ WindowsWebStorage createPlatformWebStorage(+ PlatformWebStorageCreationParams params,+ ) {+ return WindowsWebStorage(params);+ }++ /// Creates a new [WindowsLocalStorage].+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [LocalStorage] in `flutter_inappwebview` instead.+ @override+ WindowsLocalStorage createPlatformLocalStorage(+ PlatformLocalStorageCreationParams params,+ ) {+ return WindowsLocalStorage(params);+ }++ /// Creates a new [WindowsSessionStorage].+ ///+ /// This function should only be called by the app-facing package.+ /// Look at using [SessionStorage] in `flutter_inappwebview` instead.+ @override+ WindowsSessionStorage createPlatformSessionStorage(+ PlatformSessionStorageCreationParams params,+ ) {+ return WindowsSessionStorage(params);+ }+}diff --git a/packages/flutter_inappwebview_windows/lib/src/main.dart b/packages/flutter_inappwebview_windows/lib/src/main.dartnew file mode 100644index 00000000..4fce8f8c--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/main.dart@@ -0,0 +1,11 @@+export 'inappwebview_platform.dart';+export 'in_app_webview/main.dart';+export 'in_app_browser/main.dart';+export 'web_storage/main.dart';+export 'cookie_manager.dart' hide InternalCookieManager;+export 'http_auth_credentials_database.dart'+ hide InternalHttpAuthCredentialDatabase;+export 'web_message/main.dart';+export 'print_job/main.dart';+export 'find_interaction/main.dart';+export 'webview_environment/main.dart';diff --git a/packages/flutter_inappwebview_windows/lib/src/platform_util.dart b/packages/flutter_inappwebview_windows/lib/src/platform_util.dartnew file mode 100644index 00000000..27e96478--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/platform_util.dart@@ -0,0 +1,64 @@+import 'package:flutter/services.dart';++///Platform native utilities+class PlatformUtil {+ static PlatformUtil? _instance;+ static const MethodChannel _channel =+ MethodChannel('com.pichillilorenzo/flutter_inappwebview_platformutil');++ PlatformUtil._();++ ///Get [PlatformUtil] instance.+ static PlatformUtil instance() {+ return (_instance != null) ? _instance! : _init();+ }++ static PlatformUtil _init() {+ _channel.setMethodCallHandler((call) async {+ try {+ return await _handleMethod(call);+ } on Error catch (e) {+ print(e);+ print(e.stackTrace);+ }+ });+ _instance = PlatformUtil._();+ return _instance!;+ }++ static Future<dynamic> _handleMethod(MethodCall call) async {}++ String? _cachedSystemVersion;++ ///Get current platform system version.+ Future<String> getSystemVersion() async {+ if (_cachedSystemVersion != null) {+ return _cachedSystemVersion!;+ }+ Map<String, dynamic> args = <String, dynamic>{};+ _cachedSystemVersion =+ await _channel.invokeMethod('getSystemVersion', args);+ return _cachedSystemVersion!;+ }++ ///Format date.+ Future<String> formatDate(+ {required DateTime date,+ required String format,+ String locale = "en_US",+ String timezone = "UTC"}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('date', () => date.millisecondsSinceEpoch);+ args.putIfAbsent('format', () => format);+ args.putIfAbsent('locale', () => locale);+ args.putIfAbsent('timezone', () => timezone);+ return await _channel.invokeMethod('formatDate', args);+ }++ ///Get cookie expiration date used by Web platform.+ Future<String> getWebCookieExpirationDate({required DateTime date}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('date', () => date.millisecondsSinceEpoch);+ return await _channel.invokeMethod('getWebCookieExpirationDate', args);+ }+}diff --git a/packages/flutter_inappwebview_windows/lib/src/print_job/main.dart b/packages/flutter_inappwebview_windows/lib/src/print_job/main.dartnew file mode 100644index 00000000..4e70ad94--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/print_job/main.dart@@ -0,0 +1 @@+export 'print_job_controller.dart';diff --git a/packages/flutter_inappwebview_windows/lib/src/print_job/print_job_controller.dart b/packages/flutter_inappwebview_windows/lib/src/print_job/print_job_controller.dartnew file mode 100644index 00000000..a1da365a--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/print_job/print_job_controller.dart@@ -0,0 +1,73 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++/// Object specifying creation parameters for creating a [WindowsPrintJobController].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformPrintJobControllerCreationParams] for+/// more information.+@immutable+class WindowsPrintJobControllerCreationParams+ extends PlatformPrintJobControllerCreationParams {+ /// Creates a new [WindowsPrintJobControllerCreationParams] instance.+ const WindowsPrintJobControllerCreationParams(+ {required super.id, super.onComplete});++ /// Creates a [WindowsPrintJobControllerCreationParams] instance based on [PlatformPrintJobControllerCreationParams].+ factory WindowsPrintJobControllerCreationParams.fromPlatformPrintJobControllerCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformPrintJobControllerCreationParams params) {+ return WindowsPrintJobControllerCreationParams(+ id: params.id, onComplete: params.onComplete);+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformPrintJobController}+class WindowsPrintJobController extends PlatformPrintJobController+ with ChannelController {+ /// Constructs a [WindowsPrintJobController].+ WindowsPrintJobController(PlatformPrintJobControllerCreationParams params)+ : super.implementation(+ params is WindowsPrintJobControllerCreationParams+ ? params+ : WindowsPrintJobControllerCreationParams+ .fromPlatformPrintJobControllerCreationParams(params),+ ) {+ onComplete = params.onComplete;+ channel = MethodChannel(+ 'com.pichillilorenzo/flutter_inappwebview_printjobcontroller_${params.id}');+ handler = _handleMethod;+ initMethodCallHandler();+ }++ Future<dynamic> _handleMethod(MethodCall call) async {+ switch (call.method) {+ case "onComplete":+ bool completed = call.arguments["completed"];+ String? error = call.arguments["error"];+ if (onComplete != null) {+ onComplete!(completed, error);+ }+ break;+ default:+ throw UnimplementedError("Unimplemented ${call.method} method");+ }+ }++ @override+ Future<PrintJobInfo?> getInfo() async {+ Map<String, dynamic> args = <String, dynamic>{};+ Map<String, dynamic>? infoMap =+ (await channel?.invokeMethod('getInfo', args))?.cast<String, dynamic>();+ return PrintJobInfo.fromMap(infoMap);+ }++ @override+ Future<void> dispose() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('dispose', args);+ disposeChannel();+ }+}diff --git a/packages/flutter_inappwebview_windows/lib/src/web_message/main.dart b/packages/flutter_inappwebview_windows/lib/src/web_message/main.dartnew file mode 100644index 00000000..d41e30c7--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/web_message/main.dart@@ -0,0 +1,3 @@+export 'web_message_port.dart' hide InternalWebMessagePort;+export 'web_message_channel.dart' hide InternalWebMessageChannel;+export 'web_message_listener.dart';diff --git a/packages/flutter_inappwebview_windows/lib/src/web_message/web_message_channel.dart b/packages/flutter_inappwebview_windows/lib/src/web_message/web_message_channel.dartnew file mode 100644index 00000000..19c99b31--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/web_message/web_message_channel.dart@@ -0,0 +1,120 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';+import 'web_message_port.dart';++/// Object specifying creation parameters for creating a [WindowsWebMessageChannel].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformWebMessageChannelCreationParams] for+/// more information.+@immutable+class WindowsWebMessageChannelCreationParams+ extends PlatformWebMessageChannelCreationParams {+ /// Creates a new [WindowsWebMessageChannelCreationParams] instance.+ const WindowsWebMessageChannelCreationParams(+ {required super.id, required super.port1, required super.port2});++ /// Creates a [WindowsWebMessageChannelCreationParams] instance based on [PlatformWebMessageChannelCreationParams].+ factory WindowsWebMessageChannelCreationParams.fromPlatformWebMessageChannelCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformWebMessageChannelCreationParams params) {+ return WindowsWebMessageChannelCreationParams(+ id: params.id, port1: params.port1, port2: params.port2);+ }++ @override+ String toString() {+ return 'MacOSWebMessageChannelCreationParams{id: $id, port1: $port1, port2: $port2}';+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformWebMessageChannel}+class WindowsWebMessageChannel extends PlatformWebMessageChannel+ with ChannelController {+ /// Constructs a [WindowsWebMessageChannel].+ WindowsWebMessageChannel(PlatformWebMessageChannelCreationParams params)+ : super.implementation(+ params is WindowsWebMessageChannelCreationParams+ ? params+ : WindowsWebMessageChannelCreationParams+ .fromPlatformWebMessageChannelCreationParams(params),+ ) {+ channel = MethodChannel(+ 'com.pichillilorenzo/flutter_inappwebview_web_message_channel_${params.id}');+ handler = _handleMethod;+ initMethodCallHandler();+ }++ static final WindowsWebMessageChannel _staticValue = WindowsWebMessageChannel(+ WindowsWebMessageChannelCreationParams(+ id: '',+ port1: WindowsWebMessagePort(+ WindowsWebMessagePortCreationParams(index: 0)),+ port2: WindowsWebMessagePort(+ WindowsWebMessagePortCreationParams(index: 1))));++ /// Provide static access.+ factory WindowsWebMessageChannel.static() {+ return _staticValue;+ }++ WindowsWebMessagePort get _macosPort1 => port1 as WindowsWebMessagePort;++ WindowsWebMessagePort get _macosPort2 => port2 as WindowsWebMessagePort;++ static WindowsWebMessageChannel? _fromMap(Map<String, dynamic>? map) {+ if (map == null) {+ return null;+ }+ var webMessageChannel = WindowsWebMessageChannel(+ WindowsWebMessageChannelCreationParams(+ id: map["id"],+ port1: WindowsWebMessagePort(+ WindowsWebMessagePortCreationParams(index: 0)),+ port2: WindowsWebMessagePort(+ WindowsWebMessagePortCreationParams(index: 1))));+ webMessageChannel._macosPort1.webMessageChannel = webMessageChannel;+ webMessageChannel._macosPort2.webMessageChannel = webMessageChannel;+ return webMessageChannel;+ }++ Future<dynamic> _handleMethod(MethodCall call) async {+ switch (call.method) {+ case "onMessage":+ int index = call.arguments["index"];+ var port = index == 0 ? _macosPort1 : _macosPort2;+ if (port.onMessage != null) {+ WebMessage? message = call.arguments["message"] != null+ ? WebMessage.fromMap(+ call.arguments["message"].cast<String, dynamic>())+ : null;+ port.onMessage!(message);+ }+ break;+ default:+ throw UnimplementedError("Unimplemented ${call.method} method");+ }+ return null;+ }++ @override+ WindowsWebMessageChannel? fromMap(Map<String, dynamic>? map) {+ return _fromMap(map);+ }++ @override+ void dispose() {+ disposeChannel();+ }++ @override+ String toString() {+ return 'MacOSWebMessageChannel{id: $id, port1: $port1, port2: $port2}';+ }+}++extension InternalWebMessageChannel on WindowsWebMessageChannel {+ MethodChannel? get internalChannel => channel;+}diff --git a/packages/flutter_inappwebview_windows/lib/src/web_message/web_message_listener.dart b/packages/flutter_inappwebview_windows/lib/src/web_message/web_message_listener.dartnew file mode 100644index 00000000..22a9cd76--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/web_message/web_message_listener.dart@@ -0,0 +1,164 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++/// Object specifying creation parameters for creating a [WindowsWebMessageListener].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformWebMessageListenerCreationParams] for+/// more information.+@immutable+class WindowsWebMessageListenerCreationParams+ extends PlatformWebMessageListenerCreationParams {+ /// Creates a new [WindowsWebMessageListenerCreationParams] instance.+ const WindowsWebMessageListenerCreationParams(+ {required this.allowedOriginRules,+ required super.jsObjectName,+ super.onPostMessage});++ /// Creates a [WindowsWebMessageListenerCreationParams] instance based on [PlatformWebMessageListenerCreationParams].+ factory WindowsWebMessageListenerCreationParams.fromPlatformWebMessageListenerCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformWebMessageListenerCreationParams params) {+ return WindowsWebMessageListenerCreationParams(+ allowedOriginRules: params.allowedOriginRules ?? Set.from(["*"]),+ jsObjectName: params.jsObjectName,+ onPostMessage: params.onPostMessage);+ }++ @override+ final Set<String> allowedOriginRules;++ @override+ String toString() {+ return 'MacOSWebMessageListenerCreationParams{jsObjectName: $jsObjectName, allowedOriginRules: $allowedOriginRules, onPostMessage: $onPostMessage}';+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformWebMessageListener}+class WindowsWebMessageListener extends PlatformWebMessageListener+ with ChannelController {+ /// Constructs a [WindowsWebMessageListener].+ WindowsWebMessageListener(PlatformWebMessageListenerCreationParams params)+ : super.implementation(+ params is WindowsWebMessageListenerCreationParams+ ? params+ : WindowsWebMessageListenerCreationParams+ .fromPlatformWebMessageListenerCreationParams(params),+ ) {+ assert(!this._macosParams.allowedOriginRules.contains(""),+ "allowedOriginRules cannot contain empty strings");+ channel = MethodChannel(+ 'com.pichillilorenzo/flutter_inappwebview_web_message_listener_${_id}_${params.jsObjectName}');+ handler = _handleMethod;+ initMethodCallHandler();+ }++ ///Message Listener ID used internally.+ final String _id = IdGenerator.generate();++ MacOSJavaScriptReplyProxy? _replyProxy;++ WindowsWebMessageListenerCreationParams get _macosParams =>+ params as WindowsWebMessageListenerCreationParams;++ Future<dynamic> _handleMethod(MethodCall call) async {+ switch (call.method) {+ case "onPostMessage":+ if (_replyProxy == null) {+ _replyProxy = MacOSJavaScriptReplyProxy(+ PlatformJavaScriptReplyProxyCreationParams(+ webMessageListener: this));+ }+ if (onPostMessage != null) {+ WebMessage? message = call.arguments["message"] != null+ ? WebMessage.fromMap(+ call.arguments["message"].cast<String, dynamic>())+ : null;+ WebUri? sourceOrigin = call.arguments["sourceOrigin"] != null+ ? WebUri(call.arguments["sourceOrigin"])+ : null;+ bool isMainFrame = call.arguments["isMainFrame"];+ onPostMessage!(message, sourceOrigin, isMainFrame, _replyProxy!);+ }+ break;+ default:+ throw UnimplementedError("Unimplemented ${call.method} method");+ }+ return null;+ }++ @override+ void dispose() {+ disposeChannel();+ }++ @override+ Map<String, dynamic> toMap() {+ return {+ "id": _id,+ "jsObjectName": params.jsObjectName,+ "allowedOriginRules": _macosParams.allowedOriginRules.toList(),+ };+ }++ @override+ Map<String, dynamic> toJson() {+ return this.toMap();+ }++ @override+ String toString() {+ return 'MacOSWebMessageListener{id: ${_id}, jsObjectName: ${params.jsObjectName}, allowedOriginRules: ${params.allowedOriginRules}, replyProxy: $_replyProxy}';+ }+}++/// Object specifying creation parameters for creating a [MacOSJavaScriptReplyProxy].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformJavaScriptReplyProxyCreationParams] for+/// more information.+@immutable+class MacOSJavaScriptReplyProxyCreationParams+ extends PlatformJavaScriptReplyProxyCreationParams {+ /// Creates a new [MacOSJavaScriptReplyProxyCreationParams] instance.+ const MacOSJavaScriptReplyProxyCreationParams(+ {required super.webMessageListener});++ /// Creates a [MacOSJavaScriptReplyProxyCreationParams] instance based on [PlatformJavaScriptReplyProxyCreationParams].+ factory MacOSJavaScriptReplyProxyCreationParams.fromPlatformJavaScriptReplyProxyCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformJavaScriptReplyProxyCreationParams params) {+ return MacOSJavaScriptReplyProxyCreationParams(+ webMessageListener: params.webMessageListener);+ }+}++///{@macro flutter_inappwebview_platform_interface.JavaScriptReplyProxy}+class MacOSJavaScriptReplyProxy extends PlatformJavaScriptReplyProxy {+ /// Constructs a [WindowsWebMessageListener].+ MacOSJavaScriptReplyProxy(PlatformJavaScriptReplyProxyCreationParams params)+ : super.implementation(+ params is MacOSJavaScriptReplyProxyCreationParams+ ? params+ : MacOSJavaScriptReplyProxyCreationParams+ .fromPlatformJavaScriptReplyProxyCreationParams(params),+ );++ WindowsWebMessageListener get _macosWebMessageListener =>+ params.webMessageListener as WindowsWebMessageListener;++ @override+ Future<void> postMessage(WebMessage message) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('message', () => message.toMap());+ await _macosWebMessageListener.channel?.invokeMethod('postMessage', args);+ }++ @override+ String toString() {+ return 'MacOSJavaScriptReplyProxy{}';+ }+}diff --git a/packages/flutter_inappwebview_windows/lib/src/web_message/web_message_port.dart b/packages/flutter_inappwebview_windows/lib/src/web_message/web_message_port.dartnew file mode 100644index 00000000..f75c956e--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/web_message/web_message_port.dart@@ -0,0 +1,95 @@+import 'package:flutter/foundation.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++import 'web_message_channel.dart';++/// Object specifying creation parameters for creating a [WindowsWebMessagePort].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformWebMessagePortCreationParams] for+/// more information.+@immutable+class WindowsWebMessagePortCreationParams+ extends PlatformWebMessagePortCreationParams {+ /// Creates a new [WindowsWebMessagePortCreationParams] instance.+ const WindowsWebMessagePortCreationParams({required super.index});++ /// Creates a [WindowsWebMessagePortCreationParams] instance based on [PlatformWebMessagePortCreationParams].+ factory WindowsWebMessagePortCreationParams.fromPlatformWebMessagePortCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformWebMessagePortCreationParams params) {+ return WindowsWebMessagePortCreationParams(index: params.index);+ }++ @override+ String toString() {+ return 'MacOSWebMessagePortCreationParams{index: $index}';+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformWebMessagePort}+class WindowsWebMessagePort extends PlatformWebMessagePort {+ WebMessageCallback? _onMessage;+ late WindowsWebMessageChannel _webMessageChannel;++ /// Constructs a [WindowsWebMessagePort].+ WindowsWebMessagePort(PlatformWebMessagePortCreationParams params)+ : super.implementation(+ params is WindowsWebMessagePortCreationParams+ ? params+ : WindowsWebMessagePortCreationParams+ .fromPlatformWebMessagePortCreationParams(params),+ );++ @override+ Future<void> setWebMessageCallback(WebMessageCallback? onMessage) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('index', () => params.index);+ await _webMessageChannel.internalChannel+ ?.invokeMethod('setWebMessageCallback', args);+ this._onMessage = onMessage;+ }++ @override+ Future<void> postMessage(WebMessage message) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('index', () => params.index);+ args.putIfAbsent('message', () => message.toMap());+ await _webMessageChannel.internalChannel?.invokeMethod('postMessage', args);+ }++ @override+ Future<void> close() async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('index', () => params.index);+ await _webMessageChannel.internalChannel?.invokeMethod('close', args);+ }++ @override+ Map<String, dynamic> toMap() {+ return {+ "index": params.index,+ "webMessageChannelId": this._webMessageChannel.params.id+ };+ }++ @override+ Map<String, dynamic> toJson() {+ return toMap();+ }++ @override+ String toString() {+ return 'MacOSWebMessagePort{index: ${params.index}}';+ }+}++extension InternalWebMessagePort on WindowsWebMessagePort {+ WebMessageCallback? get onMessage => _onMessage;+ void set onMessage(WebMessageCallback? value) => _onMessage = value;++ WindowsWebMessageChannel get webMessageChannel => _webMessageChannel;+ void set webMessageChannel(WindowsWebMessageChannel value) =>+ _webMessageChannel = value;+}diff --git a/packages/flutter_inappwebview_windows/lib/src/web_storage/main.dart b/packages/flutter_inappwebview_windows/lib/src/web_storage/main.dartnew file mode 100644index 00000000..7265ae52--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/web_storage/main.dart@@ -0,0 +1,2 @@+export 'web_storage.dart';+export 'web_storage_manager.dart' hide InternalWebStorageManager;diff --git a/packages/flutter_inappwebview_windows/lib/src/web_storage/web_storage.dart b/packages/flutter_inappwebview_windows/lib/src/web_storage/web_storage.dartnew file mode 100644index 00000000..93e06ec2--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/web_storage/web_storage.dart@@ -0,0 +1,257 @@+import 'dart:convert';++import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++import '../in_app_webview/in_app_webview_controller.dart';++/// Object specifying creation parameters for creating a [WindowsWebStorage].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformWebStorageCreationParams] for+/// more information.+class WindowsWebStorageCreationParams extends PlatformWebStorageCreationParams {+ /// Creates a new [WindowsWebStorageCreationParams] instance.+ WindowsWebStorageCreationParams(+ {required super.localStorage, required super.sessionStorage});++ /// Creates a [WindowsWebStorageCreationParams] instance based on [PlatformWebStorageCreationParams].+ factory WindowsWebStorageCreationParams.fromPlatformWebStorageCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformWebStorageCreationParams params) {+ return WindowsWebStorageCreationParams(+ localStorage: params.localStorage,+ sessionStorage: params.sessionStorage);+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformWebStorage}+class WindowsWebStorage extends PlatformWebStorage {+ /// Constructs a [WindowsWebStorage].+ WindowsWebStorage(PlatformWebStorageCreationParams params)+ : super.implementation(+ params is WindowsWebStorageCreationParams+ ? params+ : WindowsWebStorageCreationParams+ .fromPlatformWebStorageCreationParams(params),+ );++ @override+ PlatformLocalStorage get localStorage => params.localStorage;++ @override+ PlatformSessionStorage get sessionStorage => params.sessionStorage;++ @override+ void dispose() {+ localStorage.dispose();+ sessionStorage.dispose();+ }+}++/// Object specifying creation parameters for creating a [WindowsStorage].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformStorageCreationParams] for+/// more information.+class WindowsStorageCreationParams extends PlatformStorageCreationParams {+ /// Creates a new [WindowsStorageCreationParams] instance.+ WindowsStorageCreationParams(+ {required super.controller, required super.webStorageType});++ /// Creates a [WindowsStorageCreationParams] instance based on [PlatformStorageCreationParams].+ factory WindowsStorageCreationParams.fromPlatformStorageCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformStorageCreationParams params) {+ return WindowsStorageCreationParams(+ controller: params.controller, webStorageType: params.webStorageType);+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformStorage}+abstract mixin class WindowsStorage implements PlatformStorage {+ @override+ WindowsInAppWebViewController? controller;++ @override+ Future<int?> length() async {+ var result = await controller?.evaluateJavascript(source: """+ window.$webStorageType.length;+ """);+ return result != null ? int.parse(json.decode(result)) : null;+ }++ @override+ Future<void> setItem({required String key, required dynamic value}) async {+ var encodedValue = json.encode(value);+ await controller?.evaluateJavascript(source: """+ window.$webStorageType.setItem("$key", ${value is String ? encodedValue : "JSON.stringify($encodedValue)"});+ """);+ }++ @override+ Future<dynamic> getItem({required String key}) async {+ var itemValue = await controller?.evaluateJavascript(source: """+ window.$webStorageType.getItem("$key");+ """);++ if (itemValue == null) {+ return null;+ }++ try {+ return json.decode(itemValue);+ } catch (e) {}++ return itemValue;+ }++ @override+ Future<void> removeItem({required String key}) async {+ await controller?.evaluateJavascript(source: """+ window.$webStorageType.removeItem("$key");+ """);+ }++ @override+ Future<List<WebStorageItem>> getItems() async {+ var webStorageItems = <WebStorageItem>[];++ List<Map<dynamic, dynamic>>? items =+ (await controller?.evaluateJavascript(source: """+(function() {+ var webStorageItems = [];+ for(var i = 0; i < window.$webStorageType.length; i++){+ var key = window.$webStorageType.key(i);+ webStorageItems.push(+ {+ key: key,+ value: window.$webStorageType.getItem(key)+ }+ );+ }+ return webStorageItems;+})();+ """))?.cast<Map<dynamic, dynamic>>();++ if (items == null) {+ return webStorageItems;+ }++ for (var item in items) {+ webStorageItems+ .add(WebStorageItem(key: item["key"], value: item["value"]));+ }++ return webStorageItems;+ }++ @override+ Future<void> clear() async {+ await controller?.evaluateJavascript(source: """+ window.$webStorageType.clear();+ """);+ }++ @override+ Future<String> key({required int index}) async {+ var result = await controller?.evaluateJavascript(source: """+ window.$webStorageType.key($index);+ """);+ return result != null ? json.decode(result) : null;+ }++ @override+ void dispose() {+ controller = null;+ }+}++/// Object specifying creation parameters for creating a [WindowsLocalStorage].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformLocalStorageCreationParams] for+/// more information.+class WindowsLocalStorageCreationParams+ extends PlatformLocalStorageCreationParams {+ /// Creates a new [WindowsLocalStorageCreationParams] instance.+ WindowsLocalStorageCreationParams(super.params);++ /// Creates a [WindowsLocalStorageCreationParams] instance based on [PlatformLocalStorageCreationParams].+ factory WindowsLocalStorageCreationParams.fromPlatformLocalStorageCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformLocalStorageCreationParams params) {+ return WindowsLocalStorageCreationParams(params);+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformLocalStorage}+class WindowsLocalStorage extends PlatformLocalStorage with WindowsStorage {+ /// Constructs a [WindowsLocalStorage].+ WindowsLocalStorage(PlatformLocalStorageCreationParams params)+ : super.implementation(+ params is WindowsLocalStorageCreationParams+ ? params+ : WindowsLocalStorageCreationParams+ .fromPlatformLocalStorageCreationParams(params),+ );++ /// Default storage+ factory WindowsLocalStorage.defaultStorage(+ {required PlatformInAppWebViewController? controller}) {+ return WindowsLocalStorage(WindowsLocalStorageCreationParams(+ PlatformLocalStorageCreationParams(PlatformStorageCreationParams(+ controller: controller,+ webStorageType: WebStorageType.LOCAL_STORAGE))));+ }++ @override+ WindowsInAppWebViewController? get controller =>+ params.controller as WindowsInAppWebViewController?;+}++/// Object specifying creation parameters for creating a [WindowsSessionStorage].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformSessionStorageCreationParams] for+/// more information.+class WindowsSessionStorageCreationParams+ extends PlatformSessionStorageCreationParams {+ /// Creates a new [WindowsSessionStorageCreationParams] instance.+ WindowsSessionStorageCreationParams(super.params);++ /// Creates a [WindowsSessionStorageCreationParams] instance based on [PlatformSessionStorageCreationParams].+ factory WindowsSessionStorageCreationParams.fromPlatformSessionStorageCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformSessionStorageCreationParams params) {+ return WindowsSessionStorageCreationParams(params);+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformSessionStorage}+class WindowsSessionStorage extends PlatformSessionStorage with WindowsStorage {+ /// Constructs a [WindowsSessionStorage].+ WindowsSessionStorage(PlatformSessionStorageCreationParams params)+ : super.implementation(+ params is WindowsSessionStorageCreationParams+ ? params+ : WindowsSessionStorageCreationParams+ .fromPlatformSessionStorageCreationParams(params),+ );++ /// Default storage+ factory WindowsSessionStorage.defaultStorage(+ {required PlatformInAppWebViewController? controller}) {+ return WindowsSessionStorage(WindowsSessionStorageCreationParams(+ PlatformSessionStorageCreationParams(PlatformStorageCreationParams(+ controller: controller,+ webStorageType: WebStorageType.SESSION_STORAGE))));+ }++ @override+ WindowsInAppWebViewController? get controller =>+ params.controller as WindowsInAppWebViewController?;+}diff --git a/packages/flutter_inappwebview_windows/lib/src/web_storage/web_storage_manager.dart b/packages/flutter_inappwebview_windows/lib/src/web_storage/web_storage_manager.dartnew file mode 100644index 00000000..cd9c24e6--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/web_storage/web_storage_manager.dart@@ -0,0 +1,134 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++/// Object specifying creation parameters for creating a [WindowsWebStorageManager].+///+/// When adding additional fields make sure they can be null or have a default+/// value to avoid breaking changes. See [PlatformWebStorageManagerCreationParams] for+/// more information.+@immutable+class WindowsWebStorageManagerCreationParams+ extends PlatformWebStorageManagerCreationParams {+ /// Creates a new [WindowsWebStorageManagerCreationParams] instance.+ const WindowsWebStorageManagerCreationParams(+ // This parameter prevents breaking changes later.+ // ignore: avoid_unused_constructor_parameters+ PlatformWebStorageManagerCreationParams params,+ ) : super();++ /// Creates a [WindowsWebStorageManagerCreationParams] instance based on [PlatformWebStorageManagerCreationParams].+ factory WindowsWebStorageManagerCreationParams.fromPlatformWebStorageManagerCreationParams(+ PlatformWebStorageManagerCreationParams params) {+ return WindowsWebStorageManagerCreationParams(params);+ }+}++///{@macro flutter_inappwebview_platform_interface.PlatformWebStorageManager}+class WindowsWebStorageManager extends PlatformWebStorageManager+ with ChannelController {+ /// Creates a new [WindowsWebStorageManager].+ WindowsWebStorageManager(PlatformWebStorageManagerCreationParams params)+ : super.implementation(+ params is WindowsWebStorageManagerCreationParams+ ? params+ : WindowsWebStorageManagerCreationParams+ .fromPlatformWebStorageManagerCreationParams(params),+ ) {+ channel = const MethodChannel(+ 'com.pichillilorenzo/flutter_inappwebview_webstoragemanager');+ handler = handleMethod;+ initMethodCallHandler();+ }++ static WindowsWebStorageManager? _instance;++ ///Gets the WebStorage manager shared instance.+ static WindowsWebStorageManager instance() {+ return (_instance != null) ? _instance! : _init();+ }++ static WindowsWebStorageManager _init() {+ _instance = WindowsWebStorageManager(WindowsWebStorageManagerCreationParams(+ const PlatformWebStorageManagerCreationParams()));+ return _instance!;+ }++ Future<dynamic> _handleMethod(MethodCall call) async {}++ @override+ Future<List<WebsiteDataRecord>> fetchDataRecords(+ {required Set<WebsiteDataType> dataTypes}) async {+ List<WebsiteDataRecord> recordList = [];+ List<String> dataTypesList = [];+ for (var dataType in dataTypes) {+ dataTypesList.add(dataType.toNativeValue());+ }+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("dataTypes", () => dataTypesList);+ List<Map<dynamic, dynamic>> records =+ (await channel?.invokeMethod<List>('fetchDataRecords', args))+ ?.cast<Map<dynamic, dynamic>>() ??+ [];+ for (var record in records) {+ List<String> dataTypesString = record["dataTypes"].cast<String>();+ Set<WebsiteDataType> dataTypes = Set();+ for (var dataTypeValue in dataTypesString) {+ var dataType = WebsiteDataType.fromNativeValue(dataTypeValue);+ if (dataType != null) {+ dataTypes.add(dataType);+ }+ }+ recordList.add(WebsiteDataRecord(+ displayName: record["displayName"], dataTypes: dataTypes));+ }+ return recordList;+ }++ @override+ Future<void> removeDataFor(+ {required Set<WebsiteDataType> dataTypes,+ required List<WebsiteDataRecord> dataRecords}) async {+ List<String> dataTypesList = [];+ for (var dataType in dataTypes) {+ dataTypesList.add(dataType.toNativeValue());+ }++ List<Map<String, dynamic>> recordList = [];+ for (var record in dataRecords) {+ recordList.add(record.toMap());+ }++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("dataTypes", () => dataTypesList);+ args.putIfAbsent("recordList", () => recordList);+ await channel?.invokeMethod('removeDataFor', args);+ }++ @override+ Future<void> removeDataModifiedSince(+ {required Set<WebsiteDataType> dataTypes, required DateTime date}) async {+ List<String> dataTypesList = [];+ for (var dataType in dataTypes) {+ dataTypesList.add(dataType.toNativeValue());+ }++ var timestamp = date.millisecondsSinceEpoch;++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent("dataTypes", () => dataTypesList);+ args.putIfAbsent("timestamp", () => timestamp);+ await channel?.invokeMethod('removeDataModifiedSince', args);+ }++ @override+ void dispose() {+ // empty+ }+}++extension InternalWebStorageManager on WindowsWebStorageManager {+ get handleMethod => _handleMethod;+}diff --git a/packages/flutter_inappwebview_windows/lib/src/webview_environment/main.dart b/packages/flutter_inappwebview_windows/lib/src/webview_environment/main.dartnew file mode 100644index 00000000..a018ec28--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/webview_environment/main.dart@@ -0,0 +1 @@+export 'webview_environment.dart' hide InternalWindowsWebViewEnvironment;diff --git a/packages/flutter_inappwebview_windows/lib/src/webview_environment/webview_environment.dart b/packages/flutter_inappwebview_windows/lib/src/webview_environment/webview_environment.dartnew file mode 100644index 00000000..4313b974--- /dev/null+++ b/packages/flutter_inappwebview_windows/lib/src/webview_environment/webview_environment.dart@@ -0,0 +1,116 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++/// Object specifying creation parameters for creating a [WindowsWebViewEnvironment].+///+/// Platform specific implementations can add additional fields by extending+/// this class.+@immutable+class WindowsWebViewEnvironmentCreationParams+ extends PlatformWebViewEnvironmentCreationParams {+ /// Creates a new [WindowsInAppWebViewControllerCreationParams] instance.+ const WindowsWebViewEnvironmentCreationParams({super.settings});++ /// Creates a [WindowsInAppWebViewControllerCreationParams] instance based on [PlatformInAppWebViewControllerCreationParams].+ factory WindowsWebViewEnvironmentCreationParams.fromPlatformWebViewEnvironmentCreationParams(+ // Recommended placeholder to prevent being broken by platform interface.+ // ignore: avoid_unused_constructor_parameters+ PlatformWebViewEnvironmentCreationParams params) {+ return WindowsWebViewEnvironmentCreationParams(settings: params.settings);+ }+}++///Controls a WebView Environment used by WebView instances.+///+///**Officially Supported Platforms/Implementations**:+///- Windows+class WindowsWebViewEnvironment extends PlatformWebViewEnvironment+ with ChannelController {+ static final MethodChannel _staticChannel =+ MethodChannel('com.pichillilorenzo/flutter_webview_environment');++ @override+ final String id = IdGenerator.generate();++ WindowsWebViewEnvironment(PlatformWebViewEnvironmentCreationParams params)+ : super.implementation(params is WindowsWebViewEnvironmentCreationParams+ ? params+ : WindowsWebViewEnvironmentCreationParams+ .fromPlatformWebViewEnvironmentCreationParams(params));++ static final WindowsWebViewEnvironment _staticValue =+ WindowsWebViewEnvironment(WindowsWebViewEnvironmentCreationParams());++ factory WindowsWebViewEnvironment.static() {+ return _staticValue;+ }++ _debugLog(String method, dynamic args) {+ debugLog(+ className: this.runtimeType.toString(),+ id: id,+ debugLoggingSettings: PlatformWebViewEnvironment.debugLoggingSettings,+ method: method,+ args: args);+ }++ Future<dynamic> _handleMethod(MethodCall call) async {+ if (PlatformWebViewEnvironment.debugLoggingSettings.enabled) {+ _debugLog(call.method, call.arguments);+ }++ switch (call.method) {+ default:+ throw UnimplementedError("Unimplemented ${call.method} method");+ }+ return null;+ }++ @override+ Future<WindowsWebViewEnvironment> create(+ {WebViewEnvironmentSettings? settings}) async {+ final env = WindowsWebViewEnvironment(+ WindowsWebViewEnvironmentCreationParams(settings: settings));++ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('id', () => env.id);+ args.putIfAbsent('settings', () => env.settings?.toMap());+ await _staticChannel.invokeMethod('create', args);++ env.channel =+ MethodChannel('com.pichillilorenzo/flutter_webview_environment_$id');+ env.handler = env.handleMethod;+ env.initMethodCallHandler();+ return env;+ }++ @override+ Future<String?> getAvailableVersion({String? browserExecutableFolder}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('browserExecutableFolder', () => browserExecutableFolder);+ return await _staticChannel.invokeMethod<String>(+ 'getAvailableVersion', args);+ }++ @override+ Future<int?> compareBrowserVersions(+ {required String version1, required String version2}) async {+ Map<String, dynamic> args = <String, dynamic>{};+ args.putIfAbsent('version1', () => version1);+ args.putIfAbsent('version2', () => version2);+ return await _staticChannel.invokeMethod<int>(+ 'compareBrowserVersions', args);+ }++ @override+ Future<void> dispose() async {+ Map<String, dynamic> args = <String, dynamic>{};+ await channel?.invokeMethod('dispose', args);+ disposeChannel();+ }+}++extension InternalWindowsWebViewEnvironment on WindowsWebViewEnvironment {+ get handleMethod => _handleMethod;+}diff --git a/packages/flutter_inappwebview_windows/pubspec.yaml b/packages/flutter_inappwebview_windows/pubspec.yamlnew file mode 100644index 00000000..d1c3ce45--- /dev/null+++ b/packages/flutter_inappwebview_windows/pubspec.yaml@@ -0,0 +1,80 @@+name: flutter_inappwebview_windows+description: Windows implementation of the flutter_inappwebview plugin.+version: 0.6.0+homepage: https://inappwebview.dev/+repository: https://github.com/pichillilorenzo/flutter_inappwebview/tree/master/flutter_inappwebview_windows+issue_tracker: https://github.com/pichillilorenzo/flutter_inappwebview/issues+funding:+ - https://inappwebview.dev/donate/+topics:+ - html+ - webview+ - webview-flutter+ - inappwebview+ - browser++environment:+ sdk: ^3.5.0+ flutter: ">=3.24.0"++dependencies:+ flutter:+ sdk: flutter+ flutter_inappwebview_platform_interface: ^1.3.0++dev_dependencies:+ flutter_test:+ sdk: flutter+ flutter_lints: ^4.0.0++# For information on the generic Dart part of this file, see the+# following page: https://dart.dev/tools/pub/pubspec++# The following section is specific to Flutter packages.+flutter:+ # This section identifies this Flutter project as a plugin project.+ # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.)+ # which should be registered in the plugin registry. This is required for+ # using method channels.+ # The Android 'package' specifies package in which the registered class is.+ # This is required for using method channels on Android.+ # The 'ffiPlugin' specifies that native code should be built and bundled.+ # This is required for using `dart:ffi`.+ # All these are used by the tooling to maintain consistency when+ # adding or updating assets for this project.+ plugin:+ platforms:+ windows:+ pluginClass: FlutterInappwebviewWindowsPluginCApi+ dartPluginClass: WindowsInAppWebViewPlatform++ # To add assets to your plugin package, add an assets section, like this:+ # assets:+ # - images/a_dot_burr.jpeg+ # - images/a_dot_ham.jpeg+ #+ # For details regarding assets in packages, see+ # https://flutter.dev/assets-and-images/#from-packages+ #+ # An image asset can refer to one or more resolution-specific "variants", see+ # https://flutter.dev/assets-and-images/#resolution-aware++ # To add custom fonts to your plugin package, add a fonts section here,+ # in this "flutter" section. Each entry in this list should have a+ # "family" key with the font family name, and a "fonts" key with a+ # list giving the asset and other descriptors for the font. For+ # example:+ # fonts:+ # - family: Schyler+ # fonts:+ # - asset: fonts/Schyler-Regular.ttf+ # - asset: fonts/Schyler-Italic.ttf+ # style: italic+ # - family: Trajan Pro+ # fonts:+ # - asset: fonts/TrajanPro.ttf+ # - asset: fonts/TrajanPro_Bold.ttf+ # weight: 700+ #+ # For details regarding fonts in packages, see+ # https://flutter.dev/custom-fonts/#from-packagesdiff --git a/packages/flutter_inappwebview_windows/test/flutter_inappwebview_windows_test.dart b/packages/flutter_inappwebview_windows/test/flutter_inappwebview_windows_test.dartnew file mode 100644index 00000000..e69de29bdiff --git a/packages/flutter_inappwebview_windows/windows/CMakeLists.txt b/packages/flutter_inappwebview_windows/windows/CMakeLists.txtnew file mode 100644index 00000000..adfbbf78--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/CMakeLists.txt@@ -0,0 +1,261 @@+# The Flutter tooling requires that developers have a version of Visual Studio+# installed that includes CMake 3.14 or later. You should not increase this+# version, as doing so will cause the plugin to fail to compile for some+# customers of the plugin.+cmake_minimum_required(VERSION 3.14)++set(WIL_VERSION "1.0.231216.1")+set(WEBVIEW_VERSION "1.0.2792.45")+set(NLOHMANN_JSON "3.11.2")++message(VERBOSE "CMake system version is ${CMAKE_SYSTEM_VERSION} (using SDK ${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION})")++# Project-level configuration.+set(PROJECT_NAME "flutter_inappwebview_windows")+project(${PROJECT_NAME} LANGUAGES CXX)++# Explicitly opt in to modern CMake behaviors to avoid warnings with recent+# versions of CMake.+cmake_policy(VERSION 3.14...3.25)++# This value is used when generating builds using this plugin, so it must+# not be changed+set(PLUGIN_NAME "flutter_inappwebview_windows_plugin")++find_program(NUGET nuget)+if(NOT NUGET)+ message(NOTICE "Nuget is not installed! The flutter_inappwebview_windows plugin requires it. Check https://inappwebview.dev/docs/intro#setup-windows")+endif()++add_custom_target(${PROJECT_NAME}_DEPENDENCIES_DOWNLOAD ALL)+add_custom_command(+ TARGET ${PROJECT_NAME}_DEPENDENCIES_DOWNLOAD PRE_BUILD+ COMMAND ${NUGET} install Microsoft.Windows.ImplementationLibrary -Version ${WIL_VERSION} -ExcludeVersion -OutputDirectory ${CMAKE_BINARY_DIR}/packages+ COMMAND ${NUGET} install Microsoft.Web.WebView2 -Version ${WEBVIEW_VERSION} -ExcludeVersion -OutputDirectory ${CMAKE_BINARY_DIR}/packages+ COMMAND ${NUGET} install nlohmann.json -Version ${NLOHMANN_JSON} -ExcludeVersion -OutputDirectory ${CMAKE_BINARY_DIR}/packages+ DEPENDS ${NUGET}+)++# Any new source files that you add to the plugin should be added here.+list(APPEND PLUGIN_SOURCES+ "flutter_inappwebview_windows_plugin.cpp"+ "flutter_inappwebview_windows_plugin.h"+ "utils/log.h"+ "utils/strconv.h"+ "utils/map.h"+ "utils/vector.h"+ "utils/string.h"+ "utils/util.h"+ "utils/flutter.h"+ "utils/base64.cpp"+ "utils/base64.h"+ "types/channel_delegate.cpp"+ "types/channel_delegate.h"+ "types/base_callback_result.h"+ "types/url_request.cpp"+ "types/url_request.h"+ "types/navigation_action.cpp"+ "types/navigation_action.h"+ "types/web_resource_error.cpp"+ "types/web_resource_error.h"+ "types/web_resource_request.cpp"+ "types/web_resource_request.h"+ "types/web_resource_response.cpp"+ "types/web_resource_response.h"+ "types/web_history.cpp"+ "types/web_history.h"+ "types/web_history_item.cpp"+ "types/web_history_item.h"+ "types/content_world.cpp"+ "types/content_world.h"+ "types/user_script.cpp"+ "types/user_script.h"+ "types/plugin_script.cpp"+ "types/plugin_script.h"+ "types/size_2d.cpp"+ "types/size_2d.h"+ "types/rect.cpp"+ "types/rect.h"+ "types/callbacks_complete.h"+ "types/screenshot_configuration.cpp"+ "types/screenshot_configuration.h"+ "types/create_window_action.cpp"+ "types/create_window_action.h"+ "types/new_window_requested_args.cpp"+ "types/new_window_requested_args.h"+ "types/window_features.cpp"+ "types/window_features.h"+ "types/ssl_certificate.cpp"+ "types/ssl_certificate.h"+ "types/permission_response.cpp"+ "types/permission_response.h"+ "types/custom_scheme_response.cpp"+ "types/custom_scheme_response.h"+ "types/custom_scheme_registration.cpp"+ "types/custom_scheme_registration.h"+ "custom_platform_view/custom_platform_view.cc"+ "custom_platform_view/custom_platform_view.h"+ "custom_platform_view/texture_bridge.cc"+ "custom_platform_view/texture_bridge.h"+ "custom_platform_view/graphics_context.cc"+ "custom_platform_view/graphics_context.h"+ "custom_platform_view/util/direct3d11.interop.cc"+ "custom_platform_view/util/direct3d11.interop.h"+ "custom_platform_view/util/rohelper.cc"+ "custom_platform_view/util/rohelper.h"+ "custom_platform_view/util/string_converter.cc"+ "custom_platform_view/util/string_converter.h"+ "custom_platform_view/util/swizzle.h"+ "plugin_scripts_js/plugin_scripts_util.h"+ "plugin_scripts_js/javascript_bridge_js.cpp"+ "plugin_scripts_js/javascript_bridge_js.h"+ "webview_environment/webview_environment_settings.cpp"+ "webview_environment/webview_environment_settings.h"+ "webview_environment/webview_environment.cpp"+ "webview_environment/webview_environment.h"+ "webview_environment/webview_environment_manager.cpp"+ "webview_environment/webview_environment_manager.h"+ "webview_environment/webview_environment_channel_delegate.cpp"+ "webview_environment/webview_environment_channel_delegate.h"+ "in_app_webview/user_content_controller.cpp"+ "in_app_webview/user_content_controller.h"+ "in_app_webview/in_app_webview_settings.cpp"+ "in_app_webview/in_app_webview_settings.h"+ "in_app_webview/in_app_webview.cpp"+ "in_app_webview/in_app_webview.h"+ "in_app_webview/in_app_webview_manager.cpp"+ "in_app_webview/in_app_webview_manager.h"+ "in_app_webview/webview_channel_delegate.cpp"+ "in_app_webview/webview_channel_delegate.h"+ "headless_in_app_webview/headless_in_app_webview.cpp"+ "headless_in_app_webview/headless_in_app_webview.h"+ "headless_in_app_webview/headless_in_app_webview_manager.cpp"+ "headless_in_app_webview/headless_in_app_webview_manager.h"+ "headless_in_app_webview/headless_webview_channel_delegate.cpp"+ "headless_in_app_webview/headless_webview_channel_delegate.h"+ "in_app_browser/in_app_browser_settings.cpp"+ "in_app_browser/in_app_browser_settings.h"+ "in_app_browser/in_app_browser_manager.cpp"+ "in_app_browser/in_app_browser_manager.h"+ "in_app_browser/in_app_browser.cpp"+ "in_app_browser/in_app_browser.h"+ "in_app_browser/in_app_browser_channel_delegate.cpp"+ "in_app_browser/in_app_browser_channel_delegate.h"+ "cookie_manager.cpp"+ "cookie_manager.h"+)++# Define the plugin library target. Its name must not be changed (see comment+# on PLUGIN_NAME above).+add_library(${PLUGIN_NAME} SHARED+ "include/flutter_inappwebview_windows/flutter_inappwebview_windows_plugin_c_api.h"+ "flutter_inappwebview_windows_plugin_c_api.cpp"+ ${PLUGIN_SOURCES}+)++if(NOT FLUTTER_WEBVIEW_WINDOWS_USE_TEXTURE_FALLBACK)+ message(STATUS "Building with D3D texture support.")+ target_compile_definitions("${PLUGIN_NAME}" PRIVATE+ HAVE_FLUTTER_D3D_TEXTURE+ )+ target_sources("${PLUGIN_NAME}" PRIVATE+ "custom_platform_view/texture_bridge_gpu.cc"+ "custom_platform_view/texture_bridge_gpu.h"+ )+else()+ message(STATUS "Building with fallback PixelBuffer texture.")+ target_sources("${PLUGIN_NAME}" PRIVATE+ "custom_platform_view/texture_bridge_fallback.cc"+ "custom_platform_view/texture_bridge_fallback.h"+ "custom_platform_view/util/cpuid/cpuinfo.cc"+ "custom_platform_view/util/cpuid/cpuinfo.h"+ )+ # Enable AVX2 for pixel buffer conversions+ if(MSVC)+ target_compile_options(${PLUGIN_NAME} PRIVATE "/arch:AVX2")+ endif()+endif()++# Apply a standard set of build settings that are configured in the+# application-level CMakeLists.txt. This can be removed for plugins that want+# full control over build settings.+# apply_standard_settings(${PLUGIN_NAME})+#+# IMPORTANT: The apply_standard_settings function is not used here because it+# is causing the plugin to fail to compile because of the usage of /WX flag.+# So, creating here a custom function to apply the standard settings without the /WX flag.+function(FLUTTER_INAPPWEBVIEW_WINDOWS_APPLY_STANDARD_SETTINGS TARGET)+ target_compile_features(${TARGET} PUBLIC cxx_std_17)+ target_compile_options(${TARGET} PRIVATE /W4 /wd"4100")+ target_compile_options(${TARGET} PRIVATE /EHsc)+ target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")+ target_compile_definitions(${TARGET} PRIVATE "$<$<CONFIG:Debug>:_DEBUG>")+endfunction()+flutter_inappwebview_windows_apply_standard_settings(${PLUGIN_NAME})++target_link_libraries(${PLUGIN_NAME} PRIVATE ${CMAKE_BINARY_DIR}/packages/Microsoft.Web.WebView2/build/native/Microsoft.Web.WebView2.targets)+target_link_libraries(${PLUGIN_NAME} PRIVATE ${CMAKE_BINARY_DIR}/packages/Microsoft.Windows.ImplementationLibrary/build/native/Microsoft.Windows.ImplementationLibrary.targets)+target_link_libraries(${PLUGIN_NAME} PRIVATE ${CMAKE_BINARY_DIR}/packages/nlohmann.json/build/native/nlohmann.json.targets)++# Symbols are hidden by default to reduce the chance of accidental conflicts+# between plugins. This should not be removed; any symbols that should be+# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro.+set_target_properties(${PLUGIN_NAME} PROPERTIES+ CXX_VISIBILITY_PRESET hidden)+target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL)++# Source include directories and library dependencies. Add any plugin-specific+# dependencies here.+target_include_directories(${PLUGIN_NAME} INTERFACE+ "${CMAKE_CURRENT_SOURCE_DIR}/include")+target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin)++# List of absolute paths to libraries that should be bundled with the plugin.+# This list could contain prebuilt libraries, or libraries created by an+# external build triggered from this build file.+set(flutter_inappwebview_windows_bundled_libraries+ PARENT_SCOPE+)++# === Tests ===+# These unit tests can be run from a terminal after building the example, or+# from Visual Studio after opening the generated solution file.++# Only enable test builds when building the example (which sets this variable)+# so that plugin clients aren't building the tests.+if (${include_${PROJECT_NAME}_tests})+set(TEST_RUNNER "${PROJECT_NAME}_test")+enable_testing()++# Add the Google Test dependency.+include(FetchContent)+FetchContent_Declare(+ googletest+ URL https://github.com/google/googletest/archive/release-1.11.0.zip+)+# Prevent overriding the parent project's compiler/linker settings+set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)+# Disable install commands for gtest so it doesn't end up in the bundle.+set(INSTALL_GTEST OFF CACHE BOOL "Disable installation of googletest" FORCE)+FetchContent_MakeAvailable(googletest)++# The plugin's C API is not very useful for unit testing, so build the sources+# directly into the test binary rather than using the DLL.+add_executable(${TEST_RUNNER}+ test/flutter_inappwebview_windows_plugin_test.cpp+ ${PLUGIN_SOURCES}+)+apply_standard_settings(${TEST_RUNNER})+target_include_directories(${TEST_RUNNER} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")+target_link_libraries(${TEST_RUNNER} PRIVATE flutter_wrapper_plugin)+target_link_libraries(${TEST_RUNNER} PRIVATE gtest_main gmock)+# flutter_wrapper_plugin has link dependencies on the Flutter DLL.+add_custom_command(TARGET ${TEST_RUNNER} POST_BUILD+ COMMAND ${CMAKE_COMMAND} -E copy_if_different+ "${FLUTTER_LIBRARY}" $<TARGET_FILE_DIR:${TEST_RUNNER}>+)++# Enable automatic test discovery.+include(GoogleTest)+gtest_discover_tests(${TEST_RUNNER})+endif()diff --git a/packages/flutter_inappwebview_windows/windows/cookie_manager.cpp b/packages/flutter_inappwebview_windows/windows/cookie_manager.cppnew file mode 100644index 00000000..7ea8750c--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/cookie_manager.cpp@@ -0,0 +1,349 @@+#include <ctime>+#include <nlohmann/json.hpp>+#include <Shlwapi.h>+#include <winrt/base.h>+#include <wrl/event.h>++#include "cookie_manager.h"+#include "types/callbacks_complete.h"+#include "utils/flutter.h"+#include "utils/log.h"++namespace flutter_inappwebview_plugin+{+ using namespace Microsoft::WRL;++ CookieManager::CookieManager(const FlutterInappwebviewWindowsPlugin* plugin)+ : plugin(plugin), ChannelDelegate(plugin->registrar->messenger(), CookieManager::METHOD_CHANNEL_NAME_PREFIX)+ {}++ void CookieManager::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ auto& arguments = std::get<flutter::EncodableMap>(*method_call.arguments());+ auto& methodName = method_call.method_name();++ auto webViewEnvironmentId = get_optional_fl_map_value<std::string>(arguments, "webViewEnvironmentId");++ auto webViewEnvironment = plugin && webViewEnvironmentId.has_value() && map_contains(plugin->webViewEnvironmentManager->webViewEnvironments, webViewEnvironmentId.value())+ ? plugin->webViewEnvironmentManager->webViewEnvironments.at(webViewEnvironmentId.value()).get() : nullptr;++ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));+ auto callback = [this, result_, methodName, arguments](WebViewEnvironment* webViewEnvironment)+ {+ if (!webViewEnvironment) {+ result_->Error("0", "Cannot obtain the WebViewEnvironment!");+ return;+ }++ if (string_equals(methodName, "setCookie")) {+ setCookie(webViewEnvironment, arguments, [result_](const bool& created)+ {+ result_->Success(created);+ });+ }+ else if (string_equals(methodName, "getCookie")) {+ auto url = get_fl_map_value<std::string>(arguments, "url");+ auto name = get_fl_map_value<std::string>(arguments, "name");+ getCookie(webViewEnvironment, url, name, [result_](const flutter::EncodableValue& cookie)+ {+ result_->Success(cookie);+ });+ }+ else if (string_equals(methodName, "getCookies")) {+ auto url = get_fl_map_value<std::string>(arguments, "url");+ getCookies(webViewEnvironment, url, [result_](const flutter::EncodableList& cookies)+ {+ result_->Success(cookies);+ });+ }+ else if (string_equals(methodName, "deleteCookie")) {+ auto url = get_fl_map_value<std::string>(arguments, "url");+ auto name = get_fl_map_value<std::string>(arguments, "name");+ auto path = get_fl_map_value<std::string>(arguments, "path");+ auto domain = get_optional_fl_map_value<std::string>(arguments, "domain");+ deleteCookie(webViewEnvironment, url, name, path, domain, [result_](const bool& deleted)+ {+ result_->Success(deleted);+ });+ }+ else if (string_equals(methodName, "deleteCookies")) {+ auto url = get_fl_map_value<std::string>(arguments, "url");+ auto path = get_fl_map_value<std::string>(arguments, "path");+ auto domain = get_optional_fl_map_value<std::string>(arguments, "domain");+ deleteCookies(webViewEnvironment, url, path, domain, [result_](const bool& deleted)+ {+ result_->Success(deleted);+ });+ }+ else if (string_equals(methodName, "deleteAllCookies")) {+ deleteAllCookies(webViewEnvironment, [result_](const bool& deleted)+ {+ result_->Success(deleted);+ });+ }+ else {+ result_->NotImplemented();+ }+ };++ if (webViewEnvironment) {+ callback(webViewEnvironment);+ }+ else {+ plugin->webViewEnvironmentManager->createOrGetDefaultWebViewEnvironment([callback](WebViewEnvironment* webViewEnvironment)+ {+ callback(webViewEnvironment);+ });+ }+ }++ void CookieManager::setCookie(WebViewEnvironment* webViewEnvironment, const flutter::EncodableMap& map, std::function<void(const bool&)> completionHandler) const+ {+ if (!plugin || !plugin->webViewEnvironmentManager) {+ if (completionHandler) {+ completionHandler(false);+ }+ return;+ }++ auto url = get_fl_map_value<std::string>(map, "url");+ auto name = get_fl_map_value<std::string>(map, "name");+ auto value = get_fl_map_value<std::string>(map, "value");+ auto path = get_fl_map_value<std::string>(map, "path");+ auto domain = get_optional_fl_map_value<std::string>(map, "domain");+ auto expiresDate = get_optional_fl_map_value<int64_t>(map, "expiresDate");+ auto maxAge = get_optional_fl_map_value<int64_t>(map, "maxAge");+ auto isSecure = get_optional_fl_map_value<bool>(map, "isSecure");+ auto isHttpOnly = get_optional_fl_map_value<bool>(map, "isHttpOnly");+ auto sameSite = get_optional_fl_map_value<std::string>(map, "sameSite");++ nlohmann::json parameters = {+ {"url", url},+ {"name", name},+ {"value", value},+ {"path", path}+ };+ if (domain.has_value()) {+ parameters["domain"] = domain.value();+ }+ if (expiresDate.has_value()) {+ parameters["expires"] = expiresDate.value() / 1000;+ }+ if (maxAge.has_value()) {+ // time(NULL) represents the current unix timestamp in seconds+ parameters["expires"] = time(NULL) + maxAge.value();+ }+ if (isSecure.has_value()) {+ parameters["secure"] = isSecure.value();+ }+ if (isHttpOnly.has_value()) {+ parameters["httpOnly"] = isHttpOnly.value();+ }+ if (sameSite.has_value()) {+ parameters["sameSite"] = sameSite.value();+ }++ auto hr = webViewEnvironment->getWebView()->CallDevToolsProtocolMethod(L"Network.setCookie", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ if (completionHandler) {+ completionHandler(succeededOrLog(errorCode));+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler(false);+ }+ }++ void CookieManager::getCookie(WebViewEnvironment* webViewEnvironment, const std::string& url, const std::string& name, std::function<void(const flutter::EncodableValue&)> completionHandler) const+ {+ if (!plugin || !plugin->webViewEnvironmentManager) {+ if (completionHandler) {+ completionHandler(make_fl_value());+ }+ return;+ }++ nlohmann::json parameters = {+ {"urls", std::vector<std::string>{url}}+ };++ auto hr = webViewEnvironment->getWebView()->CallDevToolsProtocolMethod(L"Network.getCookies", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [completionHandler, name](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ if (succeededOrLog(errorCode)) {+ nlohmann::json json = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson));+ auto jsonCookies = json["cookies"].get<std::vector<nlohmann::json>>();+ for (auto& jsonCookie : jsonCookies) {+ auto cookieName = jsonCookie["name"].get<std::string>();+ if (string_equals(name, cookieName)) {+ completionHandler(flutter::EncodableMap{+ {"name", cookieName},+ {"value", jsonCookie["value"].get<std::string>()},+ {"domain", jsonCookie["domain"].get<std::string>()},+ {"path", jsonCookie["path"].get<std::string>()},+ {"expiresDate", jsonCookie["expires"].get<int64_t>()},+ {"isHttpOnly", jsonCookie["httpOnly"].get<bool>()},+ {"isSecure", jsonCookie["secure"].get<bool>()},+ {"isSessionOnly", jsonCookie["session"].get<bool>()},+ {"sameSite", jsonCookie.contains("sameSite") ? jsonCookie["sameSite"].get<std::string>() : make_fl_value()}+ });+ return S_OK;+ }+ }+ }+ if (completionHandler) {+ completionHandler(make_fl_value());+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler(make_fl_value());+ }+ }++ void CookieManager::getCookies(WebViewEnvironment* webViewEnvironment, const std::string& url, std::function<void(const flutter::EncodableList&)> completionHandler) const+ {+ if (!plugin || !plugin->webViewEnvironmentManager) {+ if (completionHandler) {+ completionHandler({});+ }+ return;+ }++ nlohmann::json parameters = {+ {"urls", std::vector<std::string>{url}}+ };++ auto hr = webViewEnvironment->getWebView()->CallDevToolsProtocolMethod(L"Network.getCookies", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ std::vector<flutter::EncodableValue> cookies = {};+ if (succeededOrLog(errorCode)) {+ nlohmann::json json = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson));+ auto jsonCookies = json["cookies"].get<std::vector<nlohmann::json>>();+ for (auto& jsonCookie : jsonCookies) {+ cookies.push_back(flutter::EncodableMap{+ {"name", jsonCookie["name"].get<std::string>()},+ {"value", jsonCookie["value"].get<std::string>()},+ {"domain", jsonCookie["domain"].get<std::string>()},+ {"path", jsonCookie["path"].get<std::string>()},+ {"expiresDate", jsonCookie["expires"].get<int64_t>()},+ {"isHttpOnly", jsonCookie["httpOnly"].get<bool>()},+ {"isSecure", jsonCookie["secure"].get<bool>()},+ {"isSessionOnly", jsonCookie["session"].get<bool>()},+ {"sameSite", jsonCookie.contains("sameSite") ? jsonCookie["sameSite"].get<std::string>() : make_fl_value()}+ });+ }+ }+ if (completionHandler) {+ completionHandler(cookies);+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler({});+ }+ }++ void CookieManager::deleteCookie(WebViewEnvironment* webViewEnvironment, const std::string& url, const std::string& name, const std::string& path, const std::optional<std::string>& domain, std::function<void(const bool&)> completionHandler) const+ {+ if (!plugin || !plugin->webViewEnvironmentManager) {+ if (completionHandler) {+ completionHandler(false);+ }+ return;+ }++ nlohmann::json parameters = {+ {"url", url},+ {"name", name},+ {"path", path}+ };+ if (domain.has_value()) {+ parameters["domain"] = domain.value();+ }++ auto hr = webViewEnvironment->getWebView()->CallDevToolsProtocolMethod(L"Network.deleteCookies", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ if (completionHandler) {+ completionHandler(succeededOrLog(errorCode));+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler(false);+ }+ }++ void CookieManager::deleteCookies(WebViewEnvironment* webViewEnvironment, const std::string& url, const std::string& path, const std::optional<std::string>& domain, std::function<void(const bool&)> completionHandler) const+ {+ if (!plugin || !plugin->webViewEnvironmentManager) {+ if (completionHandler) {+ completionHandler(false);+ }+ return;+ }++ getCookies(webViewEnvironment, url, [this, webViewEnvironment, url, path, domain, completionHandler](const flutter::EncodableList& cookies)+ {+ auto callbacksComplete = std::make_shared<CallbacksComplete<bool>>(+ [completionHandler](const std::vector<bool>& values)+ {+ if (completionHandler) {+ completionHandler(true);+ }+ });++ for (auto& cookie : cookies) {+ auto cookieMap = std::get<flutter::EncodableMap>(cookie);+ auto name = get_fl_map_value<std::string>(cookieMap, "name");+ deleteCookie(webViewEnvironment, url, name, path, domain, [callbacksComplete](const bool& deleted)+ {+ callbacksComplete->addValue(deleted);+ });+ }+ });+ }++ void CookieManager::deleteAllCookies(WebViewEnvironment* webViewEnvironment, std::function<void(const bool&)> completionHandler) const+ {+ if (!plugin || !plugin->webViewEnvironmentManager) {+ if (completionHandler) {+ completionHandler(false);+ }+ return;+ }++ auto hr = webViewEnvironment->getWebView()->CallDevToolsProtocolMethod(L"Network.clearBrowserCookies", L"{}", Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ if (completionHandler) {+ completionHandler(succeededOrLog(errorCode));+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler(false);+ }+ }++ CookieManager::~CookieManager()+ {+ debugLog("dealloc CookieManager");+ plugin = nullptr;+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/cookie_manager.h b/packages/flutter_inappwebview_windows/windows/cookie_manager.hnew file mode 100644index 00000000..313fd8a2--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/cookie_manager.h@@ -0,0 +1,38 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_COOKIE_MANAGER_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_COOKIE_MANAGER_H_++#include <flutter/method_channel.h>+#include <flutter/standard_message_codec.h>+#include <functional>+#include <optional>++#include "flutter_inappwebview_windows_plugin.h"+#include "types/channel_delegate.h"+#include "webview_environment/webview_environment_manager.h"++namespace flutter_inappwebview_plugin+{+ class CookieManager : public ChannelDelegate+ {+ public:+ static inline const std::string METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_inappwebview_cookiemanager";++ const FlutterInappwebviewWindowsPlugin* plugin;++ CookieManager(const FlutterInappwebviewWindowsPlugin* plugin);+ ~CookieManager();++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);++ void setCookie(WebViewEnvironment* webViewEnvironment, const flutter::EncodableMap& map, std::function<void(const bool&)> completionHandler) const;+ void getCookie(WebViewEnvironment* webViewEnvironment, const std::string& url, const std::string& name, std::function<void(const flutter::EncodableValue&)> completionHandler) const;+ void getCookies(WebViewEnvironment* webViewEnvironment, const std::string& url, std::function<void(const flutter::EncodableList&)> completionHandler) const;+ void deleteCookie(WebViewEnvironment* webViewEnvironment, const std::string& url, const std::string& name, const std::string& path, const std::optional<std::string>& domain, std::function<void(const bool&)> completionHandler) const;+ void deleteCookies(WebViewEnvironment* webViewEnvironment, const std::string& url, const std::string& path, const std::optional<std::string>& domain, std::function<void(const bool&)> completionHandler) const;+ void deleteAllCookies(WebViewEnvironment* webViewEnvironment, std::function<void(const bool&)> completionHandler) const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_COOKIE_MANAGER_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/custom_platform_view.cc b/packages/flutter_inappwebview_windows/windows/custom_platform_view/custom_platform_view.ccnew file mode 100644index 00000000..8ce649f4--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/custom_platform_view.cc@@ -0,0 +1,337 @@+#include "../utils/log.h"+#include "custom_platform_view.h"++#include <flutter/event_stream_handler_functions.h>+#include <flutter/method_result_functions.h>++#ifdef HAVE_FLUTTER_D3D_TEXTURE+#include "texture_bridge_gpu.h"+#else+#include "texture_bridge_fallback.h"+#endif++namespace flutter_inappwebview_plugin+{+ constexpr auto kErrorInvalidArgs = "invalidArguments";++ constexpr auto kMethodSetSize = "setSize";+ constexpr auto kMethodSetPosition = "setPosition";+ constexpr auto kMethodSetCursorPos = "setCursorPos";+ constexpr auto kMethodSetPointerUpdate = "setPointerUpdate";+ constexpr auto kMethodSetPointerButton = "setPointerButton";+ constexpr auto kMethodSetScrollDelta = "setScrollDelta";+ constexpr auto kMethodSetFpsLimit = "setFpsLimit";++ constexpr auto kEventType = "type";+ constexpr auto kEventValue = "value";++ static const std::optional<std::pair<double, double>> GetPointFromArgs(+ const flutter::EncodableValue* args)+ {+ const flutter::EncodableList* list =+ std::get_if<flutter::EncodableList>(args);+ if (!list || list->size() != 2) {+ return std::nullopt;+ }+ const auto x = std::get_if<double>(&(*list)[0]);+ const auto y = std::get_if<double>(&(*list)[1]);+ if (!x || !y) {+ return std::nullopt;+ }+ return std::make_pair(*x, *y);+ }++ static const std::optional<std::tuple<double, double, double>>+ GetPointAndScaleFactorFromArgs(const flutter::EncodableValue* args)+ {+ const flutter::EncodableList* list =+ std::get_if<flutter::EncodableList>(args);+ if (!list || list->size() != 3) {+ return std::nullopt;+ }+ const auto x = std::get_if<double>(&(*list)[0]);+ const auto y = std::get_if<double>(&(*list)[1]);+ const auto z = std::get_if<double>(&(*list)[2]);+ if (!x || !y || !z) {+ return std::nullopt;+ }+ return std::make_tuple(*x, *y, *z);+ }++ static const std::string& GetCursorName(const HCURSOR cursor)+ {+ // The cursor names correspond to the Flutter Engine names:+ // in shell/platform/windows/flutter_window_win32.cc+ static const std::string kDefaultCursorName = "basic";+ static const std::pair<std::string, const wchar_t*> mappings[] = {+ {"allScroll", IDC_SIZEALL},+ {kDefaultCursorName, IDC_ARROW},+ {"click", IDC_HAND},+ {"forbidden", IDC_NO},+ {"help", IDC_HELP},+ {"move", IDC_SIZEALL},+ {"none", nullptr},+ {"noDrop", IDC_NO},+ {"precise", IDC_CROSS},+ {"progress", IDC_APPSTARTING},+ {"text", IDC_IBEAM},+ {"resizeColumn", IDC_SIZEWE},+ {"resizeDown", IDC_SIZENS},+ {"resizeDownLeft", IDC_SIZENESW},+ {"resizeDownRight", IDC_SIZENWSE},+ {"resizeLeft", IDC_SIZEWE},+ {"resizeLeftRight", IDC_SIZEWE},+ {"resizeRight", IDC_SIZEWE},+ {"resizeRow", IDC_SIZENS},+ {"resizeUp", IDC_SIZENS},+ {"resizeUpDown", IDC_SIZENS},+ {"resizeUpLeft", IDC_SIZENWSE},+ {"resizeUpRight", IDC_SIZENESW},+ {"resizeUpLeftDownRight", IDC_SIZENWSE},+ {"resizeUpRightDownLeft", IDC_SIZENESW},+ {"wait", IDC_WAIT},+ };++ static std::map<HCURSOR, std::string> cursors;+ static bool initialized = false;++ if (!initialized) {+ initialized = true;+ for (const auto& pair : mappings) {+ HCURSOR cursor_handle = LoadCursor(nullptr, pair.second);+ if (cursor_handle) {+ cursors[cursor_handle] = pair.first;+ }+ }+ }++ const auto it = cursors.find(cursor);+ if (it != cursors.end()) {+ return it->second;+ }+ return kDefaultCursorName;+ }++ CustomPlatformView::CustomPlatformView(flutter::BinaryMessenger* messenger,+ flutter::TextureRegistrar* texture_registrar,+ GraphicsContext* graphics_context,+ HWND hwnd,+ std::shared_ptr<flutter_inappwebview_plugin::InAppWebView> webView)+ : hwnd_(hwnd), view(std::move(webView)), texture_registrar_(texture_registrar)+ {+#ifdef HAVE_FLUTTER_D3D_TEXTURE+ texture_bridge_ =+ std::make_unique<TextureBridgeGpu>(graphics_context, view->surface());++ flutter_texture_ =+ std::make_unique<flutter::TextureVariant>(flutter::GpuSurfaceTexture(+ kFlutterDesktopGpuSurfaceTypeDxgiSharedHandle,+ [bridge = static_cast<TextureBridgeGpu*>(texture_bridge_.get())](+ size_t width,+ size_t height) -> const FlutterDesktopGpuSurfaceDescriptor*+ {+ return bridge->GetSurfaceDescriptor(width, height);+ }));+#else+ texture_bridge_ = std::make_unique<TextureBridgeFallback>(+ graphics_context, webview_->surface());++ flutter_texture_ =+ std::make_unique<flutter::TextureVariant>(flutter::PixelBufferTexture(+ [bridge = static_cast<TextureBridgeFallback*>(texture_bridge_.get())](+ size_t width, size_t height) -> const FlutterDesktopPixelBuffer*+ {+ return bridge->CopyPixelBuffer(width, height);+ }));+#endif++ texture_id_ = texture_registrar->RegisterTexture(flutter_texture_.get());+ texture_bridge_->SetOnFrameAvailable(+ [this]() { texture_registrar_->MarkTextureFrameAvailable(texture_id_); });+ // texture_bridge_->SetOnSurfaceSizeChanged([this](Size size) {+ // view->SetSurfaceSize(size.width, size.height);+ //});++ const auto method_channel_name = "com.pichillilorenzo/custom_platform_view_" + std::to_string(texture_id_);+ method_channel_ =+ std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(+ messenger, method_channel_name,+ &flutter::StandardMethodCodec::GetInstance());+ method_channel_->SetMethodCallHandler([this](const auto& call, auto result)+ {+ HandleMethodCall(call, std::move(result));+ });++ const auto event_channel_name = "com.pichillilorenzo/custom_platform_view_" + std::to_string(texture_id_) + "_events";+ event_channel_ =+ std::make_unique<flutter::EventChannel<flutter::EncodableValue>>(+ messenger, event_channel_name,+ &flutter::StandardMethodCodec::GetInstance());++ auto handler = std::make_unique<+ flutter::StreamHandlerFunctions<flutter::EncodableValue>>(+ [this](const flutter::EncodableValue* arguments,+ std::unique_ptr<flutter::EventSink<flutter::EncodableValue>>&&+ events)+ {+ event_sink_ = std::move(events);+ RegisterEventHandlers();+ return nullptr;+ },+ [this](const flutter::EncodableValue* arguments)+ {+ return nullptr;+ });++ event_channel_->SetStreamHandler(std::move(handler));+ }++ void CustomPlatformView::UnregisterMethodCallHandler() const+ {+ if (method_channel_) {+ method_channel_->SetMethodCallHandler(nullptr);+ if (view && view->channelDelegate) {+ view->channelDelegate->UnregisterMethodCallHandler();+ }+ }+ }++ CustomPlatformView::~CustomPlatformView()+ {+ debugLog("dealloc CustomPlatformView");+ event_sink_ = nullptr;+ texture_registrar_->UnregisterTexture(texture_id_, nullptr);+ }++ void CustomPlatformView::RegisterEventHandlers()+ {+ if (!view) {+ return;+ }++ view->onSurfaceSizeChanged([this](size_t width, size_t height)+ {+ texture_bridge_->NotifySurfaceSizeChanged();+ });++ view->onCursorChanged([this](const HCURSOR cursor)+ {+ const auto& name = GetCursorName(cursor);+ const auto event = flutter::EncodableValue(+ flutter::EncodableMap { {+ flutter::EncodableValue(kEventType),+ flutter::EncodableValue("cursorChanged")+ },+ { flutter::EncodableValue(kEventValue), name }});+ EmitEvent(event);+ });+ }++ void CustomPlatformView::HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ const auto& method_name = method_call.method_name();++ // setCursorPos: [double x, double y]+ if (method_name.compare(kMethodSetCursorPos) == 0) {+ const auto point = GetPointFromArgs(method_call.arguments());+ if (point && view) {+ view->setCursorPos(point->first, point->second);+ return result->Success();+ }+ return result->Error(kErrorInvalidArgs);+ }++ // setPointerUpdate:+ // [int pointer, int event, double x, double y, double size, double pressure]+ if (method_name.compare(kMethodSetPointerUpdate) == 0) {+ const flutter::EncodableList* list =+ std::get_if<flutter::EncodableList>(method_call.arguments());+ if (!list || list->size() != 6) {+ return result->Error(kErrorInvalidArgs);+ }++ const auto pointer = std::get_if<int32_t>(&(*list)[0]);+ const auto event = std::get_if<int32_t>(&(*list)[1]);+ const auto x = std::get_if<double>(&(*list)[2]);+ const auto y = std::get_if<double>(&(*list)[3]);+ const auto size = std::get_if<double>(&(*list)[4]);+ const auto pressure = std::get_if<double>(&(*list)[5]);++ if (pointer && event && x && y && size && pressure && view) {+ view->setPointerUpdate(*pointer,+ static_cast<flutter_inappwebview_plugin::InAppWebViewPointerEventKind>(*event),+ *x, *y, *size, *pressure);+ return result->Success();+ }+ return result->Error(kErrorInvalidArgs);+ }++ // setScrollDelta: [double dx, double dy]+ if (method_name.compare(kMethodSetScrollDelta) == 0) {+ const auto delta = GetPointFromArgs(method_call.arguments());+ if (delta && view) {+ view->setScrollDelta(delta->first, delta->second);+ return result->Success();+ }+ return result->Error(kErrorInvalidArgs);+ }++ // setPointerButton: {"button": int, "isDown": bool}+ if (method_name.compare(kMethodSetPointerButton) == 0) {+ const auto& map = std::get<flutter::EncodableMap>(*method_call.arguments());++ const auto button = map.find(flutter::EncodableValue("button"));+ const auto isDown = map.find(flutter::EncodableValue("isDown"));+ if (button != map.end() && isDown != map.end()) {+ const auto buttonValue = std::get_if<int32_t>(&button->second);+ const auto isDownValue = std::get_if<bool>(&isDown->second);+ if (buttonValue && isDownValue && view) {+ view->setPointerButtonState(+ static_cast<flutter_inappwebview_plugin::InAppWebViewPointerButton>(*buttonValue), *isDownValue);+ return result->Success();+ }+ }+ return result->Error(kErrorInvalidArgs);+ }++ // setSize: [double width, double height, double scale_factor]+ if (method_name.compare(kMethodSetSize) == 0) {+ auto size = GetPointAndScaleFactorFromArgs(method_call.arguments());+ if (size && view) {+ const auto [width, height, scale_factor] = size.value();++ view->setSurfaceSize(static_cast<size_t>(width),+ static_cast<size_t>(height),+ static_cast<float>(scale_factor));++ texture_bridge_->Start();+ return result->Success();+ }+ return result->Error(kErrorInvalidArgs);+ }+ else if (method_name.compare(kMethodSetPosition) == 0) {+ auto position = GetPointAndScaleFactorFromArgs(method_call.arguments());+ if (position && view) {+ const auto [x, y, scale_factor] = position.value();++ view->setPosition(static_cast<size_t>(x),+ static_cast<size_t>(y),+ static_cast<float>(scale_factor));++ return result->Success();+ }+ return result->Error(kErrorInvalidArgs);+ }+ else if (method_name.compare(kMethodSetFpsLimit) == 0) {+ if (const auto value = std::get_if<int32_t>(method_call.arguments())) {+ texture_bridge_->SetFpsLimit(*value == 0 ? std::nullopt+ : std::make_optional(*value));+ return result->Success();+ }+ }++ result->NotImplemented();+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/custom_platform_view.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/custom_platform_view.hnew file mode 100644index 00000000..65db5476--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/custom_platform_view.h@@ -0,0 +1,60 @@+#pragma once++#include <flutter/event_channel.h>+#include <flutter/method_channel.h>+#include <flutter/standard_method_codec.h>+#include <flutter/texture_registrar.h>++#include <memory>++#include "../in_app_webview/in_app_webview.h"+#include "graphics_context.h"+#include "texture_bridge.h"++namespace flutter_inappwebview_plugin+{+ class CustomPlatformView {+ public:+ static inline const wchar_t* CLASS_NAME = L"CustomPlatformView";++ std::shared_ptr<flutter_inappwebview_plugin::InAppWebView> view;++ CustomPlatformView(flutter::BinaryMessenger* messenger,+ flutter::TextureRegistrar* texture_registrar,+ GraphicsContext* graphics_context,+ HWND hwnd,+ std::shared_ptr<flutter_inappwebview_plugin::InAppWebView> webView);+ ~CustomPlatformView();++ TextureBridge* texture_bridge() const { return texture_bridge_.get(); }++ int64_t texture_id() const { return texture_id_; }++ void UnregisterMethodCallHandler() const;+ private:+ HWND hwnd_;+ std::unique_ptr<flutter::TextureVariant> flutter_texture_;+ std::unique_ptr<TextureBridge> texture_bridge_;+ std::unique_ptr<flutter::EventSink<flutter::EncodableValue>> event_sink_;+ std::unique_ptr<flutter::EventChannel<flutter::EncodableValue>>+ event_channel_;+ std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>>+ method_channel_;++ flutter::TextureRegistrar* texture_registrar_;+ int64_t texture_id_;++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);+ void RegisterEventHandlers();++ template <typename T>+ void EmitEvent(const T& value)+ {+ if (event_sink_) {+ event_sink_->Success(value);+ }+ }+ };+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/graphics_context.cc b/packages/flutter_inappwebview_windows/windows/custom_platform_view/graphics_context.ccnew file mode 100644index 00000000..2bbc1e74--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/graphics_context.cc@@ -0,0 +1,158 @@+#include "graphics_context.h"++#include "util/d3dutil.h"+#include "util/direct3d11.interop.h"++namespace flutter_inappwebview_plugin+{+ GraphicsContext::GraphicsContext(rx::RoHelper* rohelper) : rohelper_(rohelper)+ {+ device_ = CreateD3DDevice();+ if (!device_) {+ return;+ }++ device_->GetImmediateContext(device_context_.put());+ if (FAILED(CreateDirect3D11DeviceFromDXGIDevice(+ device_.try_as<IDXGIDevice>().get(),+ (IInspectable**)device_winrt_.put()))) {+ return;+ }++ valid_ = true;+ }++ winrt::com_ptr<ABI::Windows::UI::Composition::ICompositor>+ GraphicsContext::CreateCompositor()+ {+ HSTRING className;+ HSTRING_HEADER classNameHeader;++ if (FAILED(rohelper_->GetStringReference(+ RuntimeClass_Windows_UI_Composition_Compositor, &className,+ &classNameHeader))) {+ return nullptr;+ }++ winrt::com_ptr<IActivationFactory> af;+ if (FAILED(rohelper_->GetActivationFactory(+ className, __uuidof(IActivationFactory), af.put_void()))) {+ return nullptr;+ }++ winrt::com_ptr<ABI::Windows::UI::Composition::ICompositor> compositor;+ if (FAILED(af->ActivateInstance(+ reinterpret_cast<IInspectable**>(compositor.put())))) {+ return nullptr;+ }++ return compositor;+ }++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IGraphicsCaptureItem>+ GraphicsContext::CreateGraphicsCaptureItemFromVisual(+ ABI::Windows::UI::Composition::IVisual* visual) const+ {+ HSTRING className;+ HSTRING_HEADER classNameHeader;++ if (FAILED(rohelper_->GetStringReference(+ RuntimeClass_Windows_Graphics_Capture_GraphicsCaptureItem, &className,+ &classNameHeader))) {+ return nullptr;+ }++ ABI::Windows::Graphics::Capture::IGraphicsCaptureItemStatics*+ capture_item_statics;+ if (FAILED(rohelper_->GetActivationFactory(+ className,+ __uuidof(+ ABI::Windows::Graphics::Capture::IGraphicsCaptureItemStatics),+ (void**)&capture_item_statics))) {+ return nullptr;+ }++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IGraphicsCaptureItem>+ capture_item;+ if (FAILED(+ capture_item_statics->CreateFromVisual(visual, capture_item.put()))) {+ return nullptr;+ }++ return capture_item;+ }++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePool>+ GraphicsContext::CreateCaptureFramePool(+ ABI::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice* device,+ ABI::Windows::Graphics::DirectX::DirectXPixelFormat pixelFormat,+ INT32 numberOfBuffers, ABI::Windows::Graphics::SizeInt32 size) const+ {+ HSTRING className;+ HSTRING_HEADER classNameHeader;++ if (FAILED(rohelper_->GetStringReference(+ RuntimeClass_Windows_Graphics_Capture_Direct3D11CaptureFramePool,+ &className, &classNameHeader))) {+ return nullptr;+ }++ ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePoolStatics*+ capture_frame_pool_statics;+ if (FAILED(rohelper_->GetActivationFactory(+ className,+ __uuidof(ABI::Windows::Graphics::Capture::+ IDirect3D11CaptureFramePoolStatics),+ (void**)&capture_frame_pool_statics))) {+ return nullptr;+ }++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePool>+ capture_frame_pool;++ if (FAILED(capture_frame_pool_statics->Create(device, pixelFormat,+ numberOfBuffers, size,+ capture_frame_pool.put()))) {+ return nullptr;+ }++ return capture_frame_pool;+ }++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePool>+ GraphicsContext::CreateFreeThreadedCaptureFramePool(+ ABI::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice* device,+ ABI::Windows::Graphics::DirectX::DirectXPixelFormat pixelFormat,+ INT32 numberOfBuffers, ABI::Windows::Graphics::SizeInt32 size) const+ {+ HSTRING className;+ HSTRING_HEADER classNameHeader;++ if (FAILED(rohelper_->GetStringReference(+ RuntimeClass_Windows_Graphics_Capture_Direct3D11CaptureFramePool,+ &className, &classNameHeader))) {+ return nullptr;+ }++ ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePoolStatics2*+ capture_frame_pool_statics;+ if (FAILED(rohelper_->GetActivationFactory(+ className,+ __uuidof(ABI::Windows::Graphics::Capture::+ IDirect3D11CaptureFramePoolStatics2),+ (void**)&capture_frame_pool_statics))) {+ return nullptr;+ }++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePool>+ capture_frame_pool;++ if (FAILED(capture_frame_pool_statics->CreateFreeThreaded(+ device, pixelFormat, numberOfBuffers, size,+ capture_frame_pool.put()))) {+ return nullptr;+ }++ return capture_frame_pool;+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/graphics_context.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/graphics_context.hnew file mode 100644index 00000000..883bffe7--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/graphics_context.h@@ -0,0 +1,54 @@+#pragma once++#include <D3d11.h>+#include <windows.graphics.capture.h>+#include <windows.ui.composition.h>+#include <winrt/Windows.Foundation.h>++#include "util/rohelper.h"++namespace flutter_inappwebview_plugin+{+ class GraphicsContext {+ public:+ GraphicsContext(rx::RoHelper* rohelper);++ inline bool IsValid() const { return valid_; }++ ABI::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice* device() const+ {+ return device_winrt_.get();+ }+ ID3D11Device* d3d_device() const { return device_.get(); }+ ID3D11DeviceContext* d3d_device_context() const+ {+ return device_context_.get();+ }++ winrt::com_ptr<ABI::Windows::UI::Composition::ICompositor> CreateCompositor();++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IGraphicsCaptureItem>+ CreateGraphicsCaptureItemFromVisual(+ ABI::Windows::UI::Composition::IVisual* visual) const;++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePool>+ CreateCaptureFramePool(+ ABI::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice* device,+ ABI::Windows::Graphics::DirectX::DirectXPixelFormat pixelFormat,+ INT32 numberOfBuffers, ABI::Windows::Graphics::SizeInt32 size) const;++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePool>+ CreateFreeThreadedCaptureFramePool(+ ABI::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice* device,+ ABI::Windows::Graphics::DirectX::DirectXPixelFormat pixelFormat,+ INT32 numberOfBuffers, ABI::Windows::Graphics::SizeInt32 size) const;++ private:+ bool valid_ = false;+ rx::RoHelper* rohelper_;+ winrt::com_ptr<ABI::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice>+ device_winrt_;+ winrt::com_ptr<ID3D11Device> device_{ nullptr };+ winrt::com_ptr<ID3D11DeviceContext> device_context_{ nullptr };+ };+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge.cc b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge.ccnew file mode 100644index 00000000..658df19f--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge.cc@@ -0,0 +1,189 @@+#include "texture_bridge.h"++#include <windows.foundation.h>++#include <algorithm>+#include <atomic>+#include <cassert>+#include <iostream>++#include "util/direct3d11.interop.h"++namespace flutter_inappwebview_plugin+{+ const int kNumBuffers = 1;++ TextureBridge::TextureBridge(GraphicsContext* graphics_context,+ ABI::Windows::UI::Composition::IVisual* visual)+ : graphics_context_(graphics_context)+ {+ capture_item_ =+ graphics_context_->CreateGraphicsCaptureItemFromVisual(visual);+ assert(capture_item_);++ capture_item_->add_Closed(+ Microsoft::WRL::Callback<ABI::Windows::Foundation::ITypedEventHandler<+ ABI::Windows::Graphics::Capture::GraphicsCaptureItem*,+ IInspectable*>>(+ [](ABI::Windows::Graphics::Capture::IGraphicsCaptureItem* item,+ IInspectable* args) -> HRESULT+ {+ std::cerr << "Capture item was closed." << std::endl;+ return S_OK;+ })+ .Get(),+ &on_closed_token_);+ }++ TextureBridge::~TextureBridge()+ {+ const std::lock_guard<std::mutex> lock(mutex_);+ StopInternal();+ if (capture_item_) {+ capture_item_->remove_Closed(on_closed_token_);+ }+ }++ bool TextureBridge::Start()+ {+ const std::lock_guard<std::mutex> lock(mutex_);+ if (is_running_ || !capture_item_) {+ return false;+ }++ ABI::Windows::Graphics::SizeInt32 size;+ capture_item_->get_Size(&size);++ frame_pool_ = graphics_context_->CreateCaptureFramePool(+ graphics_context_->device(),+ static_cast<ABI::Windows::Graphics::DirectX::DirectXPixelFormat>(+ kPixelFormat),+ kNumBuffers, size);+ assert(frame_pool_);++ frame_pool_->add_FrameArrived(+ Microsoft::WRL::Callback<ABI::Windows::Foundation::ITypedEventHandler<+ ABI::Windows::Graphics::Capture::Direct3D11CaptureFramePool*,+ IInspectable*>>(+ [this](ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePool*+ pool,+ IInspectable* args) -> HRESULT+ {+ OnFrameArrived();+ return S_OK;+ })+ .Get(),+ &on_frame_arrived_token_);++ if (FAILED(frame_pool_->CreateCaptureSession(capture_item_.get(),+ capture_session_.put()))) {+ std::cerr << "Creating capture session failed." << std::endl;+ return false;+ }++ if (SUCCEEDED(capture_session_->StartCapture())) {+ is_running_ = true;+ return true;+ }++ return false;+ }++ void TextureBridge::Stop()+ {+ const std::lock_guard<std::mutex> lock(mutex_);+ StopInternal();+ }++ void TextureBridge::StopInternal()+ {+ if (is_running_) {+ is_running_ = false;+ frame_pool_->remove_FrameArrived(on_frame_arrived_token_);+ auto closable =+ capture_session_.try_as<ABI::Windows::Foundation::IClosable>();+ assert(closable);+ closable->Close();+ capture_session_ = nullptr;+ }+ }++ void TextureBridge::OnFrameArrived()+ {+ const std::lock_guard<std::mutex> lock(mutex_);+ if (!is_running_) {+ return;+ }++ bool has_frame = false;++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IDirect3D11CaptureFrame>+ frame;+ auto hr = frame_pool_->TryGetNextFrame(frame.put());+ if (SUCCEEDED(hr) && frame) {+ winrt::com_ptr<+ ABI::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface>+ frame_surface;++ if (SUCCEEDED(frame->get_Surface(frame_surface.put()))) {+ last_frame_ =+ TryGetDXGIInterfaceFromObject<ID3D11Texture2D>(frame_surface);+ has_frame = !ShouldDropFrame();+ }+ }++ if (needs_update_) {+ ABI::Windows::Graphics::SizeInt32 size;+ capture_item_->get_Size(&size);+ frame_pool_->Recreate(+ graphics_context_->device(),+ static_cast<ABI::Windows::Graphics::DirectX::DirectXPixelFormat>(+ kPixelFormat),+ kNumBuffers, size);+ needs_update_ = false;+ }++ if (has_frame && frame_available_) {+ frame_available_();+ }+ }++ bool TextureBridge::ShouldDropFrame()+ {+ if (!frame_duration_.has_value()) {+ return false;+ }+ auto now = std::chrono::high_resolution_clock::now();++ bool should_drop_frame = false;+ if (last_frame_timestamp_.has_value()) {+ auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(+ now - last_frame_timestamp_.value());+ should_drop_frame = diff < frame_duration_.value();+ }++ if (!should_drop_frame) {+ last_frame_timestamp_ = now;+ }+ return should_drop_frame;+ }++ void TextureBridge::NotifySurfaceSizeChanged()+ {+ const std::lock_guard<std::mutex> lock(mutex_);+ needs_update_ = true;+ }++ void TextureBridge::SetFpsLimit(std::optional<int> max_fps)+ {+ const std::lock_guard<std::mutex> lock(mutex_);+ auto value = max_fps.value_or(0);+ if (value != 0) {+ frame_duration_ = FrameDuration(1000.0 / value);+ }+ else {+ frame_duration_.reset();+ last_frame_timestamp_.reset();+ }+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge.hnew file mode 100644index 00000000..122c6938--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge.h@@ -0,0 +1,79 @@+#pragma once++#include <windows.graphics.capture.h>+#include <wrl.h>++#include <chrono>+#include <cstdint>+#include <functional>+#include <mutex>+#include <optional>++#include "graphics_context.h"++namespace flutter_inappwebview_plugin+{+ typedef struct {+ size_t width;+ size_t height;+ } Size;++ class TextureBridge {+ public:+ typedef std::function<void()> FrameAvailableCallback;+ typedef std::function<void(Size size)> SurfaceSizeChangedCallback;+ typedef std::chrono::duration<double, std::milli> FrameDuration;++ TextureBridge(GraphicsContext* graphics_context,+ ABI::Windows::UI::Composition::IVisual* visual);+ virtual ~TextureBridge();++ bool Start();+ void Stop();++ void SetOnFrameAvailable(FrameAvailableCallback callback)+ {+ frame_available_ = std::move(callback);+ }++ void SetOnSurfaceSizeChanged(SurfaceSizeChangedCallback callback)+ {+ surface_size_changed_ = std::move(callback);+ }++ void NotifySurfaceSizeChanged();+ void SetFpsLimit(std::optional<int> max_fps);++ protected:+ bool is_running_ = false;++ const GraphicsContext* graphics_context_;+ std::mutex mutex_;+ std::optional<FrameDuration> frame_duration_ = std::nullopt;++ FrameAvailableCallback frame_available_;+ SurfaceSizeChangedCallback surface_size_changed_;+ std::atomic<bool> needs_update_ = false;+ winrt::com_ptr<ID3D11Texture2D> last_frame_;+ std::optional<std::chrono::high_resolution_clock::time_point>+ last_frame_timestamp_;++ winrt::com_ptr<ABI::Windows::Graphics::Capture::IGraphicsCaptureItem>+ capture_item_;+ winrt::com_ptr<ABI::Windows::Graphics::Capture::IDirect3D11CaptureFramePool>+ frame_pool_;+ winrt::com_ptr<ABI::Windows::Graphics::Capture::IGraphicsCaptureSession>+ capture_session_;++ EventRegistrationToken on_closed_token_ = {};+ EventRegistrationToken on_frame_arrived_token_ = {};++ virtual void StopInternal();+ void OnFrameArrived();+ bool ShouldDropFrame();++ // corresponds to DXGI_FORMAT_B8G8R8A8_UNORM+ static constexpr auto kPixelFormat = ABI::Windows::Graphics::DirectX::+ DirectXPixelFormat::DirectXPixelFormat_B8G8R8A8UIntNormalized;+ };+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_fallback.cc b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_fallback.ccnew file mode 100644index 00000000..6aa5d58d--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_fallback.cc@@ -0,0 +1,145 @@+#include "texture_bridge_fallback.h"++#include <iostream>++#include "util/direct3d11.interop.h"+#include "util/swizzle.h"++namespace flutter_inappwebview_plugin+{+ TextureBridgeFallback::TextureBridgeFallback(+ GraphicsContext* graphics_context,+ ABI::Windows::UI::Composition::IVisual* visual)+ : TextureBridge(graphics_context, visual)+ {}++ TextureBridgeFallback::~TextureBridgeFallback()+ {+ const std::lock_guard<std::mutex> lock(buffer_mutex_);+ }++ void TextureBridgeFallback::ProcessFrame(+ winrt::com_ptr<ID3D11Texture2D> src_texture)+ {+ D3D11_TEXTURE2D_DESC desc;+ src_texture->GetDesc(&desc);++ const auto width = desc.Width;+ const auto height = desc.Height;++ bool is_exact_size;+ EnsureStagingTexture(width, height, is_exact_size);++ auto device_context = graphics_context_->d3d_device_context();+ auto staging_texture = staging_texture_.get();++ if (is_exact_size) {+ device_context->CopyResource(staging_texture, src_texture.get());+ }+ else {+ D3D11_BOX client_box;+ client_box.top = 0;+ client_box.left = 0;+ client_box.right = width;+ client_box.bottom = height;+ client_box.front = 0;+ client_box.back = 1;+ device_context->CopySubresourceRegion(staging_texture, 0, 0, 0, 0,+ src_texture.get(), 0, &client_box);+ }++ D3D11_MAPPED_SUBRESOURCE mappedResource;+ if (!SUCCEEDED(device_context->Map(staging_texture, 0, D3D11_MAP_READ, 0,+ &mappedResource))) {+ return;+ }++ {+ const std::lock_guard<std::mutex> lock(buffer_mutex_);+ if (!pixel_buffer_ || pixel_buffer_->width != width ||+ pixel_buffer_->height != height) {+ if (!pixel_buffer_) {+ pixel_buffer_ = std::make_unique<FlutterDesktopPixelBuffer>();+ pixel_buffer_->release_context = &buffer_mutex_;+ // Gets invoked after the FlutterDesktopPixelBuffer's+ // backing buffer has been uploaded.+ pixel_buffer_->release_callback = [](void* opaque)+ {+ auto mutex = reinterpret_cast<std::mutex*>(opaque);+ // Gets locked just before |CopyPixelBuffer| returns.+ mutex->unlock();+ };+ }+ pixel_buffer_->width = width;+ pixel_buffer_->height = height;+ const auto size = width * height * 4;+ backing_pixel_buffer_.reset(new uint8_t[size]);+ pixel_buffer_->buffer = backing_pixel_buffer_.get();+ }++ const auto src_pitch_in_pixels = mappedResource.RowPitch / 4;+ RGBA_to_BGRA(reinterpret_cast<uint32_t*>(backing_pixel_buffer_.get()),+ static_cast<const uint32_t*>(mappedResource.pData), height,+ src_pitch_in_pixels, width);+ }++ device_context->Unmap(staging_texture, 0);+ }++ void TextureBridgeFallback::EnsureStagingTexture(uint32_t width,+ uint32_t height,+ bool& is_exact_size)+ {+ // Only recreate an existing texture if it's too small.+ if (!staging_texture_ || staging_texture_size_.width < width ||+ staging_texture_size_.height < height) {+ D3D11_TEXTURE2D_DESC dstDesc = {};+ dstDesc.ArraySize = 1;+ dstDesc.MipLevels = 1;+ dstDesc.BindFlags = 0;+ dstDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;+ dstDesc.Format = static_cast<DXGI_FORMAT>(kPixelFormat);+ dstDesc.Width = width;+ dstDesc.Height = height;+ dstDesc.MiscFlags = 0;+ dstDesc.SampleDesc.Count = 1;+ dstDesc.SampleDesc.Quality = 0;+ dstDesc.Usage = D3D11_USAGE_STAGING;++ staging_texture_ = nullptr;+ if (!SUCCEEDED(graphics_context_->d3d_device()->CreateTexture2D(+ &dstDesc, nullptr, staging_texture_.put()))) {+ std::cerr << "Creating dst texture failed" << std::endl;+ return;+ }++ staging_texture_size_ = { width, height };+ }++ is_exact_size = staging_texture_size_.width == width &&+ staging_texture_size_.height == height;+ }++ const FlutterDesktopPixelBuffer* TextureBridgeFallback::CopyPixelBuffer(+ size_t width, size_t height)+ {+ const std::lock_guard<std::mutex> lock(mutex_);++ if (!is_running_) {+ return nullptr;+ }++ if (last_frame_) {+ ProcessFrame(last_frame_);+ }++ auto buffer = pixel_buffer_.get();+ // Only lock the mutex if the buffer is not null+ // (to ensure the release callback gets called)+ if (buffer) {+ // Gets unlocked in the FlutterDesktopPixelBuffer's release callback.+ buffer_mutex_.lock();+ }+ return buffer;+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_fallback.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_fallback.hnew file mode 100644index 00000000..ad07b77c--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_fallback.h@@ -0,0 +1,30 @@+#pragma once++#include <flutter/texture_registrar.h>++#include <mutex>++#include "texture_bridge.h"++namespace flutter_inappwebview_plugin+{+ class TextureBridgeFallback : public TextureBridge {+ public:+ TextureBridgeFallback(GraphicsContext* graphics_context,+ ABI::Windows::UI::Composition::IVisual* visual);+ ~TextureBridgeFallback() override;++ const FlutterDesktopPixelBuffer* CopyPixelBuffer(size_t width, size_t height);++ private:+ Size staging_texture_size_ = { 0, 0 };+ winrt::com_ptr<ID3D11Texture2D> staging_texture_{ nullptr };+ std::mutex buffer_mutex_;+ std::unique_ptr<uint8_t> backing_pixel_buffer_;+ std::unique_ptr<FlutterDesktopPixelBuffer> pixel_buffer_;++ void ProcessFrame(winrt::com_ptr<ID3D11Texture2D> src_texture);+ void EnsureStagingTexture(uint32_t width, uint32_t height,+ bool& is_exact_size);+ };+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_gpu.cc b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_gpu.ccnew file mode 100644index 00000000..c3bdee26--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_gpu.cc@@ -0,0 +1,108 @@+#include "texture_bridge_gpu.h"++#include <iostream>++#include "util/direct3d11.interop.h"++namespace flutter_inappwebview_plugin+{+ TextureBridgeGpu::TextureBridgeGpu(+ GraphicsContext* graphics_context,+ ABI::Windows::UI::Composition::IVisual* visual)+ : TextureBridge(graphics_context, visual)+ {+ surface_descriptor_.struct_size = sizeof(FlutterDesktopGpuSurfaceDescriptor);+ surface_descriptor_.format =+ kFlutterDesktopPixelFormatNone; // no format required for DXGI surfaces+ }++ void TextureBridgeGpu::ProcessFrame(+ winrt::com_ptr<ID3D11Texture2D> src_texture)+ {+ D3D11_TEXTURE2D_DESC desc;+ src_texture->GetDesc(&desc);++ const auto width = desc.Width;+ const auto height = desc.Height;++ EnsureSurface(width, height);++ auto device_context = graphics_context_->d3d_device_context();++ device_context->CopyResource(surface_.get(), src_texture.get());+ device_context->Flush();+ }++ void TextureBridgeGpu::EnsureSurface(uint32_t width, uint32_t height)+ {+ if (!surface_ || surface_size_.width != width ||+ surface_size_.height != height) {+ D3D11_TEXTURE2D_DESC dstDesc = {};+ dstDesc.ArraySize = 1;+ dstDesc.MipLevels = 1;+ dstDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;+ dstDesc.CPUAccessFlags = 0;+ dstDesc.Format = static_cast<DXGI_FORMAT>(kPixelFormat);+ dstDesc.Width = width;+ dstDesc.Height = height;+ dstDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED;+ dstDesc.SampleDesc.Count = 1;+ dstDesc.SampleDesc.Quality = 0;+ dstDesc.Usage = D3D11_USAGE_DEFAULT;++ surface_ = nullptr;+ if (!SUCCEEDED(graphics_context_->d3d_device()->CreateTexture2D(+ &dstDesc, nullptr, surface_.put()))) {+ std::cerr << "Creating intermediate texture failed" << std::endl;+ return;+ }++ HANDLE shared_handle;+ surface_.try_as(dxgi_surface_);+ assert(dxgi_surface_);+ dxgi_surface_->GetSharedHandle(&shared_handle);++ surface_descriptor_.handle = shared_handle;+ surface_descriptor_.width = surface_descriptor_.visible_width = width;+ surface_descriptor_.height = surface_descriptor_.visible_height = height;+ surface_descriptor_.release_context = surface_.get();+ surface_descriptor_.release_callback = [](void* release_context)+ {+ auto texture = reinterpret_cast<ID3D11Texture2D*>(release_context);+ texture->Release();+ };++ surface_size_ = { width, height };+ }+ }++ const FlutterDesktopGpuSurfaceDescriptor*+ TextureBridgeGpu::GetSurfaceDescriptor(size_t width, size_t height)+ {+ const std::lock_guard<std::mutex> lock(mutex_);++ if (!is_running_) {+ return nullptr;+ }++ if (last_frame_) {+ ProcessFrame(last_frame_);+ }++ if (surface_) {+ // Gets released in the SurfaceDescriptor's release callback.+ surface_->AddRef();+ }++ return &surface_descriptor_;+ }++ void TextureBridgeGpu::StopInternal()+ {+ TextureBridge::StopInternal();++ // For some reason, the destination surface needs to be recreated upon+ // resuming. Force |EnsureSurface| to create a new one by resetting it here.+ surface_ = nullptr;+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_gpu.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_gpu.hnew file mode 100644index 00000000..8b29a321--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/texture_bridge_gpu.h@@ -0,0 +1,29 @@+#pragma once++#include <flutter/texture_registrar.h>++#include "texture_bridge.h"++namespace flutter_inappwebview_plugin+{+ class TextureBridgeGpu : public TextureBridge {+ public:+ TextureBridgeGpu(GraphicsContext* graphics_context,+ ABI::Windows::UI::Composition::IVisual* visual);++ const FlutterDesktopGpuSurfaceDescriptor* GetSurfaceDescriptor(size_t width,+ size_t height);++ protected:+ void StopInternal() override;++ private:+ FlutterDesktopGpuSurfaceDescriptor surface_descriptor_ = {};+ Size surface_size_ = { 0, 0 };+ winrt::com_ptr<ID3D11Texture2D> surface_{ nullptr };+ winrt::com_ptr<IDXGIResource> dxgi_surface_;++ void ProcessFrame(winrt::com_ptr<ID3D11Texture2D> src_texture);+ void EnsureSurface(uint32_t width, uint32_t height);+ };+}diff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/composition.desktop.interop.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/composition.desktop.interop.hnew file mode 100644index 00000000..9b9eb0d3--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/composition.desktop.interop.h@@ -0,0 +1,22 @@+#pragma once++#include <winrt/base.h>++#include <windows.ui.composition.interop.h>++namespace util {++ winrt::com_ptr<ABI::Windows::UI::Composition::Desktop::IDesktopWindowTarget> TryCreateDesktopWindowTarget(+ const winrt::com_ptr<ABI::Windows::UI::Composition::ICompositor>&+ compositor,+ HWND window)+ {+ namespace abi = ABI::Windows::UI::Composition::Desktop;+ auto interop = compositor.try_as<abi::ICompositorDesktopInterop>();++ winrt::com_ptr<abi::IDesktopWindowTarget> target;+ interop->CreateDesktopWindowTarget(window, true, target.put());+ return target;+ }++} // namespace utildiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/cpuinfo.cc b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/cpuinfo.ccnew file mode 100644index 00000000..acee3437--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/cpuinfo.cc@@ -0,0 +1,80 @@+#include "cpuinfo.h"++#include "detail/cpuinfo_impl.h"++#if defined(_MSC_VER) && (defined(__x86_64__) || defined(_M_X64))+#include "detail/init_msvc_x86.h"+#else+#include "detail/init_unknown.hpp"+#endif++namespace cpuid {++cpuinfo::cpuinfo() : impl_(new impl) { init_cpuinfo(*impl_); }++cpuinfo::~cpuinfo() {}++// x86 member functions+bool cpuinfo::has_fpu() const { return impl_->m_has_fpu; }++bool cpuinfo::has_mmx() const { return impl_->m_has_mmx; }++bool cpuinfo::has_sse() const { return impl_->m_has_sse; }++bool cpuinfo::has_sse2() const { return impl_->m_has_sse2; }++bool cpuinfo::has_sse3() const { return impl_->m_has_sse3; }++bool cpuinfo::has_ssse3() const { return impl_->m_has_ssse3; }++bool cpuinfo::has_sse4_1() const { return impl_->m_has_sse4_1; }++bool cpuinfo::has_sse4_2() const { return impl_->m_has_sse4_2; }++bool cpuinfo::has_pclmulqdq() const { return impl_->m_has_pclmulqdq; }++bool cpuinfo::has_avx() const { return impl_->m_has_avx; }++bool cpuinfo::has_avx2() const { return impl_->m_has_avx2; }++bool cpuinfo::has_avx512_f() const { return impl_->m_has_avx512_f; }++bool cpuinfo::has_avx512_dq() const { return impl_->m_has_avx512_dq; }++bool cpuinfo::has_avx512_ifma() const { return impl_->m_has_avx512_ifma; }++bool cpuinfo::has_avx512_pf() const { return impl_->m_has_avx512_pf; }++bool cpuinfo::has_avx512_er() const { return impl_->m_has_avx512_er; }++bool cpuinfo::has_avx512_cd() const { return impl_->m_has_avx512_cd; }++bool cpuinfo::has_avx512_bw() const { return impl_->m_has_avx512_bw; }++bool cpuinfo::has_avx512_vl() const { return impl_->m_has_avx512_vl; }++bool cpuinfo::has_avx512_vbmi() const { return impl_->m_has_avx512_vbmi; }++bool cpuinfo::has_avx512_vbmi2() const { return impl_->m_has_avx512_vbmi2; }++bool cpuinfo::has_avx512_vnni() const { return impl_->m_has_avx512_vnni; }++bool cpuinfo::has_avx512_bitalg() const { return impl_->m_has_avx512_bitalg; }++bool cpuinfo::has_avx512_vpopcntdq() const {+ return impl_->m_has_avx512_vpopcntdq;+}++bool cpuinfo::has_avx512_4vnniw() const { return impl_->m_has_avx512_4vnniw; }++bool cpuinfo::has_avx512_4fmaps() const { return impl_->m_has_avx512_4fmaps; }++bool cpuinfo::has_avx512_vp2intersect() const {+ return impl_->m_has_avx512_vp2intersect;+}++bool cpuinfo::has_f16c() const { return impl_->m_has_f16c; }++// ARM member functions+bool cpuinfo::has_neon() const { return impl_->m_has_neon; }+} // namespace cpuiddiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/cpuinfo.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/cpuinfo.hnew file mode 100644index 00000000..0cee3598--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/cpuinfo.h@@ -0,0 +1,105 @@+#pragma once++#include <memory>++namespace cpuid {++class cpuinfo {+ public:+ struct impl;++ cpuinfo();+ ~cpuinfo();++ // Has X87 FPU+ bool has_fpu() const;++ // Return true if the CPU supports MMX+ bool has_mmx() const;++ // Return true if the CPU supports SSE+ bool has_sse() const;++ // Return true if the CPU supports SSE2+ bool has_sse2() const;++ // Return true if the CPU supports SSE3+ bool has_sse3() const;++ // Return true if the CPU supports SSSE3+ bool has_ssse3() const;++ // Return true if the CPU supports SSE 4.1+ bool has_sse4_1() const;++ // Return true if the CPU supports SSE 4.2+ bool has_sse4_2() const;++ // Return true if the CPU supports pclmulqdq+ bool has_pclmulqdq() const;++ // Return true if the CPU supports AVX+ bool has_avx() const;++ // Return true if the CPU supports AVX2+ bool has_avx2() const;++ // Return true if the CPU supports AVX512F+ bool has_avx512_f() const;++ // Return true if the CPU supports AVX512DQ+ bool has_avx512_dq() const;++ // Return true if the CPU supports AVX512_IFMA+ bool has_avx512_ifma() const;++ // Return true if the CPU supports AVX512PF+ bool has_avx512_pf() const;++ // Return true if the CPU supports AVX512ER+ bool has_avx512_er() const;++ // Return true if the CPU supports AVX512CD+ bool has_avx512_cd() const;++ // Return true if the CPU supports AVX512BW+ bool has_avx512_bw() const;++ // Return true if the CPU supports AVX512VL+ bool has_avx512_vl() const;++ // Return true if the CPU supports AVX512_VBMI+ bool has_avx512_vbmi() const;++ // Return true if the CPU supports AVX512_VBMI2+ bool has_avx512_vbmi2() const;++ // Return true if the CPU supports AVX512_VNNI+ bool has_avx512_vnni() const;++ // Return true if the CPU supports AVX512_BITALG+ bool has_avx512_bitalg() const;++ // Return true if the CPU supports AVX512_VPOPCNTDQ+ bool has_avx512_vpopcntdq() const;++ // Return true if the CPU supports AVX512_4VNNIW+ bool has_avx512_4vnniw() const;++ // Return true if the CPU supports AVX512_4FMAPS+ bool has_avx512_4fmaps() const;++ // Return true if the CPU supports AVX512_VP2INTERSECT+ bool has_avx512_vp2intersect() const;++ // Return true if the CPU supports F16C+ bool has_f16c() const;++ // Return true if the CPU supports NEON+ bool has_neon() const;++ private:+ // Private implementation+ std::unique_ptr<impl> impl_;+};+} // namespace cpuiddiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/cpuinfo_impl.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/cpuinfo_impl.hnew file mode 100644index 00000000..1d2ee69f--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/cpuinfo_impl.h@@ -0,0 +1,69 @@+#pragma once++#include "../cpuinfo.h"++namespace cpuid {++struct cpuinfo::impl {+ impl()+ : m_has_fpu(false),+ m_has_mmx(false),+ m_has_sse(false),+ m_has_sse2(false),+ m_has_sse3(false),+ m_has_ssse3(false),+ m_has_sse4_1(false),+ m_has_sse4_2(false),+ m_has_pclmulqdq(false),+ m_has_avx(false),+ m_has_avx2(false),+ m_has_avx512_f(false),+ m_has_avx512_dq(false),+ m_has_avx512_ifma(false),+ m_has_avx512_pf(false),+ m_has_avx512_er(false),+ m_has_avx512_cd(false),+ m_has_avx512_bw(false),+ m_has_avx512_vl(false),+ m_has_avx512_vbmi(false),+ m_has_avx512_vbmi2(false),+ m_has_avx512_vnni(false),+ m_has_avx512_bitalg(false),+ m_has_avx512_vpopcntdq(false),+ m_has_avx512_4vnniw(false),+ m_has_avx512_4fmaps(false),+ m_has_avx512_vp2intersect(false),+ m_has_f16c(false),+ m_has_neon(false) {}++ bool m_has_fpu;+ bool m_has_mmx;+ bool m_has_sse;+ bool m_has_sse2;+ bool m_has_sse3;+ bool m_has_ssse3;+ bool m_has_sse4_1;+ bool m_has_sse4_2;+ bool m_has_pclmulqdq;+ bool m_has_avx;+ bool m_has_avx2;+ bool m_has_avx512_f;+ bool m_has_avx512_dq;+ bool m_has_avx512_ifma;+ bool m_has_avx512_pf;+ bool m_has_avx512_er;+ bool m_has_avx512_cd;+ bool m_has_avx512_bw;+ bool m_has_avx512_vl;+ bool m_has_avx512_vbmi;+ bool m_has_avx512_vbmi2;+ bool m_has_avx512_vnni;+ bool m_has_avx512_bitalg;+ bool m_has_avx512_vpopcntdq;+ bool m_has_avx512_4vnniw;+ bool m_has_avx512_4fmaps;+ bool m_has_avx512_vp2intersect;+ bool m_has_f16c;+ bool m_has_neon;+};+} // namespace cpuiddiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/extract_x86_flags.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/extract_x86_flags.hnew file mode 100644index 00000000..5bea5866--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/extract_x86_flags.h@@ -0,0 +1,43 @@+#pragma once++#include <cstdint>++#include "cpuinfo_impl.h"++namespace cpuid {++void extract_x86_flags(cpuinfo::impl& info, uint32_t ecx, uint32_t edx) {+ info.m_has_fpu = (edx & (1 << 0)) != 0;+ info.m_has_mmx = (edx & (1 << 23)) != 0;+ info.m_has_sse = (edx & (1 << 25)) != 0;+ info.m_has_sse2 = (edx & (1 << 26)) != 0;+ info.m_has_sse3 = (ecx & (1 << 0)) != 0;+ info.m_has_ssse3 = (ecx & (1 << 9)) != 0;+ info.m_has_sse4_1 = (ecx & (1 << 19)) != 0;+ info.m_has_sse4_2 = (ecx & (1 << 20)) != 0;+ info.m_has_pclmulqdq = (ecx & (1 << 1)) != 0;+ info.m_has_avx = (ecx & (1 << 28)) != 0;+ info.m_has_f16c = (ecx & (1 << 29)) != 0;+}++void extract_x86_extended_flags(cpuinfo::impl& info, uint32_t ebx, uint32_t ecx,+ uint32_t edx) {+ info.m_has_avx2 = (ebx & (1 << 5)) != 0;+ info.m_has_avx512_f = (ebx & (1 << 16)) != 0;+ info.m_has_avx512_dq = (ebx & (1 << 17)) != 0;+ info.m_has_avx512_ifma = (ebx & (1 << 21)) != 0;+ info.m_has_avx512_pf = (ebx & (1 << 26)) != 0;+ info.m_has_avx512_er = (ebx & (1 << 27)) != 0;+ info.m_has_avx512_cd = (ebx & (1 << 28)) != 0;+ info.m_has_avx512_bw = (ebx & (1 << 30)) != 0;+ info.m_has_avx512_vl = (ebx & (1 << 31)) != 0;+ info.m_has_avx512_vbmi = (ecx & (1 << 1)) != 0;+ info.m_has_avx512_vbmi2 = (ecx & (1 << 6)) != 0;+ info.m_has_avx512_vnni = (ecx & (1 << 11)) != 0;+ info.m_has_avx512_bitalg = (ecx & (1 << 12)) != 0;+ info.m_has_avx512_vpopcntdq = (ecx & (1 << 14)) != 0;+ info.m_has_avx512_4vnniw = (edx & (1 << 2)) != 0;+ info.m_has_avx512_4fmaps = (edx & (1 << 3)) != 0;+ info.m_has_avx512_vp2intersect = (edx & (1 << 8)) != 0;+}+} // namespace cpuiddiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/init_msvc_x86.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/init_msvc_x86.hnew file mode 100644index 00000000..697270b1--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/init_msvc_x86.h@@ -0,0 +1,36 @@+#pragma once++#include <intrin.h>++#include "cpuinfo_impl.h"+#include "extract_x86_flags.h"++namespace cpuid {++void init_cpuinfo(cpuinfo::impl& info) {+ int registers[4];++ // The register information per input can be extracted from here:+ // http://en.wikipedia.org/wiki/CPUID+ //+ // CPUID should be called with EAX=0 first, as this will return the+ // maximum supported EAX input value for future calls+ __cpuid(registers, 0);+ uint32_t maximum_eax = registers[0];++ // Set registers for basic flag extraction, eax=1+ // All CPUs should support index=1+ if (maximum_eax >= 1U) {+ __cpuid(registers, 1);+ extract_x86_flags(info, registers[2], registers[3]);+ }++ // Set registers for extended flags extraction, eax=7 and ecx=0+ // This operation is not supported on older CPUs, so it should be skipped+ // to avoid incorrect results+ if (maximum_eax >= 7U) {+ __cpuidex(registers, 7, 0);+ extract_x86_extended_flags(info, registers[1], registers[2], registers[3]);+ }+}+} // namespace cpuiddiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/init_unknown.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/init_unknown.hnew file mode 100644index 00000000..3b52ef2b--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/cpuid/detail/init_unknown.h@@ -0,0 +1,9 @@++#pragma once++#include "cpuinfo_impl.h"++namespace cpuid {++void init_cpuinfo(cpuinfo::impl& info) { (void)info; }+} // namespace cpuiddiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/d3dutil.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/d3dutil.hnew file mode 100644index 00000000..a32bc157--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/d3dutil.h@@ -0,0 +1,31 @@+#pragma once++#include <D3d11.h>+#include <winrt/Windows.Foundation.h>+#include <winrt/Windows.System.h>++inline auto CreateD3DDevice(D3D_DRIVER_TYPE const type,+ winrt::com_ptr<ID3D11Device>& device) {+ WINRT_ASSERT(!device);++ UINT flags =+ D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT;++ //#ifdef _DEBUG+ // flags |= D3D11_CREATE_DEVICE_DEBUG;+ //#endif++ return D3D11CreateDevice(nullptr, type, nullptr, flags, nullptr, 0,+ D3D11_SDK_VERSION, device.put(), nullptr, nullptr);+}++inline auto CreateD3DDevice() {+ winrt::com_ptr<ID3D11Device> device;+ HRESULT hr = CreateD3DDevice(D3D_DRIVER_TYPE_HARDWARE, device);++ if (DXGI_ERROR_UNSUPPORTED == hr) {+ CreateD3DDevice(D3D_DRIVER_TYPE_WARP, device);+ }++ return device;+}diff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/direct3d11.interop.cc b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/direct3d11.interop.ccnew file mode 100644index 00000000..96a74ba9--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/direct3d11.interop.cc@@ -0,0 +1,47 @@+#include "direct3d11.interop.h"++namespace flutter_inappwebview_plugin+{++ namespace {++ typedef HRESULT(WINAPI* CreateDirect3D11DeviceFromDXGIDeviceFn)(IDXGIDevice*,+ LPVOID*);++ struct D3DFuncs {+ CreateDirect3D11DeviceFromDXGIDeviceFn CreateDirect3D11DeviceFromDXGIDevice =+ nullptr;++ D3DFuncs()+ {+ auto handle = GetModuleHandle(L"d3d11.dll");+ if (!handle) {+ return;+ }++ CreateDirect3D11DeviceFromDXGIDevice =+ reinterpret_cast<CreateDirect3D11DeviceFromDXGIDeviceFn>(+ GetProcAddress(handle, "CreateDirect3D11DeviceFromDXGIDevice"));+ }++ static const D3DFuncs& instance()+ {+ static D3DFuncs funcs;+ return funcs;+ }+ };++ } // namespace++ HRESULT CreateDirect3D11DeviceFromDXGIDevice(IDXGIDevice* dxgiDevice,+ IInspectable** graphicsDevice)+ {+ auto ptr = D3DFuncs::instance().CreateDirect3D11DeviceFromDXGIDevice;+ if (ptr) {+ return ptr(dxgiDevice, reinterpret_cast<LPVOID*>(graphicsDevice));+ }++ return E_NOTIMPL;+ }++} // namespace utildiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/direct3d11.interop.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/direct3d11.interop.hnew file mode 100644index 00000000..4434815d--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/direct3d11.interop.h@@ -0,0 +1,51 @@+#pragma once++#include <inspectable.h>+#include <windows.foundation.h>+#include <winrt/windows.graphics.directx.direct3d11.h>++#include "dxgi.h"++namespace Windows {+ namespace Graphics {+ namespace DirectX {+ namespace Direct3D11 {+ struct __declspec(uuid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1"))+ IDirect3DDxgiInterfaceAccess : ::IUnknown {+ virtual HRESULT __stdcall GetInterface(GUID const& id, void** object) = 0;+ };++ } // namespace Direct3D11+ } // namespace DirectX+ } // namespace Graphics+} // namespace Windows++namespace flutter_inappwebview_plugin+{++ HRESULT CreateDirect3D11DeviceFromDXGIDevice(IDXGIDevice* dxgiDevice,+ IInspectable** graphicsDevice);++ template <typename T>+ auto GetDXGIInterfaceFromObject(+ winrt::Windows::Foundation::IInspectable const& object)+ {+ auto access = object.as<+ Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess>();+ winrt::com_ptr<T> result;+ winrt::check_hresult(+ access->GetInterface(winrt::guid_of<T>(), result.put_void()));+ return result;+ }++ template <typename T>+ auto TryGetDXGIInterfaceFromObject(const winrt::com_ptr<IInspectable>& object)+ {+ auto access = object.try_as<+ Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess>();+ winrt::com_ptr<T> result;+ access->GetInterface(winrt::guid_of<T>(), result.put_void());+ return result;+ }++} // namespace utildiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/rohelper.cc b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/rohelper.ccnew file mode 100644index 00000000..6fa6ab0b--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/rohelper.cc@@ -0,0 +1,244 @@+// Based on ANGLE's RoHelper (CompositorNativeWindow11.{cpp,h})+// - https://github.com/google/angle/blob/main/src/libANGLE/renderer/d3d/d3d11/converged/CompositorNativeWindow11.h+// - https://github.com/google/angle/blob/main/src/libANGLE/renderer/d3d/d3d11/converged/CompositorNativeWindow11.cpp+// - https://gist.github.com/clarkezone/43e984fb9bdcd2cfcd9a4f41c208a02f+//+// Copyright 2018 The ANGLE Project Authors.+// All rights reserved.+//+// Redistribution and use in source and binary forms, with or without+// modification, are permitted provided that the following conditions+// are met:+//+// Redistributions of source code must retain the above copyright+// notice, this list of conditions and the following disclaimer.+//+// Redistributions in binary form must reproduce the above+// copyright notice, this list of conditions and the following+// disclaimer in the documentation and/or other materials provided+// with the distribution.+//+// Neither the name of TransGaming Inc., Google Inc., 3DLabs Inc.+// Ltd., nor the names of their contributors may be used to endorse+// or promote products derived from this software without specific+// prior written permission.+//+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE+// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+// POSSIBILITY OF SUCH DAMAGE.++#include "rohelper.h"++#include <windows.foundation.metadata.h>+#include <wrl.h>++namespace rx {+template <typename T>+bool AssignProcAddress(HMODULE comBaseModule, const char* name, T*& outProc) {+ outProc = reinterpret_cast<T*>(GetProcAddress(comBaseModule, name));+ return *outProc != nullptr;+}++RoHelper::RoHelper(RO_INIT_TYPE init_type)+ : mFpWindowsCreateStringReference(nullptr),+ mFpGetActivationFactory(nullptr),+ mFpWindowsCompareStringOrdinal(nullptr),+ mFpCreateDispatcherQueueController(nullptr),+ mFpWindowsDeleteString(nullptr),+ mFpRoInitialize(nullptr),+ mFpRoUninitialize(nullptr),+ mWinRtAvailable(false),+ mComBaseModule(nullptr),+ mCoreMessagingModule(nullptr) {+#ifdef WINUWP+ mFpWindowsCreateStringReference = &::WindowsCreateStringReference;+ mFpRoInitialize = &::RoInitialize;+ mFpRoUninitialize = &::RoUninitialize;+ mFpWindowsDeleteString = &::WindowsDeleteString;+ mFpGetActivationFactory = &::RoGetActivationFactory;+ mFpWindowsCompareStringOrdinal = &::WindowsCompareStringOrdinal;+ mFpCreateDispatcherQueueController = &::CreateDispatcherQueueController;+ mWinRtAvailable = true;+#else++ mComBaseModule = LoadLibraryA("ComBase.dll");++ if (mComBaseModule == nullptr) {+ return;+ }++ if (!AssignProcAddress(mComBaseModule, "WindowsCreateStringReference",+ mFpWindowsCreateStringReference)) {+ return;+ }++ if (!AssignProcAddress(mComBaseModule, "RoGetActivationFactory",+ mFpGetActivationFactory)) {+ return;+ }++ if (!AssignProcAddress(mComBaseModule, "WindowsCompareStringOrdinal",+ mFpWindowsCompareStringOrdinal)) {+ return;+ }++ if (!AssignProcAddress(mComBaseModule, "WindowsDeleteString",+ mFpWindowsDeleteString)) {+ return;+ }++ if (!AssignProcAddress(mComBaseModule, "RoInitialize", mFpRoInitialize)) {+ return;+ }++ if (!AssignProcAddress(mComBaseModule, "RoUninitialize", mFpRoUninitialize)) {+ return;+ }++ mCoreMessagingModule = LoadLibraryA("coremessaging.dll");++ if (mCoreMessagingModule == nullptr) {+ return;+ }++ if (!AssignProcAddress(mCoreMessagingModule,+ "CreateDispatcherQueueController",+ mFpCreateDispatcherQueueController)) {+ return;+ }++ auto result = RoInitialize(init_type);++ if (SUCCEEDED(result) || result == S_FALSE || result == RPC_E_CHANGED_MODE) {+ mWinRtAvailable = true;+ }+#endif+}++RoHelper::~RoHelper() {+#ifndef WINUWP+ if (mWinRtAvailable) {+ RoUninitialize();+ }++ if (mCoreMessagingModule != nullptr) {+ FreeLibrary(mCoreMessagingModule);+ mCoreMessagingModule = nullptr;+ }++ if (mComBaseModule != nullptr) {+ FreeLibrary(mComBaseModule);+ mComBaseModule = nullptr;+ }+#endif+}++bool RoHelper::WinRtAvailable() const { return mWinRtAvailable; }++bool RoHelper::SupportedWindowsRelease() {+ if (!mWinRtAvailable) {+ return false;+ }++ HSTRING className, contractName;+ HSTRING_HEADER classNameHeader, contractNameHeader;+ boolean isSupported = false;++ HRESULT hr = GetStringReference(+ RuntimeClass_Windows_Foundation_Metadata_ApiInformation, &className,+ &classNameHeader);++ if (FAILED(hr)) {+ return !!isSupported;+ }++ Microsoft::WRL::ComPtr<+ ABI::Windows::Foundation::Metadata::IApiInformationStatics>+ api;++ hr = GetActivationFactory(+ className,+ __uuidof(ABI::Windows::Foundation::Metadata::IApiInformationStatics),+ &api);++ if (FAILED(hr)) {+ return !!isSupported;+ }++ hr = GetStringReference(L"Windows.Foundation.UniversalApiContract",+ &contractName, &contractNameHeader);+ if (FAILED(hr)) {+ return !!isSupported;+ }++ api->IsApiContractPresentByMajor(contractName, 6, &isSupported);++ return !!isSupported;+}++HRESULT RoHelper::GetStringReference(PCWSTR source, HSTRING* act,+ HSTRING_HEADER* header) {+ if (!mWinRtAvailable) {+ return E_FAIL;+ }++ const wchar_t* str = static_cast<const wchar_t*>(source);++ unsigned int length;+ HRESULT hr = SizeTToUInt32(::wcslen(str), &length);+ if (FAILED(hr)) {+ return hr;+ }++ return mFpWindowsCreateStringReference(source, length, header, act);+}++HRESULT RoHelper::GetActivationFactory(const HSTRING act,+ const IID& interfaceId, void** fac) {+ if (!mWinRtAvailable) {+ return E_FAIL;+ }+ auto hr = mFpGetActivationFactory(act, interfaceId, fac);+ return hr;+}++HRESULT RoHelper::WindowsCompareStringOrdinal(HSTRING one, HSTRING two,+ int* result) {+ if (!mWinRtAvailable) {+ return E_FAIL;+ }+ return mFpWindowsCompareStringOrdinal(one, two, result);+}++HRESULT RoHelper::CreateDispatcherQueueController(+ DispatcherQueueOptions options,+ ABI::Windows::System::IDispatcherQueueController**+ dispatcherQueueController) {+ if (!mWinRtAvailable) {+ return E_FAIL;+ }+ return mFpCreateDispatcherQueueController(options, dispatcherQueueController);+}++HRESULT RoHelper::WindowsDeleteString(HSTRING one) {+ if (!mWinRtAvailable) {+ return E_FAIL;+ }+ return mFpWindowsDeleteString(one);+}++HRESULT RoHelper::RoInitialize(RO_INIT_TYPE type) {+ return mFpRoInitialize(type);+}++void RoHelper::RoUninitialize() { mFpRoUninitialize(); }+} // namespace rxdiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/rohelper.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/rohelper.hnew file mode 100644index 00000000..12e7e6cc--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/rohelper.h@@ -0,0 +1,97 @@+// Based on ANGLE's RoHelper (CompositorNativeWindow11.{cpp,h})+// - https://github.com/google/angle/blob/main/src/libANGLE/renderer/d3d/d3d11/converged/CompositorNativeWindow11.h+// - https://github.com/google/angle/blob/main/src/libANGLE/renderer/d3d/d3d11/converged/CompositorNativeWindow11.cpp+// - https://gist.github.com/clarkezone/43e984fb9bdcd2cfcd9a4f41c208a02f+//+// Copyright 2018 The ANGLE Project Authors.+// All rights reserved.+//+// Redistribution and use in source and binary forms, with or without+// modification, are permitted provided that the following conditions+// are met:+//+// Redistributions of source code must retain the above copyright+// notice, this list of conditions and the following disclaimer.+//+// Redistributions in binary form must reproduce the above+// copyright notice, this list of conditions and the following+// disclaimer in the documentation and/or other materials provided+// with the distribution.+//+// Neither the name of TransGaming Inc., Google Inc., 3DLabs Inc.+// Ltd., nor the names of their contributors may be used to endorse+// or promote products derived from this software without specific+// prior written permission.+//+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE+// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+// POSSIBILITY OF SUCH DAMAGE.++#pragma once++#include <dispatcherqueue.h>+#include <roapi.h>+#include <windows.ui.composition.interop.h>++namespace rx {+class RoHelper {+ public:+ RoHelper(RO_INIT_TYPE init_type);+ ~RoHelper();+ bool WinRtAvailable() const;+ bool SupportedWindowsRelease();+ HRESULT GetStringReference(PCWSTR source, HSTRING* act,+ HSTRING_HEADER* header);+ HRESULT GetActivationFactory(const HSTRING act, const IID& interfaceId,+ void** fac);+ HRESULT WindowsCompareStringOrdinal(HSTRING one, HSTRING two, int* result);+ HRESULT CreateDispatcherQueueController(+ DispatcherQueueOptions options,+ ABI::Windows::System::IDispatcherQueueController**+ dispatcherQueueController);+ HRESULT WindowsDeleteString(HSTRING one);+ HRESULT RoInitialize(RO_INIT_TYPE type);+ void RoUninitialize();++ private:+ using WindowsCreateStringReference_ = HRESULT __stdcall(PCWSTR, UINT32,+ HSTRING_HEADER*,+ HSTRING*);++ using GetActivationFactory_ = HRESULT __stdcall(HSTRING, REFIID, void**);++ using WindowsCompareStringOrginal_ = HRESULT __stdcall(HSTRING, HSTRING,+ int*);++ using WindowsDeleteString_ = HRESULT __stdcall(HSTRING);++ using CreateDispatcherQueueController_ =+ HRESULT __stdcall(DispatcherQueueOptions,+ ABI::Windows::System::IDispatcherQueueController**);++ using RoInitialize_ = HRESULT __stdcall(RO_INIT_TYPE);+ using RoUninitialize_ = void __stdcall();++ WindowsCreateStringReference_* mFpWindowsCreateStringReference;+ GetActivationFactory_* mFpGetActivationFactory;+ WindowsCompareStringOrginal_* mFpWindowsCompareStringOrdinal;+ CreateDispatcherQueueController_* mFpCreateDispatcherQueueController;+ WindowsDeleteString_* mFpWindowsDeleteString;+ RoInitialize_* mFpRoInitialize;+ RoUninitialize_* mFpRoUninitialize;++ bool mWinRtAvailable;++ HMODULE mComBaseModule;+ HMODULE mCoreMessagingModule;+};+} // namespace rxdiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/string_converter.cc b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/string_converter.ccnew file mode 100644index 00000000..7b2d8861--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/string_converter.cc@@ -0,0 +1,54 @@+#include "string_converter.h"++#include <windows.h>++namespace util {+std::string Utf8FromUtf16(std::wstring_view utf16_string) {+ if (utf16_string.empty()) {+ return std::string();+ }++ auto src_length = static_cast<int>(utf16_string.size());+ int target_length =+ ::WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string.data(),+ src_length, nullptr, 0, nullptr, nullptr);++ std::string utf8_string;+ if (target_length <= 0 || target_length > utf8_string.max_size()) {+ return utf8_string;+ }+ utf8_string.resize(target_length);+ int converted_length = ::WideCharToMultiByte(+ CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string.data(), src_length,+ utf8_string.data(), target_length, nullptr, nullptr);+ if (converted_length == 0) {+ return std::string();+ }+ return utf8_string;+}++std::wstring Utf16FromUtf8(std::string_view utf8_string) {+ if (utf8_string.empty()) {+ return std::wstring();+ }++ auto src_length = static_cast<int>(utf8_string.size());+ int target_length =+ ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(),+ src_length, nullptr, 0);++ std::wstring utf16_string;+ if (target_length <= 0 || target_length > utf16_string.max_size()) {+ return utf16_string;+ }+ utf16_string.resize(target_length);+ int converted_length =+ ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(),+ src_length, utf16_string.data(), target_length);+ if (converted_length == 0) {+ return std::wstring();+ }+ return utf16_string;+}++} // namespace utildiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/string_converter.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/string_converter.hnew file mode 100644index 00000000..0a71dbe0--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/string_converter.h@@ -0,0 +1,8 @@+#pragma once++#include <string>++namespace util {+std::string Utf8FromUtf16(std::wstring_view utf16_string);+std::wstring Utf16FromUtf8(std::string_view utf8_string);+} // namespace utildiff --git a/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/swizzle.h b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/swizzle.hnew file mode 100644index 00000000..67f5f7c6--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/custom_platform_view/util/swizzle.h@@ -0,0 +1,192 @@+/*+ * Copyright 2016 Google Inc.+ *+ * Use of this source code is governed by a BSD-style license that can be+ * found in the LICENSE file.+ */++/*+ * see skia/src/opts/SkSwizzler_opts.h+ */++#pragma once++#include "cpuid/cpuinfo.h"++/**+ * SK_CPU_SSE_LEVEL+ *+ * If defined, SK_CPU_SSE_LEVEL should be set to the highest supported level.+ * On non-intel CPU this should be undefined.+ */+#define SK_CPU_SSE_LEVEL_SSE1 10+#define SK_CPU_SSE_LEVEL_SSE2 20+#define SK_CPU_SSE_LEVEL_SSE3 30+#define SK_CPU_SSE_LEVEL_SSSE3 31+#define SK_CPU_SSE_LEVEL_SSE41 41+#define SK_CPU_SSE_LEVEL_SSE42 42+#define SK_CPU_SSE_LEVEL_AVX 51+#define SK_CPU_SSE_LEVEL_AVX2 52+#define SK_CPU_SSE_LEVEL_SKX 60++// Are we in GCC/Clang?+#ifndef SK_CPU_SSE_LEVEL+// These checks must be done in descending order to ensure we set the highest+// available SSE level.+#if defined(__AVX512F__) && defined(__AVX512DQ__) && defined(__AVX512CD__) && \+ defined(__AVX512BW__) && defined(__AVX512VL__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SKX+#elif defined(__AVX2__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX2+#elif defined(__AVX__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX+#elif defined(__SSE4_2__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE42+#elif defined(__SSE4_1__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE41+#elif defined(__SSSE3__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSSE3+#elif defined(__SSE3__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE3+#elif defined(__SSE2__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE2+#endif+#endif++// Are we in VisualStudio?+#ifndef SK_CPU_SSE_LEVEL+// These checks must be done in descending order to ensure we set the highest+// available SSE level. 64-bit intel guarantees at least SSE2 support.+#if defined(__AVX512F__) && defined(__AVX512DQ__) && defined(__AVX512CD__) && \+ defined(__AVX512BW__) && defined(__AVX512VL__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SKX+#elif defined(__AVX2__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX2+#elif defined(__AVX__)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX+#elif defined(_M_X64) || defined(_M_AMD64)+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE2+#elif defined(_M_IX86_FP)+#if _M_IX86_FP >= 2+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE2+#elif _M_IX86_FP == 1+#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE1+#endif+#endif+#endif++inline void RGBA_to_BGRA_portable(uint32_t* dst, const uint32_t* src,+ int height, int src_stride, int dst_stride) {+ auto width = std::min<int>(src_stride, dst_stride);++ for (int y = 0; y < height; y++) {+ for (int x = 0; x < width; x++) {+ uint8_t a = (src[x] >> 24) & 0xFF, b = (src[x] >> 16) & 0xFF,+ g = (src[x] >> 8) & 0xFF, r = (src[x] >> 0) & 0xFF;+ dst[x] = (uint32_t)a << 24 | (uint32_t)r << 16 | (uint32_t)g << 8 |+ (uint32_t)b << 0;+ }++ src += src_stride;+ dst += dst_stride;+ }+}++#if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SKX++inline void RGBA_to_BGRA_SKX(uint32_t* dst, const uint32_t* src, int height,+ int src_stride, int dst_stride) {+ const uint8_t mask[64] = {2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14,+ 13, 12, 15, 2, 1, 0, 3, 6, 5, 4, 7, 10, 9,+ 8, 11, 14, 13, 12, 15, 2, 1, 0, 3, 6, 5, 4,+ 7, 10, 9, 8, 11, 14, 13, 12, 15, 2, 1, 0, 3,+ 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15};+ const __m512i swapRB = _mm512_loadu_si512(mask);++ auto width = std::min<int>(src_stride, dst_stride);++ for (int y = 0; y < height; y++) {+ auto cw = width;+ auto rptr = src;+ auto dptr = dst;+ while (cw >= 16) {+ __m512i rgba = _mm512_loadu_si512((const __m512i*)rptr);+ __m512i bgra = _mm512_shuffle_epi8(rgba, swapRB);+ _mm512_storeu_si512((__m512i*)dptr, bgra);++ rptr += 16;+ dptr += 16;+ cw -= 16;+ }++ for (auto x = 0; x < cw; x++) {+ uint8_t a = (rptr[x] >> 24) & 0xFF, b = (rptr[x] >> 16) & 0xFF,+ g = (rptr[x] >> 8) & 0xFF, r = (rptr[x] >> 0) & 0xFF;+ dptr[x] = (uint32_t)a << 24 | (uint32_t)r << 16 | (uint32_t)g << 8 |+ (uint32_t)b << 0;+ }++ src += src_stride;+ dst += dst_stride;+ }+}++#endif++#if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX2++inline void RGBA_to_BGRA_AVX2(uint32_t* dst, const uint32_t* src, int height,+ int src_stride, int dst_stride) {+ const __m256i swapRB =+ _mm256_setr_epi8(2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15, 2,+ 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15);++ auto width = std::min<int>(src_stride, dst_stride);++ for (int y = 0; y < height; y++) {+ auto cw = width;+ auto rptr = src;+ auto dptr = dst;+ while (cw >= 8) {+ __m256i rgba = _mm256_loadu_si256((const __m256i*)rptr);+ __m256i bgra = _mm256_shuffle_epi8(rgba, swapRB);+ _mm256_storeu_si256((__m256i*)dptr, bgra);++ rptr += 8;+ dptr += 8;+ cw -= 8;+ }++ for (auto x = 0; x < cw; x++) {+ uint8_t a = (rptr[x] >> 24) & 0xFF, b = (rptr[x] >> 16) & 0xFF,+ g = (rptr[x] >> 8) & 0xFF, r = (rptr[x] >> 0) & 0xFF;+ dptr[x] = (uint32_t)a << 24 | (uint32_t)r << 16 | (uint32_t)g << 8 |+ (uint32_t)b << 0;+ }++ src += src_stride;+ dst += dst_stride;+ }+}++#endif++inline void RGBA_to_BGRA(uint32_t* dst, const uint32_t* src, int height,+ int src_stride, int dst_stride) {+ static cpuid::cpuinfo info;++#if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SKX+ if (info.has_avx512_f() && info.has_avx512_dq() && info.has_avx512_cd() &&+ info.has_avx512_bw() && info.has_avx512_vl()) {+ return RGBA_to_BGRA_SKX(dst, src, height, src_stride, dst_stride);+ }+#endif++#if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX2+ if (info.has_avx2()) {+ return RGBA_to_BGRA_AVX2(dst, src, height, src_stride, dst_stride);+ }+#endif++ RGBA_to_BGRA_portable(dst, src, height, src_stride, dst_stride);+}diff --git a/packages/flutter_inappwebview_windows/windows/flutter_inappwebview_windows_plugin.cpp b/packages/flutter_inappwebview_windows/windows/flutter_inappwebview_windows_plugin.cppnew file mode 100644index 00000000..ed1f29fe--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/flutter_inappwebview_windows_plugin.cpp@@ -0,0 +1,43 @@+#include "flutter_inappwebview_windows_plugin.h"++#include <flutter/plugin_registrar_windows.h>++#include "cookie_manager.h"+#include "headless_in_app_webview/headless_in_app_webview_manager.h"+#include "in_app_browser/in_app_browser_manager.h"+#include "in_app_webview/in_app_webview_manager.h"+#include "webview_environment/webview_environment_manager.h"++#pragma comment(lib, "Shlwapi.lib")+#pragma comment(lib, "dxgi.lib")+#pragma comment(lib, "d3d11.lib")++namespace flutter_inappwebview_plugin+{+ // static+ void FlutterInappwebviewWindowsPlugin::RegisterWithRegistrar(+ flutter::PluginRegistrarWindows* registrar)+ {+ auto plugin = std::make_unique<FlutterInappwebviewWindowsPlugin>(registrar);+ registrar->AddPlugin(std::move(plugin));+ }++ FlutterInappwebviewWindowsPlugin::FlutterInappwebviewWindowsPlugin(flutter::PluginRegistrarWindows* registrar)+ : registrar(registrar)+ {+ webViewEnvironmentManager = std::make_unique<WebViewEnvironmentManager>(this);+ inAppWebViewManager = std::make_unique<InAppWebViewManager>(this);+ inAppBrowserManager = std::make_unique<InAppBrowserManager>(this);+ headlessInAppWebViewManager = std::make_unique<HeadlessInAppWebViewManager>(this);+ cookieManager = std::make_unique<CookieManager>(this);+ }++ FlutterInappwebviewWindowsPlugin::~FlutterInappwebviewWindowsPlugin()+ {+ webViewEnvironmentManager = nullptr;+ inAppWebViewManager = nullptr;+ inAppBrowserManager = nullptr;+ headlessInAppWebViewManager = nullptr;+ cookieManager = nullptr;+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/flutter_inappwebview_windows_plugin.h b/packages/flutter_inappwebview_windows/windows/flutter_inappwebview_windows_plugin.hnew file mode 100644index 00000000..9d0bd403--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/flutter_inappwebview_windows_plugin.h@@ -0,0 +1,35 @@+#ifndef FLUTTER_PLUGIN_FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_H_+#define FLUTTER_PLUGIN_FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_H_++#include <flutter/method_channel.h>+#include <flutter/plugin_registrar_windows.h>++namespace flutter_inappwebview_plugin+{+ class WebViewEnvironmentManager;+ class InAppWebViewManager;+ class InAppBrowserManager;+ class HeadlessInAppWebViewManager;+ class CookieManager;++ class FlutterInappwebviewWindowsPlugin : public flutter::Plugin {+ public:+ flutter::PluginRegistrarWindows* registrar;+ std::unique_ptr<WebViewEnvironmentManager> webViewEnvironmentManager;+ std::unique_ptr<InAppWebViewManager> inAppWebViewManager;+ std::unique_ptr<InAppBrowserManager> inAppBrowserManager;+ std::unique_ptr<HeadlessInAppWebViewManager> headlessInAppWebViewManager;+ std::unique_ptr<CookieManager> cookieManager;++ static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar);++ FlutterInappwebviewWindowsPlugin(flutter::PluginRegistrarWindows* registrar);++ virtual ~FlutterInappwebviewWindowsPlugin();++ // Disallow copy and assign.+ FlutterInappwebviewWindowsPlugin(const FlutterInappwebviewWindowsPlugin&) = delete;+ FlutterInappwebviewWindowsPlugin& operator=(const FlutterInappwebviewWindowsPlugin&) = delete;+ };+}+#endif // FLUTTER_PLUGIN_FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_H_diff --git a/packages/flutter_inappwebview_windows/windows/flutter_inappwebview_windows_plugin_c_api.cpp b/packages/flutter_inappwebview_windows/windows/flutter_inappwebview_windows_plugin_c_api.cppnew file mode 100644index 00000000..9fc6f673--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/flutter_inappwebview_windows_plugin_c_api.cpp@@ -0,0 +1,13 @@+#include "include/flutter_inappwebview_windows/flutter_inappwebview_windows_plugin_c_api.h"++#include <flutter/plugin_registrar_windows.h>++#include "flutter_inappwebview_windows_plugin.h"++void FlutterInappwebviewWindowsPluginCApiRegisterWithRegistrar(+ FlutterDesktopPluginRegistrarRef registrar)+{+ flutter_inappwebview_plugin::FlutterInappwebviewWindowsPlugin::RegisterWithRegistrar(+ flutter::PluginRegistrarManager::GetInstance()+ ->GetRegistrar<flutter::PluginRegistrarWindows>(registrar));+}diff --git a/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview.cpp b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview.cppnew file mode 100644index 00000000..fc2ff2c1--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview.cpp@@ -0,0 +1,59 @@+#include "../utils/log.h"+#include "headless_in_app_webview.h"++namespace flutter_inappwebview_plugin+{+ using namespace Microsoft::WRL;++ HeadlessInAppWebView::HeadlessInAppWebView(const FlutterInappwebviewWindowsPlugin* plugin, const HeadlessInAppWebViewCreationParams& params, const HWND parentWindow, std::unique_ptr<InAppWebView> webView)+ : plugin(plugin), id(params.id),+ webView(std::move(webView)),+ channelDelegate(std::make_unique<HeadlessWebViewChannelDelegate>(this, plugin->registrar->messenger()))+ {+ prepare(params);+ ShowWindow(parentWindow, SW_HIDE);+ }++ void HeadlessInAppWebView::prepare(const HeadlessInAppWebViewCreationParams& params)+ {+ if (!webView) {+ return;+ }+ }++ void HeadlessInAppWebView::setSize(const std::shared_ptr<Size2D> size) const+ {+ if (!webView) {+ return;+ }+ RECT rect = {+ 0, 0, (LONG)size->width, (LONG)size->height+ };+ webView->webViewController->put_Bounds(rect);+ }++ std::shared_ptr<Size2D> HeadlessInAppWebView::getSize() const+ {+ if (!webView) {+ return std::make_shared<Size2D>(-1.0, -1.0);+ }+ RECT rect;+ webView->webViewController->get_Bounds(&rect);+ auto width = rect.right - rect.left;+ auto height = rect.bottom - rect.top;+ return std::make_shared<Size2D>((double)width, (double)height);+ }++ HeadlessInAppWebView::~HeadlessInAppWebView()+ {+ debugLog("dealloc HeadlessInAppWebView");+ HWND parentWindow = nullptr;+ if (webView && webView->webViewController) {+ webView->webViewController->get_ParentWindow(&parentWindow);+ }+ webView = nullptr;+ if (parentWindow) {+ DestroyWindow(parentWindow);+ }+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview.h b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview.hnew file mode 100644index 00000000..0e419602--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview.h@@ -0,0 +1,35 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_HEADLESS_IN_APP_WEBVIEW_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_HEADLESS_IN_APP_WEBVIEW_H_++#include "../flutter_inappwebview_windows_plugin.h"+#include "../in_app_webview/in_app_webview.h"+#include "../types/size_2d.h"+#include "headless_webview_channel_delegate.h"++namespace flutter_inappwebview_plugin+{+ struct HeadlessInAppWebViewCreationParams {+ const std::string id;+ const std::shared_ptr<Size2D> initialSize;+ };++ class HeadlessInAppWebView+ {+ public:+ static inline const wchar_t* CLASS_NAME = L"HeadlessInAppWebView";+ static inline const std::string METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_headless_inappwebview_";++ const FlutterInappwebviewWindowsPlugin* plugin;+ std::string id;+ std::unique_ptr<InAppWebView> webView;+ std::unique_ptr<HeadlessWebViewChannelDelegate> channelDelegate;++ HeadlessInAppWebView(const FlutterInappwebviewWindowsPlugin* plugin, const HeadlessInAppWebViewCreationParams& params, const HWND parentWindow, std::unique_ptr<InAppWebView> webView);+ ~HeadlessInAppWebView();++ void prepare(const HeadlessInAppWebViewCreationParams& params);+ void setSize(const std::shared_ptr<Size2D> size) const;+ std::shared_ptr<Size2D> getSize() const;+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_HEADLESS_IN_APP_WEBVIEW_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview_manager.cpp b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview_manager.cppnew file mode 100644index 00000000..a74587d5--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview_manager.cpp@@ -0,0 +1,148 @@+#include <DispatcherQueue.h>+#include <flutter/method_channel.h>+#include <flutter/standard_method_codec.h>+#include <shlobj.h>+#include <windows.graphics.capture.h>++#include "../in_app_webview/in_app_webview_settings.h"+#include "../types/size_2d.h"+#include "../types/url_request.h"+#include "../types/user_script.h"+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "../utils/map.h"+#include "../utils/string.h"+#include "../utils/vector.h"+#include "../webview_environment/webview_environment_manager.h"+#include "headless_in_app_webview_manager.h"++namespace flutter_inappwebview_plugin+{+ HeadlessInAppWebViewManager::HeadlessInAppWebViewManager(const FlutterInappwebviewWindowsPlugin* plugin)+ : plugin(plugin),+ ChannelDelegate(plugin->registrar->messenger(), HeadlessInAppWebViewManager::METHOD_CHANNEL_NAME)+ {+ windowClass_.lpszClassName = HeadlessInAppWebView::CLASS_NAME;+ windowClass_.lpfnWndProc = &DefWindowProc;++ RegisterClass(&windowClass_);+ }++ void HeadlessInAppWebViewManager::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ auto* arguments = std::get_if<flutter::EncodableMap>(method_call.arguments());+ auto& methodName = method_call.method_name();++ if (string_equals(methodName, "run")) {+ run(arguments, std::move(result));+ }+ else {+ result->NotImplemented();+ }+ }++ void HeadlessInAppWebViewManager::run(const flutter::EncodableMap* arguments, std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));++ if (!plugin) {+ result_->Error("0", "Cannot create the HeadlessInAppWebView instance!");+ return;+ }++ auto id = get_fl_map_value<std::string>(*arguments, "id");+ auto params = get_fl_map_value<flutter::EncodableMap>(*arguments, "params");++ auto initialSize = std::make_shared<Size2D>(get_fl_map_value<flutter::EncodableMap>(params, "initialSize"));++ auto settingsMap = get_fl_map_value<flutter::EncodableMap>(params, "initialSettings");+ auto urlRequestMap = get_optional_fl_map_value<flutter::EncodableMap>(params, "initialUrlRequest");+ auto initialFile = get_optional_fl_map_value<std::string>(params, "initialFile");+ auto initialDataMap = get_optional_fl_map_value<flutter::EncodableMap>(params, "initialData");+ auto initialUserScriptList = get_optional_fl_map_value<flutter::EncodableList>(params, "initialUserScripts");+ auto webViewEnvironmentId = get_optional_fl_map_value<std::string>(params, "webViewEnvironmentId");++ RECT bounds;+ GetClientRect(plugin->registrar->GetView()->GetNativeWindow(), &bounds);++ auto initialWidth = initialSize->width >= 0 ? initialSize->width : bounds.right - bounds.left;+ auto initialHeight = initialSize->height >= 0 ? initialSize->height : bounds.bottom - bounds.top;++ auto hwnd = CreateWindowEx(0, windowClass_.lpszClassName, L"", 0, 0,+ 0, (int)initialWidth, (int)initialHeight,+ plugin->registrar->GetView()->GetNativeWindow(),+ nullptr,+ windowClass_.hInstance, nullptr);++ auto webViewEnvironment = webViewEnvironmentId.has_value() && map_contains(plugin->webViewEnvironmentManager->webViewEnvironments, webViewEnvironmentId.value())+ ? plugin->webViewEnvironmentManager->webViewEnvironments.at(webViewEnvironmentId.value()).get() : nullptr;++ auto initialSettings = std::make_shared<InAppWebViewSettings>(settingsMap);++ InAppWebView::createInAppWebViewEnv(hwnd, false, webViewEnvironment, initialSettings,+ [=](wil::com_ptr<ICoreWebView2Environment> webViewEnv,+ wil::com_ptr<ICoreWebView2Controller> webViewController,+ wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController)+ {+ if (plugin && webViewEnv && webViewController) {+ std::optional<std::vector<std::shared_ptr<UserScript>>> initialUserScripts = initialUserScriptList.has_value() ?+ functional_map(initialUserScriptList.value(), [](const flutter::EncodableValue& map) { return std::make_shared<UserScript>(std::get<flutter::EncodableMap>(map)); }) :+ std::optional<std::vector<std::shared_ptr<UserScript>>>{};++ InAppWebViewCreationParams params = {+ id,+ std::move(initialSettings),+ initialUserScripts+ };++ auto inAppWebView = std::make_unique<InAppWebView>(plugin, params, hwnd,+ std::move(webViewEnv), std::move(webViewController), nullptr+ );++ HeadlessInAppWebViewCreationParams headlessParams = {+ id,+ std::move(initialSize)+ };++ auto headlessInAppWebView = std::make_unique<HeadlessInAppWebView>(plugin,+ headlessParams,+ hwnd,+ std::move(inAppWebView));++ headlessInAppWebView->webView->initChannel(std::nullopt, std::nullopt);++ if (headlessInAppWebView->channelDelegate) {+ headlessInAppWebView->channelDelegate->onWebViewCreated();+ }++ std::optional<std::shared_ptr<URLRequest>> urlRequest = urlRequestMap.has_value() ? std::make_shared<URLRequest>(urlRequestMap.value()) : std::optional<std::shared_ptr<URLRequest>>{};+ if (urlRequest.has_value()) {+ headlessInAppWebView->webView->loadUrl(urlRequest.value());+ }+ else if (initialFile.has_value()) {+ headlessInAppWebView->webView->loadFile(initialFile.value());+ }+ else if (initialDataMap.has_value()) {+ headlessInAppWebView->webView->loadData(get_fl_map_value<std::string>(initialDataMap.value(), "data"));+ }++ webViews.insert({ id, std::move(headlessInAppWebView) });++ result_->Success(true);+ }+ else {+ result_->Error("0", "Cannot create the HeadlessInAppWebView instance!");+ }+ }+ );+ }++ HeadlessInAppWebViewManager::~HeadlessInAppWebViewManager()+ {+ debugLog("dealloc HeadlessInAppWebViewManager");+ webViews.clear();+ UnregisterClass(windowClass_.lpszClassName, nullptr);+ plugin = nullptr;+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview_manager.h b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview_manager.hnew file mode 100644index 00000000..1e52c51f--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_in_app_webview_manager.h@@ -0,0 +1,36 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_HEADLESS_IN_APP_WEBVIEW_MANAGER_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_HEADLESS_IN_APP_WEBVIEW_MANAGER_H_++#include <flutter/method_channel.h>+#include <map>+#include <string>+#include <wil/com.h>+#include <winrt/base.h>++#include "../flutter_inappwebview_windows_plugin.h"+#include "../types/channel_delegate.h"+#include "headless_in_app_webview.h"++namespace flutter_inappwebview_plugin+{+ class HeadlessInAppWebViewManager : public ChannelDelegate+ {+ public:+ static inline const std::string METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_headless_inappwebview";++ const FlutterInappwebviewWindowsPlugin* plugin;+ std::map<std::string, std::unique_ptr<HeadlessInAppWebView>> webViews;++ HeadlessInAppWebViewManager(const FlutterInappwebviewWindowsPlugin* plugin);+ ~HeadlessInAppWebViewManager();++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);++ void run(const flutter::EncodableMap* arguments, std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);+ private:+ WNDCLASS windowClass_ = {};+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_HEADLESS_IN_APP_WEBVIEW_MANAGER_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_webview_channel_delegate.cpp b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_webview_channel_delegate.cppnew file mode 100644index 00000000..95099be6--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_webview_channel_delegate.cpp@@ -0,0 +1,62 @@+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "../utils/strconv.h"+#include "../utils/string.h"+#include "headless_in_app_webview.h"+#include "headless_webview_channel_delegate.h"++#include "headless_in_app_webview_manager.h"++namespace flutter_inappwebview_plugin+{+ HeadlessWebViewChannelDelegate::HeadlessWebViewChannelDelegate(HeadlessInAppWebView* webView, flutter::BinaryMessenger* messenger)+ : webView(webView), ChannelDelegate(messenger, HeadlessInAppWebView::METHOD_CHANNEL_NAME_PREFIX + variant_to_string(webView->id))+ {}++ void HeadlessWebViewChannelDelegate::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ if (!webView) {+ result->Success();+ return;+ }++ // auto& arguments = std::get<flutter::EncodableMap>(*method_call.arguments());+ auto& methodName = method_call.method_name();++ if (string_equals(methodName, "dispose")) {+ if (webView->plugin && webView->plugin->headlessInAppWebViewManager) {+ std::map<std::string, std::unique_ptr<HeadlessInAppWebView>>& webViews = webView->plugin->headlessInAppWebViewManager->webViews;+ auto& id = webView->id;+ if (map_contains(webViews, id)) {+ if (webView->channelDelegate) {+ webView->channelDelegate->UnregisterMethodCallHandler();+ if (webView->webView && webView->webView->channelDelegate) {+ webView->webView->channelDelegate->UnregisterMethodCallHandler();+ }+ }+ webViews.erase(id);+ }+ }+ result->Success();+ }+ else {+ result->NotImplemented();+ }+ }++ void HeadlessWebViewChannelDelegate::onWebViewCreated() const+ {+ if (!channel) {+ return;+ }++ channel->InvokeMethod("onWebViewCreated", nullptr);+ }++ HeadlessWebViewChannelDelegate::~HeadlessWebViewChannelDelegate()+ {+ debugLog("dealloc HeadlessWebViewChannelDelegate");+ webView = nullptr;+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_webview_channel_delegate.h b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_webview_channel_delegate.hnew file mode 100644index 00000000..15d3a8ed--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/headless_in_app_webview/headless_webview_channel_delegate.h@@ -0,0 +1,27 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_HEADLESS_WEBVIEW_CHANNEL_DELEGATE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_HEADLESS_WEBVIEW_CHANNEL_DELEGATE_H_++#include "../types/channel_delegate.h"+#include <flutter/method_channel.h>++namespace flutter_inappwebview_plugin+{+ class HeadlessInAppWebView;++ class HeadlessWebViewChannelDelegate : public ChannelDelegate+ {+ public:+ HeadlessInAppWebView* webView;++ HeadlessWebViewChannelDelegate(HeadlessInAppWebView* webView, flutter::BinaryMessenger* messenger);+ ~HeadlessWebViewChannelDelegate();++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);++ void onWebViewCreated() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_HEADLESS_WEBVIEW_CHANNEL_DELEGATE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser.cpp b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser.cppnew file mode 100644index 00000000..d85f1110--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser.cpp@@ -0,0 +1,260 @@+#include <Windows.h>++#include "../utils/log.h"+#include "../utils/strconv.h"+#include "../webview_environment/webview_environment_manager.h"+#include "in_app_browser.h"+#include "in_app_browser_manager.h"++namespace flutter_inappwebview_plugin+{+ InAppBrowser::InAppBrowser(const FlutterInappwebviewWindowsPlugin* plugin, const InAppBrowserCreationParams& params)+ : plugin(plugin),+ m_hInstance(GetModuleHandle(nullptr)),+ id(params.id),+ settings(params.initialSettings),+ channelDelegate(std::make_unique<InAppBrowserChannelDelegate>(id, plugin->registrar->messenger()))+ {++ WNDCLASS wndClass = {};+ wndClass.lpszClassName = InAppBrowser::CLASS_NAME;+ wndClass.hInstance = m_hInstance;+ wndClass.hIcon = LoadIcon(NULL, IDI_WINLOGO);+ wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);+ wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);+ wndClass.lpfnWndProc = InAppBrowser::WndProc;++ RegisterClass(&wndClass);++ auto parentWindow = plugin->registrar->GetView()->GetNativeWindow();+ RECT bounds;+ GetWindowRect(parentWindow, &bounds);++ auto x = CW_USEDEFAULT;+ auto y = CW_USEDEFAULT;+ auto width = bounds.right - bounds.left;+ auto height = bounds.bottom - bounds.top;++ if (settings->windowFrame) {+ x = (int)settings->windowFrame->x;+ y = (int)settings->windowFrame->y;+ width = (int)settings->windowFrame->width;+ height = (int)settings->windowFrame->height;+ }++ m_hWnd = CreateWindowEx(+ WS_EX_LAYERED, // Optional window styles.+ wndClass.lpszClassName, // Window class++ settings->toolbarTopFixedTitle.empty() ? L"" : utf8_to_wide(settings->toolbarTopFixedTitle).c_str(), // Window text++ settings->windowType == InAppBrowserWindowType::window ? WS_OVERLAPPEDWINDOW : (WS_CHILDWINDOW | WS_OVERLAPPEDWINDOW), // Window style++ // Position+ x, y,+ // Size+ width, height,++ settings->windowType == InAppBrowserWindowType::window ? nullptr : parentWindow, // Parent window+ nullptr, // Menu+ wndClass.hInstance, // Instance handle+ this // Additional application data+ );++ SetLayeredWindowAttributes(m_hWnd, 0, (BYTE)(255 * settings->windowAlphaValue), LWA_ALPHA);++ ShowWindow(m_hWnd, settings->hidden ? SW_HIDE : SW_SHOW);++ InAppWebViewCreationParams webViewParams = {+ id,+ params.initialWebViewSettings,+ params.initialUserScripts+ };++ auto webViewEnvironment = params.webViewEnvironmentId.has_value() && map_contains(plugin->webViewEnvironmentManager->webViewEnvironments, params.webViewEnvironmentId.value())+ ? plugin->webViewEnvironmentManager->webViewEnvironments.at(params.webViewEnvironmentId.value()).get() : nullptr;++ InAppWebView::createInAppWebViewEnv(m_hWnd, false, webViewEnvironment, params.initialWebViewSettings,+ [this, params, webViewParams](wil::com_ptr<ICoreWebView2Environment> webViewEnv, wil::com_ptr<ICoreWebView2Controller> webViewController, wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController) -> void+ {+ if (webViewEnv && webViewController) {+ webView = std::make_unique<InAppWebView>(this, this->plugin, webViewParams, m_hWnd, std::move(webViewEnv), std::move(webViewController), nullptr);+ webView->initChannel(std::nullopt, InAppBrowser::METHOD_CHANNEL_NAME_PREFIX + id);++ if (channelDelegate) {+ channelDelegate->onBrowserCreated();+ }++ if (params.urlRequest.has_value()) {+ webView->loadUrl(params.urlRequest.value());+ }+ else if (params.assetFilePath.has_value()) {+ webView->loadFile(params.assetFilePath.value());+ }+ else if (params.data.has_value()) {+ webView->loadData(params.data.value());+ }+ }+ else {+ std::cerr << "Cannot create the InAppWebView instance!" << std::endl;+ close();+ }+ });+ }++ void InAppBrowser::close() const+ {+ DestroyWindow(m_hWnd);+ }++ void InAppBrowser::show() const+ {+ ShowWindow(m_hWnd, SW_SHOW);+ }++ void InAppBrowser::hide() const+ {+ ShowWindow(m_hWnd, SW_HIDE);+ }++ bool InAppBrowser::isHidden() const+ {+ return !IsWindowVisible(m_hWnd);+ }++ void InAppBrowser::setSettings(const std::shared_ptr<InAppBrowserSettings> newSettings, const flutter::EncodableMap& newSettingsMap)+ {+ if (webView) {+ webView->setSettings(std::make_shared<InAppWebViewSettings>(newSettingsMap), newSettingsMap);+ }++ if (fl_map_contains_not_null(newSettingsMap, "hidden") && settings->hidden != newSettings->hidden) {+ newSettings->hidden ? hide() : show();+ }++ if (fl_map_contains_not_null(newSettingsMap, "toolbarTopFixedTitle") && !string_equals(settings->toolbarTopFixedTitle, newSettings->toolbarTopFixedTitle) && !newSettings->toolbarTopFixedTitle.empty()) {+ SetWindowText(m_hWnd, utf8_to_wide(newSettings->toolbarTopFixedTitle).c_str());+ }++ if (fl_map_contains_not_null(newSettingsMap, "windowAlphaValue") && settings->windowAlphaValue != newSettings->windowAlphaValue) {+ SetLayeredWindowAttributes(m_hWnd, 0, (BYTE)(255 * newSettings->windowAlphaValue), LWA_ALPHA);+ }++ if (fl_map_contains_not_null(newSettingsMap, "windowFrame")) {+ auto x = (int)newSettings->windowFrame->x;+ auto y = (int)newSettings->windowFrame->y;+ auto width = (int)newSettings->windowFrame->width;+ auto height = (int)newSettings->windowFrame->height;+ MoveWindow(m_hWnd, x, y, width, height, true);+ }++ settings = newSettings;+ }++ flutter::EncodableValue InAppBrowser::getSettings() const+ {+ if (!settings || !webView) {+ return make_fl_value();+ }++ auto encodableMap = settings->getRealSettings(this);+ encodableMap.merge(std::get<flutter::EncodableMap>(webView->getSettings()));+ return encodableMap;+ }++ void InAppBrowser::didChangeTitle(const std::optional<std::string>& title) const+ {+ if (title.has_value() && settings->toolbarTopFixedTitle.empty()) {+ SetWindowText(m_hWnd, utf8_to_wide(title.value()).c_str());+ }+ }++ LRESULT CALLBACK InAppBrowser::WndProc(+ HWND window,+ UINT message,+ WPARAM wparam,+ LPARAM lparam+ ) noexcept+ {+ if (message == WM_NCCREATE) {+ auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);+ SetWindowLongPtr(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));+ }+ else if (InAppBrowser* that = GetThisFromHandle(window)) {+ return that->MessageHandler(window, message, wparam, lparam);+ }++ return DefWindowProc(window, message, wparam, lparam);+ }++ LRESULT InAppBrowser::MessageHandler(+ HWND hwnd,+ UINT message,+ WPARAM wparam,+ LPARAM lparam+ ) noexcept+ {+ switch (message) {+ case WM_DESTROY: {+ // might receive multiple WM_DESTROY messages.+ if (!destroyed_) {+ destroyed_ = true;++ if (channelDelegate) {+ channelDelegate->onExit();+ }++ if (channelDelegate) {+ channelDelegate->UnregisterMethodCallHandler();+ if (webView && webView->channelDelegate) {+ webView->channelDelegate->UnregisterMethodCallHandler();+ }+ }+ webView.reset();++ if (plugin && plugin->inAppBrowserManager) {+ plugin->inAppBrowserManager->browsers.erase(id);+ }+ }+ return 0;+ }+ case WM_DPICHANGED: {+ auto newRectSize = reinterpret_cast<RECT*>(lparam);+ LONG newWidth = newRectSize->right - newRectSize->left;+ LONG newHeight = newRectSize->bottom - newRectSize->top;++ SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth,+ newHeight, SWP_NOZORDER | SWP_NOACTIVATE);+ return 0;+ }+ case WM_SIZE: {+ RECT bounds;+ GetClientRect(hwnd, &bounds);+ if (webView) {+ webView->webViewController->put_Bounds(bounds);+ }+ return 0;+ }+ case WM_ACTIVATE: {+ return 0;+ }+ }++ return DefWindowProc(hwnd, message, wparam, lparam);+ }++ InAppBrowser* InAppBrowser::GetThisFromHandle(HWND const window) noexcept+ {+ return reinterpret_cast<InAppBrowser*>(+ GetWindowLongPtr(window, GWLP_USERDATA));+ }++ InAppBrowser::~InAppBrowser()+ {+ debugLog("dealloc InAppBrowser");+ webView.reset();+ SetWindowLongPtr(m_hWnd, GWLP_USERDATA, 0);+ plugin = nullptr;+ }++}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser.h b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser.hnew file mode 100644index 00000000..3c1181c0--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser.h@@ -0,0 +1,71 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_H_++#include <optional>+#include <string>+#include <Windows.h>++#include "../flutter_inappwebview_windows_plugin.h"+#include "../in_app_webview/in_app_webview.h"+#include "../in_app_webview/in_app_webview_settings.h"+#include "../types/url_request.h"+#include "in_app_browser_channel_delegate.h"+#include "in_app_browser_settings.h"++namespace flutter_inappwebview_plugin+{+ struct InAppBrowserCreationParams+ {+ const std::string id;+ const std::optional<std::shared_ptr<URLRequest>> urlRequest;+ const std::optional<std::string> assetFilePath;+ const std::optional<std::string> data;+ const std::shared_ptr<InAppBrowserSettings> initialSettings;+ const std::shared_ptr<InAppWebViewSettings> initialWebViewSettings;+ const std::optional<std::vector<std::shared_ptr<UserScript>>> initialUserScripts;+ const std::optional<std::string> webViewEnvironmentId;+ };++ class InAppBrowser {+ public:+ static inline const std::string METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_inappbrowser_";+ static inline const wchar_t* CLASS_NAME = L"InAppBrowser";++ static LRESULT CALLBACK WndProc(HWND window,+ UINT message,+ WPARAM wparam,+ LPARAM lparam) noexcept;++ const FlutterInappwebviewWindowsPlugin* plugin;+ const std::string id;+ std::unique_ptr<InAppWebView> webView;+ std::unique_ptr<InAppBrowserChannelDelegate> channelDelegate;+ std::shared_ptr<InAppBrowserSettings> settings;++ InAppBrowser(const FlutterInappwebviewWindowsPlugin* plugin, const InAppBrowserCreationParams& params);+ ~InAppBrowser();++ void close() const;+ void show() const;+ void hide() const;+ bool isHidden() const;+ void setSettings(const std::shared_ptr<InAppBrowserSettings> newSettings, const flutter::EncodableMap& newSettingsMap);+ flutter::EncodableValue getSettings() const;++ void didChangeTitle(const std::optional<std::string>& title) const;+ HWND getHWND() const+ {+ return m_hWnd;+ }+ private:+ const HINSTANCE m_hInstance;+ HWND m_hWnd;+ bool destroyed_ = false;+ static InAppBrowser* GetThisFromHandle(HWND window) noexcept;+ LRESULT MessageHandler(HWND window,+ UINT message,+ WPARAM wparam,+ LPARAM lparam) noexcept;+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_channel_delegate.cpp b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_channel_delegate.cppnew file mode 100644index 00000000..34aa966e--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_channel_delegate.cpp@@ -0,0 +1,37 @@+#include "../utils/log.h"+#include "in_app_browser.h"+#include "in_app_browser_channel_delegate.h"++namespace flutter_inappwebview_plugin+{+ InAppBrowserChannelDelegate::InAppBrowserChannelDelegate(const std::string& id, flutter::BinaryMessenger* messenger)+ : ChannelDelegate(messenger, InAppBrowser::METHOD_CHANNEL_NAME_PREFIX + id)+ {}++ void InAppBrowserChannelDelegate::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ result->NotImplemented();+ }++ void InAppBrowserChannelDelegate::onBrowserCreated() const+ {+ if (!channel) {+ return;+ }+ channel->InvokeMethod("onBrowserCreated", nullptr);+ }++ void InAppBrowserChannelDelegate::onExit() const+ {+ if (!channel) {+ return;+ }+ channel->InvokeMethod("onExit", nullptr);+ }++ InAppBrowserChannelDelegate::~InAppBrowserChannelDelegate()+ {+ debugLog("dealloc InAppBrowserChannelDelegate");+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_channel_delegate.h b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_channel_delegate.hnew file mode 100644index 00000000..d0032cff--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_channel_delegate.h@@ -0,0 +1,26 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_CHANNEL_DELEGATE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_CHANNEL_DELEGATE_H_++#include <flutter/method_channel.h>+#include <flutter/standard_message_codec.h>++#include "../types/channel_delegate.h"++namespace flutter_inappwebview_plugin+{+ class InAppBrowserChannelDelegate : public ChannelDelegate+ {+ public:+ InAppBrowserChannelDelegate(const std::string& id, flutter::BinaryMessenger* messenger);+ ~InAppBrowserChannelDelegate();++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);++ void onBrowserCreated() const;+ void onExit() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_CHANNEL_DELEGATE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_manager.cpp b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_manager.cppnew file mode 100644index 00000000..7f210f7b--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_manager.cpp@@ -0,0 +1,94 @@+#include <flutter/method_channel.h>+#include <flutter/standard_method_codec.h>+#include <windows.h>++#include "../in_app_webview/in_app_webview_settings.h"+#include "../types/url_request.h"+#include "../types/user_script.h"+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "../utils/string.h"+#include "../utils/vector.h"+#include "in_app_browser_manager.h"+#include "in_app_browser_settings.h"++namespace flutter_inappwebview_plugin+{+ InAppBrowserManager::InAppBrowserManager(const FlutterInappwebviewWindowsPlugin* plugin)+ : plugin(plugin), ChannelDelegate(plugin->registrar->messenger(), InAppBrowserManager::METHOD_CHANNEL_NAME)+ {}++ void InAppBrowserManager::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ auto* arguments = std::get_if<flutter::EncodableMap>(method_call.arguments());+ auto& methodName = method_call.method_name();++ if (string_equals(methodName, "open")) {+ if (plugin) {+ createInAppBrowser(arguments);+ result->Success(true);+ }+ else {+ result->Error("0", "Cannot create the InAppBrowser instance!");++ }+ }+ else if (string_equals(methodName, "openWithSystemBrowser")) {+ auto url = get_fl_map_value<std::string>(*arguments, "url");++ int status = static_cast<int>(reinterpret_cast<INT_PTR>(+ ShellExecute(nullptr, TEXT("open"), utf8_to_wide(url).c_str(),+ nullptr, nullptr, SW_SHOWNORMAL)));++ // Anything >32 indicates success.+ // https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutea#return-value+ if (status <= 32) {+ std::cerr << "Failed to open " << url << ": ShellExecute error code " << status << std::endl;+ }+ }+ else {+ result->NotImplemented();+ }+ }++ void InAppBrowserManager::createInAppBrowser(const flutter::EncodableMap* arguments)+ {+ auto id = get_fl_map_value<std::string>(*arguments, "id");+ auto urlRequestMap = get_optional_fl_map_value<flutter::EncodableMap>(*arguments, "urlRequest");+ auto assetFilePath = get_optional_fl_map_value<std::string>(*arguments, "assetFilePath");+ auto data = get_optional_fl_map_value<std::string>(*arguments, "data");+ auto initialUserScriptList = get_optional_fl_map_value<flutter::EncodableList>(*arguments, "initialUserScripts");+ auto webViewEnvironmentId = get_optional_fl_map_value<std::string>(*arguments, "webViewEnvironmentId");++ std::optional<std::shared_ptr<URLRequest>> urlRequest = urlRequestMap.has_value() ? std::make_shared<URLRequest>(urlRequestMap.value()) : std::optional<std::shared_ptr<URLRequest>>{};++ auto settingsMap = get_fl_map_value<flutter::EncodableMap>(*arguments, "settings");+ auto initialSettings = std::make_unique<InAppBrowserSettings>(settingsMap);+ auto initialWebViewSettings = std::make_unique<InAppWebViewSettings>(settingsMap);+ std::optional<std::vector<std::shared_ptr<UserScript>>> initialUserScripts = initialUserScriptList.has_value() ?+ functional_map(initialUserScriptList.value(), [](const flutter::EncodableValue& map) { return std::make_shared<UserScript>(std::get<flutter::EncodableMap>(map)); }) :+ std::optional<std::vector<std::shared_ptr<UserScript>>>{};++ InAppBrowserCreationParams params = {+ id,+ urlRequest,+ assetFilePath,+ data,+ std::move(initialSettings),+ std::move(initialWebViewSettings),+ initialUserScripts,+ webViewEnvironmentId+ };++ auto inAppBrowser = std::make_unique<InAppBrowser>(plugin, params);+ browsers.insert({ id, std::move(inAppBrowser) });+ }++ InAppBrowserManager::~InAppBrowserManager()+ {+ debugLog("dealloc InAppBrowserManager");+ browsers.clear();+ plugin = nullptr;+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_manager.h b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_manager.hnew file mode 100644index 00000000..c8b53a27--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_manager.h@@ -0,0 +1,33 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_MANAGER_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_MANAGER_H_++#include <flutter/method_channel.h>+#include <flutter/standard_message_codec.h>+#include <map>+#include <string>++#include "../flutter_inappwebview_windows_plugin.h"+#include "../types/channel_delegate.h"+#include "in_app_browser.h"++namespace flutter_inappwebview_plugin+{+ class InAppBrowserManager : public ChannelDelegate+ {+ public:+ static inline const std::string METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappbrowser";++ const FlutterInappwebviewWindowsPlugin* plugin;+ std::map<std::string, std::unique_ptr<InAppBrowser>> browsers;++ InAppBrowserManager(const FlutterInappwebviewWindowsPlugin* plugin);+ ~InAppBrowserManager();++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);++ void createInAppBrowser(const flutter::EncodableMap* arguments);+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_MANAGER_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_settings.cpp b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_settings.cppnew file mode 100644index 00000000..dea7f862--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_settings.cpp@@ -0,0 +1,76 @@+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "../utils/string.h"+#include "in_app_browser_settings.h"++#include "in_app_browser.h"++namespace flutter_inappwebview_plugin+{+ namespace+ {+ InAppBrowserWindowType inAppBrowserWindowTypeFromString(const std::string& s)+ {+ if (string_equals(s, "CHILD")) {+ return InAppBrowserWindowType::child;+ }+ return InAppBrowserWindowType::window;+ }++ std::string inAppBrowserWindowTypeToString(const InAppBrowserWindowType& t)+ {+ switch (t) {+ case InAppBrowserWindowType::child:+ return "CHILD";+ default:+ return "WINDOW";+ }+ }+ }++ InAppBrowserSettings::InAppBrowserSettings() {};++ InAppBrowserSettings::InAppBrowserSettings(const flutter::EncodableMap& encodableMap)+ {+ hidden = get_fl_map_value(encodableMap, "hidden", hidden);+ windowType = inAppBrowserWindowTypeFromString(get_fl_map_value<std::string>(encodableMap, "windowType", inAppBrowserWindowTypeToString(InAppBrowserWindowType::window)));+ toolbarTopFixedTitle = get_fl_map_value(encodableMap, "toolbarTopFixedTitle", toolbarTopFixedTitle);+ windowAlphaValue = get_fl_map_value(encodableMap, "windowAlphaValue", windowAlphaValue);+ auto windowFrameMap = get_optional_fl_map_value<flutter::EncodableMap>(encodableMap, "windowFrame");+ if (windowFrameMap.has_value()) {+ windowFrame = std::make_shared<Rect>(windowFrameMap.value());+ }+ }++ flutter::EncodableMap InAppBrowserSettings::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"hidden", hidden},+ {"windowType", inAppBrowserWindowTypeToString(windowType)},+ {"toolbarTopFixedTitle", toolbarTopFixedTitle},+ {"windowAlphaValue", windowAlphaValue},+ {"windowFrame", windowFrame ? windowFrame->toEncodableMap() : make_fl_value()},+ };+ }++ flutter::EncodableMap InAppBrowserSettings::getRealSettings(const InAppBrowser* inAppBrowser) const+ {+ auto settingsMap = toEncodableMap();+ settingsMap["hidden"] = inAppBrowser->isHidden();++ BYTE alphaValue = 0;+ GetLayeredWindowAttributes(inAppBrowser->getHWND(), nullptr, &alphaValue, nullptr);+ settingsMap["windowAlphaValue"] = (double)alphaValue;++ RECT position;+ GetWindowRect(inAppBrowser->getHWND(), &position);+ settingsMap["windowFrame"] = std::make_unique<Rect>(position.left, position.top, position.right - position.left, position.bottom - position.top)->toEncodableMap();++ return settingsMap;+ }++ InAppBrowserSettings::~InAppBrowserSettings()+ {+ debugLog("dealloc InAppBrowserSettings");+ };+}diff --git a/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_settings.h b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_settings.hnew file mode 100644index 00000000..1243ca2b--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_browser/in_app_browser_settings.h@@ -0,0 +1,36 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_SETTINGS_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_SETTINGS_H_++#include <flutter/standard_message_codec.h>+#include <optional>+#include <string>++#include "../types/rect.h"++namespace flutter_inappwebview_plugin+{+ class InAppBrowser;++ enum InAppBrowserWindowType {+ window,+ child+ };++ class InAppBrowserSettings+ {+ public:+ bool hidden = false;+ InAppBrowserWindowType windowType = window;+ std::string toolbarTopFixedTitle;+ double windowAlphaValue = 1.0;+ std::shared_ptr<Rect> windowFrame;++ InAppBrowserSettings();+ InAppBrowserSettings(const flutter::EncodableMap& encodableMap);+ ~InAppBrowserSettings();++ flutter::EncodableMap toEncodableMap() const;+ flutter::EncodableMap getRealSettings(const InAppBrowser* inAppBrowser) const;+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_SETTINGS_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview.cpp b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview.cppnew file mode 100644index 00000000..3ecdedd0--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview.cpp@@ -0,0 +1,1892 @@+#include <cstring>+#include <filesystem>+#include <nlohmann/json.hpp>+#include <Shlwapi.h>+#include <wil/wrl.h>++#include "../custom_platform_view/util/composition.desktop.interop.h"+#include "../plugin_scripts_js/javascript_bridge_js.h"+#include "../types/create_window_action.h"+#include "../types/web_resource_error.h"+#include "../types/web_resource_request.h"+#include "../utils/base64.h"+#include "../utils/log.h"+#include "../utils/map.h"+#include "../utils/strconv.h"+#include "../utils/string.h"+#include "../webview_environment/webview_environment_manager.h"+#include "in_app_webview.h"+#include "in_app_webview_manager.h"++namespace flutter_inappwebview_plugin+{+ using namespace Microsoft::WRL;++ InAppWebView::InAppWebView(const FlutterInappwebviewWindowsPlugin* plugin, const InAppWebViewCreationParams& params, const HWND parentWindow, wil::com_ptr<ICoreWebView2Environment> webViewEnv,+ wil::com_ptr<ICoreWebView2Controller> webViewController,+ wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController)+ : plugin(plugin), id(params.id),+ webViewEnv(std::move(webViewEnv)), webViewController(std::move(webViewController)), webViewCompositionController(std::move(webViewCompositionController)),+ settings(params.initialSettings), userContentController(std::make_unique<UserContentController>(this))+ {+ if (failedAndLog(this->webViewController->get_CoreWebView2(webView.put()))) {+ std::cerr << "Cannot create CoreWebView2." << std::endl;+ }++ if (this->webViewCompositionController) {+ if (!createSurface(parentWindow, plugin->inAppWebViewManager->compositor())) {+ std::cerr << "Cannot create InAppWebView surface." << std::endl;+ }+ registerSurfaceEventHandlers();+ }+ else {+ this->webViewController->put_IsVisible(true);+ // Resize WebView to fit the bounds of the parent window+ RECT bounds;+ GetClientRect(parentWindow, &bounds);+ this->webViewController->put_Bounds(bounds);+ }++ prepare(params);+ }++ InAppWebView::InAppWebView(InAppBrowser* inAppBrowser, const FlutterInappwebviewWindowsPlugin* plugin, const InAppWebViewCreationParams& params, const HWND parentWindow, wil::com_ptr<ICoreWebView2Environment> webViewEnv,+ wil::com_ptr<ICoreWebView2Controller> webViewController,+ wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController)+ : InAppWebView(plugin, params, parentWindow, std::move(webViewEnv), std::move(webViewController), std::move(webViewCompositionController))+ {+ this->inAppBrowser = inAppBrowser;+ }++ void InAppWebView::createInAppWebViewEnv(const HWND parentWindow, const bool& willBeSurface, WebViewEnvironment* webViewEnvironment, const std::shared_ptr<InAppWebViewSettings> initialSettings, std::function<void(wil::com_ptr<ICoreWebView2Environment> webViewEnv,+ wil::com_ptr<ICoreWebView2Controller> webViewController,+ wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController)> completionHandler)+ {+ auto callback = [parentWindow, willBeSurface, completionHandler, initialSettings](HRESULT result, wil::com_ptr<ICoreWebView2Environment> env) -> HRESULT+ {+ if (failedAndLog(result) || !env) {+ completionHandler(nullptr, nullptr, nullptr);+ return E_FAIL;+ }++ wil::com_ptr<ICoreWebView2Environment3> webViewEnv3;+ wil::com_ptr<ICoreWebView2Environment10> webViewEnv10;+ wil::com_ptr<ICoreWebView2ControllerOptions> options;+ if (initialSettings && succeededOrLog(env->QueryInterface(IID_PPV_ARGS(&webViewEnv10))) && succeededOrLog(webViewEnv10->CreateCoreWebView2ControllerOptions(&options))) {+ options->put_IsInPrivateModeEnabled(initialSettings->incognito);+ }+ else {+ webViewEnv10 = nullptr;+ options = nullptr;+ failedLog(env->QueryInterface(IID_PPV_ARGS(&webViewEnv3)));+ }+ if (willBeSurface && (webViewEnv10 || webViewEnv3)) {+ if (webViewEnv10 && options) {+ failedLog(webViewEnv10->CreateCoreWebView2CompositionControllerWithOptions(parentWindow, options.get(), Callback<ICoreWebView2CreateCoreWebView2CompositionControllerCompletedHandler>(+ [completionHandler, env](HRESULT result, wil::com_ptr<ICoreWebView2CompositionController> compositionController) -> HRESULT+ {+ wil::com_ptr<ICoreWebView2Controller3> webViewController = compositionController.try_query<ICoreWebView2Controller3>();++ if (failedAndLog(result) || !webViewController) {+ completionHandler(nullptr, nullptr, nullptr);+ return E_FAIL;+ }++ ICoreWebView2Controller3* webViewController3;+ if (succeededOrLog(webViewController->QueryInterface(IID_PPV_ARGS(&webViewController3)))) {+ webViewController3->put_BoundsMode(COREWEBVIEW2_BOUNDS_MODE_USE_RAW_PIXELS);+ webViewController3->put_ShouldDetectMonitorScaleChanges(FALSE);+ webViewController3->put_RasterizationScale(1.0);+ }++ completionHandler(std::move(env), std::move(webViewController), std::move(compositionController));+ return S_OK;+ }+ ).Get()));+ }+ else {+ failedLog(webViewEnv3->CreateCoreWebView2CompositionController(parentWindow, Callback<ICoreWebView2CreateCoreWebView2CompositionControllerCompletedHandler>(+ [completionHandler, env](HRESULT result, wil::com_ptr<ICoreWebView2CompositionController> compositionController) -> HRESULT+ {+ wil::com_ptr<ICoreWebView2Controller3> webViewController = compositionController.try_query<ICoreWebView2Controller3>();++ if (failedAndLog(result) || !webViewController) {+ completionHandler(nullptr, nullptr, nullptr);+ return E_FAIL;+ }++ ICoreWebView2Controller3* webViewController3;+ if (succeededOrLog(webViewController->QueryInterface(IID_PPV_ARGS(&webViewController3)))) {+ webViewController3->put_BoundsMode(COREWEBVIEW2_BOUNDS_MODE_USE_RAW_PIXELS);+ webViewController3->put_ShouldDetectMonitorScaleChanges(FALSE);+ webViewController3->put_RasterizationScale(1.0);+ }++ completionHandler(std::move(env), std::move(webViewController), std::move(compositionController));+ return S_OK;+ }+ ).Get()));+ }+ }+ else {+ if (webViewEnv10 && options) {+ failedLog(webViewEnv10->CreateCoreWebView2ControllerWithOptions(parentWindow, options.get(), Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(+ [completionHandler, env](HRESULT result, wil::com_ptr<ICoreWebView2Controller> controller) -> HRESULT+ {+ if (failedAndLog(result) || !controller) {+ completionHandler(nullptr, nullptr, nullptr);+ return E_FAIL;+ }++ completionHandler(std::move(env), std::move(controller), nullptr);+ return S_OK;+ }).Get()));+ }+ else {+ failedLog(env->CreateCoreWebView2Controller(parentWindow, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(+ [completionHandler, env](HRESULT result, wil::com_ptr<ICoreWebView2Controller> controller) -> HRESULT+ {+ if (failedAndLog(result) || !controller) {+ completionHandler(nullptr, nullptr, nullptr);+ return E_FAIL;+ }++ completionHandler(std::move(env), std::move(controller), nullptr);+ return S_OK;+ }).Get()));+ }+ }+ return S_OK;+ };++ HRESULT hr;+ if (webViewEnvironment && webViewEnvironment->getEnvironment()) {+ hr = callback(S_OK, webViewEnvironment->getEnvironment());+ }+ else {+ hr = CreateCoreWebView2EnvironmentWithOptions(+ nullptr, nullptr, nullptr,+ Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(callback).Get());+ }++ if (failedAndLog(hr)) {+ completionHandler(nullptr, nullptr, nullptr);+ }+ }++ void InAppWebView::initChannel(const std::optional<std::variant<std::string, int64_t>> viewId, const std::optional<std::string> channelName)+ {+ if (viewId.has_value()) {+ id = viewId.value();+ }+ channelDelegate = channelName.has_value() ? std::make_unique<WebViewChannelDelegate>(this, plugin->registrar->messenger(), channelName.value()) :+ std::make_unique<WebViewChannelDelegate>(this, plugin->registrar->messenger());+ }++ void InAppWebView::prepare(const InAppWebViewCreationParams& params)+ {+ if (!webView) {+ return;+ }++ wil::com_ptr<ICoreWebView2Settings> webView2Settings;+ auto hrWebView2Settings = webView->get_Settings(&webView2Settings);+ if (succeededOrLog(hrWebView2Settings)) {+ webView2Settings->put_IsScriptEnabled(settings->javaScriptEnabled);+ webView2Settings->put_IsZoomControlEnabled(settings->supportZoom);+ webView2Settings->put_AreDevToolsEnabled(settings->isInspectable);+ webView2Settings->put_AreDefaultContextMenusEnabled(!settings->disableContextMenu);++ wil::com_ptr<ICoreWebView2Settings2> webView2Settings2;+ if (succeededOrLog(webView2Settings->QueryInterface(IID_PPV_ARGS(&webView2Settings2)))) {+ if (!settings->userAgent.empty()) {+ webView2Settings2->put_UserAgent(utf8_to_wide(settings->userAgent).c_str());+ }+ }+ }++ wil::com_ptr<ICoreWebView2Controller2> webViewController2;+ if (succeededOrLog(webViewController->QueryInterface(IID_PPV_ARGS(&webViewController2)))) {+ if (!settings->transparentBackground) {+ webViewController2->put_DefaultBackgroundColor({ 0, 255, 255, 255 });+ }+ }++ // required to make Runtime events work+ failedLog(webView->CallDevToolsProtocolMethod(L"Runtime.enable", L"{}", Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ failedLog(errorCode);+ return S_OK;+ }+ ).Get()));++ // required to make Page events work and to add User Scripts+ failedLog(webView->CallDevToolsProtocolMethod(L"Page.enable", L"{}", Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ failedLog(errorCode);+ return S_OK;+ }+ ).Get()));++ // required to use Network domain+ failedLog(webView->CallDevToolsProtocolMethod(L"Network.enable", L"{}", Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ failedLog(errorCode);+ return S_OK;+ }+ ).Get()));++ // required to use Fetch domain and implement the shouldOverrideUrlLoading event correctly+ failedLog(webView->CallDevToolsProtocolMethod(L"Fetch.enable", L"{\"patterns\": [{\"resourceType\": \"Document\", \"requestStage\": \"Request\"}]}", Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ failedLog(errorCode);+ return S_OK;+ }+ ).Get()));++ failedLog(webView->CallDevToolsProtocolMethod(L"Page.getFrameTree", L"{}", Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ if (succeededOrLog(errorCode)) {+ auto treeJson = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson));+ pageFrameId_ = treeJson["frameTree"]["frame"]["id"].get<std::string>();+ }+ return S_OK;+ }+ ).Get()));++ if (userContentController) {+ userContentController->addPluginScript(std::move(createJavaScriptBridgePluginScript()));+ if (params.initialUserScripts.has_value()) {+ userContentController->addUserOnlyScripts(params.initialUserScripts.value());+ }+ }++ registerEventHandlers();+ }++ void InAppWebView::registerEventHandlers()+ {+ if (!webView) {+ return;+ }++ wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceiver> fetchRequestPausedEventReceiver;++ if (succeededOrLog(webView->GetDevToolsProtocolEventReceiver(L"Fetch.requestPaused", &fetchRequestPausedEventReceiver))) {+ failedAndLog(fetchRequestPausedEventReceiver->add_DevToolsProtocolEventReceived(+ Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(+ [this](+ ICoreWebView2* sender,+ ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT+ {+ wil::unique_cotaskmem_string json;+ if (succeededOrLog(args->get_ParameterObjectAsJson(&json))) {+ auto requestPausedData = nlohmann::json::parse(wide_to_utf8(json.get()));++ auto requestId = requestPausedData.at("requestId").get<std::string>();+ auto resourceType = requestPausedData.at("resourceType").get<std::string>();+ auto isResponseStage = requestPausedData.contains("responseStatusCode");+ auto frameId = requestPausedData.at("frameId").get<std::string>();++ auto request = requestPausedData.at("request").get<nlohmann::json>();+ std::optional<std::string> url = request.at("url").is_string() ? request.at("url").get<std::string>() : std::optional<std::string>{};+ std::optional<std::string> urlFragment = request.contains("urlFragment") && request.at("urlFragment").is_string() ? request.at("urlFragment").get<std::string>() : std::optional<std::string>{};+ if (url.has_value() && urlFragment.has_value()) {+ url = url.value() + urlFragment.value();+ }+ auto isForMainFrame = pageFrameId_.empty() || string_equals(pageFrameId_, frameId);++ auto allowRequest = [this, requestId, url, isForMainFrame]()+ {+ failedAndLog(webView->CallDevToolsProtocolMethod(L"Fetch.continueRequest",+ utf8_to_wide("{\"requestId\":\"" + requestId + "\"}").c_str(),+ Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ failedLog(errorCode);+ return S_OK;+ }+ ).Get()));++ if (channelDelegate && isForMainFrame) {+ // if shouldOverrideUrlLoading is used, then call onLoadStart and onProgressChanged here+ // to match the behaviour of the other platforms+ channelDelegate->onLoadStart(url);+ channelDelegate->onProgressChanged(0);+ }+ };++ auto cancelRequest = [this, requestId]()+ {+ failedAndLog(webView->CallDevToolsProtocolMethod(L"Fetch.failRequest",+ utf8_to_wide("{\"requestId\":\"" + requestId + "\", \"errorReason\": \"Aborted\"}").c_str(),+ Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ failedLog(errorCode);+ return S_OK;+ }+ ).Get()));+ };++ if (!isResponseStage && channelDelegate && settings->useShouldOverrideUrlLoading && string_equals(resourceType, "Document")) {+ std::optional<std::string> method = request.at("method").is_string() ? request.at("method").get<std::string>() : std::optional<std::string>{};+ std::optional<std::map<std::string, std::string>> headers = request.at("headers").is_object() ? request.at("headers").get<std::map<std::string, std::string>>() : std::optional<std::map<std::string, std::string>>{};+ std::optional<std::string> redirectedRequestId = request.contains("redirectedRequestId") && request.at("redirectedRequestId").is_string() ? request.at("redirectedRequestId").get<std::string>() : std::optional<std::string>{};++ std::optional<std::vector<uint8_t>> body = std::optional<std::vector<uint8_t>>{};+ auto hasPostData = request.contains("hasPostData") && request.at("hasPostData").is_boolean() && request.at("hasPostData").get<bool>()+ && request.contains("postDataEntries") && request.at("postDataEntries").is_array();+ if (hasPostData) {+ auto postDataEntries = request.at("postDataEntries").get<std::vector<nlohmann::json>>();++ if (postDataEntries.size() > 0) {+ body = std::vector<uint8_t>{};+ for (auto const& entry : postDataEntries) {+ if (entry.contains("bytes")) {+ try {+ auto entryData = base64_decode(entry.at("bytes").get<std::string>());+ std::vector<uint8_t> bytes(entryData.begin(), entryData.end());+ body->insert(body->end(), bytes.begin(), bytes.end());+ }+ catch (const std::exception& err) {+ debugLog("Error decoding base64 data");+ debugLog(err.what());+ body = std::optional<std::vector<uint8_t>>{};+ break;+ }+ }+ }+ }+ }++ BOOL isRedirect = redirectedRequestId.has_value() && !redirectedRequestId.value().empty();++ std::optional<NavigationActionType> navigationType = isRedirect ? NavigationActionType::other : std::optional<NavigationActionType>{};++ auto urlRequest = std::make_shared<URLRequest>(url, method, headers, body);+ auto navigationAction = std::make_shared<NavigationAction>(+ urlRequest,+ isForMainFrame,+ isRedirect,+ navigationType+ );++ auto callback = std::make_unique<WebViewChannelDelegate::ShouldOverrideUrlLoadingCallback>();+ callback->nonNullSuccess = [this, allowRequest, cancelRequest](const NavigationActionPolicy actionPolicy)+ {+ if (actionPolicy == NavigationActionPolicy::allow) {+ allowRequest();+ }+ else {+ cancelRequest();+ }+ return false;+ };+ auto defaultBehaviour = [this, allowRequest](const std::optional<const NavigationActionPolicy> actionPolicy)+ {+ allowRequest();+ };+ callback->defaultBehaviour = defaultBehaviour;+ callback->error = [defaultBehaviour](const std::string& error_code, const std::string& error_message, const flutter::EncodableValue* error_details)+ {+ debugLog(error_code + ", " + error_message);+ defaultBehaviour(std::nullopt);+ };+ channelDelegate->shouldOverrideUrlLoading(std::move(navigationAction), std::move(callback));+ }+ else {+ // check if a custom event listener is found and give back the opportunity to it to handle the request+ // through the Chrome Dev Protocol API+ if (!map_contains(devToolsProtocolEventListener_, std::string("Fetch.requestPaused"))) {+ // if a custom event listener is not found, continue the request+ allowRequest();+ }+ }+ }++ return S_OK;+ })+ .Get(), nullptr));+ }++ failedLog(webView->add_NavigationStarting(+ Callback<ICoreWebView2NavigationStartingEventHandler>(+ [this](ICoreWebView2* sender, ICoreWebView2NavigationStartingEventArgs* args)+ {+ isLoading_ = true;++ if (!channelDelegate) {+ args->put_Cancel(false);+ return S_OK;+ }++ wil::unique_cotaskmem_string uri = nullptr;+ std::optional<std::string> url = SUCCEEDED(args->get_Uri(&uri)) ? wide_to_utf8(uri.get()) : std::optional<std::string>{};++ wil::unique_cotaskmem_string requestMethod = nullptr;+ wil::com_ptr<ICoreWebView2HttpRequestHeaders> requestHeaders = nullptr;+ std::optional<std::map<std::string, std::string>> headers = std::optional<std::map<std::string, std::string>>{};+ if (SUCCEEDED(args->get_RequestHeaders(&requestHeaders))) {+ headers = std::make_optional<std::map<std::string, std::string>>({});+ wil::com_ptr<ICoreWebView2HttpHeadersCollectionIterator> iterator;+ requestHeaders->GetIterator(&iterator);+ BOOL hasCurrent = FALSE;+ while (SUCCEEDED(iterator->get_HasCurrentHeader(&hasCurrent)) && hasCurrent) {+ wil::unique_cotaskmem_string name;+ wil::unique_cotaskmem_string value;++ if (SUCCEEDED(iterator->GetCurrentHeader(&name, &value))) {+ headers->insert({ wide_to_utf8(name.get()), wide_to_utf8(value.get()) });+ }++ BOOL hasNext = FALSE;+ iterator->MoveNext(&hasNext);+ }++ requestHeaders->GetHeader(L"Flutter-InAppWebView-Request-Method", &requestMethod);+ requestHeaders->RemoveHeader(L"Flutter-InAppWebView-Request-Method");+ }++ std::optional<std::string> method = requestMethod ? wide_to_utf8(requestMethod.get()) : std::optional<std::string>{};++ BOOL isUserInitiated;+ if (FAILED(args->get_IsUserInitiated(&isUserInitiated))) {+ isUserInitiated = FALSE;+ }++ BOOL isRedirect;+ if (FAILED(args->get_IsRedirected(&isRedirect))) {+ isRedirect = FALSE;+ }++ std::optional<NavigationActionType> navigationType = std::nullopt;+ wil::com_ptr<ICoreWebView2NavigationStartingEventArgs3> args3;+ if (SUCCEEDED(args->QueryInterface(IID_PPV_ARGS(&args3)))) {+ COREWEBVIEW2_NAVIGATION_KIND navigationKind;+ if (SUCCEEDED(args3->get_NavigationKind(&navigationKind))) {+ switch (navigationKind) {+ case COREWEBVIEW2_NAVIGATION_KIND_RELOAD:+ navigationType = NavigationActionType::reload;+ break;+ case COREWEBVIEW2_NAVIGATION_KIND_BACK_OR_FORWARD:+ navigationType = NavigationActionType::backForward;+ break;+ case COREWEBVIEW2_NAVIGATION_KIND_NEW_DOCUMENT:+ if (isUserInitiated && !isRedirect) {+ navigationType = NavigationActionType::linkActivated;+ }+ else {+ navigationType = NavigationActionType::other;+ }+ break;+ default:+ navigationType = NavigationActionType::other;+ }+ }+ }++ auto urlRequest = std::make_shared<URLRequest>(url, method, headers, std::nullopt);+ auto navigationAction = std::make_shared<NavigationAction>(+ urlRequest,+ true,+ isRedirect,+ navigationType+ );++ lastNavigationAction_ = navigationAction;++ UINT64 navigationId;+ if (SUCCEEDED(args->get_NavigationId(&navigationId))) {+ navigationActions_.insert({ navigationId, navigationAction });+ }++ // if shouldOverrideUrlLoading is not used, then call onLoadStart and onProgressChanged here+ if (!settings->useShouldOverrideUrlLoading) {+ channelDelegate->onLoadStart(url);+ channelDelegate->onProgressChanged(0);+ }+ args->put_Cancel(false);++ return S_OK;+ }+ ).Get(), nullptr));++ failedLog(webView->add_ContentLoading(+ Callback<ICoreWebView2ContentLoadingEventHandler>(+ [this](ICoreWebView2* sender, ICoreWebView2ContentLoadingEventArgs* args)+ {+ if (channelDelegate) {+ channelDelegate->onProgressChanged(33);+ }+ return S_OK;+ }+ ).Get(), nullptr));++ failedLog(webView->add_NavigationCompleted(+ Callback<ICoreWebView2NavigationCompletedEventHandler>(+ [this](ICoreWebView2* sender, ICoreWebView2NavigationCompletedEventArgs* args)+ {+ isLoading_ = false;++ evaluateJavascript(PLATFORM_READY_JS_SOURCE, ContentWorld::page(), nullptr);++ std::shared_ptr<NavigationAction> navigationAction;+ UINT64 navigationId;+ if (SUCCEEDED(args->get_NavigationId(&navigationId))) {+ navigationAction = map_at_or_null(navigationActions_, navigationId);+ if (navigationAction) {+ navigationActions_.erase(navigationId);+ }+ }++ COREWEBVIEW2_WEB_ERROR_STATUS webErrorType = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN;+ args->get_WebErrorStatus(&webErrorType);++ BOOL isSuccess;+ args->get_IsSuccess(&isSuccess);++ if (channelDelegate) {+ wil::unique_cotaskmem_string uri;+ std::optional<std::string> url = SUCCEEDED(webView->get_Source(&uri)) ? wide_to_utf8(uri.get()) : std::optional<std::string>{};++ channelDelegate->onProgressChanged(100);+ if (isSuccess) {+ channelDelegate->onLoadStop(url);+ }+ else if (!InAppWebView::isSslError(webErrorType) && navigationAction) {+ auto webResourceRequest = std::make_unique<WebResourceRequest>(url, navigationAction->request->method, navigationAction->request->headers, navigationAction->isForMainFrame);+ int httpStatusCode = 0;+ wil::com_ptr<ICoreWebView2NavigationCompletedEventArgs2> args2;+ if (SUCCEEDED(args->QueryInterface(IID_PPV_ARGS(&args2))) && SUCCEEDED(args2->get_HttpStatusCode(&httpStatusCode)) && httpStatusCode >= 400) {+ auto webResourceResponse = std::make_unique<WebResourceResponse>(std::optional<std::string>{},+ std::optional<std::string>{},+ httpStatusCode,+ std::optional<std::string>{},+ std::optional<std::map<std::string, std::string>>{},+ std::optional<std::vector<uint8_t>>{});+ channelDelegate->onReceivedHttpError(std::move(webResourceRequest), std::move(webResourceResponse));+ }+ else if (httpStatusCode < 400) {+ auto webResourceError = std::make_unique<WebResourceError>(WebErrorStatusDescription[webErrorType], webErrorType);+ channelDelegate->onReceivedError(std::move(webResourceRequest), std::move(webResourceError));+ }+ }+ }++ return S_OK;+ }+ ).Get(), nullptr));++ failedLog(webView->add_DocumentTitleChanged(Callback<ICoreWebView2DocumentTitleChangedEventHandler>(+ [this](ICoreWebView2* sender, IUnknown* args)+ {+ if (channelDelegate) {+ wil::unique_cotaskmem_string title;+ sender->get_DocumentTitle(&title);+ channelDelegate->onTitleChanged(title.is_valid() ? wide_to_utf8(title.get()) : std::optional<std::string>{});+ }+ return S_OK;+ }+ ).Get(), nullptr));++ failedLog(webView->add_HistoryChanged(Callback<ICoreWebView2HistoryChangedEventHandler>(+ [this](ICoreWebView2* sender, IUnknown* args)+ {+ if (channelDelegate) {+ std::optional<bool> isReload = std::nullopt;+ if (lastNavigationAction_ && lastNavigationAction_->navigationType.has_value()) {+ isReload = lastNavigationAction_->navigationType.value() == NavigationActionType::reload;+ }+ channelDelegate->onUpdateVisitedHistory(getUrl(), isReload);+ }+ return S_OK;+ }+ ).Get(), nullptr));++ failedLog(webView->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(+ [this](ICoreWebView2* sender, ICoreWebView2WebMessageReceivedEventArgs* args)+ {+ if (!channelDelegate) {+ return S_OK;+ }++ wil::unique_cotaskmem_string json;+ if (succeededOrLog(args->get_WebMessageAsJson(&json))) {+ auto message = nlohmann::json::parse(wide_to_utf8(json.get()));++ if (message.is_object() && message.contains("name") && message.at("name").is_string() && message.contains("body") && message.at("body").is_object()) {+ auto name = message.at("name").get<std::string>();+ auto body = message.at("body").get<nlohmann::json>();++ if (name.compare("callHandler") == 0 && body.contains("handlerName") && body.at("handlerName").is_string()) {+ auto handlerName = body.at("handlerName").get<std::string>();+ auto callHandlerID = body.at("_callHandlerID").is_number_integer() ? body.at("_callHandlerID").get<int64_t>() : 0;+ std::string handlerArgs = body.at("args").is_string() ? body.at("args").get<std::string>() : "";++ auto callback = std::make_unique<WebViewChannelDelegate::CallJsHandlerCallback>();+ callback->defaultBehaviour = [this, callHandlerID](const std::optional<const flutter::EncodableValue*> response)+ {+ std::string json = "null";+ // Absorb patch: a handler that returns null on the Dart side+ // (several internal ones do) arrives as a nullptr here, and+ // dereferencing it crashed the whole app the moment an epub+ // loaded. A non-string result would throw from std::get too.+ if (response.has_value() && response.value() != nullptr) {+ if (auto str = std::get_if<std::string>(response.value())) {+ json = *str;+ }+ }++ evaluateJavascript("if (window." + JAVASCRIPT_BRIDGE_NAME + "[" + std::to_string(callHandlerID) + "] != null) { \+ window." + JAVASCRIPT_BRIDGE_NAME + "[" + std::to_string(callHandlerID) + "].resolve(" + json + "); \+ delete window." + JAVASCRIPT_BRIDGE_NAME + "[" + std::to_string(callHandlerID) + "]; \+ }", ContentWorld::page(), nullptr);+ };+ callback->error = [this, callHandlerID](const std::string& error_code, const std::string& error_message, const flutter::EncodableValue* error_details)+ {+ auto errorMessage = error_code + ", " + error_message;+ debugLog(errorMessage);++ evaluateJavascript("if (window." + JAVASCRIPT_BRIDGE_NAME + "[" + std::to_string(callHandlerID) + "] != null) { \+ window." + JAVASCRIPT_BRIDGE_NAME + "[" + std::to_string(callHandlerID) + "].reject(new Error('" + replace_all_copy(errorMessage, "\'", "\\'") + "')); \+ delete window." + JAVASCRIPT_BRIDGE_NAME + "[" + std::to_string(callHandlerID) + "]; \+ }", ContentWorld::page(), nullptr);+ };+ channelDelegate->onCallJsHandler(handlerName, handlerArgs, std::move(callback));+ }+ }+ }++ return S_OK;+ }+ ).Get(), nullptr));++ wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceiver> consoleMessageReceiver;+ if (succeededOrLog(webView->GetDevToolsProtocolEventReceiver(L"Runtime.consoleAPICalled", &consoleMessageReceiver))) {+ failedLog(consoleMessageReceiver->add_DevToolsProtocolEventReceived(+ Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(+ [this](+ ICoreWebView2* sender,+ ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT+ {++ if (!channelDelegate) {+ return S_OK;+ }++ wil::unique_cotaskmem_string json;+ if (succeededOrLog(args->get_ParameterObjectAsJson(&json))) {+ auto consoleMessageJson = nlohmann::json::parse(wide_to_utf8(json.get()));++ auto level = consoleMessageJson.at("type").get<std::string>();+ int64_t messageLevel = 1;+ if (string_equals(level, "log")) {+ messageLevel = 1;+ }+ else if (string_equals(level, "debug")) {+ messageLevel = 0;+ }+ else if (string_equals(level, "error")) {+ messageLevel = 3;+ }+ else if (string_equals(level, "info")) {+ messageLevel = 1;+ }+ else if (string_equals(level, "warn")) {+ messageLevel = 2;+ }++ auto consoleArgs = consoleMessageJson.at("args").get<std::vector<nlohmann::json>>();+ auto message = join(functional_map(consoleArgs, [](const nlohmann::json& json) { return json.contains("value") ? json.at("value").dump() : (json.contains("description") ? json.at("description").dump() : json.dump()); }), std::string{ " " });+ channelDelegate->onConsoleMessage(message, messageLevel);+ }++ return S_OK;+ })+ .Get(), nullptr));+ }++ failedLog(webView->add_NewWindowRequested(+ Callback<ICoreWebView2NewWindowRequestedEventHandler>(+ [this](ICoreWebView2* sender, ICoreWebView2NewWindowRequestedEventArgs* args)+ {+ wil::com_ptr<ICoreWebView2Deferral> deferral;+ if (channelDelegate && plugin && plugin->inAppWebViewManager && succeededOrLog(args->GetDeferral(&deferral))) {+ plugin->inAppWebViewManager->windowAutoincrementId++;+ int64_t windowId = plugin->inAppWebViewManager->windowAutoincrementId;+ auto newWindowRequestedArgs = std::make_unique<NewWindowRequestedArgs>(args, deferral);+ plugin->inAppWebViewManager->windowWebViews.insert({ windowId, std::move(newWindowRequestedArgs) });++ wil::unique_cotaskmem_string uri = nullptr;+ std::optional<std::string> url = SUCCEEDED(args->get_Uri(&uri)) ? wide_to_utf8(uri.get()) : std::optional<std::string>{};++ BOOL hasGesture;+ if (FAILED(args->get_IsUserInitiated(&hasGesture))) {+ hasGesture = FALSE;+ }++ wil::com_ptr<ICoreWebView2WindowFeatures> webviewWindowFeatures;+ std::optional<std::unique_ptr<WindowFeatures>> windowFeatures;+ if (SUCCEEDED(args->get_WindowFeatures(&webviewWindowFeatures))) {+ windowFeatures = std::make_unique<WindowFeatures>(webviewWindowFeatures);+ }++ auto urlRequest = std::make_shared<URLRequest>(url, "GET", std::nullopt, std::nullopt);+ auto createWindowAction = std::make_shared<CreateWindowAction>(+ urlRequest,+ windowId,+ true,+ hasGesture,+ std::move(windowFeatures));++ auto callback = std::make_unique<WebViewChannelDelegate::CreateWindowCallback>();+ auto defaultBehaviour = [this, windowId, urlRequest, deferral, args](const std::optional<const bool> handledByClient)+ {+ if (plugin && plugin->inAppWebViewManager && map_contains(plugin->inAppWebViewManager->windowWebViews, windowId)) {+ plugin->inAppWebViewManager->windowWebViews.erase(windowId);+ }+ loadUrl(urlRequest);+ failedLog(args->put_Handled(TRUE));+ failedLog(deferral->Complete());+ };+ callback->nonNullSuccess = [this, deferral, args](const bool handledByClient)+ {+ return !handledByClient;+ };+ callback->defaultBehaviour = defaultBehaviour;+ callback->error = [this, defaultBehaviour](const std::string& error_code, const std::string& error_message, const flutter::EncodableValue* error_details)+ {+ debugLog(error_code + ", " + error_message);+ defaultBehaviour(std::nullopt);+ };+ channelDelegate->onCreateWindow(std::move(createWindowAction), std::move(callback));+ }+ return S_OK;+ }+ ).Get(), nullptr));++ failedLog(webView->add_WindowCloseRequested(Callback<ICoreWebView2WindowCloseRequestedEventHandler>(+ [this](ICoreWebView2* sender, IUnknown* args)+ {+ if (channelDelegate) {+ channelDelegate->onCloseWindow();+ }+ return S_OK;+ }+ ).Get(), nullptr));++ failedLog(webView->add_PermissionRequested(Callback<ICoreWebView2PermissionRequestedEventHandler>(+ [this](ICoreWebView2* sender, ICoreWebView2PermissionRequestedEventArgs* args)+ {+ wil::com_ptr<ICoreWebView2Deferral> deferral;+ if (channelDelegate && succeededOrLog(args->GetDeferral(&deferral))) {+ wil::unique_cotaskmem_string uri;+ std::string url = SUCCEEDED(args->get_Uri(&uri)) ? wide_to_utf8(uri.get()) : "";++ COREWEBVIEW2_PERMISSION_KIND resource = COREWEBVIEW2_PERMISSION_KIND_UNKNOWN_PERMISSION;+ failedAndLog(args->get_PermissionKind(&resource));++ auto callback = std::make_unique<WebViewChannelDelegate::PermissionRequestCallback>();+ auto defaultBehaviour = [this, deferral, args](const std::optional<const std::shared_ptr<PermissionResponse>> permissionResponse)+ {+ failedLog(args->put_State(COREWEBVIEW2_PERMISSION_STATE_DENY));+ failedLog(deferral->Complete());+ };+ callback->nonNullSuccess = [this, deferral, args](const std::shared_ptr<PermissionResponse> permissionResponse)+ {+ auto action = permissionResponse->action;+ if (action.has_value()) {+ switch (action.value()) {+ case PermissionResponseActionType::grant:+ failedLog(args->put_State(COREWEBVIEW2_PERMISSION_STATE_ALLOW));+ break;+ case PermissionResponseActionType::prompt:+ failedLog(args->put_State(COREWEBVIEW2_PERMISSION_STATE_DEFAULT));+ break;+ default:+ failedLog(args->put_State(COREWEBVIEW2_PERMISSION_STATE_DENY));+ break;+ }+ failedLog(deferral->Complete());+ return false;+ }+ return true;+ };+ callback->defaultBehaviour = defaultBehaviour;+ callback->error = [this, defaultBehaviour](const std::string& error_code, const std::string& error_message, const flutter::EncodableValue* error_details)+ {+ debugLog(error_code + ", " + error_message);+ defaultBehaviour(std::nullopt);+ };+ channelDelegate->onPermissionRequest(url, { resource }, std::move(callback));+ }+ return S_OK;+ }+ ).Get(), nullptr));++ failedLog(webView->AddWebResourceRequestedFilter(L"*", COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL));+ failedLog(webView->add_WebResourceRequested(+ Callback<ICoreWebView2WebResourceRequestedEventHandler>(+ [this](+ ICoreWebView2* sender, ICoreWebView2WebResourceRequestedEventArgs* args)+ {+ wil::com_ptr<ICoreWebView2Deferral> deferral;+ wil::com_ptr<ICoreWebView2WebResourceRequest> webResourceRequest;+ if (channelDelegate && succeededOrLog(args->get_Request(&webResourceRequest)) && succeededOrLog(args->GetDeferral(&deferral))) {+ auto request = std::make_shared<WebResourceRequest>(webResourceRequest);++ // The add_WebResourceRequested event is by default raised for file, http, and https URI schemes.+ // This is also raised for registered custom URI schemes.+ // https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2?view=webview2-1.0.2792.45#add_webresourcerequested+ auto url = request->url.has_value() ? request->url.value() : "";+ auto isCustomScheme = !url.empty() && !starts_with(url, std::string{ "file://" }) && !starts_with(url, std::string{ "http://" }) && !starts_with(url, std::string{ "https://" });++ auto onLoadResourceWithCustomSchemeCallback = [this, deferral, request, args]()+ {+ if (channelDelegate) {+ auto callback = std::make_unique<WebViewChannelDelegate::LoadResourceWithCustomSchemeCallback>();+ auto defaultBehaviour = [this, deferral, args](const std::optional<std::shared_ptr<CustomSchemeResponse>> response)+ {+ failedLog(deferral->Complete());+ };+ callback->nonNullSuccess = [this, deferral, args](const std::shared_ptr<CustomSchemeResponse> response)+ {+ args->put_Response(response->toWebView2Response(webViewEnv));+ failedLog(deferral->Complete());+ return false;+ };+ callback->defaultBehaviour = defaultBehaviour;+ callback->error = [this, defaultBehaviour](const std::string& error_code, const std::string& error_message, const flutter::EncodableValue* error_details)+ {+ debugLog(error_code + ", " + error_message);+ defaultBehaviour(std::nullopt);+ };+ channelDelegate->onLoadResourceWithCustomScheme(request, std::move(callback));+ }+ else {+ failedLog(deferral->Complete());+ }+ };++ if (settings->useShouldInterceptRequest) {+ auto callback = std::make_unique<WebViewChannelDelegate::ShouldInterceptRequestCallback>();+ auto defaultBehaviour = [this, deferral, args](const std::optional<std::shared_ptr<WebResourceResponse>> response)+ {+ failedLog(deferral->Complete());+ };+ callback->nonNullSuccess = [this, deferral, args](const std::shared_ptr<WebResourceResponse> response)+ {+ args->put_Response(response->toWebView2Response(webViewEnv));+ failedLog(deferral->Complete());+ return false;+ };+ callback->nullSuccess = [this, deferral, args, isCustomScheme, onLoadResourceWithCustomSchemeCallback]()+ {+ if (isCustomScheme) {+ onLoadResourceWithCustomSchemeCallback();+ }+ else {+ failedLog(deferral->Complete());+ }+ return false;+ };+ callback->defaultBehaviour = defaultBehaviour;+ callback->error = [this, defaultBehaviour](const std::string& error_code, const std::string& error_message, const flutter::EncodableValue* error_details)+ {+ debugLog(error_code + ", " + error_message);+ defaultBehaviour(std::nullopt);+ };+ channelDelegate->shouldInterceptRequest(request, std::move(callback));+ }+ else if (isCustomScheme) {+ onLoadResourceWithCustomSchemeCallback();+ }+ else {+ failedLog(deferral->Complete());+ }+ }+ return S_OK;+ }+ ).Get(), nullptr));++ wil::com_ptr<ICoreWebView2_2> webView2;+ if (SUCCEEDED(webView->QueryInterface(IID_PPV_ARGS(&webView2)))) {+ failedLog(webView2->add_DOMContentLoaded(+ Callback<ICoreWebView2DOMContentLoadedEventHandler>(+ [this](ICoreWebView2* sender, ICoreWebView2DOMContentLoadedEventArgs* args)+ {+ if (channelDelegate) {+ channelDelegate->onProgressChanged(66);+ }+ return S_OK;+ }+ ).Get(), nullptr));+ }++ /*+ wil::com_ptr<ICoreWebView2_14> webView14;+ if (SUCCEEDED(webView->QueryInterface(IID_PPV_ARGS(&webView14)))) {+ failedLog(webView14->add_ServerCertificateErrorDetected(+ Callback<ICoreWebView2ServerCertificateErrorDetectedEventHandler>(+ [this](ICoreWebView2* sender, ICoreWebView2ServerCertificateErrorDetectedEventArgs* args)+ {+ debugLog("add_ServerCertificateErrorDetected");+ wil::com_ptr<ICoreWebView2Certificate> certificate = nullptr;+ if (SUCCEEDED(args->get_ServerCertificate(&certificate))) {+ wil::unique_cotaskmem_string displayName = nullptr;+ std::optional<std::string> url = SUCCEEDED(certificate->get_DisplayName(&displayName)) ? wide_to_utf8(displayName.get()) : std::optional<std::string>{};+ debugLog(displayName.get());+ }+ return S_OK;+ }+ ).Get(), nullptr));+ }*/++ if (userContentController) {+ userContentController->registerEventHandlers();+ }+ }++ void InAppWebView::registerSurfaceEventHandlers()+ {+ if (!webViewCompositionController) {+ return;+ }++ failedLog(webViewCompositionController->add_CursorChanged(+ Callback<ICoreWebView2CursorChangedEventHandler>(+ [this](ICoreWebView2CompositionController* sender,+ IUnknown* args) -> HRESULT+ {+ HCURSOR cursor;+ if (cursorChangedCallback_ &&+ sender->get_Cursor(&cursor) == S_OK) {+ cursorChangedCallback_(cursor);+ }+ return S_OK;+ })+ .Get(), nullptr));+ }++ std::optional<std::string> InAppWebView::getUrl() const+ {+ wil::unique_cotaskmem_string uri;+ return webView && succeededOrLog(webView->get_Source(&uri)) ? wide_to_utf8(uri.get()) : std::optional<std::string>{};+ }++ std::optional<std::string> InAppWebView::getTitle() const+ {+ wil::unique_cotaskmem_string title;+ return webView && succeededOrLog(webView->get_DocumentTitle(&title)) ? wide_to_utf8(title.get()) : std::optional<std::string>{};+ }++ void InAppWebView::loadUrl(const std::shared_ptr<URLRequest> urlRequest) const+ {+ if (!webView || !urlRequest->url.has_value()) {+ return;+ }++ std::wstring url = utf8_to_wide(urlRequest->url.value());++ wil::com_ptr<ICoreWebView2Environment2> webViewEnv2;+ wil::com_ptr<ICoreWebView2_2> webView2;+ if (SUCCEEDED(webViewEnv->QueryInterface(IID_PPV_ARGS(&webViewEnv2))) && SUCCEEDED(webView->QueryInterface(IID_PPV_ARGS(&webView2)))) {+ wil::com_ptr<ICoreWebView2WebResourceRequest> webResourceRequest;+ std::wstring method = urlRequest->method.has_value() ? utf8_to_wide(urlRequest->method.value()) : L"GET";++ wil::com_ptr<IStream> postDataStream = nullptr;+ if (urlRequest->body.has_value()) {+ auto postData = std::string(urlRequest->body->begin(), urlRequest->body->end());+ postDataStream = SHCreateMemStream(+ reinterpret_cast<const BYTE*>(postData.data()), static_cast<UINT>(postData.length()));+ }+ if (succeededOrLog(webViewEnv2->CreateWebResourceRequest(+ url.c_str(),+ method.c_str(),+ postDataStream.get(),+ L"",+ &webResourceRequest+ ))) {+ wil::com_ptr<ICoreWebView2HttpRequestHeaders> requestHeaders;+ if (SUCCEEDED(webResourceRequest->get_Headers(&requestHeaders))) {+ if (method.compare(L"GET") != 0) {+ requestHeaders->SetHeader(L"Flutter-InAppWebView-Request-Method", method.c_str());+ }+ if (urlRequest->headers.has_value()) {+ auto& headers = urlRequest->headers.value();+ for (auto const& [key, val] : headers) {+ requestHeaders->SetHeader(utf8_to_wide(key).c_str(), utf8_to_wide(val).c_str());+ }+ }+ }+ failedLog(webView2->NavigateWithWebResourceRequest(webResourceRequest.get()));+ }+ return;+ }+ failedLog(webView->Navigate(url.c_str()));+ }+++ void InAppWebView::loadFile(const std::string& assetFilePath) const+ {+ if (!webView) {+ return;+ }++ WCHAR* buf = new WCHAR[32768];+ GetModuleFileName(NULL, buf, 32768);+ std::filesystem::path exeAbsPath = std::wstring(buf);+ delete[] buf;++ std::filesystem::path flutterAssetPath("data/flutter_assets/" + assetFilePath);+ auto absAssetFilePath = exeAbsPath.parent_path() / flutterAssetPath;++ if (!std::filesystem::exists(absAssetFilePath)) {+ debugLog(absAssetFilePath.native() + L" asset file cannot be found!");+ return;+ }+ failedLog(webView->Navigate(absAssetFilePath.c_str()));+ }++ void InAppWebView::loadData(const std::string& data) const+ {+ if (!webView) {+ return;+ }++ failedLog(webView->NavigateToString(utf8_to_wide(data).c_str()));+ }++ void InAppWebView::reload() const+ {+ if (!webView) {+ return;+ }++ failedLog(webView->Reload());+ }++ void InAppWebView::goBack()+ {+ if (!webView) {+ return;+ }++ failedLog(webView->GoBack());+ }++ bool InAppWebView::canGoBack() const+ {+ BOOL canGoBack_;+ return webView && succeededOrLog(webView->get_CanGoBack(&canGoBack_)) ? canGoBack_ : false;+ }++ void InAppWebView::goForward()+ {+ if (!webView) {+ return;+ }++ failedLog(webView->GoForward());+ }++ bool InAppWebView::canGoForward() const+ {+ BOOL canGoForward_;+ return webView && succeededOrLog(webView->get_CanGoForward(&canGoForward_)) ? canGoForward_ : false;+ }++ void InAppWebView::goBackOrForward(const int64_t& steps)+ {+ getCopyBackForwardList(+ [this, steps](std::unique_ptr<WebHistory> webHistory)+ {+ if (webHistory && webHistory->currentIndex.has_value() && webHistory->list.has_value()) {+ auto currentIndex = webHistory->currentIndex.value();+ auto items = &webHistory->list.value();+ auto nextIndex = currentIndex + steps;+ int64_t size = items->size();+ if (nextIndex >= 0 && nextIndex < size) {+ auto entryId = items->at(nextIndex)->entryId;+ if (entryId.has_value()) {+ failedAndLog(webView->CallDevToolsProtocolMethod(L"Page.navigateToHistoryEntry", utf8_to_wide("{\"entryId\": " + std::to_string(entryId.value()) + "}").c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ failedLog(errorCode);+ return S_OK;+ }+ ).Get()));+ }+ }+ }+ }+ );+ }++ void InAppWebView::canGoBackOrForward(const int64_t& steps, std::function<void(bool)> completionHandler) const+ {+ getCopyBackForwardList(+ [steps, completionHandler](std::unique_ptr<WebHistory> webHistory)+ {+ auto canGoBackOrForward_ = false;+ if (webHistory && webHistory->currentIndex.has_value() && webHistory->list.has_value()) {+ auto currentIndex = webHistory->currentIndex.value();+ auto items = &webHistory->list.value();+ auto nextIndex = currentIndex + steps;+ int64_t size = items->size();+ canGoBackOrForward_ = nextIndex >= 0 && nextIndex < size;+ }++ if (completionHandler) {+ completionHandler(canGoBackOrForward_);+ }+ }+ );+ }++ void InAppWebView::stopLoading() const+ {+ if (!webView) {+ return;+ }++ failedLog(webView->Stop());+ }++ void InAppWebView::getCopyBackForwardList(const std::function<void(std::unique_ptr<WebHistory>)> completionHandler) const+ {+ if (!webView) {+ if (completionHandler) {+ completionHandler(std::make_unique<WebHistory>(std::nullopt, std::nullopt));+ }+ return;+ }++ failedLog(webView->CallDevToolsProtocolMethod(L"Page.getNavigationHistory", L"{}", Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ if (!completionHandler) {+ return S_OK;+ }++ if (errorCode == S_OK) {+ auto historyJson = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson));++ int64_t currentIndex = historyJson.at("currentIndex").is_number_unsigned() ? historyJson.at("currentIndex").get<int64_t>() : 0;+ std::vector<nlohmann::json> entries = historyJson.at("entries").is_array() ? historyJson.at("entries").get<std::vector<nlohmann::json>>() : std::vector<nlohmann::json>{};++ std::vector<std::shared_ptr<WebHistoryItem>> webHistoryItems;+ webHistoryItems.reserve(entries.size());+ int64_t i = 0;+ for (auto const& entry : entries) {+ int64_t offset = i - currentIndex;+ webHistoryItems.push_back(std::make_shared<WebHistoryItem>(+ entry.at("id").is_number_integer() ? entry.at("id").get<int64_t>() : std::optional<int64_t>{},+ i,+ offset,+ entry.at("userTypedURL").is_string() ? entry.at("userTypedURL").get<std::string>() : std::optional<std::string>{},+ entry.at("title").is_string() ? entry.at("title").get<std::string>() : std::optional<std::string>{},+ entry.at("url").is_string() ? entry.at("url").get<std::string>() : std::optional<std::string>{}+ ));+ i++;+ }++ completionHandler(std::make_unique<WebHistory>(currentIndex, webHistoryItems));+ }+ else {+ debugLog(errorCode);+ completionHandler(std::make_unique<WebHistory>(std::nullopt, std::nullopt));+ }++ return S_OK;+ }+ ).Get()));+ }++ void InAppWebView::evaluateJavascript(const std::string& source, const std::shared_ptr<ContentWorld> contentWorld, const std::function<void(std::string)> completionHandler) const+ {+ if (!webView || !userContentController) {+ if (completionHandler) {+ completionHandler("null");+ }+ return;+ }++ userContentController->createContentWorld(contentWorld,+ [=](const int& contextId)+ {+ nlohmann::json parameters = {+ {"expression", source},+ { "returnByValue", true }+ };++ if (contextId >= 0) {+ parameters["contextId"] = contextId;+ }++ auto hr = webView->CallDevToolsProtocolMethod(L"Runtime.evaluate", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this, completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ nlohmann::json result;+ if (succeededOrLog(errorCode)) {+ nlohmann::json json = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson));+ result = json["result"].contains("value") ? json["result"]["value"] : nlohmann::json{};+ if (json.contains("exceptionDetails")) {+ nlohmann::json exceptionDetails = json["exceptionDetails"];+ auto errorMessage = exceptionDetails.contains("exception") && exceptionDetails["exception"].contains("value")+ ? exceptionDetails["exception"]["value"].dump() :+ (result["value"].is_null() ? exceptionDetails["text"].get<std::string>() : result["value"].dump());+ result = nlohmann::json{};+ debugLog(exceptionDetails.dump());+ if (channelDelegate) {+ channelDelegate->onConsoleMessage(errorMessage, 3);+ }+ }+ }+ if (completionHandler) {+ completionHandler(result.dump());+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler("null");+ }+ });+ }++ void InAppWebView::callAsyncJavaScript(const std::string& functionBody, const std::string& argumentsAsJson, const std::shared_ptr<ContentWorld> contentWorld, const std::function<void(std::string)> completionHandler) const+ {+ if (!webView || !userContentController) {+ if (completionHandler) {+ completionHandler("null");+ }+ return;+ }++ userContentController->createContentWorld(contentWorld,+ [=](const int& contextId)+ {+ std::vector<std::string> functionArgumentNamesList;+ std::vector<std::string> functionArgumentValuesList;++ auto jsonVal = nlohmann::json::parse(argumentsAsJson);+ for (auto const& [key, val] : jsonVal.items()) {+ functionArgumentNamesList.push_back(key);+ functionArgumentValuesList.push_back(val.dump());+ }++ auto source = replace_all_copy(CALL_ASYNC_JAVASCRIPT_WRAPPER_JS, VAR_FUNCTION_ARGUMENT_NAMES, join(functionArgumentNamesList, ", "));+ replace_all(source, VAR_FUNCTION_ARGUMENT_VALUES, join(functionArgumentValuesList, ", "));+ replace_all(source, VAR_FUNCTION_BODY, functionBody);++ nlohmann::json parameters = {+ {"expression", source},+ {"awaitPromise", true},+ { "returnByValue", true }+ };++ if (contextId >= 0) {+ parameters["contextId"] = contextId;+ }++ auto hr = webView->CallDevToolsProtocolMethod(L"Runtime.evaluate", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this, completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ nlohmann::json result = {+ {"value", nlohmann::json{}},+ {"error", nlohmann::json{}}+ };+ if (succeededOrLog(errorCode)) {+ nlohmann::json json = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson));+ result["value"] = json["result"].contains("value") ? json["result"]["value"] : nlohmann::json{};+ if (json.contains("exceptionDetails")) {+ nlohmann::json exceptionDetails = json["exceptionDetails"];+ auto errorMessage = exceptionDetails.contains("exception") && exceptionDetails["exception"].contains("value")+ ? exceptionDetails["exception"]["value"].dump() :+ (result["value"].is_null() ? exceptionDetails["text"].get<std::string>() : result["value"].dump());+ result["value"] = nlohmann::json{};+ result["error"] = errorMessage;+ debugLog(exceptionDetails.dump());+ if (channelDelegate) {+ channelDelegate->onConsoleMessage(errorMessage, 3);+ }+ }+ }+ if (completionHandler) {+ completionHandler(result.dump());+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler("null");+ }+ });+ }++ void InAppWebView::addUserScript(const std::shared_ptr<UserScript> userScript) const+ {+ if (!userContentController) {+ return;+ }++ userContentController->addUserOnlyScript(userScript);+ }++ void InAppWebView::removeUserScript(const int64_t index, const std::shared_ptr<UserScript> userScript) const+ {+ if (!userContentController) {+ return;+ }++ userContentController->removeUserOnlyScriptAt(index, userScript->injectionTime);+ }++ void InAppWebView::removeUserScriptsByGroupName(const std::string& groupName) const+ {+ if (!userContentController) {+ return;+ }++ userContentController->removeUserOnlyScriptsByGroupName(groupName);+ }++ void InAppWebView::removeAllUserScripts() const+ {+ if (!userContentController) {+ return;+ }++ userContentController->removeAllUserOnlyScripts();+ }++ void InAppWebView::takeScreenshot(const std::optional<std::shared_ptr<ScreenshotConfiguration>> screenshotConfiguration, const std::function<void(const std::optional<std::string>)> completionHandler) const+ {+ if (!webView) {+ if (completionHandler) {+ completionHandler(std::nullopt);+ }+ return;+ }++ nlohmann::json parameters = {};+ if (screenshotConfiguration.has_value()) {+ auto& scp = screenshotConfiguration.value();+ parameters["format"] = to_lowercase_copy(CompressFormatToString(scp->compressFormat));+ if (scp->compressFormat == CompressFormat::jpeg) {+ parameters["quality"] = scp->quality;+ }+ if (scp->rect.has_value()) {+ auto& rect = scp->rect.value();+ parameters["clip"] = {+ {"x", rect->x},+ {"y", rect->y},+ {"width", rect->width},+ {"height", rect->height},+ {"scale", scaleFactor_}+ };+ }+ }++ auto hr = webView->CallDevToolsProtocolMethod(L"Page.captureScreenshot", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this, completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ std::optional<std::string> result = std::nullopt;+ if (succeededOrLog(errorCode)) {+ nlohmann::json json = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson));+ result = json["data"].get<std::string>();+ }+ if (completionHandler) {+ completionHandler(result);+ }+ return S_OK;+ }+ ).Get());+ if (failedAndLog(hr) && completionHandler) {+ completionHandler(std::nullopt);+ }+ }++ void InAppWebView::setSettings(const std::shared_ptr<InAppWebViewSettings> newSettings, const flutter::EncodableMap& newSettingsMap)+ {+ wil::com_ptr<ICoreWebView2Settings> webView2Settings;+ if (succeededOrLog(webView->get_Settings(&webView2Settings))) {+ if (fl_map_contains_not_null(newSettingsMap, "javaScriptEnabled") && settings->javaScriptEnabled != newSettings->javaScriptEnabled) {+ webView2Settings->put_IsScriptEnabled(newSettings->javaScriptEnabled);+ }++ if (fl_map_contains_not_null(newSettingsMap, "supportZoom") && settings->supportZoom != newSettings->supportZoom) {+ webView2Settings->put_IsZoomControlEnabled(newSettings->supportZoom);+ }++ if (fl_map_contains_not_null(newSettingsMap, "isInspectable") && settings->isInspectable != newSettings->isInspectable) {+ webView2Settings->put_AreDevToolsEnabled(newSettings->isInspectable);+ }++ if (fl_map_contains_not_null(newSettingsMap, "disableContextMenu") && settings->disableContextMenu != newSettings->disableContextMenu) {+ webView2Settings->put_AreDefaultContextMenusEnabled(!newSettings->disableContextMenu);+ }++ wil::com_ptr<ICoreWebView2Settings2> webView2Settings2;+ if (succeededOrLog(webView2Settings->QueryInterface(IID_PPV_ARGS(&webView2Settings2)))) {+ if (fl_map_contains_not_null(newSettingsMap, "userAgent") && !string_equals(settings->userAgent, newSettings->userAgent)) {+ webView2Settings2->put_UserAgent(utf8_to_wide(newSettings->userAgent).c_str());+ }+ }+ }++ wil::com_ptr<ICoreWebView2Controller2> webViewController2;+ if (succeededOrLog(webViewController->QueryInterface(IID_PPV_ARGS(&webViewController2)))) {+ if (fl_map_contains_not_null(newSettingsMap, "transparentBackground") && settings->transparentBackground != newSettings->transparentBackground) {+ BYTE alpha = newSettings->transparentBackground ? 0 : 255;+ webViewController2->put_DefaultBackgroundColor({ alpha, 255, 255, 255 });+ }+ }++ settings = newSettings;+ }++ flutter::EncodableValue InAppWebView::getSettings() const+ {+ if (!settings || !webView) {+ return make_fl_value();+ }++ return settings->getRealSettings(this);+ }++ void InAppWebView::openDevTools() const+ {+ if (!webView) {+ return;+ }++ failedLog(webView->OpenDevToolsWindow());+ }++ void InAppWebView::callDevToolsProtocolMethod(const std::string& methodName, const std::optional<std::string>& parametersAsJson, const std::function<void(const HRESULT& errorCode, const std::optional<std::string>&)> completionHandler) const+ {+ if (!webView) {+ if (completionHandler) {+ completionHandler(S_OK, std::nullopt);+ }+ return;+ }++ auto hr = webView->CallDevToolsProtocolMethod(+ utf8_to_wide(methodName).c_str(),+ !parametersAsJson.has_value() || parametersAsJson.value().empty() ? L"{}" : utf8_to_wide(parametersAsJson.value()).c_str(),+ Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ failedLog(errorCode);+ if (completionHandler) {+ completionHandler(errorCode, wide_to_utf8(returnObjectAsJson));+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler(hr, std::nullopt);+ }+ }++ void InAppWebView::addDevToolsProtocolEventListener(const std::string& eventName)+ {+ if (map_contains(devToolsProtocolEventListener_, eventName)) {+ return;+ }++ wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceiver> eventReceiver;+ if (succeededOrLog(webView->GetDevToolsProtocolEventReceiver(utf8_to_wide(eventName).c_str(), &eventReceiver))) {+ EventRegistrationToken token = {};+ auto hr = eventReceiver->add_DevToolsProtocolEventReceived(+ Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(+ [this, eventName](+ ICoreWebView2* sender,+ ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT+ {+ if (!channelDelegate) {+ return S_OK;+ }++ wil::unique_cotaskmem_string json;+ failedLog(args->get_ParameterObjectAsJson(&json));+ channelDelegate->onDevToolsProtocolEventReceived(eventName, wide_to_utf8(json.get()));++ return S_OK;+ })+ .Get(), &token);+ if (succeededOrLog(hr)) {+ devToolsProtocolEventListener_.insert({ eventName, std::make_pair(std::move(eventReceiver), token) });+ }+ }+ }++ void InAppWebView::removeDevToolsProtocolEventListener(const std::string& eventName)+ {+ if (map_contains(devToolsProtocolEventListener_, eventName)) {+ auto eventReceiver = devToolsProtocolEventListener_.at(eventName).first;+ auto token = devToolsProtocolEventListener_.at(eventName).second;+ eventReceiver->remove_DevToolsProtocolEventReceived(token);+ devToolsProtocolEventListener_.erase(eventName);+ }+ }+++ void InAppWebView::pause() const+ {+ wil::com_ptr<ICoreWebView2_3> webView3;+ if (SUCCEEDED(webView->QueryInterface(IID_PPV_ARGS(&webView3))) && succeededOrLog(webViewController->put_IsVisible(false))) {+ failedLog(webView3->TrySuspend(Callback<ICoreWebView2TrySuspendCompletedHandler>(+ [this](HRESULT errorCode, BOOL isSuccessful) -> HRESULT+ {+ failedLog(errorCode);+ return S_OK;+ })+ .Get()));+ }+ }++ void InAppWebView::resume() const+ {+ wil::com_ptr<ICoreWebView2_3> webView3;+ if (SUCCEEDED(webView->QueryInterface(IID_PPV_ARGS(&webView3))) && succeededOrLog(webViewController->put_IsVisible(true))) {+ failedLog(webView3->Resume());+ }+ }+++ void InAppWebView::getCertificate(const std::function<void(const std::optional<std::unique_ptr<SslCertificate>>)> completionHandler) const+ {+ auto url = getUrl();+ if (!webView || !url.has_value()) {+ if (completionHandler) {+ completionHandler(std::nullopt);+ }+ return;+ }++ nlohmann::json parameters = {+ {"origin", url.value()}+ };++ auto hr = webView->CallDevToolsProtocolMethod(L"Network.getCertificate", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this, completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ std::optional<std::unique_ptr<SslCertificate>> result = std::nullopt;+ if (succeededOrLog(errorCode)) {+ nlohmann::json json = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson));+ if (json.at("tableNames").is_array()) {+ auto tableNames = json.at("tableNames").get<std::vector<std::string>>();+ if (tableNames.size() > 0) {+ result = std::make_unique<SslCertificate>(tableNames.at(0));+ }+ }+ }+ if (completionHandler) {+ completionHandler(std::move(result));+ }+ return S_OK;+ }+ ).Get());+ if (failedAndLog(hr) && completionHandler) {+ completionHandler(std::nullopt);+ }+ }++ // flutter_view+ void InAppWebView::setSurfaceSize(size_t width, size_t height, float scale_factor)+ {+ if (!webViewController) {+ return;+ }++ if (surface_ && width > 0 && height > 0) {+ scaleFactor_ = scale_factor;+ auto scaled_width = width * scale_factor;+ auto scaled_height = height * scale_factor;++ RECT bounds;+ bounds.left = 0;+ bounds.top = 0;+ bounds.right = static_cast<LONG>(scaled_width);+ bounds.bottom = static_cast<LONG>(scaled_height);++ surface_->put_Size({ scaled_width, scaled_height });++ wil::com_ptr<ICoreWebView2Controller3> webViewController3;+ if (SUCCEEDED(webViewController->QueryInterface(IID_PPV_ARGS(&webViewController3)))) {+ webViewController3->put_RasterizationScale(scale_factor);+ }++ if (webViewController->put_Bounds(bounds) != S_OK) {+ std::cerr << "Setting webview bounds failed." << std::endl;+ }++ if (surfaceSizeChangedCallback_) {+ surfaceSizeChangedCallback_(width, height);+ }+ }+ }+++ void InAppWebView::setPosition(size_t x, size_t y, float scale_factor)+ {+ if (!webViewController || !plugin || !plugin->registrar) {+ return;+ }++ if (x >= 0 && y >= 0) {+ scaleFactor_ = scale_factor;+ auto scaled_x = static_cast<int>(x * scale_factor);+ auto scaled_y = static_cast<int>(y * scale_factor);++ auto titleBarHeight = ((GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYFRAME)) * scale_factor) + GetSystemMetrics(SM_CXPADDEDBORDER);+ auto borderWidth = (GetSystemMetrics(SM_CXBORDER) + GetSystemMetrics(SM_CXPADDEDBORDER)) * scale_factor;++ RECT flutterWindowRect;+ HWND flutterWindowHWnd = plugin->registrar->GetView()->GetNativeWindow();+ GetWindowRect(flutterWindowHWnd, &flutterWindowRect);++ HWND webViewHWnd;+ if (succeededOrLog(webViewController->get_ParentWindow(&webViewHWnd))) {+ ::SetWindowPos(webViewHWnd,+ nullptr,+ static_cast<int>(flutterWindowRect.left + scaled_x - borderWidth),+ static_cast<int>(flutterWindowRect.top + scaled_y - titleBarHeight),+ 0, 0,+ SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);+ }+ }+ }+++ void InAppWebView::setCursorPos(double x, double y)+ {+ if (!webViewCompositionController) {+ return;+ }++ POINT point;+ point.x = static_cast<LONG>(x * scaleFactor_);+ point.y = static_cast<LONG>(y * scaleFactor_);+ lastCursorPos_ = point;++ // https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2?view=webview2-1.0.774.44+ webViewCompositionController->SendMouseInput(+ COREWEBVIEW2_MOUSE_EVENT_KIND::COREWEBVIEW2_MOUSE_EVENT_KIND_MOVE,+ virtualKeys_.state(), 0, point);+ }++ void InAppWebView::setPointerUpdate(int32_t pointer,+ InAppWebViewPointerEventKind eventKind, double x,+ double y, double size, double pressure)+ {+ if (!webViewEnv || !webViewCompositionController) {+ return;+ }++ COREWEBVIEW2_POINTER_EVENT_KIND event =+ COREWEBVIEW2_POINTER_EVENT_KIND_UPDATE;+ UINT32 pointerFlags = POINTER_FLAG_NONE;+ switch (eventKind) {+ case InAppWebViewPointerEventKind::Activate:+ event = COREWEBVIEW2_POINTER_EVENT_KIND_ACTIVATE;+ break;+ case InAppWebViewPointerEventKind::Down:+ event = COREWEBVIEW2_POINTER_EVENT_KIND_DOWN;+ pointerFlags =+ POINTER_FLAG_DOWN | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT;+ break;+ case InAppWebViewPointerEventKind::Enter:+ event = COREWEBVIEW2_POINTER_EVENT_KIND_ENTER;+ break;+ case InAppWebViewPointerEventKind::Leave:+ event = COREWEBVIEW2_POINTER_EVENT_KIND_LEAVE;+ break;+ case InAppWebViewPointerEventKind::Up:+ event = COREWEBVIEW2_POINTER_EVENT_KIND_UP;+ pointerFlags = POINTER_FLAG_UP;+ break;+ case InAppWebViewPointerEventKind::Update:+ event = COREWEBVIEW2_POINTER_EVENT_KIND_UPDATE;+ pointerFlags =+ POINTER_FLAG_UPDATE | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT;+ break;+ }++ POINT point;+ point.x = static_cast<LONG>(x * scaleFactor_);+ point.y = static_cast<LONG>(y * scaleFactor_);++ RECT rect;+ rect.left = point.x - 2;+ rect.right = point.x + 2;+ rect.top = point.y - 2;+ rect.bottom = point.y + 2;++ wil::com_ptr<ICoreWebView2Environment3> webViewEnv3;+ if (SUCCEEDED(webViewEnv->QueryInterface(IID_PPV_ARGS(&webViewEnv3)))) {+ wil::com_ptr<ICoreWebView2PointerInfo> pInfo;+ if (SUCCEEDED(webViewEnv3->CreateCoreWebView2PointerInfo(&pInfo))) {+ if (pInfo) {+ pInfo->put_PointerId(pointer);+ pInfo->put_PointerKind(PT_TOUCH);+ pInfo->put_PointerFlags(pointerFlags);+ pInfo->put_TouchFlags(TOUCH_FLAG_NONE);+ pInfo->put_TouchMask(TOUCH_MASK_CONTACTAREA | TOUCH_MASK_PRESSURE);+ pInfo->put_TouchPressure(+ std::clamp((UINT32)(pressure == 0.0 ? 1024 : 1024 * pressure),+ (UINT32)0, (UINT32)1024));+ pInfo->put_PixelLocationRaw(point);+ pInfo->put_TouchContactRaw(rect);+ webViewCompositionController->SendPointerInput(event, pInfo.get());+ }+ }+ }+ }++ void InAppWebView::setPointerButtonState(InAppWebViewPointerButton button, bool is_down)+ {+ if (!webViewCompositionController) {+ return;+ }++ COREWEBVIEW2_MOUSE_EVENT_KIND kind;+ switch (button) {+ case InAppWebViewPointerButton::Primary:+ virtualKeys_.setIsLeftButtonDown(is_down);+ kind = is_down ? COREWEBVIEW2_MOUSE_EVENT_KIND_LEFT_BUTTON_DOWN+ : COREWEBVIEW2_MOUSE_EVENT_KIND_LEFT_BUTTON_UP;+ break;+ case InAppWebViewPointerButton::Secondary:+ virtualKeys_.setIsRightButtonDown(is_down);+ kind = is_down ? COREWEBVIEW2_MOUSE_EVENT_KIND_RIGHT_BUTTON_DOWN+ : COREWEBVIEW2_MOUSE_EVENT_KIND_RIGHT_BUTTON_UP;+ break;+ case InAppWebViewPointerButton::Tertiary:+ virtualKeys_.setIsMiddleButtonDown(is_down);+ kind = is_down ? COREWEBVIEW2_MOUSE_EVENT_KIND_MIDDLE_BUTTON_DOWN+ : COREWEBVIEW2_MOUSE_EVENT_KIND_MIDDLE_BUTTON_UP;+ break;+ default:+ kind = static_cast<COREWEBVIEW2_MOUSE_EVENT_KIND>(0);+ }++ webViewCompositionController->SendMouseInput(kind, virtualKeys_.state(), 0,+ lastCursorPos_);+ }++ void InAppWebView::sendScroll(double delta, bool horizontal)+ {+ if (!webViewCompositionController) {+ return;+ }++ // delta * 6 gives me a multiple of WHEEL_DELTA (120)+ constexpr auto kScrollMultiplier = 6;++ auto offset = static_cast<short>(delta * kScrollMultiplier);++ if (horizontal) {+ webViewCompositionController->SendMouseInput(+ COREWEBVIEW2_MOUSE_EVENT_KIND_HORIZONTAL_WHEEL, virtualKeys_.state(),+ offset, lastCursorPos_);+ }+ else {+ webViewCompositionController->SendMouseInput(COREWEBVIEW2_MOUSE_EVENT_KIND_WHEEL,+ virtualKeys_.state(), offset,+ lastCursorPos_);+ }+ }++ void InAppWebView::setScrollDelta(double delta_x, double delta_y)+ {+ if (!webViewCompositionController) {+ return;+ }++ if (delta_x != 0.0) {+ sendScroll(delta_x, true);+ }+ if (delta_y != 0.0) {+ sendScroll(delta_y, false);+ }+ }++ bool InAppWebView::createSurface(const HWND parentWindow,+ winrt::com_ptr<ABI::Windows::UI::Composition::ICompositor> compositor)+ {+ if (!webViewCompositionController || !webViewController) {+ return false;+ }++ winrt::com_ptr<ABI::Windows::UI::Composition::IContainerVisual> root;+ if (FAILED(compositor->CreateContainerVisual(root.put()))) {+ return false;+ }+ surface_ = root.try_as<ABI::Windows::UI::Composition::IVisual>();+ assert(surface_);++ // initial size. doesn't matter as we resize the surface anyway.+ surface_->put_Size({ 1280, 720 });+ surface_->put_IsVisible(true);++ winrt::com_ptr<ABI::Windows::UI::Composition::IVisual> webview_visual;+ compositor->CreateContainerVisual(+ reinterpret_cast<ABI::Windows::UI::Composition::IContainerVisual**>(+ webview_visual.put()));++ auto webview_visual2 =+ webview_visual.try_as<ABI::Windows::UI::Composition::IVisual2>();+ if (webview_visual2) {+ webview_visual2->put_RelativeSizeAdjustment({ 1.0f, 1.0f });+ }++ winrt::com_ptr<ABI::Windows::UI::Composition::IVisualCollection> children;+ root->get_Children(children.put());+ children->InsertAtTop(webview_visual.get());+ webViewCompositionController->put_RootVisualTarget(webview_visual2.get());++ webViewController->put_IsVisible(true);++ return true;+ }++ bool InAppWebView::isSslError(const COREWEBVIEW2_WEB_ERROR_STATUS& webErrorStatus)+ {+ return webErrorStatus >= COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT && webErrorStatus <= COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_IS_INVALID;+ }++ InAppWebView::~InAppWebView()+ {+ debugLog("dealloc InAppWebView");+ userContentController = nullptr;+ if (webView) {+ failedLog(webView->Stop());+ }+ HWND parentWindow = nullptr;+ if (webViewCompositionController && webViewController && succeededOrLog(webViewController->get_ParentWindow(&parentWindow))) {+ // if it's an InAppWebView (so webViewCompositionController will be not a nullptr!),+ // then destroy the Window created with it+ DestroyWindow(parentWindow);+ }+ if (webViewController) {+ failedLog(webViewController->Close());+ }+ navigationActions_.clear();+ inAppBrowser = nullptr;+ plugin = nullptr;+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview.h b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview.hnew file mode 100644index 00000000..6c3c3a73--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview.h@@ -0,0 +1,205 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_H_++#include <functional>+#include <WebView2.h>+#include <wil/com.h>+#include <windows.ui.composition.desktop.h>+#include <windows.ui.composition.h>+#include <winrt/base.h>++#include "../flutter_inappwebview_windows_plugin.h"+#include "../plugin_scripts_js/plugin_scripts_util.h"+#include "../types/content_world.h"+#include "../types/navigation_action.h"+#include "../types/screenshot_configuration.h"+#include "../types/ssl_certificate.h"+#include "../types/url_request.h"+#include "../types/web_history.h"+#include "../webview_environment/webview_environment.h"+#include "in_app_webview_settings.h"+#include "user_content_controller.h"+#include "webview_channel_delegate.h"++#include <WebView2EnvironmentOptions.h>++namespace flutter_inappwebview_plugin+{+ class InAppBrowser;++ using namespace Microsoft::WRL;++ // custom_platform_view+ enum class InAppWebViewPointerButton { None, Primary, Secondary, Tertiary };+ enum class InAppWebViewPointerEventKind { Activate, Down, Enter, Leave, Up, Update };+ typedef std::function<void(size_t width, size_t height)>+ SurfaceSizeChangedCallback;+ typedef std::function<void(const HCURSOR)> CursorChangedCallback;+ struct VirtualKeyState {+ public:+ inline void setIsLeftButtonDown(bool is_down)+ {+ set(COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS::+ COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS_LEFT_BUTTON,+ is_down);+ }++ inline void setIsRightButtonDown(bool is_down)+ {+ set(COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS::+ COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS_RIGHT_BUTTON,+ is_down);+ }++ inline void setIsMiddleButtonDown(bool is_down)+ {+ set(COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS::+ COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS_MIDDLE_BUTTON,+ is_down);+ }++ inline COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS state() const { return state_; }++ private:+ COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS state_ =+ COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS::+ COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS_NONE;++ inline void set(COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS key, bool flag)+ {+ if (flag) {+ state_ |= key;+ }+ else {+ state_ &= ~key;+ }+ }+ };++ const std::string CALL_ASYNC_JAVASCRIPT_WRAPPER_JS = "(async function(" + VAR_FUNCTION_ARGUMENT_NAMES + ") { \+ " + VAR_FUNCTION_BODY + " \+ })(" + VAR_FUNCTION_ARGUMENT_VALUES + ");";++ struct InAppWebViewCreationParams {+ const std::variant<std::string, int64_t> id;+ const std::shared_ptr<InAppWebViewSettings> initialSettings;+ const std::optional<std::vector<std::shared_ptr<UserScript>>> initialUserScripts;+ };++ class InAppWebView+ {+ public:+ static inline const std::string METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_inappwebview_";++ const FlutterInappwebviewWindowsPlugin* plugin;+ std::variant<std::string, int64_t> id;+ wil::com_ptr<ICoreWebView2Environment> webViewEnv;+ wil::com_ptr<ICoreWebView2Controller> webViewController;+ wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController;+ wil::com_ptr<ICoreWebView2> webView;+ std::unique_ptr<WebViewChannelDelegate> channelDelegate;+ std::shared_ptr<InAppWebViewSettings> settings;+ InAppBrowser* inAppBrowser = nullptr;+ std::unique_ptr<UserContentController> userContentController;++ InAppWebView(const FlutterInappwebviewWindowsPlugin* plugin, const InAppWebViewCreationParams& params, const HWND parentWindow,+ wil::com_ptr<ICoreWebView2Environment> webViewEnv,+ wil::com_ptr<ICoreWebView2Controller> webViewController,+ wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController);+ InAppWebView(InAppBrowser* inAppBrowser, const FlutterInappwebviewWindowsPlugin* plugin, const InAppWebViewCreationParams& params, const HWND parentWindow,+ wil::com_ptr<ICoreWebView2Environment> webViewEnv,+ wil::com_ptr<ICoreWebView2Controller> webViewController,+ wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController);+ ~InAppWebView();++ static void createInAppWebViewEnv(const HWND parentWindow, const bool& willBeSurface, WebViewEnvironment* webViewEnvironment, const std::shared_ptr<InAppWebViewSettings> initialSettings, std::function<void(wil::com_ptr<ICoreWebView2Environment> webViewEnv,+ wil::com_ptr<ICoreWebView2Controller> webViewController,+ wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController)> completionHandler);++ // custom_platform_view+ ABI::Windows::UI::Composition::IVisual* const surface()+ {+ return surface_.get();+ }+ void setSurfaceSize(size_t width, size_t height, float scale_factor);+ void setPosition(size_t x, size_t y, float scale_factor);+ void setCursorPos(double x, double y);+ void setPointerUpdate(int32_t pointer, InAppWebViewPointerEventKind eventKind,+ double x, double y, double size, double pressure);+ void setPointerButtonState(InAppWebViewPointerButton button, bool isDown);+ void sendScroll(double offset, bool horizontal);+ void setScrollDelta(double delta_x, double delta_y);+ void onSurfaceSizeChanged(SurfaceSizeChangedCallback callback)+ {+ surfaceSizeChangedCallback_ = std::move(callback);+ }+ void onCursorChanged(CursorChangedCallback callback)+ {+ cursorChangedCallback_ = std::move(callback);+ }+ bool createSurface(const HWND parentWindow,+ winrt::com_ptr<ABI::Windows::UI::Composition::ICompositor> compositor);++ void initChannel(const std::optional<std::variant<std::string, int64_t>> viewId, const std::optional<std::string> channelName);+ void prepare(const InAppWebViewCreationParams& params);+ std::optional<std::string> getUrl() const;+ std::optional<std::string> getTitle() const;+ void loadUrl(const std::shared_ptr<URLRequest> urlRequest) const;+ void loadFile(const std::string& assetFilePath) const;+ void loadData(const std::string& data) const;+ void reload() const;+ void goBack();+ bool canGoBack() const;+ void goForward();+ bool canGoForward() const;+ void goBackOrForward(const int64_t& steps);+ void canGoBackOrForward(const int64_t& steps, std::function<void(bool)> completionHandler) const;+ bool isLoading() const+ {+ return isLoading_;+ }+ void stopLoading() const;+ void evaluateJavascript(const std::string& source, const std::shared_ptr<ContentWorld> contentWorld, const std::function<void(std::string)> completionHandler) const;+ void callAsyncJavaScript(const std::string& functionBody, const std::string& argumentsAsJson, const std::shared_ptr<ContentWorld> contentWorld, const std::function<void(std::string)> completionHandler) const;+ void getCopyBackForwardList(const std::function<void(std::unique_ptr<WebHistory>)> completionHandler) const;+ void addUserScript(const std::shared_ptr<UserScript> userScript) const;+ void removeUserScript(const int64_t index, const std::shared_ptr<UserScript> userScript) const;+ void removeUserScriptsByGroupName(const std::string& groupName) const;+ void removeAllUserScripts() const;+ void takeScreenshot(const std::optional<std::shared_ptr<ScreenshotConfiguration>> screenshotConfiguration, const std::function<void(const std::optional<std::string>)> completionHandler) const;+ void setSettings(const std::shared_ptr<InAppWebViewSettings> newSettings, const flutter::EncodableMap& newSettingsMap);+ flutter::EncodableValue getSettings() const;+ void openDevTools() const;+ void callDevToolsProtocolMethod(const std::string& methodName, const std::optional<std::string>& parametersAsJson, const std::function<void(const HRESULT& errorCode, const std::optional<std::string>&)> completionHandler) const;+ void addDevToolsProtocolEventListener(const std::string& eventName);+ void removeDevToolsProtocolEventListener(const std::string& eventName);+ void pause() const;+ void resume() const;+ void getCertificate(const std::function<void(const std::optional<std::unique_ptr<SslCertificate>>)> completionHandler) const;++ std::string pageFrameId() const+ {+ return pageFrameId_;+ }++ static bool isSslError(const COREWEBVIEW2_WEB_ERROR_STATUS& webErrorStatus);+ private:+ // custom_platform_view+ winrt::com_ptr<ABI::Windows::UI::Composition::IVisual> surface_;+ SurfaceSizeChangedCallback surfaceSizeChangedCallback_;+ CursorChangedCallback cursorChangedCallback_;+ float scaleFactor_ = 1.0;+ POINT lastCursorPos_ = { 0, 0 };+ VirtualKeyState virtualKeys_;++ std::map<UINT64, std::shared_ptr<NavigationAction>> navigationActions_ = {};+ std::shared_ptr<NavigationAction> lastNavigationAction_;+ bool isLoading_ = false;+ std::string pageFrameId_;+ std::map<std::string, std::pair<wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceiver>, EventRegistrationToken>> devToolsProtocolEventListener_ = {};++ void registerEventHandlers();+ void registerSurfaceEventHandlers();+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_manager.cpp b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_manager.cppnew file mode 100644index 00000000..5f025c67--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_manager.cpp@@ -0,0 +1,247 @@+#include <DispatcherQueue.h>+#include <flutter/method_channel.h>+#include <flutter/standard_method_codec.h>+#include <shlobj.h>+#include <windows.graphics.capture.h>++#include "../in_app_webview/in_app_webview_settings.h"+#include "../types/url_request.h"+#include "../types/user_script.h"+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "../utils/string.h"+#include "../utils/vector.h"+#include "../webview_environment/webview_environment_manager.h"+#include "in_app_webview_manager.h"++namespace flutter_inappwebview_plugin+{+ InAppWebViewManager::InAppWebViewManager(const FlutterInappwebviewWindowsPlugin* plugin)+ : plugin(plugin),+ ChannelDelegate(plugin->registrar->messenger(), InAppWebViewManager::METHOD_CHANNEL_NAME)+ {+ if (!rohelper_) {+ rohelper_ = std::make_unique<rx::RoHelper>(RO_INIT_SINGLETHREADED);++ if (rohelper_->WinRtAvailable()) {+ DispatcherQueueOptions options{ sizeof(DispatcherQueueOptions),+ DQTYPE_THREAD_CURRENT, DQTAT_COM_STA };++ if (FAILED(rohelper_->CreateDispatcherQueueController(+ options, dispatcher_queue_controller_.put()))) {+ std::cerr << "Creating DispatcherQueueController failed." << std::endl;+ return;+ }++ if (!isGraphicsCaptureSessionSupported()) {+ std::cerr << "Windows::Graphics::Capture::GraphicsCaptureSession is not "+ "supported."+ << std::endl;+ return;+ }++ graphics_context_ = std::make_unique<GraphicsContext>(rohelper_.get());+ compositor_ = graphics_context_->CreateCompositor();+ valid_ = graphics_context_->IsValid();+ }+ }++ windowClass_.lpszClassName = CustomPlatformView::CLASS_NAME;+ windowClass_.lpfnWndProc = &DefWindowProc;++ RegisterClass(&windowClass_);+ }++ void InAppWebViewManager::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ auto* arguments = std::get_if<flutter::EncodableMap>(method_call.arguments());+ auto& methodName = method_call.method_name();++ if (string_equals(methodName, "createInAppWebView")) {+ if (isSupported()) {+ createInAppWebView(arguments, std::move(result));+ }+ else {+ result->Error("0", "Creating an InAppWebView instance is not supported! Graphics Context is not valid!");+ }+ }+ else if (string_equals(methodName, "dispose")) {+ auto id = get_fl_map_value<int64_t>(*arguments, "id");+ if (map_contains(webViews, (uint64_t)id)) {+ auto platformView = webViews.at(id).get();+ if (platformView) {+ platformView->UnregisterMethodCallHandler();+ }+ webViews.erase(id);+ }+ result->Success();+ }+ else if (string_equals(methodName, "disposeKeepAlive")) {+ auto keepAliveId = get_fl_map_value<std::string>(*arguments, "keepAliveId");+ disposeKeepAlive(keepAliveId);+ result->Success();+ }+ else {+ result->NotImplemented();+ }+ }++ void InAppWebViewManager::createInAppWebView(const flutter::EncodableMap* arguments, std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));++ if (!plugin) {+ result_->Error("0", "Cannot create the InAppWebView instance!");+ return;+ }++ auto settingsMap = get_fl_map_value<flutter::EncodableMap>(*arguments, "initialSettings");+ auto urlRequestMap = get_optional_fl_map_value<flutter::EncodableMap>(*arguments, "initialUrlRequest");+ auto initialFile = get_optional_fl_map_value<std::string>(*arguments, "initialFile");+ auto initialDataMap = get_optional_fl_map_value<flutter::EncodableMap>(*arguments, "initialData");+ auto initialUserScriptList = get_optional_fl_map_value<flutter::EncodableList>(*arguments, "initialUserScripts");+ auto webViewEnvironmentId = get_optional_fl_map_value<std::string>(*arguments, "webViewEnvironmentId");+ auto keepAliveId = get_optional_fl_map_value<std::string>(*arguments, "keepAliveId");+ auto windowId = get_optional_fl_map_value<int64_t>(*arguments, "windowId");++ RECT bounds;+ GetClientRect(plugin->registrar->GetView()->GetNativeWindow(), &bounds);++ auto hwnd = CreateWindowEx(0, windowClass_.lpszClassName, L"", 0, 0,+ 0, bounds.right - bounds.left, bounds.bottom - bounds.top,+ plugin->registrar->GetView()->GetNativeWindow(),+ nullptr,+ windowClass_.hInstance, nullptr);++ if (keepAliveId.has_value() && map_contains(keepAliveWebViews, keepAliveId.value())) {+ auto webView = std::move(keepAliveWebViews.at(keepAliveId.value())->view);+ keepAliveWebViews.erase(keepAliveId.value());+ auto customPlatformView = std::make_unique<CustomPlatformView>(plugin->registrar->messenger(),+ plugin->registrar->texture_registrar(),+ graphics_context(),+ hwnd,+ std::move(webView));+ auto textureId = customPlatformView->texture_id();+ keepAliveWebViews.insert({ keepAliveId.value(), std::move(customPlatformView) });+ result_->Success(textureId);+ return;+ }++ auto webViewEnvironment = webViewEnvironmentId.has_value() && map_contains(plugin->webViewEnvironmentManager->webViewEnvironments, webViewEnvironmentId.value())+ ? plugin->webViewEnvironmentManager->webViewEnvironments.at(webViewEnvironmentId.value()).get() : nullptr;++ auto initialSettings = std::make_shared<InAppWebViewSettings>(settingsMap);++ InAppWebView::createInAppWebViewEnv(hwnd, true, webViewEnvironment, initialSettings,+ [=](wil::com_ptr<ICoreWebView2Environment> webViewEnv,+ wil::com_ptr<ICoreWebView2Controller> webViewController,+ wil::com_ptr<ICoreWebView2CompositionController> webViewCompositionController)+ {+ if (plugin && webViewEnv && webViewController && webViewCompositionController) {+ std::optional<std::vector<std::shared_ptr<UserScript>>> initialUserScripts = initialUserScriptList.has_value() ?+ functional_map(initialUserScriptList.value(), [](const flutter::EncodableValue& map) { return std::make_shared<UserScript>(std::get<flutter::EncodableMap>(map)); }) :+ std::optional<std::vector<std::shared_ptr<UserScript>>>{};++ InAppWebViewCreationParams params = {+ "",+ std::move(initialSettings),+ initialUserScripts+ };++ auto inAppWebView = std::make_unique<InAppWebView>(plugin, params, hwnd, std::move(webViewEnv), std::move(webViewController), std::move(webViewCompositionController));++ std::optional<std::shared_ptr<URLRequest>> urlRequest = urlRequestMap.has_value() ? std::make_shared<URLRequest>(urlRequestMap.value()) : std::optional<std::shared_ptr<URLRequest>>{};+ if (urlRequest.has_value()) {+ inAppWebView->loadUrl(urlRequest.value());+ }+ else if (initialFile.has_value()) {+ inAppWebView->loadFile(initialFile.value());+ }+ else if (initialDataMap.has_value()) {+ inAppWebView->loadData(get_fl_map_value<std::string>(initialDataMap.value(), "data"));+ }++ if (windowId.has_value() && map_contains(windowWebViews, windowId.value())) {+ auto windowWebViewArgs = windowWebViews.at(windowId.value()).get();+ windowWebViewArgs->args->put_NewWindow(inAppWebView->webView.get());+ windowWebViewArgs->args->put_Handled(TRUE);+ windowWebViewArgs->deferral->Complete();+ windowWebViews.erase(windowId.value());+ }++ auto customPlatformView = std::make_unique<CustomPlatformView>(plugin->registrar->messenger(),+ plugin->registrar->texture_registrar(),+ graphics_context(),+ hwnd,+ std::move(inAppWebView));++ auto textureId = customPlatformView->texture_id();++ if (keepAliveId.has_value()) {+ customPlatformView->view->initChannel(keepAliveId.value(), std::nullopt);+ keepAliveWebViews.insert({ keepAliveId.value(), std::move(customPlatformView) });+ }+ else {+ customPlatformView->view->initChannel(textureId, std::nullopt);+ webViews.insert({ textureId, std::move(customPlatformView) });+ }+ result_->Success(textureId);+ }+ else {+ result_->Error("0", "Cannot create the InAppWebView instance!");+ }+ }+ );+ }++ void InAppWebViewManager::disposeKeepAlive(const std::string& keepAliveId)+ {+ if (map_contains(keepAliveWebViews, keepAliveId)) {+ auto platformView = keepAliveWebViews.at(keepAliveId).get();+ if (platformView) {+ platformView->UnregisterMethodCallHandler();+ }+ keepAliveWebViews.erase(keepAliveId);+ }+ }++ bool InAppWebViewManager::isGraphicsCaptureSessionSupported()+ {+ HSTRING className;+ HSTRING_HEADER classNameHeader;++ if (FAILED(rohelper_->GetStringReference(+ RuntimeClass_Windows_Graphics_Capture_GraphicsCaptureSession,+ &className, &classNameHeader))) {+ return false;+ }++ ABI::Windows::Graphics::Capture::IGraphicsCaptureSessionStatics*+ capture_session_statics;+ if (FAILED(rohelper_->GetActivationFactory(+ className,+ __uuidof(+ ABI::Windows::Graphics::Capture::IGraphicsCaptureSessionStatics),+ (void**)&capture_session_statics))) {+ return false;+ }++ boolean is_supported = false;+ if (FAILED(capture_session_statics->IsSupported(&is_supported))) {+ return false;+ }++ return !!is_supported;+ }++ InAppWebViewManager::~InAppWebViewManager()+ {+ debugLog("dealloc InAppWebViewManager");+ webViews.clear();+ keepAliveWebViews.clear();+ windowWebViews.clear();+ UnregisterClass(windowClass_.lpszClassName, nullptr);+ plugin = nullptr;+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_manager.h b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_manager.hnew file mode 100644index 00000000..f66d649d--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_manager.h@@ -0,0 +1,64 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_MANAGER_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_MANAGER_H_++#include <flutter/method_channel.h>+#include <flutter/standard_message_codec.h>+#include <map>+#include <string>+#include <variant>+#include <wil/com.h>+#include <winrt/base.h>++#include "../custom_platform_view/custom_platform_view.h"+#include "../custom_platform_view/graphics_context.h"+#include "../custom_platform_view/util/rohelper.h"+#include "../flutter_inappwebview_windows_plugin.h"+#include "../types/channel_delegate.h"+#include "../types/new_window_requested_args.h"+#include "windows.ui.composition.h"++namespace flutter_inappwebview_plugin+{+ class InAppWebViewManager : public ChannelDelegate+ {+ public:+ static inline const std::string METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_manager";++ const FlutterInappwebviewWindowsPlugin* plugin;+ std::map<uint64_t, std::unique_ptr<CustomPlatformView>> webViews;+ std::map<std::string, std::unique_ptr<CustomPlatformView>> keepAliveWebViews;+ std::map<int64_t, std::unique_ptr<NewWindowRequestedArgs>> windowWebViews;+ int64_t windowAutoincrementId = 0;++ bool isSupported() const { return valid_; }+ bool isGraphicsCaptureSessionSupported();+ GraphicsContext* graphics_context() const+ {+ return graphics_context_.get();+ };+ rx::RoHelper* rohelper() const { return rohelper_.get(); }+ winrt::com_ptr<ABI::Windows::UI::Composition::ICompositor> compositor() const+ {+ return compositor_;+ }++ InAppWebViewManager(const FlutterInappwebviewWindowsPlugin* plugin);+ ~InAppWebViewManager();++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);++ void createInAppWebView(const flutter::EncodableMap* arguments, std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);+ void disposeKeepAlive(const std::string& keepAliveId);+ private:+ inline static std::shared_ptr<rx::RoHelper> rohelper_ = nullptr;+ inline static winrt::com_ptr<ABI::Windows::System::IDispatcherQueueController>+ dispatcher_queue_controller_ = nullptr;+ inline static std::unique_ptr<GraphicsContext> graphics_context_ = nullptr;+ inline static winrt::com_ptr<ABI::Windows::UI::Composition::ICompositor> compositor_ = nullptr;+ WNDCLASS windowClass_ = {};+ inline static bool valid_ = false;+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_MANAGER_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_settings.cpp b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_settings.cppnew file mode 100644index 00000000..387c919d--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_settings.cpp@@ -0,0 +1,87 @@+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "in_app_webview.h"+#include "in_app_webview_settings.h"++#include <WebView2.h>+#include <wil/com.h>++namespace flutter_inappwebview_plugin+{+ using namespace Microsoft::WRL;++ InAppWebViewSettings::InAppWebViewSettings() {};++ InAppWebViewSettings::InAppWebViewSettings(const flutter::EncodableMap& encodableMap)+ {+ useShouldOverrideUrlLoading = get_fl_map_value(encodableMap, "useShouldOverrideUrlLoading", useShouldOverrideUrlLoading);+ useOnLoadResource = get_fl_map_value(encodableMap, "useOnLoadResource", useOnLoadResource);+ useOnDownloadStart = get_fl_map_value(encodableMap, "useOnDownloadStart", useOnDownloadStart);+ useShouldInterceptRequest = get_fl_map_value(encodableMap, "useShouldInterceptRequest", useShouldInterceptRequest);+ userAgent = get_fl_map_value(encodableMap, "userAgent", userAgent);+ javaScriptEnabled = get_fl_map_value(encodableMap, "javaScriptEnabled", javaScriptEnabled);+ transparentBackground = get_fl_map_value(encodableMap, "transparentBackground", transparentBackground);+ supportZoom = get_fl_map_value(encodableMap, "supportZoom", supportZoom);+ isInspectable = get_fl_map_value(encodableMap, "isInspectable", isInspectable);+ disableContextMenu = get_fl_map_value(encodableMap, "disableContextMenu", disableContextMenu);+ incognito = get_fl_map_value(encodableMap, "incognito", incognito);+ }++ flutter::EncodableMap InAppWebViewSettings::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"useShouldOverrideUrlLoading", useShouldOverrideUrlLoading},+ {"useOnLoadResource", useOnLoadResource},+ {"useOnDownloadStart", useOnDownloadStart},+ {"useShouldInterceptRequest", useShouldInterceptRequest},+ {"userAgent", userAgent},+ {"javaScriptEnabled", javaScriptEnabled},+ {"transparentBackground", transparentBackground},+ {"supportZoom", supportZoom},+ {"isInspectable", isInspectable},+ {"disableContextMenu", disableContextMenu},+ {"incognito", incognito},+ };+ }++ flutter::EncodableMap InAppWebViewSettings::getRealSettings(const InAppWebView* inAppWebView) const+ {+ auto settingsMap = toEncodableMap();+ if (inAppWebView && inAppWebView->webView) {+ auto webView = inAppWebView->webView;+ wil::com_ptr<ICoreWebView2Settings> settings;+ if (succeededOrLog(webView->get_Settings(&settings))) {+ BOOL realJavaScriptEnabled;+ if (SUCCEEDED(settings->get_IsScriptEnabled(&realJavaScriptEnabled))) {+ settingsMap["javaScriptEnabled"] = (bool)realJavaScriptEnabled;+ }+ BOOL realSupportZoom;+ if (SUCCEEDED(settings->get_IsZoomControlEnabled(&realSupportZoom))) {+ settingsMap["supportZoom"] = (bool)realSupportZoom;+ }+ BOOL realIsInspectable;+ if (SUCCEEDED(settings->get_AreDevToolsEnabled(&realIsInspectable))) {+ settingsMap["isInspectable"] = (bool)realIsInspectable;+ }+ BOOL areDefaultContextMenusEnabled;+ if (SUCCEEDED(settings->get_AreDefaultContextMenusEnabled(&areDefaultContextMenusEnabled))) {+ settingsMap["disableContextMenu"] = !(bool)areDefaultContextMenusEnabled;+ }++ wil::com_ptr<ICoreWebView2Settings2> settings2;+ if (SUCCEEDED(settings->QueryInterface(IID_PPV_ARGS(&settings2)))) {+ wil::unique_cotaskmem_string realUserAgent;+ if (SUCCEEDED(settings2->get_UserAgent(&realUserAgent))) {+ settingsMap["userAgent"] = wide_to_utf8(realUserAgent.get());+ }+ }+ }+ }+ return settingsMap;+ }++ InAppWebViewSettings::~InAppWebViewSettings()+ {+ debugLog("dealloc InAppWebViewSettings");+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_settings.h b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_settings.hnew file mode 100644index 00000000..92c9db08--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/in_app_webview_settings.h@@ -0,0 +1,33 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_SETTINGS_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_SETTINGS_H_++#include <string>++namespace flutter_inappwebview_plugin+{+ class InAppWebView;++ class InAppWebViewSettings+ {+ public:+ bool useShouldOverrideUrlLoading = false;+ bool useOnLoadResource = false;+ bool useOnDownloadStart = false;+ bool useShouldInterceptRequest = false;+ std::string userAgent;+ bool javaScriptEnabled = true;+ bool transparentBackground = false;+ bool supportZoom = true;+ bool isInspectable = true;+ bool disableContextMenu = false;+ bool incognito = false;++ InAppWebViewSettings();+ InAppWebViewSettings(const flutter::EncodableMap& encodableMap);+ ~InAppWebViewSettings();++ flutter::EncodableMap toEncodableMap() const;+ flutter::EncodableMap getRealSettings(const InAppWebView* inAppWebView) const;+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_SETTINGS_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/user_content_controller.cpp b/packages/flutter_inappwebview_windows/windows/in_app_webview/user_content_controller.cppnew file mode 100644index 00000000..9cbe2761--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/user_content_controller.cpp@@ -0,0 +1,433 @@+#include <nlohmann/json.hpp>+#include <wil/wrl.h>++#include "../utils/log.h"+#include "../utils/string.h"+#include "../utils/vector.h"+#include "in_app_webview.h"+#include "user_content_controller.h"++namespace flutter_inappwebview_plugin+{+ using namespace Microsoft::WRL;++ UserContentController::UserContentController(InAppWebView* webView)+ : webView_(webView)+ {}++ void UserContentController::registerEventHandlers()+ {+ if (!webView_ || !(webView_->webView)) {+ return;+ }++ wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceiver> executionContextCreated;+ if (succeededOrLog(webView_->webView->GetDevToolsProtocolEventReceiver(L"Runtime.executionContextCreated", &executionContextCreated))) {+ auto hr = executionContextCreated->add_DevToolsProtocolEventReceived(+ Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(+ [this](+ ICoreWebView2* sender,+ ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT+ {+ wil::unique_cotaskmem_string json;+ if (succeededOrLog(args->get_ParameterObjectAsJson(&json))) {+ nlohmann::json context = nlohmann::json::parse(wide_to_utf8(json.get()))["context"];+ auto id = context["id"].get<int>();+ auto name = context["name"].get<std::string>();+ nlohmann::json auxData = context["auxData"];+ auto isDefault = auxData["isDefault"].get<bool>();+ auto frameId = auxData["frameId"].get<std::string>();+ if (string_equals(webView_->pageFrameId(), frameId)) {+ if (isDefault) {+ contentWorlds_.insert_or_assign(ContentWorld::page()->name, id);+ }+ else {+ contentWorlds_.insert_or_assign(name, id);+ addPluginScriptsIfRequired(std::make_shared<ContentWorld>(name));+ }+ }+ }++ return S_OK;+ })+ .Get(), nullptr);++ failedLog(hr);+ }++ /*+ wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceiver> executionContextDestroyed;+ if (succeededOrLog(webView_->webView->GetDevToolsProtocolEventReceiver(L"Runtime.executionContextDestroyed ", &executionContextDestroyed))) {+ failedLog(executionContextDestroyed->add_DevToolsProtocolEventReceived(+ Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(+ [this](+ ICoreWebView2* sender,+ ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT+ {+ wil::unique_cotaskmem_string json;+ if (succeededOrLog(args->get_ParameterObjectAsJson(&json))) {+ debugLog("executionContextDestroyed: " + wide_to_utf8(json.get()));+ }++ return S_OK;+ })+ .Get(), nullptr));+ }+ */+ }++ std::vector<std::shared_ptr<UserScript>> UserContentController::getUserOnlyScriptsAt(const UserScriptInjectionTime& injectionTime) const+ {+ return userOnlyScripts_.at(injectionTime);+ }++ void UserContentController::addUserOnlyScript(std::shared_ptr<UserScript> userScript)+ {+ if (!userScript) {+ return;+ }++ addPluginScriptsIfRequired(userScript->contentWorld);+ addScriptToWebView(userScript, nullptr);+ userOnlyScripts_.at(userScript->injectionTime).push_back(std::move(userScript));+ }++ void UserContentController::addUserOnlyScripts(std::vector<std::shared_ptr<UserScript>> userScripts)+ {+ for (auto& userScript : userScripts) {+ addUserOnlyScript(std::move(userScript));+ }+ }++ void UserContentController::removeUserOnlyScript(std::shared_ptr<UserScript> userScript)+ {+ if (!userScript) {+ return;+ }++ if (webView_) {+ removeScriptFromWebView(userScript, nullptr);+ }++ vector_remove_erase(userOnlyScripts_.at(userScript->injectionTime), std::move(userScript));+ }++ void UserContentController::removeUserOnlyScriptAt(const int64_t& index, const UserScriptInjectionTime& injectionTime)+ {+ auto& vec = userOnlyScripts_.at(injectionTime);+ int64_t size = vec.size();+ if (index >= size) {+ return;+ }++ auto& userScript = vec.at(index);+ if (userScript) {+ removeScriptFromWebView(userScript, nullptr);+ vec.erase(vec.begin() + index);+ }+ }++ void UserContentController::removeAllUserOnlyScripts()+ {+ auto& userScriptsAtStart = userOnlyScripts_.at(UserScriptInjectionTime::atDocumentStart);+ auto& userScriptsAtEnd = userOnlyScripts_.at(UserScriptInjectionTime::atDocumentEnd);++ if (webView_) {+ for (auto& userScript : userScriptsAtStart) {+ removeScriptFromWebView(userScript, nullptr);+ }+ for (auto& userScript : userScriptsAtEnd) {+ removeScriptFromWebView(userScript, nullptr);+ }+ }++ userScriptsAtStart.clear();+ userScriptsAtEnd.clear();+ }++ void UserContentController::removeUserOnlyScriptsByGroupName(const std::string& groupName)+ {+ std::vector<std::shared_ptr<UserScript>> userScriptsAtStart = userOnlyScripts_.at(UserScriptInjectionTime::atDocumentStart);+ std::vector<std::shared_ptr<UserScript>> userScriptsAtEnd = userOnlyScripts_.at(UserScriptInjectionTime::atDocumentEnd);++ for (auto& userScript : userScriptsAtStart) {+ if (string_equals(groupName, userScript->groupName)) {+ removeUserOnlyScript(userScript);+ }+ }++ for (auto& userScript : userScriptsAtEnd) {+ if (string_equals(groupName, userScript->groupName)) {+ removeUserOnlyScript(userScript);+ }+ }+ }++ std::vector<std::shared_ptr<PluginScript>> UserContentController::getPluginScriptsAt(const UserScriptInjectionTime& injectionTime) const+ {+ return pluginScripts_.at(injectionTime);+ }++ bool UserContentController::containsUserOnlyScript(std::shared_ptr<UserScript> userScript) const+ {+ if (!userScript) {+ return false;+ }++ return vector_contains(userOnlyScripts_.at(userScript->injectionTime), std::move(userScript));+ }++ bool UserContentController::containsUserOnlyScriptByGroupName(const std::string& groupName) const+ {+ return vector_contains_if(userOnlyScripts_.at(UserScriptInjectionTime::atDocumentStart), [groupName](const std::shared_ptr<UserScript> userScript) { return string_equals(groupName, userScript->groupName); }) ||+ vector_contains_if(userOnlyScripts_.at(UserScriptInjectionTime::atDocumentEnd), [groupName](const std::shared_ptr<UserScript> userScript) { return string_equals(groupName, userScript->groupName); });+ }++ void UserContentController::addPluginScript(std::shared_ptr<PluginScript> pluginScript)+ {+ if (!pluginScript) {+ return;+ }++ addScriptToWebView(pluginScript, nullptr);+ pluginScripts_.at(pluginScript->injectionTime).push_back(std::move(pluginScript));+ }++ void UserContentController::addPluginScripts(std::vector<std::shared_ptr<PluginScript>> pluginScripts)+ {+ for (auto& pluginScript : pluginScripts) {+ addPluginScript(std::move(pluginScript));+ }+ }++ void UserContentController::removePluginScript(std::shared_ptr<PluginScript> pluginScript)+ {+ if (!pluginScript) {+ return;+ }++ if (webView_) {+ removeScriptFromWebView(pluginScript, nullptr);+ }++ vector_remove_erase(pluginScripts_.at(pluginScript->injectionTime), std::move(pluginScript));+ }++ void UserContentController::removeAllPluginScripts()+ {+ auto& pluginScriptsAtStart = pluginScripts_.at(UserScriptInjectionTime::atDocumentStart);+ auto& pluginScriptsAtEnd = pluginScripts_.at(UserScriptInjectionTime::atDocumentEnd);++ if (webView_) {+ for (auto& pluginScript : pluginScriptsAtStart) {+ removeScriptFromWebView(pluginScript, nullptr);+ }+ for (auto& pluginScript : pluginScriptsAtEnd) {+ removeScriptFromWebView(pluginScript, nullptr);+ }+ }++ pluginScriptsAtStart.clear();+ pluginScriptsAtEnd.clear();+ }++ bool UserContentController::containsPluginScript(std::shared_ptr<PluginScript> pluginScript) const+ {+ if (!pluginScript) {+ return false;+ }++ auto injectionTime = pluginScript->injectionTime;+ return vector_contains(pluginScripts_.at(injectionTime), std::move(pluginScript));+ }+++ bool UserContentController::containsPluginScript(std::shared_ptr<PluginScript> pluginScript, const std::shared_ptr<ContentWorld> contentWorld) const+ {+ if (!pluginScript || !map_contains(pluginScriptsInContentWorlds_, contentWorld->name)) {+ return false;+ }++ return vector_contains(pluginScriptsInContentWorlds_.at(contentWorld->name), std::move(pluginScript));+ }++ bool UserContentController::containsPluginScriptByGroupName(const std::string& groupName) const+ {+ return vector_contains_if(pluginScripts_.at(UserScriptInjectionTime::atDocumentStart), [groupName](const std::shared_ptr<PluginScript> pluginScript) { return string_equals(groupName, pluginScript->groupName); }) ||+ vector_contains_if(pluginScripts_.at(UserScriptInjectionTime::atDocumentEnd), [groupName](const std::shared_ptr<PluginScript> pluginScript) { return string_equals(groupName, pluginScript->groupName); });+ }++ void UserContentController::removePluginScriptsByGroupName(const std::string& groupName)+ {+ std::vector<std::shared_ptr<PluginScript>> pluginScriptsAtStart = pluginScripts_.at(UserScriptInjectionTime::atDocumentStart);+ std::vector<std::shared_ptr<PluginScript>> pluginScriptsAtEnd = pluginScripts_.at(UserScriptInjectionTime::atDocumentEnd);++ for (auto& pluginScript : pluginScriptsAtStart) {+ if (string_equals(groupName, pluginScript->groupName)) {+ removePluginScript(pluginScript);+ }+ }++ for (auto& pluginScript : pluginScriptsAtEnd) {+ if (string_equals(groupName, pluginScript->groupName)) {+ removePluginScript(pluginScript);+ }+ }+ }+++ std::vector<std::shared_ptr<PluginScript>> UserContentController::getPluginScriptsRequiredInAllContentWorlds() const+ {+ std::vector<std::shared_ptr<PluginScript>> res;++ std::vector<std::shared_ptr<PluginScript>> pluginScriptsAtStart = pluginScripts_.at(UserScriptInjectionTime::atDocumentStart);+ std::vector<std::shared_ptr<PluginScript>> pluginScriptsAtEnd = pluginScripts_.at(UserScriptInjectionTime::atDocumentEnd);++ for (auto& pluginScript : pluginScriptsAtStart) {+ if (!pluginScript->contentWorld && pluginScript->isRequiredInAllContentWorlds()) {+ res.push_back(pluginScript);+ }+ }++ for (auto& pluginScript : pluginScriptsAtEnd) {+ if (!pluginScript->contentWorld && pluginScript->isRequiredInAllContentWorlds()) {+ res.push_back(pluginScript);+ }+ }++ return res;+ }++ void UserContentController::createContentWorld(const std::shared_ptr<ContentWorld> contentWorld, const std::function<void(int)> completionHandler)+ {+ if (!webView_ || !(webView_->webView) || ContentWorld::isPage(contentWorld)) {+ if (completionHandler) {+ completionHandler(-1);+ }+ return;+ }++ auto& worldName = contentWorld->name;+ if (!map_contains(contentWorlds_, worldName)) {+ nlohmann::json parameters = {+ {"frameId", webView_->pageFrameId()},+ {"worldName", worldName}+ };+ auto hr = webView_->webView->CallDevToolsProtocolMethod(L"Page.createIsolatedWorld", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [this, completionHandler, worldName](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ if (succeededOrLog(errorCode) && completionHandler) {+ auto id = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson))["executionContextId"].get<int>();+ addPluginScriptsIfRequired(std::make_shared<ContentWorld>(worldName));+ completionHandler(id);+ }+ return S_OK;+ }+ ).Get());+ if (failedAndLog(hr) && completionHandler) {+ completionHandler(-1);+ }+ }+ else if (completionHandler) {+ completionHandler(contentWorlds_.at(worldName));+ }+ }++ void UserContentController::addScriptToWebView(std::shared_ptr<UserScript> userScript, const std::function<void(std::string)> completionHandler) const+ {+ if (!webView_ || !(webView_->webView)) {+ if (completionHandler) {+ completionHandler(userScript->id);+ }+ }++ std::string source = userScript->source;+ if (userScript->injectionTime == UserScriptInjectionTime::atDocumentEnd) {+ source = replace_all_copy(USER_SCRIPTS_AT_DOCUMENT_END_WRAPPER_JS_SOURCE, VAR_PLACEHOLDER_VALUE, source);+ std::ostringstream address;+ address << std::addressof(userScript);+ replace_all(source, VAR_PLACEHOLDER_MEMORY_ADDRESS_VALUE, address.str());+ }++ nlohmann::json parameters = {+ {"source", source}+ };++ if (userScript->contentWorld && !ContentWorld::isPage(userScript->contentWorld)) {+ parameters["worldName"] = userScript->contentWorld->name;+ }++ auto hr = webView_->webView->CallDevToolsProtocolMethod(L"Page.addScriptToEvaluateOnNewDocument", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [userScript, completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ if (succeededOrLog(errorCode)) {+ nlohmann::json json = nlohmann::json::parse(wide_to_utf8(returnObjectAsJson));+ userScript->id = json["identifier"].get<std::string>();+ }+ if (completionHandler) {+ completionHandler(userScript->id);+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler(userScript->id);+ }+ }++ void UserContentController::removeScriptFromWebView(std::shared_ptr<UserScript> userScript, const std::function<void()> completionHandler) const+ {+ if (!webView_ || !(webView_->webView)) {+ if (completionHandler) {+ completionHandler();+ }+ return;+ }++ nlohmann::json parameters = {+ {"identifier", userScript->id}+ };++ auto hr = webView_->webView->CallDevToolsProtocolMethod(L"Page.removeScriptToEvaluateOnNewDocument", utf8_to_wide(parameters.dump()).c_str(), Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(+ [userScript, completionHandler](HRESULT errorCode, LPCWSTR returnObjectAsJson)+ {+ failedLog(errorCode);+ if (completionHandler) {+ completionHandler();+ }+ return S_OK;+ }+ ).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler();+ }+ }++ void UserContentController::addPluginScriptsIfRequired(const std::shared_ptr<ContentWorld> contentWorld)+ {+ if (contentWorld && !ContentWorld::isPage(contentWorld)) {+ std::vector<std::shared_ptr<PluginScript>> pluginScriptsRequiredInAllContentWorlds = getPluginScriptsRequiredInAllContentWorlds();+ for (auto& pluginScript : pluginScriptsRequiredInAllContentWorlds) {+ if (!containsPluginScript(pluginScript, contentWorld)) {+ if (!map_contains(pluginScriptsInContentWorlds_, contentWorld->name)) {+ pluginScriptsInContentWorlds_.insert({ contentWorld->name, {} });+ }+ pluginScriptsInContentWorlds_.at(contentWorld->name).push_back(pluginScript);+ addPluginScript(pluginScript->copyAndSet(contentWorld));+ }+ }+ }+ }++ UserContentController::~UserContentController()+ {+ debugLog("dealloc UserContentController");+ removeAllUserOnlyScripts();+ removeAllPluginScripts();+ contentWorlds_.clear();+ pluginScriptsInContentWorlds_.clear();+ webView_ = nullptr;+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/user_content_controller.h b/packages/flutter_inappwebview_windows/windows/in_app_webview/user_content_controller.hnew file mode 100644index 00000000..a6592913--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/user_content_controller.h@@ -0,0 +1,78 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_USER_CONTENT_CONTROLLER_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_USER_CONTENT_CONTROLLER_H_++#include <functional>+#include <map>+#include <vector>++#include "../plugin_scripts_js/javascript_bridge_js.h"+#include "../plugin_scripts_js/plugin_scripts_util.h"+#include "../types/content_world.h"+#include "../types/plugin_script.h"+#include "../types/user_script.h"++namespace flutter_inappwebview_plugin+{+ class InAppWebView;++ const std::string USER_SCRIPTS_AT_DOCUMENT_END_WRAPPER_JS_SOURCE = "window.addEventListener('load', () => { \+ if (window." + JAVASCRIPT_BRIDGE_NAME + " != null && (window." + JAVASCRIPT_BRIDGE_NAME + "._userScript" + VAR_PLACEHOLDER_MEMORY_ADDRESS_VALUE + "AtDocumentEndLoaded == null || !window." + JAVASCRIPT_BRIDGE_NAME + "._userScript" + VAR_PLACEHOLDER_MEMORY_ADDRESS_VALUE + "AtDocumentEndLoaded)) { \+ window." + JAVASCRIPT_BRIDGE_NAME + "._userScript" + VAR_PLACEHOLDER_MEMORY_ADDRESS_VALUE + "AtDocumentEndLoaded = true; \+ " + VAR_PLACEHOLDER_VALUE + " \+ } \+ });";++ class UserContentController+ {+ public:+ UserContentController(InAppWebView* webView);+ ~UserContentController();++ std::vector<std::shared_ptr<UserScript>> getUserOnlyScriptsAt(const UserScriptInjectionTime& injectionTime) const;+ void addUserOnlyScript(std::shared_ptr<UserScript> userScript);+ void addUserOnlyScripts(std::vector<std::shared_ptr<UserScript>> userScripts);+ void removeUserOnlyScript(std::shared_ptr<UserScript> userScript);+ void removeUserOnlyScriptAt(const int64_t& index, const UserScriptInjectionTime& injectionTime);+ void removeAllUserOnlyScripts();+ bool containsUserOnlyScript(std::shared_ptr<UserScript> userScript) const;+ bool containsUserOnlyScriptByGroupName(const std::string& groupName) const;+ void removeUserOnlyScriptsByGroupName(const std::string& groupName);++ std::vector<std::shared_ptr<PluginScript>> getPluginScriptsAt(const UserScriptInjectionTime& injectionTime) const;+ void addPluginScript(std::shared_ptr<PluginScript> pluginScript);+ void addPluginScripts(std::vector<std::shared_ptr<PluginScript>> pluginScripts);+ void removePluginScript(std::shared_ptr<PluginScript> pluginScript);+ void removeAllPluginScripts();+ bool containsPluginScript(std::shared_ptr<PluginScript> pluginScript) const;+ bool containsPluginScript(std::shared_ptr<PluginScript> pluginScript, const std::shared_ptr<ContentWorld> contentWorld) const;+ bool containsPluginScriptByGroupName(const std::string& groupName) const;+ void removePluginScriptsByGroupName(const std::string& groupName);+ std::vector<std::shared_ptr<PluginScript>> getPluginScriptsRequiredInAllContentWorlds() const;++ void registerEventHandlers();+ void createContentWorld(const std::shared_ptr<ContentWorld> contentWorld, const std::function<void(int)> completionHandler);+ private:+ InAppWebView* webView_;++ // used to track Content World names -> Execution Context ID+ std::map<std::string, int> contentWorlds_;+ // used only to track plugin script to inject inside new Content Worlds+ std::map<std::string, std::vector<std::shared_ptr<PluginScript>>> pluginScriptsInContentWorlds_;++ std::map<UserScriptInjectionTime, std::vector<std::shared_ptr<PluginScript>>> pluginScripts_ = {+ {UserScriptInjectionTime::atDocumentStart, {}},+ {UserScriptInjectionTime::atDocumentEnd, {}}+ };++ std::map<UserScriptInjectionTime, std::vector<std::shared_ptr<UserScript>>> userOnlyScripts_ = {+ {UserScriptInjectionTime::atDocumentStart, {}},+ {UserScriptInjectionTime::atDocumentEnd, {}}+ };++ void addScriptToWebView(std::shared_ptr<UserScript> userScript, const std::function<void(std::string)> completionHandler) const;+ void removeScriptFromWebView(std::shared_ptr<UserScript> userScript, const std::function<void()> completionHandler) const;++ void addPluginScriptsIfRequired(const std::shared_ptr<ContentWorld> contentWorld);+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_USER_CONTENT_CONTROLLER_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/webview_channel_delegate.cpp b/packages/flutter_inappwebview_windows/windows/in_app_webview/webview_channel_delegate.cppnew file mode 100644index 00000000..df6a4bc8--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/webview_channel_delegate.cpp@@ -0,0 +1,496 @@+#include "../in_app_browser/in_app_browser.h"+#include "../types/base_callback_result.h"+#include "../types/content_world.h"+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "../utils/strconv.h"+#include "../utils/string.h"+#include "in_app_webview.h"+#include "webview_channel_delegate.h"++namespace flutter_inappwebview_plugin+{+ WebViewChannelDelegate::WebViewChannelDelegate(InAppWebView* webView, flutter::BinaryMessenger* messenger)+ : webView(webView), ChannelDelegate(messenger, InAppWebView::METHOD_CHANNEL_NAME_PREFIX + variant_to_string(webView->id))+ {}++ WebViewChannelDelegate::WebViewChannelDelegate(InAppWebView* webView, flutter::BinaryMessenger* messenger, const std::string& name)+ : webView(webView), ChannelDelegate(messenger, name)+ {}++ WebViewChannelDelegate::ShouldOverrideUrlLoadingCallback::ShouldOverrideUrlLoadingCallback()+ {+ decodeResult = [](const flutter::EncodableValue* value)+ {+ if (!value || value->IsNull()) {+ return NavigationActionPolicy::cancel;+ }+ auto navigationPolicy = std::get<int>(*value);+ return static_cast<NavigationActionPolicy>(navigationPolicy);+ };+ }++ WebViewChannelDelegate::CallJsHandlerCallback::CallJsHandlerCallback()+ {+ decodeResult = [](const flutter::EncodableValue* value)+ {+ return value;+ };+ }++ WebViewChannelDelegate::CreateWindowCallback::CreateWindowCallback()+ {+ decodeResult = [](const flutter::EncodableValue* value)+ {+ if (!value || value->IsNull()) {+ return false;+ }+ auto handledByClient = std::get<bool>(*value);+ return handledByClient;+ };+ }++ WebViewChannelDelegate::PermissionRequestCallback::PermissionRequestCallback()+ {+ decodeResult = [](const flutter::EncodableValue* value)+ {+ return std::make_shared<PermissionResponse>(std::get<flutter::EncodableMap>(*value));+ };+ }++ WebViewChannelDelegate::ShouldInterceptRequestCallback::ShouldInterceptRequestCallback()+ {+ decodeResult = [](const flutter::EncodableValue* value)+ {+ return value == nullptr || value->IsNull() ? std::optional<std::shared_ptr<WebResourceResponse>>{} : std::make_shared<WebResourceResponse>(std::get<flutter::EncodableMap>(*value));+ };+ }++ WebViewChannelDelegate::LoadResourceWithCustomSchemeCallback::LoadResourceWithCustomSchemeCallback()+ {+ decodeResult = [](const flutter::EncodableValue* value)+ {+ return value == nullptr || value->IsNull() ? std::optional<std::shared_ptr<CustomSchemeResponse>>{} : std::make_shared<CustomSchemeResponse>(std::get<flutter::EncodableMap>(*value));+ };+ }++ void WebViewChannelDelegate::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ if (!webView) {+ result->Success();+ return;+ }++ auto& arguments = std::get<flutter::EncodableMap>(*method_call.arguments());+ auto& methodName = method_call.method_name();++ if (string_equals(methodName, "getUrl")) {+ result->Success(make_fl_value(webView->getUrl()));+ }+ else if (string_equals(methodName, "getTitle")) {+ result->Success(make_fl_value(webView->getUrl()));+ }+ else if (string_equals(methodName, "loadUrl")) {+ auto urlRequest = std::make_unique<URLRequest>(get_fl_map_value<flutter::EncodableMap>(arguments, "urlRequest"));+ webView->loadUrl(std::move(urlRequest));+ result->Success(true);+ }+ else if (string_equals(methodName, "loadFile")) {+ auto assetFilePath = get_fl_map_value<std::string>(arguments, "assetFilePath");+ webView->loadFile(assetFilePath);+ result->Success(true);+ }+ else if (string_equals(methodName, "loadData")) {+ auto data = get_fl_map_value<std::string>(arguments, "data");+ webView->loadData(data);+ result->Success(true);+ }+ else if (string_equals(methodName, "reload")) {+ webView->reload();+ result->Success(true);+ }+ else if (string_equals(methodName, "goBack")) {+ webView->goBack();+ result->Success(true);+ }+ else if (string_equals(methodName, "canGoBack")) {+ result->Success(webView->canGoBack());+ }+ else if (string_equals(methodName, "goForward")) {+ webView->goForward();+ result->Success(true);+ }+ else if (string_equals(methodName, "canGoForward")) {+ result->Success(webView->canGoForward());+ }+ else if (string_equals(methodName, "goBackOrForward")) {+ auto steps = get_fl_map_value<int>(arguments, "steps");+ webView->goBackOrForward(steps);+ result->Success(true);+ }+ else if (string_equals(methodName, "canGoBackOrForward")) {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));++ auto steps = get_fl_map_value<int>(arguments, "steps");+ webView->canGoBackOrForward(steps, [result_ = std::move(result_)](const bool& value)+ {+ result_->Success(value);+ });+ }+ else if (string_equals(methodName, "isLoading")) {+ result->Success(webView->isLoading());+ }+ else if (string_equals(methodName, "stopLoading")) {+ webView->stopLoading();+ result->Success(true);+ }+ else if (string_equals(methodName, "evaluateJavascript")) {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));++ auto source = get_fl_map_value<std::string>(arguments, "source");+ auto contentWorldMap = get_optional_fl_map_value<flutter::EncodableMap>(arguments, "contentWorld");+ std::shared_ptr<ContentWorld> contentWorld = contentWorldMap.has_value() ? std::make_shared<ContentWorld>(contentWorldMap.value()) : ContentWorld::page();+ webView->evaluateJavascript(source, std::move(contentWorld), [result_ = std::move(result_)](const std::string& value)+ {+ result_->Success(value);+ });+ }+ else if (string_equals(methodName, "callAsyncJavaScript")) {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));++ auto functionBody = get_fl_map_value<std::string>(arguments, "functionBody");+ auto argumentsAsJson = get_fl_map_value<std::string>(arguments, "arguments");+ auto contentWorldMap = get_optional_fl_map_value<flutter::EncodableMap>(arguments, "contentWorld");+ std::shared_ptr<ContentWorld> contentWorld = contentWorldMap.has_value() ? std::make_shared<ContentWorld>(contentWorldMap.value()) : ContentWorld::page();+ webView->callAsyncJavaScript(functionBody, argumentsAsJson, std::move(contentWorld), [result_ = std::move(result_)](const std::string& value)+ {+ result_->Success(value);+ });+ }+ else if (string_equals(methodName, "getCopyBackForwardList")) {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));+ webView->getCopyBackForwardList([result_ = std::move(result_)](const std::unique_ptr<WebHistory> value)+ {+ result_->Success(value->toEncodableMap());+ });+ }+ else if (string_equals(methodName, "addUserScript")) {+ auto userScript = std::make_unique<UserScript>(get_fl_map_value<flutter::EncodableMap>(arguments, "userScript"));+ webView->addUserScript(std::move(userScript));+ result->Success(true);+ }+ else if (string_equals(methodName, "removeUserScript")) {+ auto index = get_fl_map_value<int>(arguments, "index");+ auto userScript = std::make_unique<UserScript>(get_fl_map_value<flutter::EncodableMap>(arguments, "userScript"));+ webView->removeUserScript(index, std::move(userScript));+ result->Success(true);+ }+ else if (string_equals(methodName, "removeUserScriptsByGroupName")) {+ auto groupName = get_fl_map_value<std::string>(arguments, "groupName");+ webView->removeUserScriptsByGroupName(groupName);+ result->Success(true);+ }+ else if (string_equals(methodName, "removeAllUserScripts")) {+ webView->removeAllUserScripts();+ result->Success(true);+ }+ else if (string_equals(methodName, "takeScreenshot")) {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));+ auto screenshotConfigurationMap = get_optional_fl_map_value<flutter::EncodableMap>(arguments, "screenshotConfiguration");+ std::optional<std::unique_ptr<ScreenshotConfiguration>> screenshotConfiguration =+ screenshotConfigurationMap.has_value() ? std::make_unique<ScreenshotConfiguration>(screenshotConfigurationMap.value()) : std::optional<std::unique_ptr<ScreenshotConfiguration>>{};+ webView->takeScreenshot(std::move(screenshotConfiguration), [result_ = std::move(result_)](const std::optional<std::string> data)+ {+ result_->Success(make_fl_value(data));+ });+ }+ else if (string_equals(methodName, "setSettings")) {+ if (webView->inAppBrowser) {+ auto settingsMap = get_fl_map_value<flutter::EncodableMap>(arguments, "settings");+ auto settings = std::make_unique<InAppBrowserSettings>(settingsMap);+ webView->inAppBrowser->setSettings(std::move(settings), settingsMap);+ }+ else {+ auto settingsMap = get_fl_map_value<flutter::EncodableMap>(arguments, "settings");+ auto settings = std::make_unique<InAppWebViewSettings>(settingsMap);+ webView->setSettings(std::move(settings), settingsMap);+ }+ result->Success(true);+ }+ else if (string_equals(methodName, "getSettings")) {+ if (webView->inAppBrowser) {+ result->Success(webView->inAppBrowser->getSettings());+ }+ else {+ result->Success(webView->getSettings());+ }+ }+ else if (string_equals(methodName, "openDevTools")) {+ webView->openDevTools();+ result->Success(true);+ }+ else if (string_equals(methodName, "callDevToolsProtocolMethod")) {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));+ auto cdpMethodName = get_fl_map_value<std::string>(arguments, "methodName");+ auto parametersAsJson = get_optional_fl_map_value<std::string>(arguments, "parametersAsJson");+ webView->callDevToolsProtocolMethod(cdpMethodName, parametersAsJson, [result_ = std::move(result_)](const HRESULT& errorCode, const std::optional<std::string>& data)+ {+ if (SUCCEEDED(errorCode)) {+ result_->Success(make_fl_value(data));+ }+ else {+ result_->Error(std::to_string(errorCode), getHRMessage(errorCode));+ }+ });+ }+ else if (string_equals(methodName, "addDevToolsProtocolEventListener")) {+ auto eventName = get_fl_map_value<std::string>(arguments, "eventName");+ webView->addDevToolsProtocolEventListener(eventName);+ result->Success(true);+ }+ else if (string_equals(methodName, "removeDevToolsProtocolEventListener")) {+ auto eventName = get_fl_map_value<std::string>(arguments, "eventName");+ webView->removeDevToolsProtocolEventListener(eventName);+ result->Success(true);+ }+ else if (string_equals(methodName, "pause")) {+ webView->pause();+ result->Success(true);+ }+ else if (string_equals(methodName, "resume")) {+ webView->resume();+ result->Success(true);+ }+ else if (string_equals(methodName, "getCertificate")) {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));+ webView->getCertificate([result_ = std::move(result_)](const std::optional<std::unique_ptr<SslCertificate>> data)+ {+ result_->Success(data.has_value() ? data.value()->toEncodableMap() : make_fl_value());+ });+ }+ // for inAppBrowser+ else if (webView->inAppBrowser && string_equals(methodName, "show")) {+ webView->inAppBrowser->show();+ result->Success(true);+ }+ else if (webView->inAppBrowser && string_equals(methodName, "hide")) {+ webView->inAppBrowser->hide();+ result->Success(true);+ }+ else if (webView->inAppBrowser && string_equals(methodName, "close")) {+ webView->inAppBrowser->close();+ result->Success(true);+ }+ else {+ result->NotImplemented();+ }+ }++ void WebViewChannelDelegate::onLoadStart(const std::optional<std::string>& url) const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"url", make_fl_value(url)},+ });+ channel->InvokeMethod("onLoadStart", std::move(arguments));+ }++ void WebViewChannelDelegate::onLoadStop(const std::optional<std::string>& url) const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"url", make_fl_value(url)},+ });+ channel->InvokeMethod("onLoadStop", std::move(arguments));+ }++ void WebViewChannelDelegate::shouldOverrideUrlLoading(std::shared_ptr<NavigationAction> navigationAction, std::unique_ptr<ShouldOverrideUrlLoadingCallback> callback) const+ {+ if (!channel) {+ callback->defaultBehaviour(std::nullopt);+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(navigationAction->toEncodableMap());+ channel->InvokeMethod("shouldOverrideUrlLoading", std::move(arguments), std::move(callback));+ }++ void WebViewChannelDelegate::onReceivedError(std::shared_ptr<WebResourceRequest> request, std::shared_ptr<WebResourceError> error) const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"request", request->toEncodableMap()},+ {"error", error->toEncodableMap()},+ });+ channel->InvokeMethod("onReceivedError", std::move(arguments));+ }++ void WebViewChannelDelegate::onReceivedHttpError(std::shared_ptr<WebResourceRequest> request, std::shared_ptr<WebResourceResponse> errorResponse) const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"request", request->toEncodableMap()},+ {"errorResponse", errorResponse->toEncodableMap()},+ });+ channel->InvokeMethod("onReceivedHttpError", std::move(arguments));+ }++ void WebViewChannelDelegate::onTitleChanged(const std::optional<std::string>& title) const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"title", make_fl_value(title)}+ });+ channel->InvokeMethod("onTitleChanged", std::move(arguments));++ if (webView && webView->inAppBrowser) {+ webView->inAppBrowser->didChangeTitle(title);+ }+ }++ void WebViewChannelDelegate::onUpdateVisitedHistory(const std::optional<std::string>& url, const std::optional<bool>& isReload) const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"url", make_fl_value(url)},+ {"isReload", make_fl_value(isReload)}+ });+ channel->InvokeMethod("onUpdateVisitedHistory", std::move(arguments));+ }++ void WebViewChannelDelegate::onCallJsHandler(const std::string& handlerName, const std::string& args, std::unique_ptr<CallJsHandlerCallback> callback) const+ {+ if (!channel) {+ callback->defaultBehaviour(std::nullopt);+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"handlerName", handlerName},+ {"args", args}+ });+ channel->InvokeMethod("onCallJsHandler", std::move(arguments), std::move(callback));+ }++ void WebViewChannelDelegate::onConsoleMessage(const std::string& message, const int64_t& messageLevel) const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"message", message},+ {"messageLevel", messageLevel}+ });+ channel->InvokeMethod("onConsoleMessage", std::move(arguments));+ }++ void WebViewChannelDelegate::onDevToolsProtocolEventReceived(const std::string& eventName, const std::string& data) const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"eventName", eventName},+ {"data", data}+ });+ channel->InvokeMethod("onDevToolsProtocolEventReceived", std::move(arguments));+ }++ void WebViewChannelDelegate::onProgressChanged(const int64_t& progress) const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"progress", progress}+ });+ channel->InvokeMethod("onProgressChanged", std::move(arguments));+ }++ void WebViewChannelDelegate::onCreateWindow(std::shared_ptr<CreateWindowAction> createWindowAction, std::unique_ptr<CreateWindowCallback> callback) const+ {+ if (!channel) {+ callback->defaultBehaviour(std::nullopt);+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(createWindowAction->toEncodableMap());+ channel->InvokeMethod("onCreateWindow", std::move(arguments), std::move(callback));+ }++ void WebViewChannelDelegate::onCloseWindow() const+ {+ if (!channel) {+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>();+ channel->InvokeMethod("onCloseWindow", std::move(arguments));+ }++ void WebViewChannelDelegate::onPermissionRequest(const std::string& origin, const std::vector<int64_t>& resources, std::unique_ptr<PermissionRequestCallback> callback) const+ {+ if (!channel) {+ callback->defaultBehaviour(std::nullopt);+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"origin", origin},+ {"resources", make_fl_value(resources)}+ });+ channel->InvokeMethod("onPermissionRequest", std::move(arguments), std::move(callback));+ }++ void WebViewChannelDelegate::shouldInterceptRequest(std::shared_ptr<WebResourceRequest> request, std::unique_ptr<ShouldInterceptRequestCallback> callback) const+ {+ if (!channel) {+ callback->defaultBehaviour(std::nullopt);+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(make_fl_value(request->toEncodableMap()));+ channel->InvokeMethod("shouldInterceptRequest", std::move(arguments), std::move(callback));+ }++ void WebViewChannelDelegate::onLoadResourceWithCustomScheme(std::shared_ptr<WebResourceRequest> request, std::unique_ptr<LoadResourceWithCustomSchemeCallback> callback) const+ {+ if (!channel) {+ callback->defaultBehaviour(std::nullopt);+ return;+ }++ auto arguments = std::make_unique<flutter::EncodableValue>(flutter::EncodableMap{+ {"request", request->toEncodableMap()},+ });+ channel->InvokeMethod("onLoadResourceWithCustomScheme", std::move(arguments), std::move(callback));+ }++ WebViewChannelDelegate::~WebViewChannelDelegate()+ {+ debugLog("dealloc WebViewChannelDelegate");+ webView = nullptr;+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/in_app_webview/webview_channel_delegate.h b/packages/flutter_inappwebview_windows/windows/in_app_webview/webview_channel_delegate.hnew file mode 100644index 00000000..005e782d--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/in_app_webview/webview_channel_delegate.h@@ -0,0 +1,91 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_CHANNEL_DELEGATE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_CHANNEL_DELEGATE_H_++#include <flutter/method_channel.h>+#include <flutter/standard_message_codec.h>++#include "../types/base_callback_result.h"+#include "../types/channel_delegate.h"+#include "../types/create_window_action.h"+#include "../types/custom_scheme_response.h"+#include "../types/navigation_action.h"+#include "../types/permission_response.h"+#include "../types/web_resource_error.h"+#include "../types/web_resource_request.h"+#include "../types/web_resource_response.h"++namespace flutter_inappwebview_plugin+{+ class InAppWebView;++ enum NavigationActionPolicy { cancel = 0, allow = 1 };++ class WebViewChannelDelegate : public ChannelDelegate+ {+ public:+ InAppWebView* webView;++ class ShouldOverrideUrlLoadingCallback : public BaseCallbackResult<const NavigationActionPolicy> {+ public:+ ShouldOverrideUrlLoadingCallback();+ ~ShouldOverrideUrlLoadingCallback() = default;+ };++ class CallJsHandlerCallback : public BaseCallbackResult<const flutter::EncodableValue*> {+ public:+ CallJsHandlerCallback();+ ~CallJsHandlerCallback() = default;+ };++ class CreateWindowCallback : public BaseCallbackResult<const bool> {+ public:+ CreateWindowCallback();+ ~CreateWindowCallback() = default;+ };++ class PermissionRequestCallback : public BaseCallbackResult<const std::shared_ptr<PermissionResponse>> {+ public:+ PermissionRequestCallback();+ ~PermissionRequestCallback() = default;+ };++ class ShouldInterceptRequestCallback : public BaseCallbackResult<const std::shared_ptr<WebResourceResponse>> {+ public:+ ShouldInterceptRequestCallback();+ ~ShouldInterceptRequestCallback() = default;+ };++ class LoadResourceWithCustomSchemeCallback : public BaseCallbackResult<const std::shared_ptr<CustomSchemeResponse>> {+ public:+ LoadResourceWithCustomSchemeCallback();+ ~LoadResourceWithCustomSchemeCallback() = default;+ };++ WebViewChannelDelegate(InAppWebView* webView, flutter::BinaryMessenger* messenger);+ WebViewChannelDelegate(InAppWebView* webView, flutter::BinaryMessenger* messenger, const std::string& name);+ ~WebViewChannelDelegate();++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);++ void onLoadStart(const std::optional<std::string>& url) const;+ void onLoadStop(const std::optional<std::string>& url) const;+ void onProgressChanged(const int64_t& progress) const;+ void shouldOverrideUrlLoading(std::shared_ptr<NavigationAction> navigationAction, std::unique_ptr<ShouldOverrideUrlLoadingCallback> callback) const;+ void onReceivedError(std::shared_ptr<WebResourceRequest> request, std::shared_ptr<WebResourceError> error) const;+ void onReceivedHttpError(std::shared_ptr<WebResourceRequest> request, std::shared_ptr<WebResourceResponse> error) const;+ void onTitleChanged(const std::optional<std::string>& title) const;+ void onUpdateVisitedHistory(const std::optional<std::string>& url, const std::optional<bool>& isReload) const;+ void onCallJsHandler(const std::string& handlerName, const std::string& args, std::unique_ptr<CallJsHandlerCallback> callback) const;+ void onConsoleMessage(const std::string& message, const int64_t& messageLevel) const;+ void onDevToolsProtocolEventReceived(const std::string& eventName, const std::string& data) const;+ void onCreateWindow(std::shared_ptr<CreateWindowAction> createWindowAction, std::unique_ptr<CreateWindowCallback> callback) const;+ void onCloseWindow() const;+ void onPermissionRequest(const std::string& origin, const std::vector<int64_t>& resources, std::unique_ptr<PermissionRequestCallback> callback) const;+ void shouldInterceptRequest(std::shared_ptr<WebResourceRequest> request, std::unique_ptr<ShouldInterceptRequestCallback> callback) const;+ void onLoadResourceWithCustomScheme(std::shared_ptr<WebResourceRequest> request, std::unique_ptr<LoadResourceWithCustomSchemeCallback> callback) const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_CHANNEL_DELEGATE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/include/flutter_inappwebview_windows/flutter_inappwebview_windows_plugin_c_api.h b/packages/flutter_inappwebview_windows/windows/include/flutter_inappwebview_windows/flutter_inappwebview_windows_plugin_c_api.hnew file mode 100644index 00000000..6a318ec0--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/include/flutter_inappwebview_windows/flutter_inappwebview_windows_plugin_c_api.h@@ -0,0 +1,23 @@+#ifndef FLUTTER_PLUGIN_FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_C_API_H_+#define FLUTTER_PLUGIN_FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_C_API_H_++#include <flutter_plugin_registrar.h>++#ifdef FLUTTER_PLUGIN_IMPL+#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport)+#else+#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport)+#endif++#if defined(__cplusplus)+extern "C" {+#endif++ FLUTTER_PLUGIN_EXPORT void FlutterInappwebviewWindowsPluginCApiRegisterWithRegistrar(+ FlutterDesktopPluginRegistrarRef registrar);++#if defined(__cplusplus)+} // extern "C"+#endif++#endif // FLUTTER_PLUGIN_FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_C_API_H_diff --git a/packages/flutter_inappwebview_windows/windows/plugin_scripts_js/javascript_bridge_js.cpp b/packages/flutter_inappwebview_windows/windows/plugin_scripts_js/javascript_bridge_js.cppnew file mode 100644index 00000000..dcb743bf--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/plugin_scripts_js/javascript_bridge_js.cpp@@ -0,0 +1,19 @@+#include <vector>++#include "javascript_bridge_js.h"++namespace flutter_inappwebview_plugin+{+ std::unique_ptr<PluginScript> createJavaScriptBridgePluginScript()+ {+ const std::vector<std::string> allowedOriginRules = { "*" };+ return std::make_unique<PluginScript>(+ JAVASCRIPT_BRIDGE_JS_PLUGIN_SCRIPT_GROUP_NAME,+ JAVASCRIPT_BRIDGE_JS_SOURCE,+ UserScriptInjectionTime::atDocumentStart,+ allowedOriginRules,+ nullptr,+ true+ );+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/plugin_scripts_js/javascript_bridge_js.h b/packages/flutter_inappwebview_windows/windows/plugin_scripts_js/javascript_bridge_js.hnew file mode 100644index 00000000..a10c832c--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/plugin_scripts_js/javascript_bridge_js.h@@ -0,0 +1,31 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_JAVASCRIPT_BRIDGE_JS_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_JAVASCRIPT_BRIDGE_JS_H_++#include <memory>+#include <string>++#include "../types/plugin_script.h"++namespace flutter_inappwebview_plugin+{+ const std::string JAVASCRIPT_BRIDGE_NAME = "flutter_inappwebview";+ const std::string JAVASCRIPT_BRIDGE_JS_SOURCE = "window." + JAVASCRIPT_BRIDGE_NAME + " = {}; \+ window." + JAVASCRIPT_BRIDGE_NAME + ".callHandler = function() { \+ var _callHandlerID = setTimeout(function() {}); \+ window.chrome.webview.postMessage({ 'name': 'callHandler', 'body': {'handlerName': arguments[0], '_callHandlerID' : _callHandlerID, 'args' : JSON.stringify(Array.prototype.slice.call(arguments, 1))} }); \+ return new Promise(function(resolve, reject) { \+ window." + JAVASCRIPT_BRIDGE_NAME + "[_callHandlerID] = { resolve: resolve, reject : reject };\+ });\+ };";+ const std::string JAVASCRIPT_BRIDGE_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_JAVASCRIPT_BRIDGE_JS_PLUGIN_SCRIPT";+ const std::string PLATFORM_READY_JS_SOURCE = "(function() { \+ if ((window.top == null || window.top === window) && window." + JAVASCRIPT_BRIDGE_NAME + " != null && window." + JAVASCRIPT_BRIDGE_NAME + "._platformReady == null) { \+ window.dispatchEvent(new Event('flutterInAppWebViewPlatformReady')); \+ window." + JAVASCRIPT_BRIDGE_NAME + "._platformReady = true; \+ } \+ })();";++ std::unique_ptr<PluginScript> createJavaScriptBridgePluginScript();+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_JAVASCRIPT_BRIDGE_JS_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/plugin_scripts_js/plugin_scripts_util.h b/packages/flutter_inappwebview_windows/windows/plugin_scripts_js/plugin_scripts_util.hnew file mode 100644index 00000000..239783c3--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/plugin_scripts_js/plugin_scripts_util.h@@ -0,0 +1,15 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_SCRIPTS_UTIL_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_SCRIPTS_UTIL_H_++#include <string>++namespace flutter_inappwebview_plugin+{+ const std::string VAR_PLACEHOLDER_VALUE = "$IN_APP_WEBVIEW_PLACEHOLDER_VALUE";+ const std::string VAR_PLACEHOLDER_MEMORY_ADDRESS_VALUE = "$IN_APP_WEBVIEW_PLACEHOLDER_MEMORY_ADDRESS_VALUE";+ const std::string VAR_FUNCTION_ARGUMENT_NAMES = "$IN_APP_WEBVIEW_FUNCTION_ARGUMENT_NAMES";+ const std::string VAR_FUNCTION_ARGUMENT_VALUES = "$IN_APP_WEBVIEW_FUNCTION_ARGUMENT_VALUES";+ const std::string VAR_FUNCTION_BODY = "$IN_APP_WEBVIEW_FUNCTION_BODY";+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_SCRIPTS_UTIL_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/test/flutter_inappwebview_windows_plugin_test.cpp b/packages/flutter_inappwebview_windows/windows/test/flutter_inappwebview_windows_plugin_test.cppnew file mode 100644index 00000000..f2504fd6--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/test/flutter_inappwebview_windows_plugin_test.cpp@@ -0,0 +1,43 @@+#include <flutter/method_call.h>+#include <flutter/method_result_functions.h>+#include <flutter/standard_method_codec.h>+#include <gtest/gtest.h>+#include <windows.h>++#include <memory>+#include <string>+#include <variant>++#include "flutter_inappwebview_windows_plugin.h"++namespace flutter_inappwebview_windows {+namespace test {++namespace {++using flutter::EncodableMap;+using flutter::EncodableValue;+using flutter::MethodCall;+using flutter::MethodResultFunctions;++} // namespace++TEST(FlutterInappwebviewWindowsPlugin, GetPlatformVersion) {+ FlutterInappwebviewWindowsPlugin plugin;+ // Save the reply value from the success callback.+ std::string result_string;+ plugin.HandleMethodCall(+ MethodCall("getPlatformVersion", std::make_unique<EncodableValue>()),+ std::make_unique<MethodResultFunctions<>>(+ [&result_string](const EncodableValue* result) {+ result_string = std::get<std::string>(*result);+ },+ nullptr, nullptr));++ // Since the exact string varies by host, just ensure that it's a string+ // with the expected format.+ EXPECT_TRUE(result_string.rfind("Windows ", 0) == 0);+}++} // namespace test+} // namespace flutter_inappwebview_windowsdiff --git a/packages/flutter_inappwebview_windows/windows/types/base_callback_result.h b/packages/flutter_inappwebview_windows/windows/types/base_callback_result.hnew file mode 100644index 00000000..d156e1e6--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/base_callback_result.h@@ -0,0 +1,57 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_BASE_CALLBACK_RESULT_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_BASE_CALLBACK_RESULT_H_++#include <flutter/method_result_functions.h>+#include <flutter/standard_method_codec.h>+#include <optional>++namespace flutter_inappwebview_plugin+{+ template <typename T>+ class BaseCallbackResult : public flutter::MethodResultFunctions<flutter::EncodableValue>+ {+ public:+ flutter::ResultHandlerError<flutter::EncodableValue> error;+ flutter::ResultHandlerNotImplemented<flutter::EncodableValue> notImplemented;+ std::function<bool(const T result)> nonNullSuccess = [](const T result) { return true; };+ std::function<bool()> nullSuccess = []() { return true; };+ std::function<void(const std::optional<T> result)> defaultBehaviour = [](const std::optional<T> result) {};+ std::function<std::optional<T>(const flutter::EncodableValue* result)> decodeResult = [](const flutter::EncodableValue* result) { return std::nullopt; };++ BaseCallbackResult<T>() :+ MethodResultFunctions(+ [this](const flutter::EncodableValue* val)+ {+ std::optional<T> result = decodeResult ? decodeResult(val) : std::nullopt;+ auto shouldRunDefaultBehaviour = false;+ if (result.has_value()) {+ shouldRunDefaultBehaviour = nonNullSuccess ? nonNullSuccess(result.value()) : shouldRunDefaultBehaviour;+ }+ else {+ shouldRunDefaultBehaviour = nullSuccess ? nullSuccess() : shouldRunDefaultBehaviour;+ }+ if (shouldRunDefaultBehaviour && defaultBehaviour) {+ defaultBehaviour(result);+ }+ },+ [this](const std::string& error_code, const std::string& error_message, const flutter::EncodableValue* error_details)+ {+ if (error) {+ error(error_code, error_message, error_details);+ }+ },+ [this]()+ {+ if (defaultBehaviour) {+ defaultBehaviour(std::nullopt);+ }+ if (notImplemented) {+ notImplemented();+ }+ })+ {};+ virtual ~BaseCallbackResult<T>() {};+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_BASE_CALLBACK_RESULT_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/callbacks_complete.h b/packages/flutter_inappwebview_windows/windows/types/callbacks_complete.hnew file mode 100644index 00000000..c2ba5704--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/callbacks_complete.h@@ -0,0 +1,39 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_CALLBACKS_COMPLETE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_CALLBACKS_COMPLETE_H_++#include <functional>+#include <mutex>+#include <vector>++namespace flutter_inappwebview_plugin+{+ template<typename T>+ class CallbacksComplete+ {+ public:+ std::function<void(const std::vector<T>&)> onComplete;++ CallbacksComplete(const std::function<void(const std::vector<T>&)> onComplete)+ : onComplete(onComplete)+ {}++ ~CallbacksComplete()+ {+ if (onComplete) {+ onComplete(values_);+ }+ }++ void addValue(const T& value)+ {+ const std::lock_guard<std::mutex> lock(mutex_);+ values_.push_back(value);+ }++ private:+ std::vector<T> values_;+ std::mutex mutex_;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_CALLBACKS_COMPLETE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/channel_delegate.cpp b/packages/flutter_inappwebview_windows/windows/types/channel_delegate.cppnew file mode 100644index 00000000..b5db1504--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/channel_delegate.cpp@@ -0,0 +1,39 @@+#include <flutter/method_channel.h>+#include <flutter/standard_method_codec.h>++#include "../utils/util.h"+#include "channel_delegate.h"++namespace flutter_inappwebview_plugin+{+ ChannelDelegate::ChannelDelegate(flutter::BinaryMessenger* messenger, const std::string& name) : messenger(messenger)+ {+ channel = std::make_shared<flutter::MethodChannel<flutter::EncodableValue>>(+ this->messenger, name,+ &flutter::StandardMethodCodec::GetInstance()+ );+ channel->SetMethodCallHandler(+ [this](const auto& call, auto result)+ {+ this->HandleMethodCall(call, std::move(result));+ });+ }++ void ChannelDelegate::HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {}++ void ChannelDelegate::UnregisterMethodCallHandler() const+ {+ if (channel) {+ channel->SetMethodCallHandler(nullptr);+ }+ }++ ChannelDelegate::~ChannelDelegate()+ {+ messenger = nullptr;+ channel.reset();+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/channel_delegate.h b/packages/flutter_inappwebview_windows/windows/types/channel_delegate.hnew file mode 100644index 00000000..5ccfdfa1--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/channel_delegate.h@@ -0,0 +1,27 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_CHANNEL_DELEGATE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_CHANNEL_DELEGATE_H_++#include <flutter/method_channel.h>++namespace flutter_inappwebview_plugin+{+ class ChannelDelegate+ {+ using FlutterMethodChannel = std::shared_ptr<flutter::MethodChannel<flutter::EncodableValue>>;++ public:+ FlutterMethodChannel channel;+ flutter::BinaryMessenger* messenger;++ ChannelDelegate(flutter::BinaryMessenger* messenger, const std::string& name);+ virtual ~ChannelDelegate();++ virtual void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);++ void UnregisterMethodCallHandler() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_CHANNEL_DELEGATE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/content_world.cpp b/packages/flutter_inappwebview_windows/windows/types/content_world.cppnew file mode 100644index 00000000..a95e773c--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/content_world.cpp@@ -0,0 +1,60 @@+#include "content_world.h"++namespace flutter_inappwebview_plugin+{+ namespace {+ const std::shared_ptr<ContentWorld> ContentWorldPage = std::make_shared<ContentWorld>("page");+ const std::shared_ptr<ContentWorld> ContentWorldDefaultClient = std::make_shared<ContentWorld>("defaultClient");+ }++ ContentWorld::ContentWorld(const std::string& name)+ : name(name)+ {}++ ContentWorld::ContentWorld(const flutter::EncodableMap& map)+ : name(get_fl_map_value<std::string>(map, "name"))+ {}++ bool ContentWorld::isSame(const ContentWorld& contentWorld) const+ {+ return name == contentWorld.name;+ }++ bool ContentWorld::isSame(const std::shared_ptr<ContentWorld> contentWorld) const+ {+ return contentWorld && name == contentWorld->name;+ }++ const std::shared_ptr<ContentWorld> ContentWorld::page()+ {+ return ContentWorldPage;+ }++ const std::shared_ptr<ContentWorld> ContentWorld::defaultClient()+ {+ return ContentWorldDefaultClient;+ }++ bool ContentWorld::isPage(const ContentWorld& contentWorld)+ {+ return contentWorld.isSame(*ContentWorld::page());+ }++ bool ContentWorld::isPage(const std::shared_ptr<ContentWorld> contentWorld)+ {+ return ContentWorld::page()->isSame(contentWorld);+ }++ bool ContentWorld::isDefaultClient(const ContentWorld& contentWorld)+ {+ return contentWorld.isSame(*ContentWorld::defaultClient());+ }++ bool ContentWorld::isDefaultClient(const std::shared_ptr<ContentWorld> contentWorld)+ {+ return ContentWorld::defaultClient()->isSame(contentWorld);+ }++ ContentWorld::~ContentWorld()+ {}+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/content_world.h b/packages/flutter_inappwebview_windows/windows/types/content_world.hnew file mode 100644index 00000000..46622289--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/content_world.h@@ -0,0 +1,33 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_CONTENT_WORLD_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_CONTENT_WORLD_H_++#include <flutter/standard_method_codec.h>+#include <string>++#include "../utils/flutter.h"++namespace flutter_inappwebview_plugin+{+ class ContentWorld+ {+ public:++ const std::string name;++ ContentWorld(const std::string& name);+ ContentWorld(const flutter::EncodableMap& map);+ ~ContentWorld();++ bool isSame(const ContentWorld& contentWorld) const;+ bool isSame(const std::shared_ptr<ContentWorld> contentWorld) const;++ const static std::shared_ptr<ContentWorld> page();+ const static std::shared_ptr<ContentWorld> defaultClient();++ static bool isPage(const ContentWorld& contentWorld);+ static bool isPage(const std::shared_ptr<ContentWorld> contentWorld);+ static bool isDefaultClient(const ContentWorld& contentWorld);+ static bool isDefaultClient(const std::shared_ptr<ContentWorld> contentWorld);+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_CONTENT_WORLD_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/create_window_action.cpp b/packages/flutter_inappwebview_windows/windows/types/create_window_action.cppnew file mode 100644index 00000000..087b24cc--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/create_window_action.cpp@@ -0,0 +1,22 @@+#include "../utils/flutter.h"+#include "create_window_action.h"++namespace flutter_inappwebview_plugin+{+ CreateWindowAction::CreateWindowAction(std::shared_ptr<URLRequest> request, const int64_t& windowId,+ const bool& isForMainFrame, const std::optional<bool>& hasGesture, const std::optional<std::shared_ptr<WindowFeatures>> windowFeatures)+ : request(std::move(request)), windowId(windowId), isForMainFrame(isForMainFrame),+ hasGesture(hasGesture), windowFeatures(std::move(windowFeatures))+ {}++ flutter::EncodableMap CreateWindowAction::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"request", request->toEncodableMap()},+ {"isForMainFrame", isForMainFrame},+ {"windowId", windowId},+ {"hasGesture", make_fl_value(hasGesture)},+ {"windowFeatures", windowFeatures.has_value() ? windowFeatures.value()->toEncodableMap() : make_fl_value()}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/create_window_action.h b/packages/flutter_inappwebview_windows/windows/types/create_window_action.hnew file mode 100644index 00000000..84c20cd5--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/create_window_action.h@@ -0,0 +1,28 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_CREATE_WINDOW_ACTION_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_CREATE_WINDOW_ACTION_H_++#include <flutter/standard_method_codec.h>+#include <optional>++#include "url_request.h"+#include "window_features.h"++namespace flutter_inappwebview_plugin+{+ class CreateWindowAction+ {+ public:+ const std::shared_ptr<URLRequest> request;+ const int64_t windowId;+ const bool isForMainFrame;+ const std::optional<bool> hasGesture;+ const std::optional<std::shared_ptr<WindowFeatures>> windowFeatures;++ CreateWindowAction(std::shared_ptr<URLRequest> request, const int64_t& windowId, const bool& isForMainFrame, const std::optional<bool>& hasGesture, const std::optional<std::shared_ptr<WindowFeatures>> windowFeatures);+ ~CreateWindowAction() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_CREATE_WINDOW_ACTION_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/custom_scheme_registration.cpp b/packages/flutter_inappwebview_windows/windows/types/custom_scheme_registration.cppnew file mode 100644index 00000000..b3cd295c--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/custom_scheme_registration.cpp@@ -0,0 +1,55 @@+#include "../utils/flutter.h"+#include "../utils/strconv.h"+#include "custom_scheme_registration.h"++namespace flutter_inappwebview_plugin+{+ CustomSchemeRegistration::CustomSchemeRegistration(const std::string& scheme, const std::optional<std::vector<std::string>>& allowedOrigins,+ const std::optional<bool>& treatAsSecure, const std::optional<bool>& hasAuthorityComponent)+ : scheme(scheme), allowedOrigins(allowedOrigins), treatAsSecure(treatAsSecure), hasAuthorityComponent(hasAuthorityComponent)+ {}++ CustomSchemeRegistration::CustomSchemeRegistration(const flutter::EncodableMap& map)+ : scheme(get_fl_map_value<std::string>(map, "scheme")),+ allowedOrigins(get_optional_fl_map_value<std::vector<std::string>>(map, "allowedOrigins")),+ treatAsSecure(get_optional_fl_map_value<bool>(map, "treatAsSecure")),+ hasAuthorityComponent(get_optional_fl_map_value<bool>(map, "hasAuthorityComponent"))+ {}++ flutter::EncodableMap CustomSchemeRegistration::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"scheme", make_fl_value(scheme)},+ {"allowedOrigins", make_fl_value(allowedOrigins)},+ {"treatAsSecure", make_fl_value(treatAsSecure)},+ {"hasAuthorityComponent", make_fl_value(hasAuthorityComponent)}+ };+ }++ CoreWebView2CustomSchemeRegistration* CustomSchemeRegistration::toWebView2CustomSchemeRegistration() const+ {+ auto customSchemeRegistration = Microsoft::WRL::Make<CoreWebView2CustomSchemeRegistration>(utf8_to_wide(scheme).c_str());++ if (allowedOrigins.has_value()) {+ std::vector<const WCHAR*> wideAllowedOrigins;+ for (const auto& origin : allowedOrigins.value()) {+ wideAllowedOrigins.push_back(utf8_to_wide(origin).c_str());+ }+ customSchemeRegistration->SetAllowedOrigins(+ static_cast<UINT32>(wideAllowedOrigins.size()),+ wideAllowedOrigins.data());+ }++ if (treatAsSecure.has_value()) {+ customSchemeRegistration->put_TreatAsSecure(treatAsSecure.value());+ }++ if (hasAuthorityComponent.has_value()) {+ customSchemeRegistration->put_HasAuthorityComponent(hasAuthorityComponent.value());+ }++ customSchemeRegistration->AddRef();+ return customSchemeRegistration.Get();+ }++}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/custom_scheme_registration.h b/packages/flutter_inappwebview_windows/windows/types/custom_scheme_registration.hnew file mode 100644index 00000000..d3c89efd--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/custom_scheme_registration.h@@ -0,0 +1,27 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_CUSTOM_SCHEME_REGISTRATION_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_CUSTOM_SCHEME_REGISTRATION_H_++#include <flutter/standard_method_codec.h>+#include <optional>+#include <WebView2EnvironmentOptions.h>++namespace flutter_inappwebview_plugin+{+ class CustomSchemeRegistration+ {+ public:+ const std::string scheme;+ const std::optional<std::vector<std::string>> allowedOrigins;+ const std::optional<bool> treatAsSecure;+ const std::optional<bool> hasAuthorityComponent;++ CustomSchemeRegistration(const std::string& scheme, const std::optional<std::vector<std::string>>& allowedOrigins, const std::optional<bool>& treatAsSecure, const std::optional<bool>& hasAuthorityComponent);+ CustomSchemeRegistration(const flutter::EncodableMap& map);+ ~CustomSchemeRegistration() = default;++ flutter::EncodableMap toEncodableMap() const;+ CoreWebView2CustomSchemeRegistration* toWebView2CustomSchemeRegistration() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_CUSTOM_SCHEME_REGISTRATION_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/custom_scheme_response.cpp b/packages/flutter_inappwebview_windows/windows/types/custom_scheme_response.cppnew file mode 100644index 00000000..848aa391--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/custom_scheme_response.cpp@@ -0,0 +1,62 @@+#include "../utils/flutter.h"+#include "../utils/string.h"+#include "custom_scheme_response.h"++#include <Shlwapi.h>++namespace flutter_inappwebview_plugin+{+ CustomSchemeResponse::CustomSchemeResponse(const std::vector<uint8_t>& data, const std::string& contentType, const std::string& contentEncoding)+ : data(data), contentType(contentType), contentEncoding(contentEncoding)+ {}++ CustomSchemeResponse::CustomSchemeResponse(const flutter::EncodableMap& map)+ : data(get_fl_map_value<std::vector<uint8_t>>(map, "data")),+ contentType(get_fl_map_value<std::string>(map, "contentType")),+ contentEncoding(get_fl_map_value<std::string>(map, "contentEncoding"))+ {}++ flutter::EncodableMap CustomSchemeResponse::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"data", make_fl_value(data)},+ {"contentType", make_fl_value(contentType)},+ {"contentEncoding", make_fl_value(contentEncoding)}+ };+ }++ ICoreWebView2WebResourceResponse* CustomSchemeResponse::toWebView2Response(const wil::com_ptr<ICoreWebView2Environment> webViewEnvironment) const+ {+ wil::com_ptr<ICoreWebView2WebResourceResponse> webResourceResponse;++ if (webViewEnvironment) {+ wil::com_ptr<IStream> postDataStream = nullptr;+ if (!data.empty()) {+ auto postData = std::string(data.begin(), data.end());+ postDataStream = SHCreateMemStream(+ reinterpret_cast<const BYTE*>(postData.data()), static_cast<UINT>(postData.length()));+ }++ webViewEnvironment->CreateWebResourceResponse(+ postDataStream.get(),+ 200, // Default to 200+ L"OK", // Default to "OK"+ nullptr,+ &webResourceResponse);++ wil::com_ptr<ICoreWebView2HttpResponseHeaders> responseHeaders;+ if (SUCCEEDED(webResourceResponse->get_Headers(&responseHeaders))) {+ if (!contentType.empty()) {+ responseHeaders->AppendHeader(L"Content-Type", utf8_to_wide(contentType).c_str());+ }+ if (!contentEncoding.empty()) {+ responseHeaders->AppendHeader(L"Content-Encoding", utf8_to_wide(contentEncoding).c_str());+ }+ }++ webResourceResponse->AddRef();+ }++ return webResourceResponse.get();+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/types/custom_scheme_response.h b/packages/flutter_inappwebview_windows/windows/types/custom_scheme_response.hnew file mode 100644index 00000000..6b98d909--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/custom_scheme_response.h@@ -0,0 +1,26 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_CUSTOM_SCHEME_RESPONSE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_CUSTOM_SCHEME_RESPONSE_H_++#include <flutter/standard_method_codec.h>+#include <WebView2.h>+#include <wil/com.h>++namespace flutter_inappwebview_plugin+{+ class CustomSchemeResponse+ {+ public:+ const std::vector<uint8_t> data;+ const std::string contentType;+ const std::string contentEncoding;++ CustomSchemeResponse(const std::vector<uint8_t>& data, const std::string& contentType, const std::string& contentEncoding);+ CustomSchemeResponse(const flutter::EncodableMap& map);+ ~CustomSchemeResponse() = default;++ flutter::EncodableMap toEncodableMap() const;+ ICoreWebView2WebResourceResponse* toWebView2Response(const wil::com_ptr<ICoreWebView2Environment> webViewEnvironment) const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_CUSTOM_SCHEME_RESPONSE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/navigation_action.cpp b/packages/flutter_inappwebview_windows/windows/types/navigation_action.cppnew file mode 100644index 00000000..543553e7--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/navigation_action.cpp@@ -0,0 +1,21 @@+#include "../utils/flutter.h"+#include "navigation_action.h"++namespace flutter_inappwebview_plugin+{+ NavigationAction::NavigationAction(std::shared_ptr<URLRequest> request, const bool& isForMainFrame,+ const std::optional<bool>& isRedirect, const std::optional<NavigationActionType>& navigationType)+ : request(std::move(request)), isForMainFrame(isForMainFrame),+ isRedirect(isRedirect), navigationType(navigationType)+ {}++ flutter::EncodableMap NavigationAction::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"request", request->toEncodableMap()},+ {"isForMainFrame", isForMainFrame},+ {"isRedirect", make_fl_value(isRedirect)},+ {"navigationType", make_fl_value(navigationType)}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/navigation_action.h b/packages/flutter_inappwebview_windows/windows/types/navigation_action.hnew file mode 100644index 00000000..886640be--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/navigation_action.h@@ -0,0 +1,33 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_NAVIGATION_ACTION_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_NAVIGATION_ACTION_H_++#include <flutter/standard_method_codec.h>+#include <optional>++#include "url_request.h"++namespace flutter_inappwebview_plugin+{+ enum NavigationActionType {+ linkActivated = 0,+ backForward,+ reload,+ other+ };++ class NavigationAction+ {+ public:+ const std::shared_ptr<URLRequest> request;+ const bool isForMainFrame;+ const std::optional<bool> isRedirect;+ const std::optional<NavigationActionType> navigationType;++ NavigationAction(std::shared_ptr<URLRequest> request, const bool& isForMainFrame, const std::optional<bool>& isRedirect, const std::optional<NavigationActionType>& navigationType);+ ~NavigationAction() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_NAVIGATION_ACTION_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/new_window_requested_args.cpp b/packages/flutter_inappwebview_windows/windows/types/new_window_requested_args.cppnew file mode 100644index 00000000..50c9f947--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/new_window_requested_args.cpp@@ -0,0 +1,9 @@+#include "new_window_requested_args.h"++namespace flutter_inappwebview_plugin+{+ NewWindowRequestedArgs::NewWindowRequestedArgs(wil::com_ptr<ICoreWebView2NewWindowRequestedEventArgs> args,+ wil::com_ptr<ICoreWebView2Deferral> deferral)+ : args(std::move(args)), deferral(std::move(deferral))+ {}+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/new_window_requested_args.h b/packages/flutter_inappwebview_windows/windows/types/new_window_requested_args.hnew file mode 100644index 00000000..781a854e--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/new_window_requested_args.h@@ -0,0 +1,20 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_NEW_WINDOW_REQUESTED_ARGS_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_NEW_WINDOW_REQUESTED_ARGS_H_++#include <WebView2.h>+#include <wil/com.h>++namespace flutter_inappwebview_plugin+{+ class NewWindowRequestedArgs+ {+ public:+ wil::com_ptr<ICoreWebView2NewWindowRequestedEventArgs> args;+ wil::com_ptr<ICoreWebView2Deferral> deferral;++ NewWindowRequestedArgs(wil::com_ptr<ICoreWebView2NewWindowRequestedEventArgs> args, wil::com_ptr<ICoreWebView2Deferral> deferral);+ ~NewWindowRequestedArgs() = default;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_NEW_WINDOW_REQUESTED_ARGS_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/permission_response.cpp b/packages/flutter_inappwebview_windows/windows/types/permission_response.cppnew file mode 100644index 00000000..e0559822--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/permission_response.cpp@@ -0,0 +1,21 @@+#include "permission_response.h"++namespace flutter_inappwebview_plugin+{+ PermissionResponse::PermissionResponse(const std::optional<std::vector<int64_t>>& resources, const std::optional<PermissionResponseActionType>& action)+ : resources(resources), action(action)+ {}++ PermissionResponse::PermissionResponse(const flutter::EncodableMap& map)+ : resources(get_optional_fl_map_value<std::vector<int64_t>>(map, "resources")),+ action(PermissionResponseActionTypeFromInteger(get_optional_fl_map_value<int64_t>(map, "action")))+ {}++ flutter::EncodableMap PermissionResponse::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"resources", make_fl_value(resources)},+ {"action", make_fl_value(action)},+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/permission_response.h b/packages/flutter_inappwebview_windows/windows/types/permission_response.hnew file mode 100644index 00000000..e9678314--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/permission_response.h@@ -0,0 +1,56 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_PERMISSION_RESPONSE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_PERMISSION_RESPONSE_H_++#include <flutter/standard_method_codec.h>+#include <WebView2.h>++#include "../utils/flutter.h"++namespace flutter_inappwebview_plugin+{+ enum PermissionResponseActionType {+ deny = 0,+ grant,+ prompt+ };++ inline PermissionResponseActionType PermissionResponseActionTypeFromInteger(const std::optional<int64_t>& action)+ {+ if (!action.has_value()) {+ return PermissionResponseActionType::prompt;+ }+ switch (action.value()) {+ case 0:+ return PermissionResponseActionType::deny;+ case 1:+ return PermissionResponseActionType::grant;+ case 2:+ default:+ return PermissionResponseActionType::prompt;+ }+ }++ class PermissionResponse+ {+ public:+ const std::optional<std::vector<int64_t>> resources;+ const std::optional<PermissionResponseActionType> action;++ PermissionResponse(const std::optional<std::vector<int64_t>>& resources, const std::optional<PermissionResponseActionType>& action);+ PermissionResponse(const flutter::EncodableMap& map);+ ~PermissionResponse() = default;++ bool PermissionResponse::operator==(const PermissionResponse& other)+ {+ return resources == other.resources && action == other.action;+ }+ bool PermissionResponse::operator!=(const PermissionResponse& other)+ {+ return !(*this == other);+ }++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_PERMISSION_RESPONSE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/plugin_script.cpp b/packages/flutter_inappwebview_windows/windows/types/plugin_script.cppnew file mode 100644index 00000000..cc37467a--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/plugin_script.cpp@@ -0,0 +1,30 @@+#include "plugin_script.h"++namespace flutter_inappwebview_plugin+{+ PluginScript::PluginScript(+ const std::optional<std::string>& groupName,+ const std::string& source,+ const UserScriptInjectionTime& injectionTime,+ const std::vector<std::string>& allowedOriginRules,+ std::shared_ptr<ContentWorld> contentWorld,+ const bool& requiredInAllContentWorlds+ ) : UserScript(groupName, source, injectionTime, allowedOriginRules, std::move(contentWorld)),+ requiredInAllContentWorlds_(requiredInAllContentWorlds)+ {}+++ std::shared_ptr<PluginScript> PluginScript::copyAndSet(const std::shared_ptr<ContentWorld> cw) const+ {+ return std::make_unique<PluginScript>(+ this->groupName,+ this->source,+ this->injectionTime,+ this->allowedOriginRules,+ cw,+ this->requiredInAllContentWorlds_+ );+ }++ PluginScript::~PluginScript() {}+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/plugin_script.h b/packages/flutter_inappwebview_windows/windows/types/plugin_script.hnew file mode 100644index 00000000..e2fae03f--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/plugin_script.h@@ -0,0 +1,33 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_SCRIPT_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_SCRIPT_H_++#include "user_script.h"++namespace flutter_inappwebview_plugin+{+ class PluginScript : public UserScript+ {+ public:++ PluginScript(+ const std::optional<std::string>& groupName,+ const std::string& source,+ const UserScriptInjectionTime& injectionTime,+ const std::vector<std::string>& allowedOriginRules,+ std::shared_ptr<ContentWorld> contentWorld,+ const bool& requiredInAllContentWorlds+ );+ ~PluginScript();++ bool isRequiredInAllContentWorlds() const+ {+ return requiredInAllContentWorlds_;+ }++ std::shared_ptr<PluginScript> copyAndSet(const std::shared_ptr<ContentWorld> cw) const;++ private:+ bool requiredInAllContentWorlds_;+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_PLUGIN_SCRIPT_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/rect.cpp b/packages/flutter_inappwebview_windows/windows/types/rect.cppnew file mode 100644index 00000000..a0a41ab0--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/rect.cpp@@ -0,0 +1,25 @@+#include "rect.h"++namespace flutter_inappwebview_plugin+{+ Rect::Rect(const double& x, const double& y, const double& width, const double& height)+ : x(x), y(y), width(width), height(height)+ {}++ Rect::Rect(const flutter::EncodableMap& map)+ : x(get_fl_map_value<double>(map, "x")),+ y(get_fl_map_value<double>(map, "y")),+ width(get_fl_map_value<double>(map, "width")),+ height(get_fl_map_value<double>(map, "height"))+ {}++ flutter::EncodableMap Rect::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"x", x},+ {"y", y},+ {"width", width},+ {"height", height}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/rect.h b/packages/flutter_inappwebview_windows/windows/types/rect.hnew file mode 100644index 00000000..57c94eeb--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/rect.h@@ -0,0 +1,36 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_RECT_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_RECT_H_++#include <flutter/standard_method_codec.h>+#include <optional>++#include "../utils/flutter.h"++namespace flutter_inappwebview_plugin+{+ class Rect+ {+ public:+ const double x;+ const double y;+ const double width;+ const double height;++ Rect(const double& x, const double& y, const double& width, const double& height);+ Rect(const flutter::EncodableMap& map);+ ~Rect() = default;++ bool Rect::operator==(const Rect& other)+ {+ return x == other.x && y == other.y && width == other.width && height == other.height;+ }+ bool Rect::operator!=(const Rect& other)+ {+ return !(*this == other);+ }++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_RECT_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/screenshot_configuration.cpp b/packages/flutter_inappwebview_windows/windows/types/screenshot_configuration.cppnew file mode 100644index 00000000..5e0f027e--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/screenshot_configuration.cpp@@ -0,0 +1,48 @@+#include "../utils/flutter.h"+#include "../utils/map.h"+#include "screenshot_configuration.h"++namespace flutter_inappwebview_plugin+{+ CompressFormat CompressFormatFromString(const std::string& compressFormat)+ {+ if (string_equals(compressFormat, "PNG")) {+ return CompressFormat::png;+ }+ else if (string_equals(compressFormat, "JPEG")) {+ return CompressFormat::jpeg;+ }+ else if (string_equals(compressFormat, "WEBP")) {+ return CompressFormat::webp;+ }+ return CompressFormat::png;+ }++ std::string CompressFormatToString(const CompressFormat& compressFormat)+ {+ switch (compressFormat) {+ case CompressFormat::jpeg:+ return "JPEG";+ case CompressFormat::webp:+ return "WEBP";+ case CompressFormat::png:+ default:+ return "PNG";+ }+ }++ ScreenshotConfiguration::ScreenshotConfiguration(+ const CompressFormat& compressFormat,+ const int64_t& quality,+ const std::optional<std::shared_ptr<Rect>> rect+ ) : compressFormat(compressFormat), quality(quality), rect(rect)+ {}++ ScreenshotConfiguration::ScreenshotConfiguration(const flutter::EncodableMap& map)+ : compressFormat(CompressFormatFromString(get_fl_map_value<std::string>(map, "compressFormat"))),+ quality(get_fl_map_value<int>(map, "quality")),+ rect(fl_map_contains_not_null(map, "rect") ? std::make_shared<Rect>(get_fl_map_value<flutter::EncodableMap>(map, "rect")) : std::optional<std::shared_ptr<Rect>>{})+ {}++ ScreenshotConfiguration::~ScreenshotConfiguration() {}+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/screenshot_configuration.h b/packages/flutter_inappwebview_windows/windows/types/screenshot_configuration.hnew file mode 100644index 00000000..f05ee7f0--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/screenshot_configuration.h@@ -0,0 +1,38 @@+#ifndef FLUTTER_INAPPWEBVIEW_SCREENSHOT_CONFIGURATION_H_+#define FLUTTER_INAPPWEBVIEW_SCREENSHOT_CONFIGURATION_H_++#include <flutter/standard_method_codec.h>+#include <optional>+#include <string>++#include "../types/rect.h"+#include "../utils/string.h"++namespace flutter_inappwebview_plugin+{+ enum CompressFormat {+ png,+ jpeg,+ webp+ };++ CompressFormat CompressFormatFromString(const std::string& compressFormat);+ std::string CompressFormatToString(const CompressFormat& compressFormat);++ class ScreenshotConfiguration+ {+ public:+ const CompressFormat compressFormat;+ const int64_t quality;+ const std::optional<std::shared_ptr<Rect>> rect;++ ScreenshotConfiguration(+ const CompressFormat& compressFormat,+ const int64_t& quality,+ const std::optional<std::shared_ptr<Rect>> rect+ );+ ScreenshotConfiguration(const flutter::EncodableMap& map);+ ~ScreenshotConfiguration();+ };+}+#endif //FLUTTER_INAPPWEBVIEW_SCREENSHOT_CONFIGURATION_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/size_2d.cpp b/packages/flutter_inappwebview_windows/windows/types/size_2d.cppnew file mode 100644index 00000000..e1239026--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/size_2d.cpp@@ -0,0 +1,21 @@+#include "size_2d.h"++namespace flutter_inappwebview_plugin+{+ Size2D::Size2D(const double& width, const double& height)+ : width(width), height(height)+ {}++ Size2D::Size2D(const flutter::EncodableMap& map)+ : width(get_fl_map_value<double>(map, "width")),+ height(get_fl_map_value<double>(map, "height"))+ {}++ flutter::EncodableMap Size2D::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"width", width},+ {"height", height}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/size_2d.h b/packages/flutter_inappwebview_windows/windows/types/size_2d.hnew file mode 100644index 00000000..e2cc28f6--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/size_2d.h@@ -0,0 +1,34 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_SIZE_2D_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_SIZE_2D_H_++#include <flutter/standard_method_codec.h>+#include <optional>++#include "../utils/flutter.h"++namespace flutter_inappwebview_plugin+{+ class Size2D+ {+ public:+ const double width;+ const double height;++ Size2D(const double& width, const double& height);+ Size2D(const flutter::EncodableMap& map);+ ~Size2D() = default;++ bool Size2D::operator==(const Size2D& other)+ {+ return width == other.width && height == other.height;+ }+ bool Size2D::operator!=(const Size2D& other)+ {+ return !(*this == other);+ }++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_SIZE_2D_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/ssl_certificate.cpp b/packages/flutter_inappwebview_windows/windows/types/ssl_certificate.cppnew file mode 100644index 00000000..8cd2f37c--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/ssl_certificate.cpp@@ -0,0 +1,16 @@+#include "../utils/flutter.h"+#include "ssl_certificate.h"++namespace flutter_inappwebview_plugin+{+ SslCertificate::SslCertificate(std::string x509Certificate)+ : x509Certificate(x509Certificate)+ {}++ flutter::EncodableMap SslCertificate::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"x509Certificate", make_fl_value(x509Certificate)}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/ssl_certificate.h b/packages/flutter_inappwebview_windows/windows/types/ssl_certificate.hnew file mode 100644index 00000000..649978cd--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/ssl_certificate.h@@ -0,0 +1,20 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_SSL_CERTIFICATE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_SSL_CERTIFICATE_H_++#include <flutter/standard_method_codec.h>++namespace flutter_inappwebview_plugin+{+ class SslCertificate+ {+ public:+ const std::string x509Certificate;++ SslCertificate(std::string x509Certificate);+ ~SslCertificate() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_SSL_CERTIFICATE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/url_request.cpp b/packages/flutter_inappwebview_windows/windows/types/url_request.cppnew file mode 100644index 00000000..42340dd0--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/url_request.cpp@@ -0,0 +1,27 @@+#include "../utils/flutter.h"+#include "url_request.h"++namespace flutter_inappwebview_plugin+{+ URLRequest::URLRequest(const std::optional<std::string>& url, const std::optional<std::string>& method,+ const std::optional<std::map<std::string, std::string>>& headers, const std::optional<std::vector<uint8_t>>& body)+ : url(url), method(method), headers(headers), body(body)+ {}++ URLRequest::URLRequest(const flutter::EncodableMap& map)+ : url(get_optional_fl_map_value<std::string>(map, "url")),+ method(get_optional_fl_map_value<std::string>(map, "method")),+ headers(get_optional_fl_map_value<std::map<std::string, std::string>>(map, "headers")),+ body(get_optional_fl_map_value<std::vector<uint8_t>>(map, "body"))+ {}++ flutter::EncodableMap URLRequest::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"url", make_fl_value(url)},+ {"method", make_fl_value(method)},+ {"headers", make_fl_value(headers)},+ {"body", make_fl_value(body)}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/url_request.h b/packages/flutter_inappwebview_windows/windows/types/url_request.hnew file mode 100644index 00000000..ded69b6e--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/url_request.h@@ -0,0 +1,26 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_URL_REQUEST_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_URL_REQUEST_H_++#include <flutter/standard_method_codec.h>+#include <optional>++namespace flutter_inappwebview_plugin+{+ class URLRequest+ {+ public:+ const std::optional<std::string> url;+ const std::optional<std::string> method;+ const std::optional<std::map<std::string, std::string>> headers;+ const std::optional<std::vector<uint8_t>> body;++ URLRequest(const std::optional<std::string>& url, const std::optional<std::string>& method,+ const std::optional<std::map<std::string, std::string>>& headers, const std::optional<std::vector<uint8_t>>& body);+ URLRequest(const flutter::EncodableMap& map);+ ~URLRequest() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_URL_REQUEST_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/user_script.cpp b/packages/flutter_inappwebview_windows/windows/types/user_script.cppnew file mode 100644index 00000000..6a783fe0--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/user_script.cpp@@ -0,0 +1,25 @@+#include "../utils/map.h"+#include "user_script.h"++namespace flutter_inappwebview_plugin+{+ UserScript::UserScript(+ const std::optional<std::string>& groupName,+ const std::string& source,+ const UserScriptInjectionTime& injectionTime,+ const std::vector<std::string>& allowedOriginRules,+ std::shared_ptr<ContentWorld> contentWorld+ ) : groupName(groupName), source(source), injectionTime(injectionTime), allowedOriginRules(allowedOriginRules), contentWorld(std::move(contentWorld))+ {}++ UserScript::UserScript(const flutter::EncodableMap& map)+ : groupName(get_optional_fl_map_value<std::string>(map, "groupName")),+ source(get_fl_map_value<std::string>(map, "source")),+ injectionTime(static_cast<UserScriptInjectionTime>(get_fl_map_value<int>(map, "injectionTime"))),+ allowedOriginRules(functional_map(get_fl_map_value<flutter::EncodableList>(map, "allowedOriginRules"), [](const flutter::EncodableValue& m) { return std::get<std::string>(m); })),+ contentWorld(std::make_shared<ContentWorld>(get_fl_map_value<flutter::EncodableMap>(map, "contentWorld")))+ {}++ UserScript::~UserScript()+ {}+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/user_script.h b/packages/flutter_inappwebview_windows/windows/types/user_script.hnew file mode 100644index 00000000..473661f0--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/user_script.h@@ -0,0 +1,40 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_USER_SCRIPT_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_USER_SCRIPT_H_++#include <flutter/standard_method_codec.h>+#include <optional>+#include <string>+#include <vector>++#include "../utils/flutter.h"+#include "content_world.h"++namespace flutter_inappwebview_plugin+{+ enum UserScriptInjectionTime {+ atDocumentStart = 0,+ atDocumentEnd+ };++ class UserScript+ {+ public:+ std::string id;+ const std::optional<std::string> groupName;+ const std::string source;+ const UserScriptInjectionTime injectionTime;+ const std::vector<std::string> allowedOriginRules;+ const std::shared_ptr<ContentWorld> contentWorld;++ UserScript(+ const std::optional<std::string>& groupName,+ const std::string& source,+ const UserScriptInjectionTime& injectionTime,+ const std::vector<std::string>& allowedOriginRules,+ std::shared_ptr<ContentWorld> contentWorld+ );+ UserScript(const flutter::EncodableMap& map);+ ~UserScript();+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_USER_SCRIPT_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/web_history.cpp b/packages/flutter_inappwebview_windows/windows/types/web_history.cppnew file mode 100644index 00000000..aa89d9a2--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_history.cpp@@ -0,0 +1,22 @@+#include "../utils/vector.h"+#include "web_history.h"++namespace flutter_inappwebview_plugin+{+ WebHistory::WebHistory(const std::optional<int64_t> currentIndex, const std::optional<std::vector<std::shared_ptr<WebHistoryItem>>>& list)+ : currentIndex(currentIndex), list(list)+ {}++ WebHistory::WebHistory(const flutter::EncodableMap& map)+ : currentIndex(get_optional_fl_map_value<int64_t>(map, "currentIndex")),+ list(functional_map(get_optional_fl_map_value<flutter::EncodableList>(map, "list"), [](const flutter::EncodableValue& m) { return std::make_shared<WebHistoryItem>(std::get<flutter::EncodableMap>(m)); }))+ {}++ flutter::EncodableMap WebHistory::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"currentIndex", make_fl_value(currentIndex)},+ {"list", make_fl_value(functional_map(list, [](const std::shared_ptr<WebHistoryItem>& item) { return item->toEncodableMap(); }))}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/web_history.h b/packages/flutter_inappwebview_windows/windows/types/web_history.hnew file mode 100644index 00000000..95c41bad--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_history.h@@ -0,0 +1,26 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_HISTORY_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_HISTORY_H_++#include <flutter/standard_method_codec.h>+#include <optional>++#include "../utils/flutter.h"+#include "web_history_item.h"++namespace flutter_inappwebview_plugin+{+ class WebHistory+ {+ public:+ const std::optional<int64_t> currentIndex;+ const std::optional<std::vector<std::shared_ptr<WebHistoryItem>>> list;++ WebHistory(const std::optional<int64_t> currentIndex, const std::optional<std::vector<std::shared_ptr<WebHistoryItem>>>& list);+ WebHistory(const flutter::EncodableMap& map);+ ~WebHistory() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_HISTORY_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/web_history_item.cpp b/packages/flutter_inappwebview_windows/windows/types/web_history_item.cppnew file mode 100644index 00000000..11350eeb--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_history_item.cpp@@ -0,0 +1,31 @@+#include "web_history_item.h"++namespace flutter_inappwebview_plugin+{+ WebHistoryItem::WebHistoryItem(const std::optional<int64_t>& entryId, const std::optional<int64_t>& index, const std::optional<int64_t>& offset,+ const std::optional<std::string>& originalUrl, const std::optional<std::string>& title,+ const std::optional<std::string>& url)+ : entryId(entryId), index(index), offset(offset), originalUrl(originalUrl), title(title), url(url)+ {}++ WebHistoryItem::WebHistoryItem(const flutter::EncodableMap& map)+ : entryId(get_optional_fl_map_value<int64_t>(map, "entryId")),+ index(get_optional_fl_map_value<int64_t>(map, "index")),+ offset(get_optional_fl_map_value<int64_t>(map, "offset")),+ originalUrl(get_optional_fl_map_value<std::string>(map, "originalUrl")),+ title(get_optional_fl_map_value<std::string>(map, "title")),+ url(get_optional_fl_map_value<std::string>(map, "url"))+ {}++ flutter::EncodableMap WebHistoryItem::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"entryId", make_fl_value(entryId)},+ {"index", make_fl_value(index)},+ {"offset", make_fl_value(offset)},+ {"originalUrl", make_fl_value(originalUrl)},+ {"title", make_fl_value(title)},+ {"url", make_fl_value(url)}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/web_history_item.h b/packages/flutter_inappwebview_windows/windows/types/web_history_item.hnew file mode 100644index 00000000..e58181e3--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_history_item.h@@ -0,0 +1,31 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_HISTORY_ITEM_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_HISTORY_ITEM_H_++#include <flutter/standard_method_codec.h>+#include <optional>++#include "../utils/flutter.h"++namespace flutter_inappwebview_plugin+{+ class WebHistoryItem+ {+ public:+ const std::optional<int64_t> entryId;+ const std::optional<int64_t> index;+ const std::optional<int64_t> offset;+ const std::optional<std::string> originalUrl;+ const std::optional<std::string> title;+ const std::optional<std::string> url;++ WebHistoryItem(const std::optional<int64_t>& entryId, const std::optional<int64_t>& index, const std::optional<int64_t>& offset,+ const std::optional<std::string>& originalUrl, const std::optional<std::string>& title,+ const std::optional<std::string>& url);+ WebHistoryItem(const flutter::EncodableMap& map);+ ~WebHistoryItem() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_HISTORY_ITEM_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/web_resource_error.cpp b/packages/flutter_inappwebview_windows/windows/types/web_resource_error.cppnew file mode 100644index 00000000..5059a3dc--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_resource_error.cpp@@ -0,0 +1,22 @@+#include "../utils/flutter.h"+#include "web_resource_error.h"++namespace flutter_inappwebview_plugin+{+ WebResourceError::WebResourceError(const std::string& description, const int64_t type)+ : description(description), type(type)+ {}++ WebResourceError::WebResourceError(const flutter::EncodableMap& map)+ : description(get_fl_map_value<std::string>(map, "description")),+ type(get_fl_map_value<int>(map, "type"))+ {}++ flutter::EncodableMap WebResourceError::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"description", make_fl_value(description)},+ {"type", make_fl_value(type)}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/web_resource_error.h b/packages/flutter_inappwebview_windows/windows/types/web_resource_error.hnew file mode 100644index 00000000..f5a0a5aa--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_resource_error.h@@ -0,0 +1,46 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_RESOURCE_ERROR_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_RESOURCE_ERROR_H_++#include <flutter/standard_method_codec.h>+#include <optional>++namespace flutter_inappwebview_plugin+{+ static const std::string WebErrorStatusDescription[] =+ {+ "Indicates that an unknown error occurred.",+ "Indicates that the SSL certificate common name does not match the web address.",+ "Indicates that the SSL certificate has expired.",+ "Indicates that the SSL client certificate contains errors.",+ "Indicates that the SSL certificate has been revoked.",+ "Indicates that the SSL certificate is not valid.",+ "Indicates that the host is unreachable.",+ "Indicates that the connection has timed out.",+ "Indicates that the server returned an invalid or unrecognized response.",+ "Indicates that the connection was stopped.",+ "Indicates that the connection was reset.",+ "Indicates that the Internet connection has been lost.",+ "Indicates that a connection to the destination was not established.",+ "Indicates that the provided host name was not able to be resolved.",+ "Indicates that the operation was canceled.",+ "Indicates that the request redirect failed.",+ "Indicates that an unexpected error occurred.",+ "Indicates that user is prompted with a login, waiting on user action.",+ "Indicates that user lacks proper authentication credentials for a proxy server.",+ };++ class WebResourceError+ {+ public:+ const std::string description;+ const int64_t type;++ WebResourceError(const std::string& description, const int64_t type);+ WebResourceError(const flutter::EncodableMap& map);+ ~WebResourceError() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_RESOURCE_ERROR_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/web_resource_request.cpp b/packages/flutter_inappwebview_windows/windows/types/web_resource_request.cppnew file mode 100644index 00000000..437fa190--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_resource_request.cpp@@ -0,0 +1,59 @@+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "web_resource_request.h"++namespace flutter_inappwebview_plugin+{+ WebResourceRequest::WebResourceRequest(const std::optional<std::string>& url, const std::optional<std::string>& method,+ const std::optional<std::map<std::string, std::string>>& headers, const std::optional<bool>& isForMainFrame)+ : url(url), method(method), headers(headers), isForMainFrame(isForMainFrame)+ {}++ WebResourceRequest::WebResourceRequest(const flutter::EncodableMap& map)+ : url(get_optional_fl_map_value<std::string>(map, "url")),+ method(get_optional_fl_map_value<std::string>(map, "method")),+ headers(get_optional_fl_map_value<std::map<std::string, std::string>>(map, "headers")),+ isForMainFrame(get_optional_fl_map_value<bool>(map, "isForMainFrame"))+ {}++ WebResourceRequest::WebResourceRequest(wil::com_ptr<ICoreWebView2WebResourceRequest> webResourceRequest)+ {+ wil::unique_cotaskmem_string uri;+ url = SUCCEEDED(webResourceRequest->get_Uri(&uri)) ? wide_to_utf8(uri.get()) : std::optional<std::string>{};++ wil::unique_cotaskmem_string methodStr;+ method = SUCCEEDED(webResourceRequest->get_Method(&methodStr)) ? wide_to_utf8(methodStr.get()) : std::optional<std::string>{};++ // Get the headers+ wil::com_ptr<ICoreWebView2HttpRequestHeaders> requestHeaders;+ if (SUCCEEDED(webResourceRequest->get_Headers(&requestHeaders))) {+ std::map<std::string, std::string> headersMap;+ wil::com_ptr<ICoreWebView2HttpHeadersCollectionIterator> iterator;+ if (SUCCEEDED(requestHeaders->GetIterator(&iterator))) {+ BOOL hasCurrent = FALSE;+ iterator->get_HasCurrentHeader(&hasCurrent);+ while (hasCurrent) {+ wil::unique_cotaskmem_string name, value;+ iterator->GetCurrentHeader(&name, &value);+ headersMap.emplace(wide_to_utf8(name.get()), wide_to_utf8(value.get()));+ iterator->MoveNext(&hasCurrent);+ }+ if (!headersMap.empty()) {+ headers = headersMap;+ }+ }+ }++ isForMainFrame = true;+ }++ flutter::EncodableMap WebResourceRequest::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"url", make_fl_value(url)},+ {"method", make_fl_value(method)},+ {"headers", make_fl_value(headers)},+ {"isForMainFrame", make_fl_value(isForMainFrame)}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/web_resource_request.h b/packages/flutter_inappwebview_windows/windows/types/web_resource_request.hnew file mode 100644index 00000000..39f559a8--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_resource_request.h@@ -0,0 +1,29 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_RESOURCE_REQUEST_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_RESOURCE_REQUEST_H_++#include <flutter/standard_method_codec.h>+#include <optional>+#include <WebView2.h>+#include <wil/com.h>++namespace flutter_inappwebview_plugin+{+ class WebResourceRequest+ {+ public:+ std::optional<std::string> url;+ std::optional<std::string> method;+ std::optional<std::map<std::string, std::string>> headers;+ std::optional<bool> isForMainFrame;++ WebResourceRequest(const std::optional<std::string>& url, const std::optional<std::string>& method,+ const std::optional<std::map<std::string, std::string>>& headers, const std::optional<bool>& isForMainFrame);+ WebResourceRequest(const flutter::EncodableMap& map);+ WebResourceRequest(wil::com_ptr<ICoreWebView2WebResourceRequest> webResourceRequest);+ ~WebResourceRequest() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_RESOURCE_REQUEST_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/web_resource_response.cpp b/packages/flutter_inappwebview_windows/windows/types/web_resource_response.cppnew file mode 100644index 00000000..bd17832c--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_resource_response.cpp@@ -0,0 +1,80 @@+#include "../utils/flutter.h"+#include "../utils/strconv.h"+#include "web_resource_response.h"++#include <Shlwapi.h>++namespace flutter_inappwebview_plugin+{+ WebResourceResponse::WebResourceResponse(const std::optional<std::string>& contentType,+ const std::optional<std::string>& contentEncoding,+ const std::optional<int64_t>& statusCode,+ const std::optional<std::string>& reasonPhrase,+ const std::optional<std::map<std::string, std::string>>& headers,+ const std::optional<std::vector<uint8_t>>& data)+ : contentType(contentType), contentEncoding(contentEncoding), statusCode(statusCode),+ reasonPhrase(reasonPhrase), headers(headers), data(data)+ {}++ WebResourceResponse::WebResourceResponse(const flutter::EncodableMap& map)+ : contentType(get_optional_fl_map_value<std::string>(map, "contentType")),+ contentEncoding(get_optional_fl_map_value<std::string>(map, "contentEncoding")),+ statusCode(get_optional_fl_map_value<int64_t>(map, "statusCode")),+ reasonPhrase(get_optional_fl_map_value<std::string>(map, "reasonPhrase")),+ headers(get_optional_fl_map_value<std::map<std::string, std::string>>(map, "headers")),+ data(get_optional_fl_map_value<std::vector<uint8_t>>(map, "data"))+ {}++ flutter::EncodableMap WebResourceResponse::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"contentEncoding", make_fl_value(contentEncoding)},+ {"contentType", make_fl_value(contentType)},+ {"statusCode", make_fl_value(statusCode)},+ {"reasonPhrase", make_fl_value(reasonPhrase)},+ {"headers", make_fl_value(headers)},+ {"data", make_fl_value(data)}+ };+ }++ ICoreWebView2WebResourceResponse* WebResourceResponse::toWebView2Response(const wil::com_ptr<ICoreWebView2Environment> webViewEnvironment) const+ {+ wil::com_ptr<ICoreWebView2WebResourceResponse> webResourceResponse;++ if (webViewEnvironment) {+ wil::com_ptr<IStream> postDataStream = nullptr;+ if (data.has_value()) {+ auto postData = std::string(data.value().begin(), data.value().end());+ postDataStream = SHCreateMemStream(+ reinterpret_cast<const BYTE*>(postData.data()), static_cast<UINT>(postData.length()));+ }++ webViewEnvironment->CreateWebResourceResponse(+ postDataStream.get(),+ statusCode.value_or(200), // Default to 200 if statusCode is not set+ reasonPhrase.has_value() ? utf8_to_wide(reasonPhrase.value()).c_str() : L"OK", // Default to "OK" if reasonPhrase is not set+ nullptr,+ &webResourceResponse);++ wil::com_ptr<ICoreWebView2HttpResponseHeaders> responseHeaders;+ if (SUCCEEDED(webResourceResponse->get_Headers(&responseHeaders))) {+ // Set the headers+ if (headers.has_value()) {+ for (auto const& [key, val] : headers.value()) {+ responseHeaders->AppendHeader(utf8_to_wide(key).c_str(), utf8_to_wide(val).c_str());+ }+ }+ if (contentType.has_value() && !contentType.value().empty()) {+ responseHeaders->AppendHeader(L"Content-Type", utf8_to_wide(contentType.value()).c_str());+ }+ if (contentEncoding.has_value() && !contentEncoding.value().empty()) {+ responseHeaders->AppendHeader(L"Content-Encoding", utf8_to_wide(contentEncoding.value()).c_str());+ }+ }++ webResourceResponse->AddRef();+ }++ return webResourceResponse.get();+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/types/web_resource_response.h b/packages/flutter_inappwebview_windows/windows/types/web_resource_response.hnew file mode 100644index 00000000..0cc4ed52--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/web_resource_response.h@@ -0,0 +1,35 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_RESOURCE_RESPONSE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_RESOURCE_RESPONSE_H_++#include <flutter/standard_method_codec.h>+#include <optional>+#include <WebView2.h>+#include <wil/com.h>++namespace flutter_inappwebview_plugin+{+ class WebResourceResponse+ {+ public:+ const std::optional<std::string> contentType;+ const std::optional<std::string> contentEncoding;+ const std::optional<int64_t> statusCode;+ const std::optional<std::string> reasonPhrase;+ const std::optional<std::map<std::string, std::string>> headers;+ const std::optional<std::vector<uint8_t>> data;++ WebResourceResponse(const std::optional<std::string>& contentType,+ const std::optional<std::string>& contentEncoding,+ const std::optional<int64_t>& statusCode,+ const std::optional<std::string>& reasonPhrase,+ const std::optional<std::map<std::string, std::string>>& headers,+ const std::optional<std::vector<uint8_t>>& data);+ WebResourceResponse(const flutter::EncodableMap& map);+ ~WebResourceResponse() = default;++ flutter::EncodableMap toEncodableMap() const;+ ICoreWebView2WebResourceResponse* WebResourceResponse::toWebView2Response(const wil::com_ptr<ICoreWebView2Environment> webViewEnvironment) const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEB_RESOURCE_RESPONSE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/window_features.cpp b/packages/flutter_inappwebview_windows/windows/types/window_features.cppnew file mode 100644index 00000000..513528df--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/window_features.cpp@@ -0,0 +1,63 @@+#include "../utils/flutter.h"+#include "window_features.h"++namespace flutter_inappwebview_plugin+{+ WindowFeatures::WindowFeatures(const std::optional<double>& width,+ const std::optional<double>& height,+ const std::optional<double>& x,+ const std::optional<double>& y,+ const std::optional<bool>& menuBarVisibility,+ const std::optional<bool>& statusBarVisibility,+ const std::optional<bool>& toolbarsVisibility)+ : width(width), height(height), x(x), y(y),+ menuBarVisibility(menuBarVisibility), statusBarVisibility(statusBarVisibility),+ toolbarsVisibility(toolbarsVisibility)+ {}++ WindowFeatures::WindowFeatures(const wil::com_ptr<ICoreWebView2WindowFeatures> features)+ {+ UINT32 _x = 0;+ UINT32 _y = 0;+ UINT32 _height = 0;+ UINT32 _width = 0;+ BOOL _menuBarVisibility = FALSE;+ BOOL _statusBarVisibility = FALSE;+ BOOL _toolbarsVisibility = FALSE;++ if (SUCCEEDED(features->get_Left(&_x))) {+ x = static_cast<double>(_x);+ }+ if (SUCCEEDED(features->get_Top(&_y))) {+ y = static_cast<double>(_y);+ }+ if (SUCCEEDED(features->get_Height(&_height))) {+ height = static_cast<double>(_height);+ }+ if (SUCCEEDED(features->get_Width(&_width))) {+ width = static_cast<double>(_width);+ }+ if (SUCCEEDED(features->get_ShouldDisplayMenuBar(&_menuBarVisibility))) {+ menuBarVisibility = static_cast<bool>(_menuBarVisibility);+ }+ if (SUCCEEDED(features->get_ShouldDisplayStatus(&_statusBarVisibility))) {+ statusBarVisibility = static_cast<bool>(_statusBarVisibility);+ }+ if (SUCCEEDED(features->get_ShouldDisplayToolbar(&_toolbarsVisibility))) {+ toolbarsVisibility = static_cast<bool>(_toolbarsVisibility);+ }+ }++ flutter::EncodableMap WindowFeatures::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"width", make_fl_value(width)},+ {"height", make_fl_value(height)},+ {"x", make_fl_value(x)},+ {"y", make_fl_value(y)},+ {"menuBarVisibility", make_fl_value(menuBarVisibility)},+ {"statusBarVisibility", make_fl_value(statusBarVisibility)},+ {"toolbarsVisibility", make_fl_value(toolbarsVisibility)}+ };+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/types/window_features.h b/packages/flutter_inappwebview_windows/windows/types/window_features.hnew file mode 100644index 00000000..9c5f124d--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/types/window_features.h@@ -0,0 +1,38 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WINDOW_FEATURES_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WINDOW_FEATURES_H_++#include <flutter/standard_method_codec.h>+#include <optional>+#include <WebView2.h>+#include <wil/com.h>++namespace flutter_inappwebview_plugin+{+ class WindowFeatures+ {+ public:+ std::optional<double> width;+ std::optional<double> height;+ std::optional<double> x;+ std::optional<double> y;+ std::optional<bool> menuBarVisibility;+ std::optional<bool> statusBarVisibility;+ std::optional<bool> toolbarsVisibility;++ WindowFeatures(const std::optional<double>& width,+ const std::optional<double>& height,+ const std::optional<double>& x,+ const std::optional<double>& y,+ const std::optional<bool>& menuBarVisibility,+ const std::optional<bool>& statusBarVisibility,+ const std::optional<bool>& toolbarsVisibility);++ WindowFeatures(wil::com_ptr<ICoreWebView2WindowFeatures> features);++ ~WindowFeatures() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WINDOW_FEATURES_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/utils/base64.cpp b/packages/flutter_inappwebview_windows/windows/utils/base64.cppnew file mode 100644index 00000000..843719ec--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/utils/base64.cpp@@ -0,0 +1,282 @@+/*+ base64.cpp and base64.h++ base64 encoding and decoding with C++.+ More information at+ https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp++ Version: 2.rc.09 (release candidate)++ Copyright (C) 2004-2017, 2020-2022 René Nyffenegger++ This source code is provided 'as-is', without any express or implied+ warranty. In no event will the author be held liable for any damages+ arising from the use of this software.++ Permission is granted to anyone to use this software for any purpose,+ including commercial applications, and to alter it and redistribute it+ freely, subject to the following restrictions:++ 1. The origin of this source code must not be misrepresented; you must not+ claim that you wrote the original source code. If you use this source code+ in a product, an acknowledgment in the product documentation would be+ appreciated but is not required.++ 2. Altered source versions must be plainly marked as such, and must not be+ misrepresented as being the original source code.++ 3. This notice may not be removed or altered from any source distribution.++ René Nyffenegger [email protected]++*/++#include "base64.h"++#include <algorithm>+#include <stdexcept>++ //+ // Depending on the url parameter in base64_chars, one of+ // two sets of base64 characters needs to be chosen.+ // They differ in their last two characters.+ //+static const char* base64_chars[2] = {+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ "abcdefghijklmnopqrstuvwxyz"+ "0123456789"+ "+/",++ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ "abcdefghijklmnopqrstuvwxyz"+ "0123456789"+ "-_"};++static unsigned int pos_of_char(const unsigned char chr) {+ //+ // Return the position of chr within base64_encode()+ //++ if (chr >= 'A' && chr <= 'Z') return chr - 'A';+ else if (chr >= 'a' && chr <= 'z') return chr - 'a' + ('Z' - 'A') + 1;+ else if (chr >= '0' && chr <= '9') return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2;+ else if (chr == '+' || chr == '-') return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters (+ else if (chr == '/' || chr == '_') return 63; // Ditto for '/' and '_'+ else+ //+ // 2020-10-23: Throw std::exception rather than const char*+ //(Pablo Martin-Gomez, https://github.com/Bouska)+ //+ throw std::runtime_error("Input is not valid base64-encoded data.");+}++static std::string insert_linebreaks(std::string str, size_t distance) {+ //+ // Provided by https://github.com/JomaCorpFX, adapted by me.+ //+ if (!str.length()) {+ return "";+ }++ size_t pos = distance;++ while (pos < str.size()) {+ str.insert(pos, "\n");+ pos += distance + 1;+ }++ return str;+}++template <typename String, unsigned int line_length>+static std::string encode_with_line_breaks(String s) {+ return insert_linebreaks(base64_encode(s, false), line_length);+}++template <typename String>+static std::string encode_pem(String s) {+ return encode_with_line_breaks<String, 64>(s);+}++template <typename String>+static std::string encode_mime(String s) {+ return encode_with_line_breaks<String, 76>(s);+}++template <typename String>+static std::string encode(String s, bool url) {+ return base64_encode(reinterpret_cast<const unsigned char*>(s.data()), s.length(), url);+}++std::string base64_encode(unsigned char const* bytes_to_encode, size_t in_len, bool url) {++ size_t len_encoded = (in_len +2) / 3 * 4;++ unsigned char trailing_char = url ? '.' : '=';++ //+ // Choose set of base64 characters. They differ+ // for the last two positions, depending on the url+ // parameter.+ // A bool (as is the parameter url) is guaranteed+ // to evaluate to either 0 or 1 in C++ therefore,+ // the correct character set is chosen by subscripting+ // base64_chars with url.+ //+ const char* base64_chars_ = base64_chars[url];++ std::string ret;+ ret.reserve(len_encoded);++ unsigned int pos = 0;++ while (pos < in_len) {+ ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0xfc) >> 2]);++ if (pos+1 < in_len) {+ ret.push_back(base64_chars_[((bytes_to_encode[pos + 0] & 0x03) << 4) + ((bytes_to_encode[pos + 1] & 0xf0) >> 4)]);++ if (pos+2 < in_len) {+ ret.push_back(base64_chars_[((bytes_to_encode[pos + 1] & 0x0f) << 2) + ((bytes_to_encode[pos + 2] & 0xc0) >> 6)]);+ ret.push_back(base64_chars_[ bytes_to_encode[pos + 2] & 0x3f]);+ }+ else {+ ret.push_back(base64_chars_[(bytes_to_encode[pos + 1] & 0x0f) << 2]);+ ret.push_back(trailing_char);+ }+ }+ else {++ ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0x03) << 4]);+ ret.push_back(trailing_char);+ ret.push_back(trailing_char);+ }++ pos += 3;+ }+++ return ret;+}++template <typename String>+static std::string decode(String const& encoded_string, bool remove_linebreaks) {+ //+ // decode(…) is templated so that it can be used with String = const std::string&+ // or std::string_view (requires at least C++17)+ //++ if (encoded_string.empty()) return std::string();++ if (remove_linebreaks) {++ std::string copy(encoded_string);++ copy.erase(std::remove(copy.begin(), copy.end(), '\n'), copy.end());++ return base64_decode(copy, false);+ }++ size_t length_of_string = encoded_string.length();+ size_t pos = 0;++ //+ // The approximate length (bytes) of the decoded string might be one or+ // two bytes smaller, depending on the amount of trailing equal signs+ // in the encoded string. This approximation is needed to reserve+ // enough space in the string to be returned.+ //+ size_t approx_length_of_decoded_string = length_of_string / 4 * 3;+ std::string ret;+ ret.reserve(approx_length_of_decoded_string);++ while (pos < length_of_string) {+ //+ // Iterate over encoded input string in chunks. The size of all+ // chunks except the last one is 4 bytes.+ //+ // The last chunk might be padded with equal signs or dots+ // in order to make it 4 bytes in size as well, but this+ // is not required as per RFC 2045.+ //+ // All chunks except the last one produce three output bytes.+ //+ // The last chunk produces at least one and up to three bytes.+ //++ size_t pos_of_char_1 = pos_of_char(encoded_string.at(pos+1) );++ //+ // Emit the first output byte that is produced in each chunk:+ //+ ret.push_back(static_cast<std::string::value_type>( ( (pos_of_char(encoded_string.at(pos+0)) ) << 2 ) + ( (pos_of_char_1 & 0x30 ) >> 4)));++ if ( ( pos + 2 < length_of_string ) && // Check for data that is not padded with equal signs (which is allowed by RFC 2045)+ encoded_string.at(pos+2) != '=' &&+ encoded_string.at(pos+2) != '.' // accept URL-safe base 64 strings, too, so check for '.' also.+ )+ {+ //+ // Emit a chunk's second byte (which might not be produced in the last chunk).+ //+ unsigned int pos_of_char_2 = pos_of_char(encoded_string.at(pos+2) );+ ret.push_back(static_cast<std::string::value_type>( (( pos_of_char_1 & 0x0f) << 4) + (( pos_of_char_2 & 0x3c) >> 2)));++ if ( ( pos + 3 < length_of_string ) &&+ encoded_string.at(pos+3) != '=' &&+ encoded_string.at(pos+3) != '.'+ )+ {+ //+ // Emit a chunk's third byte (which might not be produced in the last chunk).+ //+ ret.push_back(static_cast<std::string::value_type>( ( (pos_of_char_2 & 0x03 ) << 6 ) + pos_of_char(encoded_string.at(pos+3)) ));+ }+ }++ pos += 4;+ }++ return ret;+}++std::string base64_decode(std::string const& s, bool remove_linebreaks) {+ return decode(s, remove_linebreaks);+}++std::string base64_encode(std::string const& s, bool url) {+ return encode(s, url);+}++std::string base64_encode_pem (std::string const& s) {+ return encode_pem(s);+}++std::string base64_encode_mime(std::string const& s) {+ return encode_mime(s);+}++#if __cplusplus >= 201703L+//+// Interface with std::string_view rather than const std::string&+// Requires C++17+// Provided by Yannic Bonenberger (https://github.com/Yannic)+//++std::string base64_encode(std::string_view s, bool url) {+ return encode(s, url);+}++std::string base64_encode_pem(std::string_view s) {+ return encode_pem(s);+}++std::string base64_encode_mime(std::string_view s) {+ return encode_mime(s);+}++std::string base64_decode(std::string_view s, bool remove_linebreaks) {+ return decode(s, remove_linebreaks);+}++#endif // __cplusplus >= 201703Ldiff --git a/packages/flutter_inappwebview_windows/windows/utils/base64.h b/packages/flutter_inappwebview_windows/windows/utils/base64.hnew file mode 100644index 00000000..4860d63d--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/utils/base64.h@@ -0,0 +1,35 @@+//+// base64 encoding and decoding with C++.+// Version: 2.rc.09 (release candidate)+//++#ifndef BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A+#define BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A++#include <string>++#if __cplusplus >= 201703L+#include <string_view>+#endif // __cplusplus >= 201703L++std::string base64_encode (std::string const& s, bool url = false);+std::string base64_encode_pem (std::string const& s);+std::string base64_encode_mime(std::string const& s);++std::string base64_decode(std::string const& s, bool remove_linebreaks = false);+std::string base64_encode(unsigned char const*, size_t len, bool url = false);++#if __cplusplus >= 201703L+//+// Interface with std::string_view rather than const std::string&+// Requires C++17+// Provided by Yannic Bonenberger (https://github.com/Yannic)+//+std::string base64_encode (std::string_view s, bool url = false);+std::string base64_encode_pem (std::string_view s);+std::string base64_encode_mime(std::string_view s);++std::string base64_decode(std::string_view s, bool remove_linebreaks = false);+#endif // __cplusplus >= 201703L++#endif /* BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A */diff --git a/packages/flutter_inappwebview_windows/windows/utils/flutter.h b/packages/flutter_inappwebview_windows/windows/utils/flutter.hnew file mode 100644index 00000000..45c1390c--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/utils/flutter.h@@ -0,0 +1,197 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_FLUTTER_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_FLUTTER_H_++#include <flutter/encodable_value.h>++#include "map.h"+#include "util.h"+#include "vector.h"++namespace flutter_inappwebview_plugin+{+ static inline flutter::EncodableValue make_fl_value()+ {+ return flutter::EncodableValue();+ }++ template<typename T>+ static inline flutter::EncodableValue make_fl_value(const T& val)+ {+ return flutter::EncodableValue(val);+ }++ template<typename T>+ static inline flutter::EncodableValue make_fl_value(const T* val)+ {+ return val == nullptr ? make_fl_value() : flutter::EncodableValue(val);+ }++ template<typename T>+ static inline flutter::EncodableValue make_fl_value(const std::vector<T>& vec)+ {+ auto encodableList = flutter::EncodableList{};+ for (auto const& val : vec) {+ encodableList.push_back(make_fl_value(val));+ }+ return encodableList;+ }++ template<typename K, typename T>+ static inline flutter::EncodableValue make_fl_value(const std::map<K, T>& map)+ {+ auto encodableMap = flutter::EncodableMap{};+ for (auto const& [key, val] : map) {+ encodableMap.insert({ make_fl_value(key), make_fl_value(val) });+ }+ return encodableMap;+ }++ template<typename T>+ static inline flutter::EncodableValue make_fl_value(const std::optional<T>& optional)+ {+ return optional.has_value() ? make_fl_value(optional.value()) : make_fl_value();+ }++ template<typename T>+ static inline flutter::EncodableValue make_fl_value(const std::optional<std::vector<T>>& optional)+ {+ if (!optional.has_value()) {+ return make_fl_value();+ }+ auto& vecValue = optional.value();+ auto encodableList = flutter::EncodableList{};+ for (auto const& val : vecValue) {+ encodableList.push_back(make_fl_value(val));+ }+ return encodableList;+ }++ template<typename K, typename T>+ static inline flutter::EncodableValue make_fl_value(const std::optional<std::map<K, T>>& optional)+ {+ if (!optional.has_value()) {+ return make_fl_value();+ }+ auto& mapValue = optional.value();+ auto encodableMap = flutter::EncodableMap{};+ for (auto const& [key, val] : mapValue) {+ encodableMap.insert({ make_fl_value(key), make_fl_value(val) });+ }+ return encodableMap;+ }++ static inline bool fl_map_contains(const flutter::EncodableMap& map, const char* key)+ {+ return map_contains(map, make_fl_value(key));+ }++ static inline bool fl_map_contains_not_null(const flutter::EncodableMap& map, const char* key)+ {+ return fl_map_contains(map, key) && !map.at(make_fl_value(key)).IsNull();+ }++ template<typename T, typename std::enable_if<(!std::is_same<T, int32_t>::value && !std::is_same<T, int64_t>::value), bool>::type* = nullptr>+ static inline T get_fl_map_value(const flutter::EncodableMap& map, const char* key)+ {+ return std::get<T>(map.at(make_fl_value(key)));+ }++ template<typename T, typename std::enable_if<std::is_same<T, int32_t>::value, bool>::type* = nullptr>+ static inline int64_t get_fl_map_value(const flutter::EncodableMap& map, const char* key)+ {+ return map.at(make_fl_value(key)).LongValue();+ }++ template<typename T, typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type* = nullptr>+ static inline int64_t get_fl_map_value(const flutter::EncodableMap& map, const char* key)+ {+ return map.at(make_fl_value(key)).LongValue();+ }++ template<typename T, typename std::enable_if<((!is_mappish<T>::value && !is_vector<T>::value && !std::is_same<T, int32_t>::value && !std::is_same<T, int64_t>::value) ||+ std::is_same<T, flutter::EncodableMap>::value || std::is_same<T, flutter::EncodableList>::value), int>::type* = nullptr>+ static inline std::optional<T> get_optional_fl_map_value(const flutter::EncodableMap& map, const char* key)+ {+ if (fl_map_contains_not_null(map, key)) {+ auto fl_key = make_fl_value(key);+ return make_pointer_optional<T>(std::get_if<T>(&map.at(fl_key)));+ }+ return std::nullopt;+ }++ template<typename T, typename std::enable_if<std::is_same<T, int32_t>::value, bool>::type* = nullptr>+ static inline std::optional<int64_t> get_optional_fl_map_value(const flutter::EncodableMap& map, const char* key)+ {+ if (fl_map_contains_not_null(map, key)) {+ auto fl_key = make_fl_value(key);+ return std::make_optional<int64_t>(map.at(fl_key).LongValue());+ }+ return std::nullopt;+ }++ template<typename T, typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type* = nullptr>+ static inline std::optional<int64_t> get_optional_fl_map_value(const flutter::EncodableMap& map, const char* key)+ {+ if (fl_map_contains_not_null(map, key)) {+ auto fl_key = make_fl_value(key);+ return std::make_optional<int64_t>(map.at(fl_key).LongValue());+ }+ return std::nullopt;+ }++ template<typename T>+ static inline T get_fl_map_value(const flutter::EncodableMap& map, const char* key, const T& defaultValue)+ {+ auto optional = get_optional_fl_map_value<T>(map, key);+ return !optional.has_value() ? defaultValue : optional.value();+ }++ template<typename T, typename std::enable_if<(is_mappish<T>::value && !std::is_same<T, flutter::EncodableMap>::value)>::type* = nullptr>+ static inline std::optional<T> get_optional_fl_map_value(const flutter::EncodableMap& map, const char* key)+ {+ using K = typename T::key_type;+ using V = typename T::mapped_type;++ auto flMap = std::get_if<flutter::EncodableMap>(&map.at(make_fl_value(key)));+ if (flMap) {+ T mapValue = {};+ for (auto itr = flMap->begin(); itr != flMap->end(); itr++) {+ mapValue.insert({ std::get<K>(itr->first), std::get<V>(itr->second) });+ }+ return make_pointer_optional<T>(&mapValue);+ }+ return std::nullopt;+ }++ template<typename K, typename T>+ static inline std::map<K, T> get_fl_map_value(const flutter::EncodableMap& map, const char* key, const std::map<K, T>& defaultValue)+ {+ auto optional = get_optional_fl_map_value<std::map<K, T>>(map, key);+ return !optional.has_value() ? defaultValue : optional.value();+ }++ template<typename T, typename std::enable_if<(is_vector<T>::value && !std::is_same<T, flutter::EncodableList>::value), bool>::type* = nullptr>+ static inline std::optional<T> get_optional_fl_map_value(const flutter::EncodableMap& map, const char* key)+ {+ using V = typename T::value_type;++ auto flList = std::get_if<flutter::EncodableList>(&map.at(make_fl_value(key)));+ if (flList) {+ T vecValue(flList->size());+ for (auto itr = flList->begin(); itr != flList->end(); itr++) {+ vecValue.push_back(std::get<V>(*itr));+ }+ return make_pointer_optional<T>(&vecValue);+ }+ return std::nullopt;+ }++ template<typename T>+ static inline std::vector<T> get_fl_map_value(const flutter::EncodableMap& map, const char* key, const std::vector<T>& defaultValue)+ {+ auto optional = get_optional_fl_map_value<std::vector<T>>(map, key);+ return !optional.has_value() ? defaultValue : optional.value();+ }+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_FLUTTER_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/utils/log.h b/packages/flutter_inappwebview_windows/windows/utils/log.hnew file mode 100644index 00000000..e61dcb61--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/utils/log.h@@ -0,0 +1,103 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_LOG_UTIL_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_LOG_UTIL_H_++#include <comdef.h>+#include <iostream>+#include <string>+#include <type_traits>++#include "strconv.h"+#include "string.h"++namespace flutter_inappwebview_plugin+{+ template <typename T>+ static inline void debugLog(const std::basic_string<T>& msg, const bool& isError = false, const std::string& filename = "", const int& line = 0)+ {+#ifndef NDEBUG+ std::basic_string<T> debugMsg = msg;+ if (!filename.empty() && line > 0) {+ auto filenameSplit = split(filename, std::string{ "\\flutter_inappwebview_windows\\" });+ std::string reduceFilenamePath = filenameSplit.size() > 0 ? "flutter_inappwebview_windows\\" + filenameSplit.back() : filename;+ debugMsg = reduceFilenamePath + "(" + std::to_string(line) + "): " + debugMsg;+ }+ if (isError) {+ std::cerr << debugMsg << std::endl;+ }+ else {+ std::cout << debugMsg << std::endl;+ }+ OutputDebugString(utf8_to_wide("\n" + debugMsg + "\n").c_str());+#endif+ }++ static inline void debugLog(const char* msg, const bool& isError = false, const std::string& filename = "", const int& line = 0)+ {+ debugLog(std::string(msg), isError, filename, line);+ }++ static inline void debugLog(const std::wstring& msg, const bool& isError = false, const std::string& filename = "", const int& line = 0)+ {+ debugLog(wide_to_utf8(msg), isError, filename, line);+ }++ static inline void debugLog(const bool& value, const bool& isError = false, const std::string& filename = "", const int& line = 0)+ {+ debugLog(value ? "true" : "false", isError, filename, line);+ }++ template<+ typename T,+ typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type+ >+ static inline void debugLog(const T& value, const bool& isError = false, const std::string& filename = "", const int& line = 0)+ {+ debugLog(std::to_string(value), isError);+ }++ static inline std::string getHRMessage(const HRESULT& error)+ {+ return wide_to_utf8(_com_error(error).ErrorMessage());+ }++ static inline void debugLog(const HRESULT& hr, const std::string& filename = "", const int& line = 0)+ {+ auto isError = hr != S_OK;+ auto errorCode = std::to_string(hr);+ debugLog((isError ? "Error " + errorCode + ": " : "Message: ") + getHRMessage(hr), isError, filename, line);+ }++ static inline bool succeededOrLog(const HRESULT& hr, const std::string& filename = "", const int& line = 0)+ {+ if (SUCCEEDED(hr)) {+ return true;+ }+ debugLog(hr, filename, line);+ return false;+ }++ static inline bool failedAndLog(const HRESULT& hr, const std::string& filename = "", const int& line = 0)+ {+ if (FAILED(hr)) {+ debugLog(hr, filename, line);+ return true;+ }+ return false;+ }++ static inline void failedLog(const HRESULT& hr, const std::string& filename = "", const int& line = 0)+ {+ if (FAILED(hr)) {+ debugLog(hr, filename, line);+ }+ }+}++#ifndef NDEBUG+#define debugLog(value) debugLog(value, false, __FILE__, __LINE__)+#define succeededOrLog(value) succeededOrLog(value, __FILE__, __LINE__)+#define failedAndLog(value) failedAndLog(value, __FILE__, __LINE__)+#define failedLog(value) failedLog(value, __FILE__, __LINE__)+#endif++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_LOG_UTIL_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/utils/map.h b/packages/flutter_inappwebview_windows/windows/utils/map.hnew file mode 100644index 00000000..c46d4a17--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/utils/map.h@@ -0,0 +1,37 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_MAP_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_MAP_H_++#include <algorithm>+#include <iterator>+#include <map>+#include <optional>++namespace flutter_inappwebview_plugin+{+ template<typename T, typename U = void>+ struct is_mappish_impl : std::false_type { };++ template<typename T>+ struct is_mappish_impl<T, std::void_t<typename T::key_type,+ typename T::mapped_type,+ decltype(std::declval<T&>()[std::declval<const typename T::key_type&>()])>>+ : std::true_type { };++ template<typename T>+ struct is_mappish : is_mappish_impl<T>::type { };++ template<typename K, typename T>+ static inline bool map_contains(const std::map<K, T>& map, const K& key)+ {+ return map.find(key) != map.end();+ }++ template<typename K, typename T>+ static inline T map_at_or_null(const std::map<K, T>& map, const K& key)+ {+ auto itr = map.find(key);+ return itr != map.end() ? itr->second : nullptr;+ }+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_MAP_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/utils/strconv.h b/packages/flutter_inappwebview_windows/windows/utils/strconv.hnew file mode 100644index 00000000..0f1483ff--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/utils/strconv.h@@ -0,0 +1,558 @@+// from https://github.com/javacommons/strconv++/* strconv.h v1.8.10 */+/* Last Modified: 2021/08/30 21:53 */++/*+------------------------------------------------------------------------------+This software is available under 2 licenses -- choose whichever you prefer.+------------------------------------------------------------------------------+ALTERNATIVE A - MIT License+Copyright (c) 2019-2021 JavaCommons+Permission is hereby granted, free of charge, to any person obtaining a copy of+this software and associated documentation files (the "Software"), to deal in+the Software without restriction, including without limitation the rights to+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies+of the Software, and to permit persons to whom the Software is furnished to do+so, subject to the following conditions:+The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+------------------------------------------------------------------------------+ALTERNATIVE B - Public Domain (www.unlicense.org)+This is free and unencumbered software released into the public domain.+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this+software, either in source code form or as a compiled binary, for any purpose,+commercial or non-commercial, and by any means.+In jurisdictions that recognize copyright laws, the author or authors of this+software dedicate any and all copyright interest in the software to the public+domain. We make this dedication for the benefit of the public at large and to+the detriment of our heirs and successors. We intend this dedication to be an+overt act of relinquishment in perpetuity of all present and future rights to+this software under copyright law.+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+-----------------------------------------------------------------------------+ */++#ifndef STRCONV_H+#define STRCONV_H++#include <windows.h>+#include <string>+#include <vector>+#include <iostream>+#include <sstream>++namespace flutter_inappwebview_plugin+{+#if __cplusplus >= 201103L && !defined(STRCONV_CPP98)+ static inline std::wstring cp_to_wide(const std::string& s, UINT codepage)+ {+ int in_length = (int)s.length();+ int out_length = MultiByteToWideChar(codepage, 0, s.c_str(), in_length, 0, 0);+ std::wstring result(out_length, L'\0');+ if (out_length)+ MultiByteToWideChar(codepage, 0, s.c_str(), in_length, &result[0], out_length);+ return result;+ }+ static inline std::string wide_to_cp(const std::wstring& s, UINT codepage)+ {+ int in_length = (int)s.length();+ int out_length = WideCharToMultiByte(codepage, 0, s.c_str(), in_length, 0, 0, 0, 0);+ std::string result(out_length, '\0');+ if (out_length)+ WideCharToMultiByte(codepage, 0, s.c_str(), in_length, &result[0], out_length, 0, 0);+ return result;+ }+#else /* __cplusplus < 201103L */+ static inline std::wstring cp_to_wide(const std::string& s, UINT codepage)+ {+ int in_length = (int)s.length();+ int out_length = MultiByteToWideChar(codepage, 0, s.c_str(), in_length, 0, 0);+ std::vector<wchar_t> buffer(out_length);+ if (out_length)+ MultiByteToWideChar(codepage, 0, s.c_str(), in_length, &buffer[0], out_length);+ std::wstring result(buffer.begin(), buffer.end());+ return result;+ }+ static inline std::string wide_to_cp(const std::wstring& s, UINT codepage)+ {+ int in_length = (int)s.length();+ int out_length = WideCharToMultiByte(codepage, 0, s.c_str(), in_length, 0, 0, 0, 0);+ std::vector<char> buffer(out_length);+ if (out_length)+ WideCharToMultiByte(codepage, 0, s.c_str(), in_length, &buffer[0], out_length, 0, 0);+ std::string result(buffer.begin(), buffer.end());+ return result;+ }+#endif++ static inline std::string cp_to_utf8(const std::string& s, UINT codepage)+ {+ if (codepage == CP_UTF8)+ return s;+ std::wstring wide = cp_to_wide(s, codepage);+ return wide_to_cp(wide, CP_UTF8);+ }+ static inline std::string utf8_to_cp(const std::string& s, UINT codepage)+ {+ if (codepage == CP_UTF8)+ return s;+ std::wstring wide = cp_to_wide(s, CP_UTF8);+ return wide_to_cp(wide, codepage);+ }++ static inline std::wstring ansi_to_wide(const std::string& s)+ {+ return cp_to_wide(s, CP_ACP);+ }+ static inline std::string wide_to_ansi(const std::wstring& s)+ {+ return wide_to_cp(s, CP_ACP);+ }++ static inline std::wstring sjis_to_wide(const std::string& s)+ {+ return cp_to_wide(s, 932);+ }+ static inline std::string wide_to_sjis(const std::wstring& s)+ {+ return wide_to_cp(s, 932);+ }++ static inline std::wstring utf8_to_wide(const std::string& s)+ {+ return cp_to_wide(s, CP_UTF8);+ }+ static inline std::string wide_to_utf8(const std::wstring& s)+ {+ return wide_to_cp(s, CP_UTF8);+ }++ static inline std::string ansi_to_utf8(const std::string& s)+ {+ return cp_to_utf8(s, CP_ACP);+ }+ static inline std::string utf8_to_ansi(const std::string& s)+ {+ return utf8_to_cp(s, CP_ACP);+ }++ static inline std::string sjis_to_utf8(const std::string& s)+ {+ return cp_to_utf8(s, 932);+ }+ static inline std::string utf8_to_sjis(const std::string& s)+ {+ return utf8_to_cp(s, 932);+ }++#ifdef __cpp_char8_t+ static inline std::u8string utf8_to_char8(const std::string& s)+ {+ return std::u8string(s.begin(), s.end());+ }+ static inline std::string char8_to_utf8(const std::u8string& s)+ {+ return std::string(s.begin(), s.end());+ }++ static inline std::wstring char8_to_wide(const std::u8string& s)+ {+ return cp_to_wide(char8_to_utf8(s), CP_UTF8);+ }+ static inline std::u8string wide_to_char8(const std::wstring& s)+ {+ return utf8_to_char8(wide_to_cp(s, CP_UTF8));+ }++ static inline std::u8string cp_to_char8(const std::string& s, UINT codepage)+ {+ return utf8_to_char8(cp_to_utf8(s, codepage));+ }+ static inline std::string char8_to_cp(const std::u8string& s, UINT codepage)+ {+ return utf8_to_cp(char8_to_utf8(s), codepage);+ }++ static inline std::u8string ansi_to_char8(const std::string& s)+ {+ return cp_to_char8(s, CP_ACP);+ }+ static inline std::string char8_to_ansi(const std::u8string& s)+ {+ return char8_to_cp(s, CP_ACP);+ }++ static inline std::u8string sjis_to_char8(const std::string& s)+ {+ return cp_to_char8(s, 932);+ }+ static inline std::string char8_to_sjis(const std::u8string& s)+ {+ return char8_to_cp(s, 932);+ }+#endif++#if defined(_MSC_VER)+#pragma warning(push)+#pragma warning(disable : 4996)+#endif++ static inline std::wstring vformat(const wchar_t* format, va_list args)+ {+ int len = _vsnwprintf(0, 0, format, args);+ if (len < 0)+ return L"";+ std::vector<wchar_t> buffer(len + 1);+ len = _vsnwprintf(&buffer[0], len, format, args);+ if (len < 0)+ return L"";+ buffer[len] = L'\0';+ return &buffer[0];+ }+ static inline std::string vformat(const char* format, va_list args)+ {+ int len = _vsnprintf(0, 0, format, args);+ if (len < 0)+ return "";+ std::vector<char> buffer(len + 1);+ len = _vsnprintf(&buffer[0], len, format, args);+ if (len < 0)+ return "";+ buffer[len] = '\0';+ return &buffer[0];+ }+#ifdef __cpp_char8_t+ static inline std::u8string vformat(const char8_t* format, va_list args)+ {+ int len = _vsnprintf(0, 0, (const char*)format, args);+ if (len < 0)+ return u8"";+ std::vector<char> buffer(len + 1);+ len = _vsnprintf(&buffer[0], len, (const char*)format, args);+ if (len < 0)+ return u8"";+ buffer[len] = '\0';+ return (char8_t*)&buffer[0];+ }+#endif++#if defined(_MSC_VER)+#pragma warning(pop)+#endif++ static inline std::wstring format(const wchar_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::wstring s = vformat(format, args);+ va_end(args);+ return s;+ }+ static inline std::string format(const char* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::string s = vformat(format, args);+ va_end(args);+ return s;+ }+#ifdef __cpp_char8_t+ static inline std::u8string format(const char8_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::u8string s = vformat(format, args);+ va_end(args);+ return s;+ }+#endif++ static inline void format(std::ostream& ostrm, const wchar_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::wstring s = vformat(format, args);+ va_end(args);+ ostrm << wide_to_utf8(s) << std::flush;+ }+ static inline void format(std::ostream& ostrm, const char* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::string s = vformat(format, args);+ va_end(args);+ ostrm << s << std::flush;+ }+#ifdef __cpp_char8_t+ static inline void format(std::ostream& ostrm, const char8_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::u8string s = vformat(format, args);+ va_end(args);+ ostrm << char8_to_utf8(s) << std::flush;+ }+#endif++ static inline std::string formatA(const wchar_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::wstring s = vformat(format, args);+ va_end(args);+ return wide_to_ansi(s);+ }+ static inline std::string formatA(const char* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::string s = vformat(format, args);+ va_end(args);+ return utf8_to_ansi(s);+ }+#ifdef __cpp_char8_t+ static inline std::string formatA(const char8_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::u8string s = vformat(format, args);+ va_end(args);+ return char8_to_ansi(s);+ }+#endif++ static inline void formatA(std::ostream& ostrm, const wchar_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::wstring s = vformat(format, args);+ va_end(args);+ ostrm << wide_to_ansi(s) << std::flush;+ }+ static inline void formatA(std::ostream& ostrm, const char* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::string s = vformat(format, args);+ va_end(args);+ ostrm << utf8_to_ansi(s) << std::flush;+ }+#ifdef __cpp_char8_t+ static inline void formatA(std::ostream& ostrm, const char8_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::u8string s = vformat(format, args);+ va_end(args);+ ostrm << char8_to_ansi(s) << std::flush;+ }+#endif++ static inline void dbgmsg(const wchar_t* title, const wchar_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::wstring s = vformat(format, args);+ va_end(args);+ MessageBoxW(0, s.c_str(), title, MB_OK);+ }+ static inline void dbgmsg(const char* title, const char* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::string s = vformat(format, args);+ va_end(args);+ MessageBoxW(0, utf8_to_wide(s).c_str(), utf8_to_wide(title).c_str(), MB_OK);+ }+#ifdef __cpp_char8_t+ static inline void dbgmsg(const char8_t* title, const char8_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::u8string s = vformat(format, args);+ va_end(args);+ MessageBoxW(0, char8_to_wide(s).c_str(), char8_to_wide(title).c_str(), MB_OK);+ }+#endif++ static inline HANDLE handle_for_ostream(std::ostream& ostrm)+ {+ if (&ostrm == &std::cout) {+ return GetStdHandle(STD_OUTPUT_HANDLE);+ }+ else if (&ostrm == &std::cerr) {+ return GetStdHandle(STD_ERROR_HANDLE);+ }+ return INVALID_HANDLE_VALUE;+ }+ static inline void dbgout(std::ostream& ostrm, const wchar_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::wstring ws = vformat(format, args);+ va_end(args);+ HANDLE h = handle_for_ostream(ostrm);+ if (h == INVALID_HANDLE_VALUE) {+ return;+ }+ DWORD dwNumberOfCharsWrite;+ if (GetFileType(h) != FILE_TYPE_CHAR) {+ std::string s = wide_to_cp(ws, GetConsoleOutputCP());+ WriteFile(h, s.c_str(), (DWORD)s.size(), &dwNumberOfCharsWrite, NULL);+ }+ else {+ WriteConsoleW(h,+ ws.c_str(),+ (DWORD)ws.size(),+ &dwNumberOfCharsWrite,+ NULL);+ }+ }+ static inline void dbgout(std::ostream& ostrm, const char* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::string s = vformat(format, args);+ va_end(args);+ HANDLE h = handle_for_ostream(ostrm);+ if (h == INVALID_HANDLE_VALUE) {+ return;+ }+ DWORD dwNumberOfCharsWrite;+ if (GetFileType(h) != FILE_TYPE_CHAR) {+ s = utf8_to_cp(s, GetConsoleOutputCP());+ WriteFile(h, s.c_str(), (DWORD)s.size(), &dwNumberOfCharsWrite, NULL);+ }+ else {+ std::wstring ws = utf8_to_wide(s);+ WriteConsoleW(h,+ ws.c_str(),+ (DWORD)ws.size(),+ &dwNumberOfCharsWrite,+ NULL);+ }+ }+#ifdef __cpp_char8_t+ static inline void dbgout(std::ostream& ostrm, const char8_t* format, ...)+ {+ va_list args;+ va_start(args, format);+ std::u8string s = vformat(format, args);+ va_end(args);+ HANDLE h = handle_for_ostream(ostrm);+ if (h == INVALID_HANDLE_VALUE) {+ return;+ }+ DWORD dwNumberOfCharsWrite;+ if (GetFileType(h) != FILE_TYPE_CHAR) {+ std::string str = char8_to_cp(s, GetConsoleOutputCP());+ WriteFile(h, (const char*)str.c_str(), (DWORD)str.size(), &dwNumberOfCharsWrite, NULL);+ }+ else {+ std::wstring ws = char8_to_wide(s);+ WriteConsoleW(h,+ ws.c_str(),+ (DWORD)ws.size(),+ &dwNumberOfCharsWrite,+ NULL);+ }+ }+#endif++ class unicode_ostream+ {+ private:+ std::ostream* m_ostrm;+ UINT m_target_cp;+ bool is_ascii(const std::string& s)+ {+ for (std::size_t i = 0; i < s.size(); i++) {+ unsigned char c = (unsigned char)s[i];+ if (c > 0x7f)+ return false;+ }+ return true;+ }++ public:+ unicode_ostream(std::ostream& ostrm, UINT target_cp = CP_ACP) : m_ostrm(&ostrm), m_target_cp(target_cp) {}+ std::ostream& stream() { return *m_ostrm; }+ void stream(std::ostream& ostrm) { m_ostrm = &ostrm; }+ UINT target_cp() { return m_target_cp; }+ void target_cp(UINT cp) { m_target_cp = cp; }+ template <typename T>+ unicode_ostream& operator<<(const T& x)+ {+ std::ostringstream oss;+ oss << x;+ std::string output = oss.str();+ if (is_ascii(output)) {+ (*m_ostrm) << x;+ }+ else {+ (*m_ostrm) << utf8_to_cp(output, m_target_cp);+ }+ return *this;+ }+ unicode_ostream& operator<<(const std::wstring& x)+ {+ (*m_ostrm) << wide_to_cp(x, m_target_cp);+ return *this;+ }+ unicode_ostream& operator<<(const wchar_t* x)+ {+ (*m_ostrm) << wide_to_cp(x, m_target_cp);+ return *this;+ }+ unicode_ostream& operator<<(const std::string& x)+ {+ (*m_ostrm) << utf8_to_cp(x, m_target_cp);+ return *this;+ }+ unicode_ostream& operator<<(const char* x)+ {+ (*m_ostrm) << utf8_to_cp(x, m_target_cp);+ return *this;+ }+#ifdef __cpp_char8_t+ unicode_ostream& operator<<(const std::u8string& x)+ {+ (*m_ostrm) << char8_to_cp(x, m_target_cp);+ return *this;+ }+ unicode_ostream& operator<<(const char8_t* x)+ {+ (*m_ostrm) << char8_to_cp(x, m_target_cp);+ return *this;+ }+#endif+ unicode_ostream& operator<<(std::ostream& (*pf)(std::ostream&)) // For manipulators...+ {+ (*m_ostrm) << pf;+ return *this;+ }+ unicode_ostream& operator<<(std::basic_ios<char>& (*pf)(std::basic_ios<char>&)) // For manipulators...+ {+ (*m_ostrm) << pf;+ return *this;+ }+ };+}++#define U8(X) ((const char *)u8##X)+#define WIDE(X) (L##X)++#endif /* STRCONV_H */\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/utils/string.h b/packages/flutter_inappwebview_windows/windows/utils/string.hnew file mode 100644index 00000000..618e18f1--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/utils/string.h@@ -0,0 +1,193 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_STRING_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_STRING_H_++#include <algorithm>+#include <numeric>+#include <optional>+#include <string>+#include <vector>++#include "strconv.h"++namespace flutter_inappwebview_plugin+{+ template <typename T>+ struct is_string+ : std::false_type+ {};++ // Partial specialization - parameters used to qualify the specialization+ template <typename CharT, typename TraitsT, typename AllocT>+ struct is_string<std::basic_string<CharT, TraitsT, AllocT>>+ : std::true_type+ {};++ template <typename T>+ using is_basic_string = is_string<std::remove_cv_t<T>>;++ template <typename T>+ static inline bool string_equals(const std::basic_string<T>& s1, const std::basic_string<T>& s2)+ {+ return s1.compare(s2) == 0;+ }++ template <typename T>+ static inline bool string_equals(const std::basic_string<T>& s1, const char* s2)+ {+ return s1.compare(s2) == 0;+ }++ template <typename T>+ static inline bool string_equals(const char* s1, const std::basic_string<T>& s2)+ {+ return s2.compare(s1) == 0;+ }++ static inline bool string_equals(const std::string& s1, const std::wstring& s2)+ {+ return string_equals(s1, wide_to_utf8(s2));+ }++ static inline bool string_equals(const std::wstring& s1, const std::string& s2)+ {+ return string_equals(wide_to_utf8(s1), s2);+ }++ template <typename T>+ static inline bool string_equals(const std::optional<std::basic_string<T>>& s1, const std::basic_string<T>& s2)+ {+ return s1.has_value() ? string_equals(s1.value(), s2) : false;+ }++ template <typename T>+ static inline bool string_equals(const std::basic_string<T>& s1, const std::optional<std::basic_string<T>>& s2)+ {+ return s2.has_value() ? string_equals(s1, s2.value()) : false;+ }++ template <typename T>+ static inline bool string_equals(const std::optional<std::basic_string<T>>& s1, const std::optional<std::basic_string<T>>& s2)+ {+ return s1.has_value() && s2.has_value() ? string_equals(s1.value(), s2.value()) : true;+ }++ static inline void replace_all(std::string& source, const std::string& from, const std::string& to)+ {+ std::string newString;+ newString.reserve(source.length()); // avoids a few memory allocations++ std::string::size_type lastPos = 0;+ std::string::size_type findPos;++ while (std::string::npos != (findPos = source.find(from, lastPos))) {+ newString.append(source, lastPos, findPos - lastPos);+ newString += to;+ lastPos = findPos + from.length();+ }++ // Care for the rest after last occurrence+ newString += source.substr(lastPos);++ source.swap(newString);+ }++ static inline std::string replace_all_copy(const std::string& source, const std::string& from, const std::string& to)+ {+ std::string newString;+ newString.reserve(source.length()); // avoids a few memory allocations++ std::string::size_type lastPos = 0;+ std::string::size_type findPos;++ while (std::string::npos != (findPos = source.find(from, lastPos))) {+ newString.append(source, lastPos, findPos - lastPos);+ newString += to;+ lastPos = findPos + from.length();+ }++ // Care for the rest after last occurrence+ newString += source.substr(lastPos);++ return newString;+ }++ template <typename T>+ static inline std::basic_string<T> join(const std::vector<std::basic_string<T>>& vec, const std::basic_string<T>& delim)+ {+ return vec.empty() ? std::basic_string<T>{ "" } : /* leave early if there are no items in the list */+ std::accumulate( /* otherwise, accumulate */+ ++vec.begin(), vec.end(), /* the range 2nd to after-last */+ *vec.begin(), /* and start accumulating with the first item */+ [delim](auto& a, auto& b) { return a + delim + b; });+ }++ template <typename T>+ static inline std::basic_string<T> join(const std::vector<std::basic_string<T>>& vec, const char* delim)+ {+ return join(vec, std::basic_string<T>{ delim });+ }++ template <typename T>+ static inline std::vector<std::basic_string<T>> split(const std::basic_string<T>& s, std::basic_string<T> delimiter)+ {+ size_t pos_start = 0, pos_end, delim_len = delimiter.length();+ std::basic_string<T> token;+ std::vector<std::basic_string<T>> res;++ while ((pos_end = s.find(delimiter, pos_start)) != std::basic_string<T>::npos) {+ token = s.substr(pos_start, pos_end - pos_start);+ pos_start = pos_end + delim_len;+ res.push_back(token);+ }++ res.push_back(s.substr(pos_start));+ return res;+ }++ template <typename T>+ void to_lowercase(const std::basic_string<T>& s)+ {+ std::transform(s.begin(), s.end(), s.begin(),+ [](const T v) { return static_cast<T>(std::tolower(v)); });+ }++ template <typename T>+ std::basic_string<T> to_lowercase_copy(const std::basic_string<T>& s)+ {+ std::basic_string<T> s2 = s;+ std::transform(s2.begin(), s2.end(), s2.begin(),+ [](const T v) { return static_cast<T>(std::tolower(v)); });+ return s2;+ }++ template <typename T>+ void to_uppercase(const std::basic_string<T>& s)+ {+ std::transform(s.begin(), s.end(), s.begin(),+ [](const T v) { return static_cast<T>(std::toupper(v)); });+ return s2;+ }++ template <typename T>+ std::basic_string<T> to_uppercase_copy(const std::basic_string<T>& s)+ {+ std::basic_string<T> s2 = s;+ std::transform(s2.begin(), s2.end(), s2.begin(),+ [](const T v) { return static_cast<T>(std::toupper(v)); });+ return s2;+ }++ template <typename T>+ bool starts_with(const std::basic_string<T>& str, const std::basic_string<T>& prefix)+ {+ return str.size() >= prefix.size() && str.compare(0, prefix.size(), prefix) == 0;+ }++ template <typename T>+ bool ends_with(const std::basic_string<T>& str, const std::basic_string<T>& suffix)+ {+ return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;+ }+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_STRING_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/utils/util.h b/packages/flutter_inappwebview_windows/windows/utils/util.hnew file mode 100644index 00000000..bbac292d--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/utils/util.h@@ -0,0 +1,38 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_H_++#include <optional>+#include <string>+#include <variant>+#include <Windows.h>++namespace flutter_inappwebview_plugin+{+ template<typename T>+ static inline std::optional<T> make_pointer_optional(const T* value)+ {+ return value == nullptr ? std::nullopt : std::make_optional<T>(*value);+ }++ static inline std::string variant_to_string(const std::variant<std::string, int64_t>& var)+ {+ return std::visit([](auto&& arg)+ {+ using T = std::decay_t<decltype(arg)>;+ if constexpr (std::is_same_v<T, std::string>)+ return arg;+ else if constexpr (std::is_arithmetic_v<T>)+ return std::to_string(arg);+ else+ static_assert(always_false_v<T>, "non-exhaustive visitor!");+ }, var);+ }++ static inline float get_current_scale_factor(HWND hwnd)+ {+ auto dpi = GetDpiForWindow(hwnd);+ return dpi > 0 ? dpi / 96.0f : 1.0f;+ }+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/utils/vector.h b/packages/flutter_inappwebview_windows/windows/utils/vector.hnew file mode 100644index 00000000..4a70e8a4--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/utils/vector.h@@ -0,0 +1,99 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_VECTOR_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_VECTOR_H_++#include <algorithm>+#include <functional>+#include <iterator>+#include <optional>+#include <string>+#include <vector>++namespace flutter_inappwebview_plugin+{+ template<typename T = void, typename = void>+ struct is_vector_impl : std::false_type { };++ template<typename T>+ struct is_vector_impl<T, std::enable_if_t<+ std::is_same<T, typename std::vector<std::string>>::value>+ > : std::true_type { };++ template<typename T>+ struct is_vector_impl<T, std::enable_if_t<+ std::is_same<T, typename std::vector<typename std::iterator_traits<T>::value_type>::iterator>::value>+ > : std::true_type { };++ template<typename T>+ struct is_vector : is_vector_impl<T>::type { };++ template <typename T>+ static inline void vector_remove(std::vector<T>& vec, const T& el)+ {+ std::remove(vec.begin(), vec.end(), el);+ }++ template <typename T, typename UnaryPredicate>+ static inline void vector_remove_if(std::vector<T>& vec, UnaryPredicate&& predicate)+ {+ std::remove_if(vec.begin(), vec.end(), std::forward<UnaryPredicate>(predicate));+ }++ template <typename T>+ static inline void vector_remove_erase(std::vector<T>& vec, const T& el)+ {+ vec.erase(std::remove(vec.begin(), vec.end(), el), vec.end());+ }++ template <typename T, typename UnaryPredicate>+ static inline void vector_remove_erase_if(std::vector<T>& vec, UnaryPredicate&& predicate)+ {+ vec.erase(std::remove_if(vec.begin(), vec.end(), std::forward<UnaryPredicate>(predicate)), vec.end());+ }++ template <typename T>+ static inline bool vector_contains(const std::vector<T>& vec, const T& value)+ {+ return std::find(vec.begin(), vec.end(), value) != vec.end();+ }++ template <typename T, typename UnaryPredicate>+ static inline bool vector_contains_if(const std::vector<T>& vec, UnaryPredicate&& predicate)+ {+ return std::find_if(vec.begin(), vec.end(), std::forward<UnaryPredicate>(predicate)) != vec.end();+ }++ template <typename Iterator, typename Func>+ static inline auto functional_map(Iterator begin, Iterator end, Func&& func) ->+ std::vector<decltype(func(std::declval<typename Iterator::value_type>()))>+ {+ using value_type = decltype(func(std::declval<typename Iterator::value_type>()));++ std::vector<value_type> out_vector;+ out_vector.reserve(std::distance(begin, end));++ std::transform(begin, end, std::back_inserter(out_vector),+ std::forward<Func>(func));++ return out_vector;+ }++ template <typename T, typename Func>+ static inline auto functional_map(const T& iterable, Func&& func) ->+ std::vector<decltype(func(std::declval<typename T::value_type>()))>+ {+ return functional_map(std::begin(iterable), std::end(iterable),+ std::forward<Func>(func));+ }++ template <typename T, typename Func>+ static inline auto functional_map(const std::optional<T>& iterable, Func&& func) ->+ std::vector<decltype(func(std::declval<typename T::value_type>()))>+ {+ if (!iterable.has_value()) {+ return {};+ }+ return functional_map(iterable.value(), std::forward<Func>(func));+ }+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_UTIL_VECTOR_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment.cpp b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment.cppnew file mode 100644index 00000000..580a1787--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment.cpp@@ -0,0 +1,102 @@+#include <WebView2EnvironmentOptions.h>+#include <wil/wrl.h>++#include "../utils/log.h"+#include "webview_environment.h"++#include "webview_environment_manager.h"++namespace flutter_inappwebview_plugin+{+ using namespace Microsoft::WRL;++ WebViewEnvironment::WebViewEnvironment(const FlutterInappwebviewWindowsPlugin* plugin, const std::string& id)+ : plugin(plugin), id(id),+ channelDelegate(std::make_unique<WebViewEnvironmentChannelDelegate>(this, plugin->registrar->messenger()))+ {}++ void WebViewEnvironment::create(const std::unique_ptr<WebViewEnvironmentSettings> settings, const std::function<void(HRESULT)> completionHandler)+ {+ if (!plugin) {+ if (completionHandler) {+ completionHandler(E_FAIL);+ }+ return;+ }++ auto hwnd = plugin->webViewEnvironmentManager->getHWND();+ if (!hwnd) {+ if (completionHandler) {+ completionHandler(E_FAIL);+ }+ return;+ }++ auto options = Make<CoreWebView2EnvironmentOptions>();+ if (settings) {+ if (settings->additionalBrowserArguments.has_value()) {+ options->put_AdditionalBrowserArguments(utf8_to_wide(settings->additionalBrowserArguments.value()).c_str());+ }+ if (settings->allowSingleSignOnUsingOSPrimaryAccount.has_value()) {+ options->put_AllowSingleSignOnUsingOSPrimaryAccount(settings->allowSingleSignOnUsingOSPrimaryAccount.value());+ }+ if (settings->language.has_value()) {+ options->put_Language(utf8_to_wide(settings->language.value()).c_str());+ }+ if (settings->targetCompatibleBrowserVersion.has_value()) {+ options->put_TargetCompatibleBrowserVersion(utf8_to_wide(settings->targetCompatibleBrowserVersion.value()).c_str());+ }+ wil::com_ptr<ICoreWebView2EnvironmentOptions4> options4;+ if (succeededOrLog(options->QueryInterface(IID_PPV_ARGS(&options4))) && settings->customSchemeRegistrations.has_value()) {+ std::vector<ICoreWebView2CustomSchemeRegistration*> registrations = {};+ for (auto& customSchemeRegistration : settings->customSchemeRegistrations.value()) {+ registrations.push_back(std::move(customSchemeRegistration->toWebView2CustomSchemeRegistration()));+ }+ options4->SetCustomSchemeRegistrations(static_cast<UINT32>(registrations.size()), registrations.data());+ }+ }++ auto hr = CreateCoreWebView2EnvironmentWithOptions(+ settings && settings->browserExecutableFolder.has_value() ? utf8_to_wide(settings->browserExecutableFolder.value()).c_str() : nullptr,+ settings && settings->userDataFolder.has_value() ? utf8_to_wide(settings->userDataFolder.value()).c_str() : nullptr,+ options.Get(),+ Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(+ [this, hwnd, completionHandler](HRESULT result, wil::com_ptr<ICoreWebView2Environment> environment) -> HRESULT+ {+ if (succeededOrLog(result)) {+ environment_ = std::move(environment);++ auto hr = environment_->CreateCoreWebView2Controller(hwnd, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(+ [this, completionHandler](HRESULT result, wil::com_ptr<ICoreWebView2Controller> controller) -> HRESULT+ {+ if (succeededOrLog(result)) {+ webViewController_ = std::move(controller);+ webViewController_->get_CoreWebView2(&webView_);+ webViewController_->put_IsVisible(false);+ }+ if (completionHandler) {+ completionHandler(result);+ }+ return S_OK;+ }).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler(hr);+ }+ }+ else if (completionHandler) {+ completionHandler(result);+ }+ return S_OK;+ }).Get());++ if (failedAndLog(hr) && completionHandler) {+ completionHandler(hr);+ }+ }++ WebViewEnvironment::~WebViewEnvironment()+ {+ debugLog("dealloc WebViewEnvironment");+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment.h b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment.hnew file mode 100644index 00000000..615442d4--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment.h@@ -0,0 +1,48 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_H_++#include <functional>+#include <WebView2.h>+#include <wil/com.h>++#include "../flutter_inappwebview_windows_plugin.h"+#include "webview_environment_channel_delegate.h"+#include "webview_environment_settings.h"++namespace flutter_inappwebview_plugin+{+ class WebViewEnvironment+ {+ public:+ static inline const wchar_t* CLASS_NAME = L"WebViewEnvironment";+ static inline const std::string METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_webview_environment_";++ const FlutterInappwebviewWindowsPlugin* plugin;+ std::string id;++ std::unique_ptr<WebViewEnvironmentChannelDelegate> channelDelegate;++ WebViewEnvironment(const FlutterInappwebviewWindowsPlugin* plugin, const std::string& id);+ ~WebViewEnvironment();++ void create(const std::unique_ptr<WebViewEnvironmentSettings> settings, const std::function<void(HRESULT)> completionHandler);+ wil::com_ptr<ICoreWebView2Environment> getEnvironment()+ {+ return environment_;+ }+ wil::com_ptr<ICoreWebView2Controller> getWebViewController()+ {+ return webViewController_;+ }+ wil::com_ptr<ICoreWebView2> getWebView()+ {+ return webView_;+ }+ private:+ wil::com_ptr<ICoreWebView2Environment> environment_;+ wil::com_ptr<ICoreWebView2Controller> webViewController_;+ wil::com_ptr<ICoreWebView2> webView_;+ WNDCLASS windowClass_ = {};+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_channel_delegate.cpp b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_channel_delegate.cppnew file mode 100644index 00000000..d5b9e4d2--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_channel_delegate.cpp@@ -0,0 +1,47 @@+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "../utils/strconv.h"+#include "../utils/string.h"+#include "webview_environment.h"+#include "webview_environment_channel_delegate.h"++#include "webview_environment_manager.h"++namespace flutter_inappwebview_plugin+{+ WebViewEnvironmentChannelDelegate::WebViewEnvironmentChannelDelegate(WebViewEnvironment* webViewEnv, flutter::BinaryMessenger* messenger)+ : webViewEnvironment(webViewEnv), ChannelDelegate(messenger, WebViewEnvironment::METHOD_CHANNEL_NAME_PREFIX + webViewEnv->id)+ {}++ void WebViewEnvironmentChannelDelegate::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ if (!webViewEnvironment) {+ result->Success();+ return;+ }++ // auto& arguments = std::get<flutter::EncodableMap>(*method_call.arguments());+ auto& methodName = method_call.method_name();++ if (string_equals(methodName, "dispose")) {+ if (webViewEnvironment->plugin && webViewEnvironment->plugin->webViewEnvironmentManager) {+ std::map<std::string, std::unique_ptr<WebViewEnvironment>>& webViewEnvironments = webViewEnvironment->plugin->webViewEnvironmentManager->webViewEnvironments;+ auto& id = webViewEnvironment->id;+ if (map_contains(webViewEnvironments, id)) {+ webViewEnvironments.erase(id);+ }+ }+ result->Success();+ }+ else {+ result->NotImplemented();+ }+ }++ WebViewEnvironmentChannelDelegate::~WebViewEnvironmentChannelDelegate()+ {+ debugLog("dealloc WebViewEnvironmentChannelDelegate");+ webViewEnvironment = nullptr;+ }+}diff --git a/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_channel_delegate.h b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_channel_delegate.hnew file mode 100644index 00000000..b98e67ab--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_channel_delegate.h@@ -0,0 +1,25 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_CHANNEL_DELEGATE_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_CHANNEL_DELEGATE_H_++#include "../types/channel_delegate.h"+#include <flutter/method_channel.h>++namespace flutter_inappwebview_plugin+{+ class WebViewEnvironment;++ class WebViewEnvironmentChannelDelegate : public ChannelDelegate+ {+ public:+ WebViewEnvironment* webViewEnvironment;++ WebViewEnvironmentChannelDelegate(WebViewEnvironment* webViewEnv, flutter::BinaryMessenger* messenger);+ ~WebViewEnvironmentChannelDelegate();++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);+ };+}++#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_CHANNEL_DELEGATE_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_manager.cpp b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_manager.cppnew file mode 100644index 00000000..bae69c1a--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_manager.cpp@@ -0,0 +1,129 @@+#include <DispatcherQueue.h>+#include <flutter/method_channel.h>+#include <flutter/standard_method_codec.h>++#include "../in_app_webview/in_app_webview_settings.h"+#include "../utils/flutter.h"+#include "../utils/log.h"+#include "../utils/string.h"+#include "../utils/vector.h"+#include "webview_environment_manager.h"++namespace flutter_inappwebview_plugin+{+ WebViewEnvironmentManager::WebViewEnvironmentManager(const FlutterInappwebviewWindowsPlugin* plugin)+ : plugin(plugin),+ ChannelDelegate(plugin->registrar->messenger(), WebViewEnvironmentManager::METHOD_CHANNEL_NAME)+ {+ windowClass_.lpszClassName = WebViewEnvironmentManager::CLASS_NAME;+ windowClass_.lpfnWndProc = &DefWindowProc;++ RegisterClass(&windowClass_);++ hwnd_ = CreateWindowEx(0, windowClass_.lpszClassName, L"", 0, 0,+ 0, 0, 0,+ plugin->registrar->GetView()->GetNativeWindow(),+ nullptr,+ windowClass_.hInstance, nullptr);+ }++ void WebViewEnvironmentManager::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ auto* arguments = std::get_if<flutter::EncodableMap>(method_call.arguments());+ auto& methodName = method_call.method_name();++ if (string_equals(methodName, "create")) {+ auto id = get_fl_map_value<std::string>(*arguments, "id");+ auto settingsMap = get_optional_fl_map_value<flutter::EncodableMap>(*arguments, "settings");+ auto settings = settingsMap.has_value() ? std::make_unique<WebViewEnvironmentSettings>(settingsMap.value()) : nullptr;+ createWebViewEnvironment(id, std::move(settings), std::move(result));+ }+ else if (string_equals(methodName, "getAvailableVersion")) {+ auto browserExecutableFolder = get_optional_fl_map_value<std::string>(*arguments, "browserExecutableFolder");+ result->Success(make_fl_value(getAvailableVersion(browserExecutableFolder)));+ }+ else if (string_equals(methodName, "compareBrowserVersions")) {+ auto version1 = get_fl_map_value<std::string>(*arguments, "version1");+ auto version2 = get_fl_map_value<std::string>(*arguments, "version2");+ result->Success(make_fl_value(compareBrowserVersions(version1, version2)));+ }+ else {+ result->NotImplemented();+ }+ }++ void WebViewEnvironmentManager::createWebViewEnvironment(const std::string& id, std::unique_ptr<WebViewEnvironmentSettings> settings, std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)+ {+ auto result_ = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>(std::move(result));++ auto webViewEnvironment = std::make_unique<WebViewEnvironment>(plugin, id);+ webViewEnvironment->create(std::move(settings),+ [this, id, result_](HRESULT errorCode)+ {+ if (succeededOrLog(errorCode)) {+ result_->Success(true);+ }+ else {+ result_->Error("0", "Cannot create WebViewEnvironment: " + getHRMessage(errorCode));+ if (map_contains(webViewEnvironments, id)) {+ webViewEnvironments.erase(id);+ }+ }+ });+ webViewEnvironments.insert({ id, std::move(webViewEnvironment) });+ }++ void WebViewEnvironmentManager::createOrGetDefaultWebViewEnvironment(const std::function<void(WebViewEnvironment*)> completionHandler)+ {+ if (defaultEnvironment_) {+ if (completionHandler) {+ completionHandler(defaultEnvironment_.get());+ }+ return;+ }++ defaultEnvironment_ = std::make_unique<WebViewEnvironment>(plugin, "-1");+ defaultEnvironment_->create(nullptr, [this, completionHandler](HRESULT errorCode)+ {+ if (succeededOrLog(errorCode)) {+ if (completionHandler) {+ completionHandler(defaultEnvironment_.get());+ }+ }+ else if (completionHandler) {+ defaultEnvironment_ = nullptr;+ completionHandler(nullptr);+ }+ });+ }++ std::optional<std::string> WebViewEnvironmentManager::getAvailableVersion(std::optional<std::string> browserExecutableFolder)+ {+ wil::unique_cotaskmem_string versionInfo;+ if (succeededOrLog(GetAvailableCoreWebView2BrowserVersionString(browserExecutableFolder.has_value() ? utf8_to_wide(browserExecutableFolder.value()).c_str() : nullptr, &versionInfo))) {+ return wide_to_utf8(versionInfo.get());+ }+ return std::nullopt;+ }++ std::optional<int> WebViewEnvironmentManager::compareBrowserVersions(std::string version1, std::string version2)+ {+ int result = 0;+ if (succeededOrLog(CompareBrowserVersions(utf8_to_wide(version1).c_str(), utf8_to_wide(version2).c_str(), &result))) {+ return result;+ }+ return std::nullopt;+ }++ WebViewEnvironmentManager::~WebViewEnvironmentManager()+ {+ debugLog("dealloc WebViewEnvironmentManager");+ webViewEnvironments.clear();+ plugin = nullptr;+ defaultEnvironment_ = nullptr;+ if (hwnd_) {+ DestroyWindow(hwnd_);+ }+ }+}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_manager.h b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_manager.hnew file mode 100644index 00000000..6bfcafcb--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_manager.h@@ -0,0 +1,46 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_MANAGER_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_MANAGER_H_++#include <flutter/method_channel.h>+#include <map>+#include <string>+#include <winrt/base.h>++#include "../flutter_inappwebview_windows_plugin.h"+#include "../types/channel_delegate.h"+#include "webview_environment.h"++namespace flutter_inappwebview_plugin+{+ class WebViewEnvironmentManager : public ChannelDelegate+ {+ public:+ static inline const wchar_t* CLASS_NAME = L"WebViewEnvironmentManager";+ static inline const std::string METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_webview_environment";++ const FlutterInappwebviewWindowsPlugin* plugin;+ std::map<std::string, std::unique_ptr<WebViewEnvironment>> webViewEnvironments;++ WebViewEnvironmentManager(const FlutterInappwebviewWindowsPlugin* plugin);+ ~WebViewEnvironmentManager();++ void HandleMethodCall(+ const flutter::MethodCall<flutter::EncodableValue>& method_call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);++ void createWebViewEnvironment(const std::string& id, std::unique_ptr<WebViewEnvironmentSettings> settings, std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);+ void createOrGetDefaultWebViewEnvironment(const std::function<void(WebViewEnvironment*)> completionHandler);+ HWND getHWND()+ {+ return hwnd_;+ }++ static std::optional<std::string> getAvailableVersion(std::optional<std::string> browserExecutableFolder);+ static std::optional<int> compareBrowserVersions(std::string version1, std::string version2);+ private:+ std::unique_ptr<WebViewEnvironment> defaultEnvironment_;+ WNDCLASS windowClass_ = {};+ HWND hwnd_ = nullptr;+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_MANAGER_H_\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_settings.cpp b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_settings.cppnew file mode 100644index 00000000..7667f600--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_settings.cpp@@ -0,0 +1,29 @@+#include "../utils/flutter.h"+#include "webview_environment_settings.h"++namespace flutter_inappwebview_plugin+{+ WebViewEnvironmentSettings::WebViewEnvironmentSettings(const flutter::EncodableMap& map)+ : browserExecutableFolder(get_optional_fl_map_value<std::string>(map, "browserExecutableFolder")),+ userDataFolder(get_optional_fl_map_value<std::string>(map, "userDataFolder")),+ additionalBrowserArguments(get_optional_fl_map_value<std::string>(map, "additionalBrowserArguments")),+ allowSingleSignOnUsingOSPrimaryAccount(get_optional_fl_map_value<bool>(map, "allowSingleSignOnUsingOSPrimaryAccount")),+ language(get_optional_fl_map_value<std::string>(map, "language")),+ targetCompatibleBrowserVersion(get_optional_fl_map_value<std::string>(map, "targetCompatibleBrowserVersion")),+ customSchemeRegistrations(functional_map(get_optional_fl_map_value<flutter::EncodableList>(map, "customSchemeRegistrations"), [](const flutter::EncodableValue& m) { return std::make_shared<CustomSchemeRegistration>(std::get<flutter::EncodableMap>(m)); }))+ {}++ flutter::EncodableMap WebViewEnvironmentSettings::toEncodableMap() const+ {+ return flutter::EncodableMap{+ {"browserExecutableFolder", make_fl_value(browserExecutableFolder)},+ {"userDataFolder", make_fl_value(userDataFolder)},+ {"additionalBrowserArguments", make_fl_value(additionalBrowserArguments)},+ {"allowSingleSignOnUsingOSPrimaryAccount", make_fl_value(allowSingleSignOnUsingOSPrimaryAccount)},+ {"language", make_fl_value(language)},+ {"targetCompatibleBrowserVersion", make_fl_value(targetCompatibleBrowserVersion)},+ {"customSchemeRegistrations", make_fl_value(functional_map(customSchemeRegistrations, [](const std::shared_ptr<CustomSchemeRegistration>& item) { return item->toEncodableMap(); }))}+ };+ }++}\ No newline at end of filediff --git a/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_settings.h b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_settings.hnew file mode 100644index 00000000..84314aac--- /dev/null+++ b/packages/flutter_inappwebview_windows/windows/webview_environment/webview_environment_settings.h@@ -0,0 +1,31 @@+#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_CREATION_PARAMS_H_+#define FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_CREATION_PARAMS_H_++#include <flutter/standard_method_codec.h>+#include <optional>+#include <string>++#include "../flutter_inappwebview_windows_plugin.h"+#include "../types/custom_scheme_registration.h"++namespace flutter_inappwebview_plugin+{+ class WebViewEnvironmentSettings+ {+ public:+ const std::optional<std::string> browserExecutableFolder;+ const std::optional<std::string> userDataFolder;+ const std::optional<std::string> additionalBrowserArguments;+ const std::optional<bool> allowSingleSignOnUsingOSPrimaryAccount;+ const std::optional<std::string> language;+ const std::optional<std::string> targetCompatibleBrowserVersion;+ const std::optional<std::vector<std::shared_ptr<CustomSchemeRegistration>>> customSchemeRegistrations;++ WebViewEnvironmentSettings() = default;+ WebViewEnvironmentSettings(const flutter::EncodableMap& map);+ ~WebViewEnvironmentSettings() = default;++ flutter::EncodableMap toEncodableMap() const;+ };+}+#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_ENVIRONMENT_CREATION_PARAMS_H_\ No newline at end of filediff --git a/packages/whisper_ggml_plus/windows/CMakeLists.txt b/packages/whisper_ggml_plus/windows/CMakeLists.txtindex 2df97ea5..806cc0cd 100644--- a/packages/whisper_ggml_plus/windows/CMakeLists.txt+++ b/packages/whisper_ggml_plus/windows/CMakeLists.txt@@ -17,6 +17,13 @@ set(GGML_ROOT_DIR "${WHISPER_ROOT_DIR}/ggml")set(JSON_ROOT_DIR "${PLATFORM_SHARED_ROOT}/json")set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build vendored libs static" FORCE)+# Absorb patch: native builds for whatever CPU compiled them (AVX-512 on an+# 11th gen Intel or a CI box), and crashed other PCs the moment whisper ran.+# Off falls back to the AVX2 baseline, like the Android build.+set(GGML_NATIVE OFF CACHE BOOL "Portable CPU build" FORCE)+set(GGML_AVX ON CACHE BOOL "AVX baseline" FORCE)+set(GGML_AVX2 ON CACHE BOOL "AVX2 baseline (implies FMA/F16C on MSVC)" FORCE)+set(GGML_AVX512 OFF CACHE BOOL "Most PCs lack AVX-512" FORCE)set(GGML_METAL OFF CACHE BOOL "Disable Metal backend on Windows" FORCE)set(GGML_ACCELERATE OFF CACHE BOOL "Disable Accelerate on Windows" FORCE)set(GGML_BLAS OFF CACHE BOOL "Disable BLAS auto-linking on Windows" FORCE)diff --git a/packages/whisper_ggml_plus/windows/whisper_ggml_plus.cpp b/packages/whisper_ggml_plus/windows/whisper_ggml_plus.cppindex d29277cf..9c0a2dfa 100644--- a/packages/whisper_ggml_plus/windows/whisper_ggml_plus.cpp+++ b/packages/whisper_ggml_plus/windows/whisper_ggml_plus.cpp@@ -142,7 +142,12 @@ static json transcribe(const json & json_body) {params.diarize = json_body["diarize"];params.speed_up = json_body["speed_up"];params.vad_mode = parse_vad_mode(json_body);- params.vad_model_path = json_body.value("vad_model_path", std::string(""));+ // Absorb patch: Dart sends "vad_model_path": null when there is none, and+ // value() throws on an explicit null (json type_error.302), which failed+ // every Windows transcription. Read it the way the iOS side does.+ if (json_body.contains("vad_model_path") && json_body["vad_model_path"].is_string()) {+ params.vad_model_path = json_body["vad_model_path"].get<std::string>();+ }json json_result;json_result["@type"] = "transcribe";diff --git a/pubspec.lock b/pubspec.lockindex 504b4268..d980daaa 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -442,12 +442,11 @@ packages:source: hostedversion: "1.1.2"flutter_inappwebview_windows:- dependency: transitive+ dependency: "direct overridden"description:- name: flutter_inappwebview_windows- sha256: "8b4d3a46078a2cdc636c4a3d10d10f2a16882f6be607962dbfff8874d1642055"- url: "https://pub.dev"- source: hosted+ path: "packages/flutter_inappwebview_windows"+ relative: true+ source: pathversion: "0.6.0"flutter_launcher_icons:dependency: "direct dev"@@ -703,6 +702,14 @@ packages:relative: truesource: pathversion: "0.9.46"+ just_audio_media_kit:+ dependency: "direct main"+ description:+ name: just_audio_media_kit+ sha256: f3cf04c3a50339709e87e90b4e841eef4364ab4be2bdbac0c54cc48679f84d23+ url: "https://pub.dev"+ source: hosted+ version: "2.1.0"just_audio_platform_interface:dependency: transitivedescription:@@ -799,6 +806,22 @@ packages:url: "https://pub.dev"source: hostedversion: "0.13.0"+ media_kit:+ dependency: transitive+ description:+ name: media_kit+ sha256: ae9e79597500c7ad6083a3c7b7b7544ddabfceacce7ae5c9709b0ec16a5d6643+ url: "https://pub.dev"+ source: hosted+ version: "1.2.6"+ media_kit_libs_windows_audio:+ dependency: "direct main"+ description:+ name: media_kit_libs_windows_audio+ sha256: c2fd558cc87b9d89a801141fcdffe02e338a3b21a41a18fbd63d5b221a1b8e53+ url: "https://pub.dev"+ source: hosted+ version: "1.0.9"meta:dependency: transitivedescription:@@ -1167,6 +1190,14 @@ packages:url: "https://pub.dev"source: hostedversion: "0.28.0"+ safe_local_storage:+ dependency: transitive+ description:+ name: safe_local_storage+ sha256: "494b982d5edb71030650ea463d939670e91b232b588323dc75229d2c5f23e7b7"+ url: "https://pub.dev"+ source: hosted+ version: "2.0.6"sensors_plus:dependency: "direct main"description:@@ -1468,6 +1499,22 @@ packages:url: "https://pub.dev"source: hostedversion: "2.3.1"+ universal_platform:+ dependency: transitive+ description:+ name: universal_platform+ sha256: "64e16458a0ea9b99260ceb5467a214c1f298d647c659af1bff6d3bf82536b1ec"+ url: "https://pub.dev"+ source: hosted+ version: "1.1.0"+ uri_parser:+ dependency: transitive+ description:+ name: uri_parser+ sha256: "051c62e5f693de98ca9f130ee707f8916e2266945565926be3ff20659f7853ce"+ url: "https://pub.dev"+ source: hosted+ version: "3.0.2"url_launcher:dependency: "direct main"description:diff --git a/pubspec.yaml b/pubspec.yamlindex 5206aafb..6129ed96 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -33,6 +33,10 @@ dependencies:audio_service:path: packages/audio_service+ # Windows has no just_audio engine of its own; this plays through libmpv.+ just_audio_media_kit: ^2.1.0+ media_kit_libs_windows_audio: ^1.0.9+# On-device bookmark transcription (Whisper, opt-in). No ffmpeg companion:# we feed it 16kHz mono WAV produced by native decoders (MediaCodec / AVAssetReader).# Vendored from 1.5.2: the arm64 build was plain armv8-a with no dotprod/fp16@@ -138,6 +142,10 @@ dev_dependencies:dependency_overrides:audio_service_web:path: packages/audio_service_web+ # Vendored for a null-pointer fix in its JavaScript handler reply, which+ # crashed the Windows app whenever the reader loaded a book.+ flutter_inappwebview_windows:+ path: packages/flutter_inappwebview_windowsflutter:generate: truediff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.ccindex 077e6d24..2567712d 100644--- a/windows/flutter/generated_plugin_registrant.cc+++ b/windows/flutter/generated_plugin_registrant.cc@@ -10,6 +10,7 @@#include <connectivity_plus/connectivity_plus_windows_plugin.h>#include <desktop_webview_window/desktop_webview_window_plugin.h>#include <flutter_inappwebview_windows/flutter_inappwebview_windows_plugin_c_api.h>+#include <media_kit_libs_windows_audio/media_kit_libs_windows_audio_plugin_c_api.h>#include <permission_handler_windows/permission_handler_windows_plugin.h>#include <share_plus/share_plus_windows_plugin_c_api.h>#include <url_launcher_windows/url_launcher_windows.h>@@ -24,6 +25,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {registry->GetRegistrarForPlugin("DesktopWebviewWindowPlugin"));FlutterInappwebviewWindowsPluginCApiRegisterWithRegistrar(registry->GetRegistrarForPlugin("FlutterInappwebviewWindowsPluginCApi"));+ MediaKitLibsWindowsAudioPluginCApiRegisterWithRegistrar(+ registry->GetRegistrarForPlugin("MediaKitLibsWindowsAudioPluginCApi"));PermissionHandlerWindowsPluginRegisterWithRegistrar(registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin"));SharePlusWindowsPluginCApiRegisterWithRegistrar(diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmakeindex 6e344ae8..8ee87241 100644--- a/windows/flutter/generated_plugins.cmake+++ b/windows/flutter/generated_plugins.cmake@@ -7,6 +7,7 @@ list(APPEND FLUTTER_PLUGIN_LISTconnectivity_plusdesktop_webview_windowflutter_inappwebview_windows+ media_kit_libs_windows_audiopermission_handler_windowsshare_plusurl_launcher_windowsdiff --git a/windows/installer/absorb.iss b/windows/installer/absorb.issnew file mode 100644index 00000000..a917f019--- /dev/null+++ b/windows/installer/absorb.iss@@ -0,0 +1,56 @@+; Inno Setup script for the Windows desktop app. CI passes the version and+; the output name: iscc /DAppVersion=1.11.1.286 /DOutputBase=... absorb.iss+; Paths are relative to this file.++#ifndef AppVersion+ #define AppVersion "0.0.0"+#endif+#ifndef OutputBase+ #define OutputBase "absorb-windows-setup"+#endif+#define SourceDir "..\..\build\windows\x64\runner\Release"++[Setup]+; Never change the AppId: it's how an update finds the installed copy.+AppId={{3229A98C-AAE4-4106-8B9B-4778E2C857E9}+AppName=Absorb+AppVersion={#AppVersion}+AppVerName=Absorb {#AppVersion}+AppPublisher=Barnabas+AppPublisherURL=https://github.com/pounat/absorb+AppSupportURL=https://github.com/pounat/absorb/issues+; Per-user install into %LOCALAPPDATA%\Programs\Absorb, no admin prompt.+; Per-user only: the reader's WebView2 keeps its data folder next to the+; exe, which Program Files wouldn't let it write.+DefaultDirName={autopf}\Absorb+DisableProgramGroupPage=yes+PrivilegesRequired=lowest+ArchitecturesAllowed=x64compatible+ArchitecturesInstallIn64BitMode=x64compatible+OutputDir=..\..\build\installer+OutputBaseFilename={#OutputBase}+SetupIconFile=..\runner\resources\app_icon.ico+UninstallDisplayIcon={app}\absorb.exe+UninstallDisplayName=Absorb+Compression=lzma2+SolidCompression=yes+WizardStyle=modern+CloseApplications=yes++[Tasks]+Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked++[InstallDelete]+; Flutter's asset bundle changes every build; clear the old one so stale+; assets from a previous version don't linger after an update.+Type: filesandordirs; Name: "{app}\data"++[Files]+Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs++[Icons]+Name: "{autoprograms}\Absorb"; Filename: "{app}\absorb.exe"+Name: "{autodesktop}\Absorb"; Filename: "{app}\absorb.exe"; Tasks: desktopicon++[Run]+Filename: "{app}\absorb.exe"; Description: "{cm:LaunchProgram,Absorb}"; Flags: nowait postinstall skipifsilentdiff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txtindex 394917c0..e8be1a0f 100644--- a/windows/runner/CMakeLists.txt+++ b/windows/runner/CMakeLists.txt@@ -7,6 +7,7 @@ project(runner LANGUAGES CXX)## Any new source files that you add to the application should be added here.add_executable(${BINARY_NAME} WIN32+ "audio_window_channel.cpp""flutter_window.cpp""main.cpp""utils.cpp"@@ -34,6 +35,8 @@ target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")# dependencies here.target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")+# Media Foundation, for decoding audio windows for transcription.+target_link_libraries(${BINARY_NAME} PRIVATE "mfplat.lib" "mfreadwrite.lib" "mfuuid.lib")target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")# Run the Flutter tool portions of the build. This must not be removed.diff --git a/windows/runner/audio_window_channel.cpp b/windows/runner/audio_window_channel.cppnew file mode 100644index 00000000..59d44eeb--- /dev/null+++ b/windows/runner/audio_window_channel.cpp@@ -0,0 +1,223 @@+#include "audio_window_channel.h"++#include <flutter/standard_method_codec.h>+#include <mfapi.h>+#include <mferror.h>+#include <mfidl.h>+#include <mfreadwrite.h>+#include <wrl/client.h>++#include <algorithm>+#include <cstdint>+#include <fstream>+#include <thread>++using Microsoft::WRL::ComPtr;++namespace {++constexpr int kTargetRate = 16000;+constexpr LONGLONG kHnsPerSecond = 10000000;+// The reader's stream selectors are negative enum values taken as DWORDs.+constexpr DWORD kAudioStream =+ static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM);+constexpr DWORD kAllStreams = static_cast<DWORD>(MF_SOURCE_READER_ALL_STREAMS);++std::wstring Widen(const std::string& s) {+ if (s.empty()) return std::wstring();+ const int n = MultiByteToWideChar(CP_UTF8, 0, s.data(),+ static_cast<int>(s.size()), nullptr, 0);+ std::wstring w(n, L'\0');+ MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast<int>(s.size()),+ w.data(), n);+ return w;+}++bool WriteWav(const std::string& path, const std::vector<int16_t>& pcm) {+ std::ofstream f(Widen(path), std::ios::binary);+ if (!f) return false;+ const uint32_t data_bytes = static_cast<uint32_t>(pcm.size() * 2);+ auto u32 = [&f](uint32_t v) { f.write(reinterpret_cast<const char*>(&v), 4); };+ auto u16 = [&f](uint16_t v) { f.write(reinterpret_cast<const char*>(&v), 2); };+ f.write("RIFF", 4);+ u32(36 + data_bytes);+ f.write("WAVE", 4);+ f.write("fmt ", 4);+ u32(16);+ u16(1); // PCM+ u16(1); // mono+ u32(kTargetRate);+ u32(kTargetRate * 2);+ u16(2);+ u16(16);+ f.write("data", 4);+ u32(data_bytes);+ f.write(reinterpret_cast<const char*>(pcm.data()), data_bytes);+ return static_cast<bool>(f);+}++std::string ReadString(const flutter::EncodableMap& args, const char* key) {+ auto it = args.find(flutter::EncodableValue(key));+ if (it == args.end()) return std::string();+ if (auto s = std::get_if<std::string>(&it->second)) return *s;+ return std::string();+}++double ReadNumber(const flutter::EncodableMap& args, const char* key) {+ auto it = args.find(flutter::EncodableValue(key));+ if (it == args.end()) return 0;+ if (auto d = std::get_if<double>(&it->second)) return *d;+ if (auto i = std::get_if<int32_t>(&it->second)) return *i;+ if (auto l = std::get_if<int64_t>(&it->second)) return static_cast<double>(*l);+ return 0;+}++} // namespace++std::string AudioWindowChannel::DecodeWindow(const std::string& source,+ double start, double duration,+ const std::string& out) {+ ComPtr<IMFSourceReader> reader;+ if (FAILED(MFCreateSourceReaderFromURL(Widen(source).c_str(), nullptr,+ &reader))) {+ return "could not open the audio";+ }+ reader->SetStreamSelection(kAllStreams, FALSE);+ reader->SetStreamSelection(kAudioStream, TRUE);++ ComPtr<IMFMediaType> wanted;+ MFCreateMediaType(&wanted);+ wanted->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);+ wanted->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM);+ wanted->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 16);+ if (FAILED(reader->SetCurrentMediaType(kAudioStream,+ nullptr, wanted.Get()))) {+ return "no decoder for this audio";+ }+ ComPtr<IMFMediaType> actual;+ reader->GetCurrentMediaType(kAudioStream, &actual);+ UINT32 channels = 0;+ UINT32 rate = 0;+ actual->GetUINT32(MF_MT_AUDIO_NUM_CHANNELS, &channels);+ actual->GetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, &rate);+ if (channels == 0 || rate == 0) return "unreadable audio format";++ const LONGLONG start_hns = static_cast<LONGLONG>(start * kHnsPerSecond);+ if (start_hns > 0) {+ PROPVARIANT pos;+ PropVariantInit(&pos);+ pos.vt = VT_I8;+ pos.hVal.QuadPart = start_hns;+ reader->SetCurrentPosition(GUID_NULL, pos);+ PropVariantClear(&pos);+ }++ const size_t wanted_frames = static_cast<size_t>(duration * rate);+ std::vector<float> mono;+ mono.reserve(wanted_frames);+ while (mono.size() < wanted_frames) {+ DWORD flags = 0;+ LONGLONG timestamp = 0;+ ComPtr<IMFSample> sample;+ if (FAILED(reader->ReadSample(kAudioStream, 0,+ nullptr, &flags, ×tamp, &sample))) {+ return "decoding failed";+ }+ if (flags & MF_SOURCE_READERF_ENDOFSTREAM) break;+ if (!sample) continue;+ ComPtr<IMFMediaBuffer> buffer;+ if (FAILED(sample->ConvertToContiguousBuffer(&buffer))) continue;+ BYTE* data = nullptr;+ DWORD length = 0;+ if (FAILED(buffer->Lock(&data, nullptr, &length))) continue;+ const auto* samples = reinterpret_cast<const int16_t*>(data);+ const size_t frames = length / (2 * channels);+ // A seek lands on the frame before the target; drop the lead-in.+ size_t skip = 0;+ if (timestamp < start_hns) {+ skip = static_cast<size_t>((start_hns - timestamp) * rate / kHnsPerSecond);+ skip = (std::min)(skip, frames);+ }+ for (size_t i = skip; i < frames && mono.size() < wanted_frames; ++i) {+ float sum = 0;+ for (UINT32 c = 0; c < channels; ++c) sum += samples[i * channels + c];+ mono.push_back(sum / channels / 32768.0f);+ }+ buffer->Unlock();+ }+ if (mono.empty()) return "no audio in that window";++ const size_t out_frames =+ static_cast<size_t>(static_cast<double>(mono.size()) * kTargetRate / rate);+ const double step = static_cast<double>(rate) / kTargetRate;+ std::vector<int16_t> pcm(out_frames);+ for (size_t i = 0; i < out_frames; ++i) {+ const double p = i * step;+ const size_t a = (std::min)(static_cast<size_t>(p), mono.size() - 1);+ const size_t b = (std::min)(a + 1, mono.size() - 1);+ const double t = p - static_cast<double>(a);+ float v = static_cast<float>(mono[a] + (mono[b] - mono[a]) * t);+ v = (std::max)(-1.0f, (std::min)(1.0f, v));+ pcm[i] = static_cast<int16_t>(v * 32767.0f);+ }+ return WriteWav(out, pcm) ? std::string() : "could not write the WAV";+}++AudioWindowChannel::AudioWindowChannel(flutter::BinaryMessenger* messenger,+ HWND window)+ : state_(std::make_shared<State>()) {+ state_->window = window;+ channel_ = std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(+ messenger, "com.barnabas.absorb/transcription",+ &flutter::StandardMethodCodec::GetInstance());+ auto state = state_;+ channel_->SetMethodCallHandler(+ [state](const flutter::MethodCall<flutter::EncodableValue>& call,+ std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>>+ result) {+ if (call.method_name() != "extractWav") {+ result->NotImplemented();+ return;+ }+ const auto* args = std::get_if<flutter::EncodableMap>(call.arguments());+ if (args == nullptr) {+ result->Error("bad_args", "extractWav needs a map");+ return;+ }+ const std::string source = ReadString(*args, "sourcePath");+ const std::string out = ReadString(*args, "outPath");+ const double start = ReadNumber(*args, "startSeconds");+ const double duration = ReadNumber(*args, "durationSeconds");+ Result shared(std::move(result));+ // Decoding a window takes a moment; keep it off the UI thread.+ std::thread([state, shared, source, out, start, duration]() {+ const HRESULT com = CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ std::string error = "Media Foundation is unavailable";+ if (SUCCEEDED(MFStartup(MF_VERSION))) {+ error = DecodeWindow(source, start, duration, out);+ MFShutdown();+ }+ if (SUCCEEDED(com)) CoUninitialize();+ {+ std::lock_guard<std::mutex> lock(state->mutex);+ state->done.push_back({shared, error});+ }+ PostMessage(state->window, kDoneMessage, 0, 0);+ }).detach();+ });+}++void AudioWindowChannel::DrainResults() {+ std::vector<Done> done;+ {+ std::lock_guard<std::mutex> lock(state_->mutex);+ done.swap(state_->done);+ }+ for (auto& d : done) {+ if (d.error.empty()) {+ d.result->Success(flutter::EncodableValue(true));+ } else {+ d.result->Error("extract_failed", d.error);+ }+ }+}diff --git a/windows/runner/audio_window_channel.h b/windows/runner/audio_window_channel.hnew file mode 100644index 00000000..7a80fe33--- /dev/null+++ b/windows/runner/audio_window_channel.h@@ -0,0 +1,50 @@+#ifndef RUNNER_AUDIO_WINDOW_CHANNEL_H_+#define RUNNER_AUDIO_WINDOW_CHANNEL_H_++#include <flutter/binary_messenger.h>+#include <flutter/encodable_value.h>+#include <flutter/method_channel.h>+#include <windows.h>++#include <memory>+#include <mutex>+#include <string>+#include <vector>++// Windows side of com.barnabas.absorb/transcription: decodes a time window of+// an audio file into the 16kHz mono 16-bit WAV whisper.cpp reads, with Media+// Foundation, so nothing extra ships. Android does the same with MediaCodec+// (AudioWindowExtractor.kt) and iOS with AVAssetReader.+class AudioWindowChannel {+ public:+ // Posted to the window when a decode finishes; the window calls+ // DrainResults() so the reply goes out on the platform thread.+ static constexpr UINT kDoneMessage = WM_APP + 0x41;++ AudioWindowChannel(flutter::BinaryMessenger* messenger, HWND window);++ void DrainResults();++ // Decodes [start, start + duration) of |source| into a WAV at |out|.+ // Returns an empty string on success, otherwise what went wrong.+ static std::string DecodeWindow(const std::string& source, double start,+ double duration, const std::string& out);++ private:+ using Result = std::shared_ptr<flutter::MethodResult<flutter::EncodableValue>>;+ struct Done {+ Result result;+ std::string error;+ };+ // Shared with the worker threads, which can outlive a call.+ struct State {+ HWND window;+ std::mutex mutex;+ std::vector<Done> done;+ };++ std::shared_ptr<State> state_;+ std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>> channel_;+};++#endif // RUNNER_AUDIO_WINDOW_CHANNEL_H_diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cppindex 955ee303..ed547abe 100644--- a/windows/runner/flutter_window.cpp+++ b/windows/runner/flutter_window.cpp@@ -25,6 +25,8 @@ bool FlutterWindow::OnCreate() {return false;}RegisterPlugins(flutter_controller_->engine());+ audio_window_channel_ = std::make_unique<AudioWindowChannel>(+ flutter_controller_->engine()->messenger(), GetHandle());SetChildContent(flutter_controller_->view()->GetNativeWindow());flutter_controller_->engine()->SetNextFrameCallback([&]() {@@ -40,6 +42,7 @@ bool FlutterWindow::OnCreate() {}void FlutterWindow::OnDestroy() {+ audio_window_channel_ = nullptr;if (flutter_controller_) {flutter_controller_ = nullptr;}@@ -65,6 +68,9 @@ FlutterWindow::MessageHandler(HWND hwnd, UINT const message,case WM_FONTCHANGE:flutter_controller_->engine()->ReloadSystemFonts();break;+ case AudioWindowChannel::kDoneMessage:+ if (audio_window_channel_) audio_window_channel_->DrainResults();+ return 0;}return Win32Window::MessageHandler(hwnd, message, wparam, lparam);diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.hindex 6da0652f..aa04ca73 100644--- a/windows/runner/flutter_window.h+++ b/windows/runner/flutter_window.h@@ -6,6 +6,7 @@#include <memory>+#include "audio_window_channel.h"#include "win32_window.h"// A window that does nothing but host a Flutter view.@@ -28,6 +29,9 @@ class FlutterWindow : public Win32Window {// The Flutter instance hosted by this window.std::unique_ptr<flutter::FlutterViewController> flutter_controller_;++ // Decodes audio windows for transcription.+ std::unique_ptr<AudioWindowChannel> audio_window_channel_;};#endif // RUNNER_FLUTTER_WINDOW_H_