basic initial windows support
This commit is contained in:
parent
751a104716
commit
81b72b3213
|
@ -4,5 +4,27 @@
|
|||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: d927c9331005f81157fa39dff7b5dab415ad330b
|
||||
channel: master
|
||||
revision: "78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9"
|
||||
channel: "stable"
|
||||
|
||||
project_type: app
|
||||
|
||||
# Tracks metadata for the flutter migrate command
|
||||
migration:
|
||||
platforms:
|
||||
- platform: root
|
||||
create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9
|
||||
base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9
|
||||
- platform: windows
|
||||
create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9
|
||||
base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9
|
||||
|
||||
# User provided section
|
||||
|
||||
# List of Local paths (relative to this file) that should be
|
||||
# ignored by the migrate tool.
|
||||
#
|
||||
# Files that are not part of the templates will be ignored by default.
|
||||
unmanaged_files:
|
||||
- 'lib/main.dart'
|
||||
- 'ios/Runner.xcodeproj/project.pbxproj'
|
||||
|
|
|
@ -26,10 +26,6 @@ Future main() async {
|
|||
await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
|
||||
}
|
||||
|
||||
if (!kIsWeb) {
|
||||
await localhostServer.start();
|
||||
}
|
||||
|
||||
runApp(MyApp());
|
||||
}
|
||||
|
||||
|
@ -75,6 +71,41 @@ PointerInterceptor myDrawer({required BuildContext context}) {
|
|||
},
|
||||
)
|
||||
];
|
||||
} else if (defaultTargetPlatform == TargetPlatform.macOS ||
|
||||
defaultTargetPlatform == TargetPlatform.windows ||
|
||||
defaultTargetPlatform == TargetPlatform.linux) {
|
||||
children = [
|
||||
// ListTile(
|
||||
// title: Text('InAppWebView'),
|
||||
// onTap: () {
|
||||
// Navigator.pushReplacementNamed(context, '/');
|
||||
// },
|
||||
// ),
|
||||
// ListTile(
|
||||
// title: Text('InAppBrowser'),
|
||||
// onTap: () {
|
||||
// Navigator.pushReplacementNamed(context, '/InAppBrowser');
|
||||
// },
|
||||
// ),
|
||||
ListTile(
|
||||
title: Text('InAppBrowser'),
|
||||
onTap: () {
|
||||
Navigator.pushReplacementNamed(context, '/');
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
title: Text('WebAuthenticationSession'),
|
||||
onTap: () {
|
||||
Navigator.pushReplacementNamed(context, '/WebAuthenticationSession');
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
title: Text('HeadlessInAppWebView'),
|
||||
onTap: () {
|
||||
Navigator.pushReplacementNamed(context, '/HeadlessInAppWebView');
|
||||
},
|
||||
),
|
||||
];
|
||||
} else if (defaultTargetPlatform == TargetPlatform.macOS) {
|
||||
children = [
|
||||
// ListTile(
|
||||
|
@ -108,6 +139,34 @@ PointerInterceptor myDrawer({required BuildContext context}) {
|
|||
},
|
||||
),
|
||||
];
|
||||
} else if (defaultTargetPlatform == TargetPlatform.windows ||
|
||||
defaultTargetPlatform == TargetPlatform.linux) {
|
||||
children = [
|
||||
// ListTile(
|
||||
// title: Text('InAppWebView'),
|
||||
// onTap: () {
|
||||
// Navigator.pushReplacementNamed(context, '/');
|
||||
// },
|
||||
// ),
|
||||
// ListTile(
|
||||
// title: Text('InAppBrowser'),
|
||||
// onTap: () {
|
||||
// Navigator.pushReplacementNamed(context, '/InAppBrowser');
|
||||
// },
|
||||
// ),
|
||||
ListTile(
|
||||
title: Text('InAppBrowser'),
|
||||
onTap: () {
|
||||
Navigator.pushReplacementNamed(context, '/');
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
title: Text('HeadlessInAppWebView'),
|
||||
onTap: () {
|
||||
Navigator.pushReplacementNamed(context, '/HeadlessInAppWebView');
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
return PointerInterceptor(
|
||||
child: Drawer(
|
||||
|
@ -160,6 +219,15 @@ class _MyAppState extends State<MyApp> {
|
|||
'/WebAuthenticationSession': (context) =>
|
||||
WebAuthenticationSessionExampleScreen(),
|
||||
});
|
||||
} else if (defaultTargetPlatform == TargetPlatform.windows ||
|
||||
defaultTargetPlatform == TargetPlatform.linux) {
|
||||
return MaterialApp(initialRoute: '/', routes: {
|
||||
// '/': (context) => InAppWebViewExampleScreen(),
|
||||
// '/InAppBrowser': (context) => InAppBrowserExampleScreen(),
|
||||
'/': (context) => InAppBrowserExampleScreen(),
|
||||
'/HeadlessInAppWebView': (context) =>
|
||||
HeadlessInAppWebViewExampleScreen(),
|
||||
});
|
||||
}
|
||||
return MaterialApp(initialRoute: '/', routes: {
|
||||
'/': (context) => InAppWebViewExampleScreen(),
|
||||
|
|
|
@ -43,6 +43,8 @@ dependency_overrides:
|
|||
path: ../../flutter_inappwebview_macos
|
||||
flutter_inappwebview_web:
|
||||
path: ../../flutter_inappwebview_web
|
||||
flutter_inappwebview_windows:
|
||||
path: ../../flutter_inappwebview_windows
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
// This is a basic Flutter widget test.
|
||||
//
|
||||
// To perform an interaction with a widget in your test, use the WidgetTester
|
||||
// utility in the flutter_test package. For example, you can send tap and scroll
|
||||
// gestures. You can also use WidgetTester to find child widgets in the widget
|
||||
// tree, read text, and verify that the values of widget properties are correct.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:example/main.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
|
||||
// Build our app and trigger a frame.
|
||||
await tester.pumpWidget(const MyApp());
|
||||
|
||||
// Verify that our counter starts at 0.
|
||||
expect(find.text('0'), findsOneWidget);
|
||||
expect(find.text('1'), findsNothing);
|
||||
|
||||
// Tap the '+' icon and trigger a frame.
|
||||
await tester.tap(find.byIcon(Icons.add));
|
||||
await tester.pump();
|
||||
|
||||
// Verify that our counter has incremented.
|
||||
expect(find.text('0'), findsNothing);
|
||||
expect(find.text('1'), findsOneWidget);
|
||||
});
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
flutter/ephemeral/
|
||||
|
||||
# Visual Studio user-specific files.
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# Visual Studio build-related files.
|
||||
x64/
|
||||
x86/
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!*.[Cc]ache/
|
||||
|
||||
cmake-build-*
|
|
@ -0,0 +1,108 @@
|
|||
# Project-level configuration.
|
||||
cmake_minimum_required(VERSION 3.14)
|
||||
project(example LANGUAGES CXX)
|
||||
|
||||
# The name of the executable created for the application. Change this to change
|
||||
# the on-disk name of your application.
|
||||
set(BINARY_NAME "example")
|
||||
|
||||
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
|
||||
# versions of CMake.
|
||||
cmake_policy(VERSION 3.14...3.25)
|
||||
|
||||
# Define build configuration option.
|
||||
get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
|
||||
if(IS_MULTICONFIG)
|
||||
set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
|
||||
CACHE STRING "" FORCE)
|
||||
else()
|
||||
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
|
||||
set(CMAKE_BUILD_TYPE "Debug" CACHE
|
||||
STRING "Flutter build mode" FORCE)
|
||||
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
|
||||
"Debug" "Profile" "Release")
|
||||
endif()
|
||||
endif()
|
||||
# Define settings for the Profile build mode.
|
||||
set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
|
||||
set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
|
||||
set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
|
||||
set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
|
||||
|
||||
# Use Unicode for all projects.
|
||||
add_definitions(-DUNICODE -D_UNICODE)
|
||||
|
||||
# Compilation settings that should be applied to most targets.
|
||||
#
|
||||
# Be cautious about adding new options here, as plugins use this function by
|
||||
# default. In most cases, you should add new options to specific targets instead
|
||||
# of modifying this function.
|
||||
function(APPLY_STANDARD_SETTINGS TARGET)
|
||||
target_compile_features(${TARGET} PUBLIC cxx_std_17)
|
||||
target_compile_options(${TARGET} PRIVATE /W4 /WX /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 library and tool build rules.
|
||||
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
|
||||
add_subdirectory(${FLUTTER_MANAGED_DIR})
|
||||
|
||||
# Application build; see runner/CMakeLists.txt.
|
||||
add_subdirectory("runner")
|
||||
|
||||
|
||||
# Generated plugin build rules, which manage building the plugins and adding
|
||||
# them to the application.
|
||||
include(flutter/generated_plugins.cmake)
|
||||
|
||||
|
||||
# === Installation ===
|
||||
# Support files are copied into place next to the executable, so that it can
|
||||
# run in place. This is done instead of making a separate bundle (as on Linux)
|
||||
# so that building and running from within Visual Studio will work.
|
||||
set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")
|
||||
# Make the "install" step default, as it's required to run.
|
||||
set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
|
||||
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
|
||||
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
|
||||
endif()
|
||||
|
||||
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
|
||||
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
|
||||
|
||||
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
if(PLUGIN_BUNDLED_LIBRARIES)
|
||||
install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
|
||||
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
|
||||
# Copy the native assets provided by the build.dart from all packages.
|
||||
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/")
|
||||
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
|
||||
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
# Fully re-copy the assets directory on each build to avoid having stale files
|
||||
# from a previous install.
|
||||
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
|
||||
install(CODE "
|
||||
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
|
||||
" COMPONENT Runtime)
|
||||
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
|
||||
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
|
||||
|
||||
# Install the AOT library on non-Debug builds only.
|
||||
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||
CONFIGURATIONS Profile;Release
|
||||
COMPONENT Runtime)
|
|
@ -0,0 +1,109 @@
|
|||
# This file controls Flutter-level build steps. It should not be edited.
|
||||
cmake_minimum_required(VERSION 3.14)
|
||||
|
||||
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
|
||||
|
||||
# Configuration provided via flutter tool.
|
||||
include(${EPHEMERAL_DIR}/generated_config.cmake)
|
||||
|
||||
# TODO: Move the rest of this into files in ephemeral. See
|
||||
# https://github.com/flutter/flutter/issues/57146.
|
||||
set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
|
||||
|
||||
# Set fallback configurations for older versions of the flutter tool.
|
||||
if (NOT DEFINED FLUTTER_TARGET_PLATFORM)
|
||||
set(FLUTTER_TARGET_PLATFORM "windows-x64")
|
||||
endif()
|
||||
|
||||
# === Flutter Library ===
|
||||
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
|
||||
|
||||
# Published to parent scope for install step.
|
||||
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
|
||||
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
|
||||
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
|
||||
set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)
|
||||
|
||||
list(APPEND FLUTTER_LIBRARY_HEADERS
|
||||
"flutter_export.h"
|
||||
"flutter_windows.h"
|
||||
"flutter_messenger.h"
|
||||
"flutter_plugin_registrar.h"
|
||||
"flutter_texture_registrar.h"
|
||||
)
|
||||
list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
|
||||
add_library(flutter INTERFACE)
|
||||
target_include_directories(flutter INTERFACE
|
||||
"${EPHEMERAL_DIR}"
|
||||
)
|
||||
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
|
||||
add_dependencies(flutter flutter_assemble)
|
||||
|
||||
# === Wrapper ===
|
||||
list(APPEND CPP_WRAPPER_SOURCES_CORE
|
||||
"core_implementations.cc"
|
||||
"standard_codec.cc"
|
||||
)
|
||||
list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
|
||||
list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
|
||||
"plugin_registrar.cc"
|
||||
)
|
||||
list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
|
||||
list(APPEND CPP_WRAPPER_SOURCES_APP
|
||||
"flutter_engine.cc"
|
||||
"flutter_view_controller.cc"
|
||||
)
|
||||
list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
|
||||
|
||||
# Wrapper sources needed for a plugin.
|
||||
add_library(flutter_wrapper_plugin STATIC
|
||||
${CPP_WRAPPER_SOURCES_CORE}
|
||||
${CPP_WRAPPER_SOURCES_PLUGIN}
|
||||
)
|
||||
apply_standard_settings(flutter_wrapper_plugin)
|
||||
set_target_properties(flutter_wrapper_plugin PROPERTIES
|
||||
POSITION_INDEPENDENT_CODE ON)
|
||||
set_target_properties(flutter_wrapper_plugin PROPERTIES
|
||||
CXX_VISIBILITY_PRESET hidden)
|
||||
target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
|
||||
target_include_directories(flutter_wrapper_plugin PUBLIC
|
||||
"${WRAPPER_ROOT}/include"
|
||||
)
|
||||
add_dependencies(flutter_wrapper_plugin flutter_assemble)
|
||||
|
||||
# Wrapper sources needed for the runner.
|
||||
add_library(flutter_wrapper_app STATIC
|
||||
${CPP_WRAPPER_SOURCES_CORE}
|
||||
${CPP_WRAPPER_SOURCES_APP}
|
||||
)
|
||||
apply_standard_settings(flutter_wrapper_app)
|
||||
target_link_libraries(flutter_wrapper_app PUBLIC flutter)
|
||||
target_include_directories(flutter_wrapper_app PUBLIC
|
||||
"${WRAPPER_ROOT}/include"
|
||||
)
|
||||
add_dependencies(flutter_wrapper_app flutter_assemble)
|
||||
|
||||
# === Flutter tool backend ===
|
||||
# _phony_ is a non-existent file to force this command to run every time,
|
||||
# since currently there's no way to get a full input/output list from the
|
||||
# flutter tool.
|
||||
set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
|
||||
set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
|
||||
add_custom_command(
|
||||
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
|
||||
${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
|
||||
${CPP_WRAPPER_SOURCES_APP}
|
||||
${PHONY_OUTPUT}
|
||||
COMMAND ${CMAKE_COMMAND} -E env
|
||||
${FLUTTER_TOOL_ENVIRONMENT}
|
||||
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
|
||||
${FLUTTER_TARGET_PLATFORM} $<CONFIG>
|
||||
VERBATIM
|
||||
)
|
||||
add_custom_target(flutter_assemble DEPENDS
|
||||
"${FLUTTER_LIBRARY}"
|
||||
${FLUTTER_LIBRARY_HEADERS}
|
||||
${CPP_WRAPPER_SOURCES_CORE}
|
||||
${CPP_WRAPPER_SOURCES_PLUGIN}
|
||||
${CPP_WRAPPER_SOURCES_APP}
|
||||
)
|
|
@ -0,0 +1,20 @@
|
|||
//
|
||||
// Generated file. Do not edit.
|
||||
//
|
||||
|
||||
// clang-format off
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <flutter_inappwebview_windows/flutter_inappwebview_windows_plugin_c_api.h>
|
||||
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
||||
#include <url_launcher_windows/url_launcher_windows.h>
|
||||
|
||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||
FlutterInappwebviewWindowsPluginCApiRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("FlutterInappwebviewWindowsPluginCApi"));
|
||||
PermissionHandlerWindowsPluginRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin"));
|
||||
UrlLauncherWindowsRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
//
|
||||
// Generated file. Do not edit.
|
||||
//
|
||||
|
||||
// clang-format off
|
||||
|
||||
#ifndef GENERATED_PLUGIN_REGISTRANT_
|
||||
#define GENERATED_PLUGIN_REGISTRANT_
|
||||
|
||||
#include <flutter/plugin_registry.h>
|
||||
|
||||
// Registers Flutter plugins.
|
||||
void RegisterPlugins(flutter::PluginRegistry* registry);
|
||||
|
||||
#endif // GENERATED_PLUGIN_REGISTRANT_
|
|
@ -0,0 +1,26 @@
|
|||
#
|
||||
# Generated file, do not edit.
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
flutter_inappwebview_windows
|
||||
permission_handler_windows
|
||||
url_launcher_windows
|
||||
)
|
||||
|
||||
list(APPEND FLUTTER_FFI_PLUGIN_LIST
|
||||
)
|
||||
|
||||
set(PLUGIN_BUNDLED_LIBRARIES)
|
||||
|
||||
foreach(plugin ${FLUTTER_PLUGIN_LIST})
|
||||
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin})
|
||||
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
|
||||
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
|
||||
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
|
||||
endforeach(plugin)
|
||||
|
||||
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
|
||||
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin})
|
||||
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
|
||||
endforeach(ffi_plugin)
|
|
@ -0,0 +1,40 @@
|
|||
cmake_minimum_required(VERSION 3.14)
|
||||
project(runner LANGUAGES CXX)
|
||||
|
||||
# Define the application target. To change its name, change BINARY_NAME in the
|
||||
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
|
||||
# work.
|
||||
#
|
||||
# Any new source files that you add to the application should be added here.
|
||||
add_executable(${BINARY_NAME} WIN32
|
||||
"flutter_window.cpp"
|
||||
"main.cpp"
|
||||
"utils.cpp"
|
||||
"win32_window.cpp"
|
||||
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
|
||||
"Runner.rc"
|
||||
"runner.exe.manifest"
|
||||
)
|
||||
|
||||
# Apply the standard set of build settings. This can be removed for applications
|
||||
# that need different build settings.
|
||||
apply_standard_settings(${BINARY_NAME})
|
||||
|
||||
# Add preprocessor definitions for the build version.
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")
|
||||
|
||||
# Disable Windows macros that collide with C++ standard library functions.
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
|
||||
|
||||
# Add dependency libraries and include directories. Add any application-specific
|
||||
# dependencies here.
|
||||
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
|
||||
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
|
||||
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
|
||||
|
||||
# Run the Flutter tool portions of the build. This must not be removed.
|
||||
add_dependencies(${BINARY_NAME} flutter_assemble)
|
|
@ -0,0 +1,121 @@
|
|||
// Microsoft Visual C++ generated resource script.
|
||||
//
|
||||
#pragma code_page(65001)
|
||||
#include "resource.h"
|
||||
|
||||
#define APSTUDIO_READONLY_SYMBOLS
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Generated from the TEXTINCLUDE 2 resource.
|
||||
//
|
||||
#include "winres.h"
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
#undef APSTUDIO_READONLY_SYMBOLS
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// English (United States) resources
|
||||
|
||||
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
|
||||
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
|
||||
|
||||
#ifdef APSTUDIO_INVOKED
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// TEXTINCLUDE
|
||||
//
|
||||
|
||||
1 TEXTINCLUDE
|
||||
BEGIN
|
||||
"resource.h\0"
|
||||
END
|
||||
|
||||
2 TEXTINCLUDE
|
||||
BEGIN
|
||||
"#include ""winres.h""\r\n"
|
||||
"\0"
|
||||
END
|
||||
|
||||
3 TEXTINCLUDE
|
||||
BEGIN
|
||||
"\r\n"
|
||||
"\0"
|
||||
END
|
||||
|
||||
#endif // APSTUDIO_INVOKED
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Icon
|
||||
//
|
||||
|
||||
// Icon with lowest ID value placed first to ensure application icon
|
||||
// remains consistent on all systems.
|
||||
IDI_APP_ICON ICON "resources\\app_icon.ico"
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Version
|
||||
//
|
||||
|
||||
#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)
|
||||
#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD
|
||||
#else
|
||||
#define VERSION_AS_NUMBER 1,0,0,0
|
||||
#endif
|
||||
|
||||
#if defined(FLUTTER_VERSION)
|
||||
#define VERSION_AS_STRING FLUTTER_VERSION
|
||||
#else
|
||||
#define VERSION_AS_STRING "1.0.0"
|
||||
#endif
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION VERSION_AS_NUMBER
|
||||
PRODUCTVERSION VERSION_AS_NUMBER
|
||||
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
|
||||
#ifdef _DEBUG
|
||||
FILEFLAGS VS_FF_DEBUG
|
||||
#else
|
||||
FILEFLAGS 0x0L
|
||||
#endif
|
||||
FILEOS VOS__WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
FILESUBTYPE 0x0L
|
||||
BEGIN
|
||||
BLOCK "StringFileInfo"
|
||||
BEGIN
|
||||
BLOCK "040904e4"
|
||||
BEGIN
|
||||
VALUE "CompanyName", "com.pichillilorenzo" "\0"
|
||||
VALUE "FileDescription", "example" "\0"
|
||||
VALUE "FileVersion", VERSION_AS_STRING "\0"
|
||||
VALUE "InternalName", "example" "\0"
|
||||
VALUE "LegalCopyright", "Copyright (C) 2023 com.pichillilorenzo. All rights reserved." "\0"
|
||||
VALUE "OriginalFilename", "example.exe" "\0"
|
||||
VALUE "ProductName", "example" "\0"
|
||||
VALUE "ProductVersion", VERSION_AS_STRING "\0"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
BEGIN
|
||||
VALUE "Translation", 0x409, 1252
|
||||
END
|
||||
END
|
||||
|
||||
#endif // English (United States) resources
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
#ifndef APSTUDIO_INVOKED
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Generated from the TEXTINCLUDE 3 resource.
|
||||
//
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
#endif // not APSTUDIO_INVOKED
|
|
@ -0,0 +1,71 @@
|
|||
#include "flutter_window.h"
|
||||
|
||||
#include <optional>
|
||||
|
||||
#include "flutter/generated_plugin_registrant.h"
|
||||
|
||||
FlutterWindow::FlutterWindow(const flutter::DartProject& project)
|
||||
: project_(project) {}
|
||||
|
||||
FlutterWindow::~FlutterWindow() {}
|
||||
|
||||
bool FlutterWindow::OnCreate() {
|
||||
if (!Win32Window::OnCreate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
RECT frame = GetClientArea();
|
||||
|
||||
// The size here must match the window dimensions to avoid unnecessary surface
|
||||
// creation / destruction in the startup path.
|
||||
flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
|
||||
frame.right - frame.left, frame.bottom - frame.top, project_);
|
||||
// Ensure that basic setup of the controller was successful.
|
||||
if (!flutter_controller_->engine() || !flutter_controller_->view()) {
|
||||
return false;
|
||||
}
|
||||
RegisterPlugins(flutter_controller_->engine());
|
||||
SetChildContent(flutter_controller_->view()->GetNativeWindow());
|
||||
|
||||
flutter_controller_->engine()->SetNextFrameCallback([&]() {
|
||||
this->Show();
|
||||
});
|
||||
|
||||
// Flutter can complete the first frame before the "show window" callback is
|
||||
// registered. The following call ensures a frame is pending to ensure the
|
||||
// window is shown. It is a no-op if the first frame hasn't completed yet.
|
||||
flutter_controller_->ForceRedraw();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void FlutterWindow::OnDestroy() {
|
||||
if (flutter_controller_) {
|
||||
flutter_controller_ = nullptr;
|
||||
}
|
||||
|
||||
Win32Window::OnDestroy();
|
||||
}
|
||||
|
||||
LRESULT
|
||||
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept {
|
||||
// Give Flutter, including plugins, an opportunity to handle window messages.
|
||||
if (flutter_controller_) {
|
||||
std::optional<LRESULT> result =
|
||||
flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
|
||||
lparam);
|
||||
if (result) {
|
||||
return *result;
|
||||
}
|
||||
}
|
||||
|
||||
switch (message) {
|
||||
case WM_FONTCHANGE:
|
||||
flutter_controller_->engine()->ReloadSystemFonts();
|
||||
break;
|
||||
}
|
||||
|
||||
return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
#ifndef RUNNER_FLUTTER_WINDOW_H_
|
||||
#define RUNNER_FLUTTER_WINDOW_H_
|
||||
|
||||
#include <flutter/dart_project.h>
|
||||
#include <flutter/flutter_view_controller.h>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "win32_window.h"
|
||||
|
||||
// A window that does nothing but host a Flutter view.
|
||||
class FlutterWindow : public Win32Window {
|
||||
public:
|
||||
// Creates a new FlutterWindow hosting a Flutter view running |project|.
|
||||
explicit FlutterWindow(const flutter::DartProject& project);
|
||||
virtual ~FlutterWindow();
|
||||
|
||||
protected:
|
||||
// Win32Window:
|
||||
bool OnCreate() override;
|
||||
void OnDestroy() override;
|
||||
LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept override;
|
||||
|
||||
private:
|
||||
// The project to run.
|
||||
flutter::DartProject project_;
|
||||
|
||||
// The Flutter instance hosted by this window.
|
||||
std::unique_ptr<flutter::FlutterViewController> flutter_controller_;
|
||||
};
|
||||
|
||||
#endif // RUNNER_FLUTTER_WINDOW_H_
|
|
@ -0,0 +1,43 @@
|
|||
#include <flutter/dart_project.h>
|
||||
#include <flutter/flutter_view_controller.h>
|
||||
#include <windows.h>
|
||||
|
||||
#include "flutter_window.h"
|
||||
#include "utils.h"
|
||||
|
||||
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
||||
_In_ wchar_t *command_line, _In_ int show_command) {
|
||||
// Attach to console when present (e.g., 'flutter run') or create a
|
||||
// new console when running with a debugger.
|
||||
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
|
||||
CreateAndAttachConsole();
|
||||
}
|
||||
|
||||
// Initialize COM, so that it is available for use in the library and/or
|
||||
// plugins.
|
||||
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
|
||||
flutter::DartProject project(L"data");
|
||||
|
||||
std::vector<std::string> command_line_arguments =
|
||||
GetCommandLineArguments();
|
||||
|
||||
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
|
||||
|
||||
FlutterWindow window(project);
|
||||
Win32Window::Point origin(10, 10);
|
||||
Win32Window::Size size(1280, 720);
|
||||
if (!window.Create(L"example", origin, size)) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
window.SetQuitOnClose(true);
|
||||
|
||||
::MSG msg;
|
||||
while (::GetMessage(&msg, nullptr, 0, 0)) {
|
||||
::TranslateMessage(&msg);
|
||||
::DispatchMessage(&msg);
|
||||
}
|
||||
|
||||
::CoUninitialize();
|
||||
return EXIT_SUCCESS;
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
//{{NO_DEPENDENCIES}}
|
||||
// Microsoft Visual C++ generated include file.
|
||||
// Used by Runner.rc
|
||||
//
|
||||
#define IDI_APP_ICON 101
|
||||
|
||||
// Next default values for new objects
|
||||
//
|
||||
#ifdef APSTUDIO_INVOKED
|
||||
#ifndef APSTUDIO_READONLY_SYMBOLS
|
||||
#define _APS_NEXT_RESOURCE_VALUE 102
|
||||
#define _APS_NEXT_COMMAND_VALUE 40001
|
||||
#define _APS_NEXT_CONTROL_VALUE 1001
|
||||
#define _APS_NEXT_SYMED_VALUE 101
|
||||
#endif
|
||||
#endif
|
Binary file not shown.
After Width: | Height: | Size: 33 KiB |
|
@ -0,0 +1,20 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<!-- Windows 10 and Windows 11 -->
|
||||
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
|
||||
<!-- Windows 8.1 -->
|
||||
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
|
||||
<!-- Windows 8 -->
|
||||
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
|
||||
<!-- Windows 7 -->
|
||||
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
|
||||
</application>
|
||||
</compatibility>
|
||||
</assembly>
|
|
@ -0,0 +1,65 @@
|
|||
#include "utils.h"
|
||||
|
||||
#include <flutter_windows.h>
|
||||
#include <io.h>
|
||||
#include <stdio.h>
|
||||
#include <windows.h>
|
||||
|
||||
#include <iostream>
|
||||
|
||||
void CreateAndAttachConsole() {
|
||||
if (::AllocConsole()) {
|
||||
FILE *unused;
|
||||
if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
|
||||
_dup2(_fileno(stdout), 1);
|
||||
}
|
||||
if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
|
||||
_dup2(_fileno(stdout), 2);
|
||||
}
|
||||
std::ios::sync_with_stdio();
|
||||
FlutterDesktopResyncOutputStreams();
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> GetCommandLineArguments() {
|
||||
// Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
|
||||
int argc;
|
||||
wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
|
||||
if (argv == nullptr) {
|
||||
return std::vector<std::string>();
|
||||
}
|
||||
|
||||
std::vector<std::string> command_line_arguments;
|
||||
|
||||
// Skip the first argument as it's the binary name.
|
||||
for (int i = 1; i < argc; i++) {
|
||||
command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
|
||||
}
|
||||
|
||||
::LocalFree(argv);
|
||||
|
||||
return command_line_arguments;
|
||||
}
|
||||
|
||||
std::string Utf8FromUtf16(const wchar_t* utf16_string) {
|
||||
if (utf16_string == nullptr) {
|
||||
return std::string();
|
||||
}
|
||||
int target_length = ::WideCharToMultiByte(
|
||||
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
|
||||
-1, nullptr, 0, nullptr, nullptr)
|
||||
-1; // remove the trailing null character
|
||||
int input_length = (int)wcslen(utf16_string);
|
||||
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,
|
||||
input_length, utf8_string.data(), target_length, nullptr, nullptr);
|
||||
if (converted_length == 0) {
|
||||
return std::string();
|
||||
}
|
||||
return utf8_string;
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
#ifndef RUNNER_UTILS_H_
|
||||
#define RUNNER_UTILS_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// Creates a console for the process, and redirects stdout and stderr to
|
||||
// it for both the runner and the Flutter library.
|
||||
void CreateAndAttachConsole();
|
||||
|
||||
// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
|
||||
// encoded in UTF-8. Returns an empty std::string on failure.
|
||||
std::string Utf8FromUtf16(const wchar_t* utf16_string);
|
||||
|
||||
// Gets the command line arguments passed in as a std::vector<std::string>,
|
||||
// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.
|
||||
std::vector<std::string> GetCommandLineArguments();
|
||||
|
||||
#endif // RUNNER_UTILS_H_
|
|
@ -0,0 +1,288 @@
|
|||
#include "win32_window.h"
|
||||
|
||||
#include <dwmapi.h>
|
||||
#include <flutter_windows.h>
|
||||
|
||||
#include "resource.h"
|
||||
|
||||
namespace {
|
||||
|
||||
/// Window attribute that enables dark mode window decorations.
|
||||
///
|
||||
/// Redefined in case the developer's machine has a Windows SDK older than
|
||||
/// version 10.0.22000.0.
|
||||
/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
|
||||
#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
|
||||
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
|
||||
#endif
|
||||
|
||||
constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";
|
||||
|
||||
/// Registry key for app theme preference.
|
||||
///
|
||||
/// A value of 0 indicates apps should use dark mode. A non-zero or missing
|
||||
/// value indicates apps should use light mode.
|
||||
constexpr const wchar_t kGetPreferredBrightnessRegKey[] =
|
||||
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
|
||||
constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";
|
||||
|
||||
// The number of Win32Window objects that currently exist.
|
||||
static int g_active_window_count = 0;
|
||||
|
||||
using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);
|
||||
|
||||
// Scale helper to convert logical scaler values to physical using passed in
|
||||
// scale factor
|
||||
int Scale(int source, double scale_factor) {
|
||||
return static_cast<int>(source * scale_factor);
|
||||
}
|
||||
|
||||
// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.
|
||||
// This API is only needed for PerMonitor V1 awareness mode.
|
||||
void EnableFullDpiSupportIfAvailable(HWND hwnd) {
|
||||
HMODULE user32_module = LoadLibraryA("User32.dll");
|
||||
if (!user32_module) {
|
||||
return;
|
||||
}
|
||||
auto enable_non_client_dpi_scaling =
|
||||
reinterpret_cast<EnableNonClientDpiScaling*>(
|
||||
GetProcAddress(user32_module, "EnableNonClientDpiScaling"));
|
||||
if (enable_non_client_dpi_scaling != nullptr) {
|
||||
enable_non_client_dpi_scaling(hwnd);
|
||||
}
|
||||
FreeLibrary(user32_module);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Manages the Win32Window's window class registration.
|
||||
class WindowClassRegistrar {
|
||||
public:
|
||||
~WindowClassRegistrar() = default;
|
||||
|
||||
// Returns the singleton registrar instance.
|
||||
static WindowClassRegistrar* GetInstance() {
|
||||
if (!instance_) {
|
||||
instance_ = new WindowClassRegistrar();
|
||||
}
|
||||
return instance_;
|
||||
}
|
||||
|
||||
// Returns the name of the window class, registering the class if it hasn't
|
||||
// previously been registered.
|
||||
const wchar_t* GetWindowClass();
|
||||
|
||||
// Unregisters the window class. Should only be called if there are no
|
||||
// instances of the window.
|
||||
void UnregisterWindowClass();
|
||||
|
||||
private:
|
||||
WindowClassRegistrar() = default;
|
||||
|
||||
static WindowClassRegistrar* instance_;
|
||||
|
||||
bool class_registered_ = false;
|
||||
};
|
||||
|
||||
WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;
|
||||
|
||||
const wchar_t* WindowClassRegistrar::GetWindowClass() {
|
||||
if (!class_registered_) {
|
||||
WNDCLASS window_class{};
|
||||
window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
|
||||
window_class.lpszClassName = kWindowClassName;
|
||||
window_class.style = CS_HREDRAW | CS_VREDRAW;
|
||||
window_class.cbClsExtra = 0;
|
||||
window_class.cbWndExtra = 0;
|
||||
window_class.hInstance = GetModuleHandle(nullptr);
|
||||
window_class.hIcon =
|
||||
LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
|
||||
window_class.hbrBackground = 0;
|
||||
window_class.lpszMenuName = nullptr;
|
||||
window_class.lpfnWndProc = Win32Window::WndProc;
|
||||
RegisterClass(&window_class);
|
||||
class_registered_ = true;
|
||||
}
|
||||
return kWindowClassName;
|
||||
}
|
||||
|
||||
void WindowClassRegistrar::UnregisterWindowClass() {
|
||||
UnregisterClass(kWindowClassName, nullptr);
|
||||
class_registered_ = false;
|
||||
}
|
||||
|
||||
Win32Window::Win32Window() {
|
||||
++g_active_window_count;
|
||||
}
|
||||
|
||||
Win32Window::~Win32Window() {
|
||||
--g_active_window_count;
|
||||
Destroy();
|
||||
}
|
||||
|
||||
bool Win32Window::Create(const std::wstring& title,
|
||||
const Point& origin,
|
||||
const Size& size) {
|
||||
Destroy();
|
||||
|
||||
const wchar_t* window_class =
|
||||
WindowClassRegistrar::GetInstance()->GetWindowClass();
|
||||
|
||||
const POINT target_point = {static_cast<LONG>(origin.x),
|
||||
static_cast<LONG>(origin.y)};
|
||||
HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);
|
||||
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
|
||||
double scale_factor = dpi / 96.0;
|
||||
|
||||
HWND window = CreateWindow(
|
||||
window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
|
||||
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
|
||||
Scale(size.width, scale_factor), Scale(size.height, scale_factor),
|
||||
nullptr, nullptr, GetModuleHandle(nullptr), this);
|
||||
|
||||
if (!window) {
|
||||
return false;
|
||||
}
|
||||
|
||||
UpdateTheme(window);
|
||||
|
||||
return OnCreate();
|
||||
}
|
||||
|
||||
bool Win32Window::Show() {
|
||||
return ShowWindow(window_handle_, SW_SHOWNORMAL);
|
||||
}
|
||||
|
||||
// static
|
||||
LRESULT CALLBACK Win32Window::WndProc(HWND const window,
|
||||
UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept {
|
||||
if (message == WM_NCCREATE) {
|
||||
auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
|
||||
SetWindowLongPtr(window, GWLP_USERDATA,
|
||||
reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));
|
||||
|
||||
auto that = static_cast<Win32Window*>(window_struct->lpCreateParams);
|
||||
EnableFullDpiSupportIfAvailable(window);
|
||||
that->window_handle_ = window;
|
||||
} else if (Win32Window* that = GetThisFromHandle(window)) {
|
||||
return that->MessageHandler(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
return DefWindowProc(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
LRESULT
|
||||
Win32Window::MessageHandler(HWND hwnd,
|
||||
UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept {
|
||||
switch (message) {
|
||||
case WM_DESTROY:
|
||||
window_handle_ = nullptr;
|
||||
Destroy();
|
||||
if (quit_on_close_) {
|
||||
PostQuitMessage(0);
|
||||
}
|
||||
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 rect = GetClientArea();
|
||||
if (child_content_ != nullptr) {
|
||||
// Size and position the child window.
|
||||
MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,
|
||||
rect.bottom - rect.top, TRUE);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
case WM_ACTIVATE:
|
||||
if (child_content_ != nullptr) {
|
||||
SetFocus(child_content_);
|
||||
}
|
||||
return 0;
|
||||
|
||||
case WM_DWMCOLORIZATIONCOLORCHANGED:
|
||||
UpdateTheme(hwnd);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return DefWindowProc(window_handle_, message, wparam, lparam);
|
||||
}
|
||||
|
||||
void Win32Window::Destroy() {
|
||||
OnDestroy();
|
||||
|
||||
if (window_handle_) {
|
||||
DestroyWindow(window_handle_);
|
||||
window_handle_ = nullptr;
|
||||
}
|
||||
if (g_active_window_count == 0) {
|
||||
WindowClassRegistrar::GetInstance()->UnregisterWindowClass();
|
||||
}
|
||||
}
|
||||
|
||||
Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {
|
||||
return reinterpret_cast<Win32Window*>(
|
||||
GetWindowLongPtr(window, GWLP_USERDATA));
|
||||
}
|
||||
|
||||
void Win32Window::SetChildContent(HWND content) {
|
||||
child_content_ = content;
|
||||
SetParent(content, window_handle_);
|
||||
RECT frame = GetClientArea();
|
||||
|
||||
MoveWindow(content, frame.left, frame.top, frame.right - frame.left,
|
||||
frame.bottom - frame.top, true);
|
||||
|
||||
SetFocus(child_content_);
|
||||
}
|
||||
|
||||
RECT Win32Window::GetClientArea() {
|
||||
RECT frame;
|
||||
GetClientRect(window_handle_, &frame);
|
||||
return frame;
|
||||
}
|
||||
|
||||
HWND Win32Window::GetHandle() {
|
||||
return window_handle_;
|
||||
}
|
||||
|
||||
void Win32Window::SetQuitOnClose(bool quit_on_close) {
|
||||
quit_on_close_ = quit_on_close;
|
||||
}
|
||||
|
||||
bool Win32Window::OnCreate() {
|
||||
// No-op; provided for subclasses.
|
||||
return true;
|
||||
}
|
||||
|
||||
void Win32Window::OnDestroy() {
|
||||
// No-op; provided for subclasses.
|
||||
}
|
||||
|
||||
void Win32Window::UpdateTheme(HWND const window) {
|
||||
DWORD light_mode;
|
||||
DWORD light_mode_size = sizeof(light_mode);
|
||||
LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
|
||||
kGetPreferredBrightnessRegValue,
|
||||
RRF_RT_REG_DWORD, nullptr, &light_mode,
|
||||
&light_mode_size);
|
||||
|
||||
if (result == ERROR_SUCCESS) {
|
||||
BOOL enable_dark_mode = light_mode == 0;
|
||||
DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,
|
||||
&enable_dark_mode, sizeof(enable_dark_mode));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
#ifndef RUNNER_WIN32_WINDOW_H_
|
||||
#define RUNNER_WIN32_WINDOW_H_
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
// A class abstraction for a high DPI-aware Win32 Window. Intended to be
|
||||
// inherited from by classes that wish to specialize with custom
|
||||
// rendering and input handling
|
||||
class Win32Window {
|
||||
public:
|
||||
struct Point {
|
||||
unsigned int x;
|
||||
unsigned int y;
|
||||
Point(unsigned int x, unsigned int y) : x(x), y(y) {}
|
||||
};
|
||||
|
||||
struct Size {
|
||||
unsigned int width;
|
||||
unsigned int height;
|
||||
Size(unsigned int width, unsigned int height)
|
||||
: width(width), height(height) {}
|
||||
};
|
||||
|
||||
Win32Window();
|
||||
virtual ~Win32Window();
|
||||
|
||||
// Creates a win32 window with |title| that is positioned and sized using
|
||||
// |origin| and |size|. New windows are created on the default monitor. Window
|
||||
// sizes are specified to the OS in physical pixels, hence to ensure a
|
||||
// consistent size this function will scale the inputted width and height as
|
||||
// as appropriate for the default monitor. The window is invisible until
|
||||
// |Show| is called. Returns true if the window was created successfully.
|
||||
bool Create(const std::wstring& title, const Point& origin, const Size& size);
|
||||
|
||||
// Show the current window. Returns true if the window was successfully shown.
|
||||
bool Show();
|
||||
|
||||
// Release OS resources associated with window.
|
||||
void Destroy();
|
||||
|
||||
// Inserts |content| into the window tree.
|
||||
void SetChildContent(HWND content);
|
||||
|
||||
// Returns the backing Window handle to enable clients to set icon and other
|
||||
// window properties. Returns nullptr if the window has been destroyed.
|
||||
HWND GetHandle();
|
||||
|
||||
// If true, closing this window will quit the application.
|
||||
void SetQuitOnClose(bool quit_on_close);
|
||||
|
||||
// Return a RECT representing the bounds of the current client area.
|
||||
RECT GetClientArea();
|
||||
|
||||
protected:
|
||||
// Processes and route salient window messages for mouse handling,
|
||||
// size change and DPI. Delegates handling of these to member overloads that
|
||||
// inheriting classes can handle.
|
||||
virtual LRESULT MessageHandler(HWND window,
|
||||
UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept;
|
||||
|
||||
// Called when CreateAndShow is called, allowing subclass window-related
|
||||
// setup. Subclasses should return false if setup fails.
|
||||
virtual bool OnCreate();
|
||||
|
||||
// Called when Destroy is called.
|
||||
virtual void OnDestroy();
|
||||
|
||||
private:
|
||||
friend class WindowClassRegistrar;
|
||||
|
||||
// OS callback called by message pump. Handles the WM_NCCREATE message which
|
||||
// is passed when the non-client area is being created and enables automatic
|
||||
// non-client DPI scaling so that the non-client area automatically
|
||||
// responds to changes in DPI. All other messages are handled by
|
||||
// MessageHandler.
|
||||
static LRESULT CALLBACK WndProc(HWND const window,
|
||||
UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept;
|
||||
|
||||
// Retrieves a class instance pointer for |window|
|
||||
static Win32Window* GetThisFromHandle(HWND const window) noexcept;
|
||||
|
||||
// Update the window frame's theme to match the system theme.
|
||||
static void UpdateTheme(HWND const window);
|
||||
|
||||
bool quit_on_close_ = false;
|
||||
|
||||
// window handle for top level window.
|
||||
HWND window_handle_ = nullptr;
|
||||
|
||||
// window handle for hosted content.
|
||||
HWND child_content_ = nullptr;
|
||||
};
|
||||
|
||||
#endif // RUNNER_WIN32_WINDOW_H_
|
|
@ -81,7 +81,7 @@ packages:
|
|||
path: ".."
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.0.11"
|
||||
version: "1.0.12"
|
||||
flutter_inappwebview_internal_annotations:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
|
|
@ -0,0 +1,29 @@
|
|||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
build/
|
|
@ -0,0 +1,30 @@
|
|||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9"
|
||||
channel: "stable"
|
||||
|
||||
project_type: plugin
|
||||
|
||||
# Tracks metadata for the flutter migrate command
|
||||
migration:
|
||||
platforms:
|
||||
- platform: root
|
||||
create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9
|
||||
base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9
|
||||
- platform: windows
|
||||
create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9
|
||||
base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9
|
||||
|
||||
# User provided section
|
||||
|
||||
# List of Local paths (relative to this file) that should be
|
||||
# ignored by the migrate tool.
|
||||
#
|
||||
# Files that are not part of the templates will be ignored by default.
|
||||
unmanaged_files:
|
||||
- 'lib/main.dart'
|
||||
- 'ios/Runner.xcodeproj/project.pbxproj'
|
|
@ -0,0 +1,3 @@
|
|||
## 0.0.1
|
||||
|
||||
* TODO: Describe initial release.
|
|
@ -0,0 +1 @@
|
|||
TODO: Add your license here.
|
|
@ -0,0 +1,15 @@
|
|||
# flutter_inappwebview_windows
|
||||
|
||||
A new Flutter project.
|
||||
|
||||
## Getting Started
|
||||
|
||||
This project is a starting point for a Flutter
|
||||
[plug-in package](https://flutter.dev/developing-packages/),
|
||||
a specialized package that includes platform-specific implementation code for
|
||||
Android and/or iOS.
|
||||
|
||||
For help getting started with Flutter development, view the
|
||||
[online documentation](https://flutter.dev/docs), which offers tutorials,
|
||||
samples, guidance on mobile development, and a full API reference.
|
||||
|
|
@ -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: ignore
|
|
@ -0,0 +1,43 @@
|
|||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
**/doc/api/
|
||||
**/ios/Flutter/.last_build_id
|
||||
.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
.pub-cache/
|
||||
.pub/
|
||||
/build/
|
||||
|
||||
# Symbolication related
|
||||
app.*.symbols
|
||||
|
||||
# Obfuscation related
|
||||
app.*.map.json
|
||||
|
||||
# Android Studio will place build artifacts here
|
||||
/android/app/debug
|
||||
/android/app/profile
|
||||
/android/app/release
|
|
@ -0,0 +1,16 @@
|
|||
# flutter_inappwebview_windows_example
|
||||
|
||||
Demonstrates how to use the flutter_inappwebview_windows plugin.
|
||||
|
||||
## Getting Started
|
||||
|
||||
This project is a starting point for a Flutter application.
|
||||
|
||||
A few resources to get you started if this is your first Flutter project:
|
||||
|
||||
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
|
||||
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
|
||||
|
||||
For help getting started with Flutter development, view the
|
||||
[online documentation](https://docs.flutter.dev/), which offers tutorials,
|
||||
samples, guidance on mobile development, and a full API reference.
|
|
@ -0,0 +1,28 @@
|
|||
# This file configures the analyzer, which statically analyzes Dart code to
|
||||
# check for errors, warnings, and lints.
|
||||
#
|
||||
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
|
||||
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
|
||||
# invoked from the command line by running `flutter analyze`.
|
||||
|
||||
# The following line activates a set of recommended lints for Flutter apps,
|
||||
# packages, and plugins designed to encourage good coding practices.
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
linter:
|
||||
# The lint rules applied to this project can be customized in the
|
||||
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
|
||||
# included above or to enable additional rules. A list of all available lints
|
||||
# and their documentation is published at https://dart.dev/lints.
|
||||
#
|
||||
# Instead of disabling a lint rule for the entire project in the
|
||||
# section below, it can also be suppressed for a single line of code
|
||||
# or a specific dart file by using the `// ignore: name_of_lint` and
|
||||
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
|
||||
# producing the lint.
|
||||
rules:
|
||||
# avoid_print: false # Uncomment to disable the `avoid_print` rule
|
||||
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
|
||||
|
||||
# Additional information about this file can be found at
|
||||
# https://dart.dev/guides/language/analysis-options
|
|
@ -0,0 +1,283 @@
|
|||
# Generated by pub
|
||||
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||
packages:
|
||||
async:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: async
|
||||
sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.11.0"
|
||||
boolean_selector:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: boolean_selector
|
||||
sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.1"
|
||||
characters:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: characters
|
||||
sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.0"
|
||||
clock:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: clock
|
||||
sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: collection
|
||||
sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.18.0"
|
||||
cupertino_icons:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: cupertino_icons
|
||||
sha256: d57953e10f9f8327ce64a508a355f0b1ec902193f66288e8cb5070e7c47eeb2d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.6"
|
||||
fake_async:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: fake_async
|
||||
sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.1"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file
|
||||
sha256: "1b92bec4fc2a72f59a8e15af5f52cd441e4a7860b49499d69dfa817af20e925d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.1.4"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_driver:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_inappwebview_internal_annotations:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_inappwebview_internal_annotations
|
||||
sha256: "5f80fd30e208ddded7dbbcd0d569e7995f9f63d45ea3f548d8dd4c0b473fb4c8"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
flutter_inappwebview_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_inappwebview_platform_interface
|
||||
sha256: "545fd4c25a07d2775f7d5af05a979b2cac4fbf79393b0a7f5d33ba39ba4f6187"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.10"
|
||||
flutter_inappwebview_windows:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: ".."
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.0.11"
|
||||
flutter_lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: flutter_lints
|
||||
sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.3"
|
||||
flutter_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
fuchsia_remote_debug_protocol:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
integration_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
lints:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: lints
|
||||
sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.1"
|
||||
matcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: matcher
|
||||
sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.12.16"
|
||||
material_color_utilities:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: material_color_utilities
|
||||
sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.5.0"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: meta
|
||||
sha256: a6e590c838b18133bb482a2745ad77c5bb7715fb0451209e1a7567d416678b8e
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.10.0"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path
|
||||
sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.8.3"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: platform
|
||||
sha256: ae68c7bfcd7383af3629daafb32fb4e8681c7154428da4febcff06200585f102
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.2"
|
||||
plugin_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: plugin_platform_interface
|
||||
sha256: f4f88d4a900933e7267e2b353594774fc0d07fb072b47eedcd5b54e1ea3269f8
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.7"
|
||||
process:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: process
|
||||
sha256: "53fd8db9cec1d37b0574e12f07520d582019cb6c44abf5479a01505099a34a09"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.2.4"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.99"
|
||||
source_span:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: source_span
|
||||
sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.10.0"
|
||||
stack_trace:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: stack_trace
|
||||
sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.11.1"
|
||||
stream_channel:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: stream_channel
|
||||
sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.2"
|
||||
string_scanner:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: string_scanner
|
||||
sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.0"
|
||||
sync_http:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sync_http
|
||||
sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.1"
|
||||
term_glyph:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: term_glyph
|
||||
sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.1"
|
||||
test_api:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: test_api
|
||||
sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.6.1"
|
||||
vector_math:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vector_math
|
||||
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.4"
|
||||
vm_service:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vm_service
|
||||
sha256: c538be99af830f478718b51630ec1b6bee5e74e52c8a802d328d9e71d35d2583
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "11.10.0"
|
||||
web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: web
|
||||
sha256: afe077240a270dcfd2aafe77602b4113645af95d0ad31128cc02bce5ac5d5152
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.0"
|
||||
webdriver:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webdriver
|
||||
sha256: "3c923e918918feeb90c4c9fdf1fe39220fa4c0e8e2c0fffaded174498ef86c49"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.2"
|
||||
sdks:
|
||||
dart: ">=3.2.3 <4.0.0"
|
||||
flutter: ">=3.0.0"
|
|
@ -0,0 +1,85 @@
|
|||
name: flutter_inappwebview_windows_example
|
||||
description: "Demonstrates how to use the flutter_inappwebview_windows plugin."
|
||||
# The following line prevents the package from being accidentally published to
|
||||
# pub.dev using `flutter pub publish`. This is preferred for private packages.
|
||||
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||
|
||||
environment:
|
||||
sdk: '>=3.2.3 <4.0.0'
|
||||
|
||||
# Dependencies specify other packages that your package needs in order to work.
|
||||
# To automatically upgrade your package dependencies to the latest versions
|
||||
# consider running `flutter pub upgrade --major-versions`. Alternatively,
|
||||
# dependencies can be manually updated by changing the version numbers below to
|
||||
# the latest version available on pub.dev. To see which dependencies have newer
|
||||
# versions available, run `flutter pub outdated`.
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
|
||||
flutter_inappwebview_windows:
|
||||
# When depending on this package from a real application you should use:
|
||||
# flutter_inappwebview_windows: ^x.y.z
|
||||
# See https://dart.dev/tools/pub/dependencies#version-constraints
|
||||
# The example app is bundled with the plugin so we use a path dependency on
|
||||
# the parent directory to use the current plugin's version.
|
||||
path: ../
|
||||
|
||||
# The following adds the Cupertino Icons font to your application.
|
||||
# Use with the CupertinoIcons class for iOS style icons.
|
||||
cupertino_icons: ^1.0.2
|
||||
|
||||
dev_dependencies:
|
||||
integration_test:
|
||||
sdk: flutter
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
|
||||
# The "flutter_lints" package below contains a set of recommended lints to
|
||||
# encourage good coding practices. The lint set provided by the package is
|
||||
# activated in the `analysis_options.yaml` file located at the root of your
|
||||
# package. See that file for information about deactivating specific lint
|
||||
# rules and activating additional ones.
|
||||
flutter_lints: ^2.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:
|
||||
|
||||
# The following line ensures that the Material Icons font is
|
||||
# included with your application, so that you can use the icons in
|
||||
# the material Icons class.
|
||||
uses-material-design: true
|
||||
|
||||
# To add assets to your application, add an assets section, like this:
|
||||
# assets:
|
||||
# - images/a_dot_burr.jpeg
|
||||
# - images/a_dot_ham.jpeg
|
||||
|
||||
# An image asset can refer to one or more resolution-specific "variants", see
|
||||
# https://flutter.dev/assets-and-images/#resolution-aware
|
||||
|
||||
# For details regarding adding assets from package dependencies, see
|
||||
# https://flutter.dev/assets-and-images/#from-packages
|
||||
|
||||
# To add custom fonts to your application, 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 from package dependencies,
|
||||
# see https://flutter.dev/custom-fonts/#from-packages
|
|
@ -0,0 +1,17 @@
|
|||
flutter/ephemeral/
|
||||
|
||||
# Visual Studio user-specific files.
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# Visual Studio build-related files.
|
||||
x64/
|
||||
x86/
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!*.[Cc]ache/
|
|
@ -0,0 +1,110 @@
|
|||
# Project-level configuration.
|
||||
cmake_minimum_required(VERSION 3.14)
|
||||
project(flutter_inappwebview_windows_example LANGUAGES CXX)
|
||||
|
||||
# The name of the executable created for the application. Change this to change
|
||||
# the on-disk name of your application.
|
||||
set(BINARY_NAME "flutter_inappwebview_windows_example")
|
||||
|
||||
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
|
||||
# versions of CMake.
|
||||
cmake_policy(VERSION 3.14...3.25)
|
||||
|
||||
# Define build configuration option.
|
||||
get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
|
||||
if(IS_MULTICONFIG)
|
||||
set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
|
||||
CACHE STRING "" FORCE)
|
||||
else()
|
||||
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
|
||||
set(CMAKE_BUILD_TYPE "Debug" CACHE
|
||||
STRING "Flutter build mode" FORCE)
|
||||
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
|
||||
"Debug" "Profile" "Release")
|
||||
endif()
|
||||
endif()
|
||||
# Define settings for the Profile build mode.
|
||||
set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
|
||||
set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
|
||||
set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
|
||||
set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
|
||||
|
||||
# Use Unicode for all projects.
|
||||
add_definitions(-DUNICODE -D_UNICODE)
|
||||
|
||||
# Compilation settings that should be applied to most targets.
|
||||
#
|
||||
# Be cautious about adding new options here, as plugins use this function by
|
||||
# default. In most cases, you should add new options to specific targets instead
|
||||
# of modifying this function.
|
||||
function(APPLY_STANDARD_SETTINGS TARGET)
|
||||
target_compile_features(${TARGET} PUBLIC cxx_std_17)
|
||||
target_compile_options(${TARGET} PRIVATE /W4 /WX /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 library and tool build rules.
|
||||
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
|
||||
add_subdirectory(${FLUTTER_MANAGED_DIR})
|
||||
|
||||
# Application build; see runner/CMakeLists.txt.
|
||||
add_subdirectory("runner")
|
||||
|
||||
# Enable the test target.
|
||||
set(include_flutter_inappwebview_windows_tests TRUE)
|
||||
|
||||
# Generated plugin build rules, which manage building the plugins and adding
|
||||
# them to the application.
|
||||
include(flutter/generated_plugins.cmake)
|
||||
|
||||
|
||||
# === Installation ===
|
||||
# Support files are copied into place next to the executable, so that it can
|
||||
# run in place. This is done instead of making a separate bundle (as on Linux)
|
||||
# so that building and running from within Visual Studio will work.
|
||||
set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")
|
||||
# Make the "install" step default, as it's required to run.
|
||||
set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
|
||||
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
|
||||
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
|
||||
endif()
|
||||
|
||||
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
|
||||
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
|
||||
|
||||
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
if(PLUGIN_BUNDLED_LIBRARIES)
|
||||
install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
|
||||
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||
COMPONENT Runtime)
|
||||
endif()
|
||||
|
||||
# Copy the native assets provided by the build.dart from all packages.
|
||||
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/")
|
||||
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
|
||||
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||
COMPONENT Runtime)
|
||||
|
||||
# Fully re-copy the assets directory on each build to avoid having stale files
|
||||
# from a previous install.
|
||||
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
|
||||
install(CODE "
|
||||
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
|
||||
" COMPONENT Runtime)
|
||||
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
|
||||
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
|
||||
|
||||
# Install the AOT library on non-Debug builds only.
|
||||
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||
CONFIGURATIONS Profile;Release
|
||||
COMPONENT Runtime)
|
|
@ -0,0 +1,109 @@
|
|||
# This file controls Flutter-level build steps. It should not be edited.
|
||||
cmake_minimum_required(VERSION 3.14)
|
||||
|
||||
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
|
||||
|
||||
# Configuration provided via flutter tool.
|
||||
include(${EPHEMERAL_DIR}/generated_config.cmake)
|
||||
|
||||
# TODO: Move the rest of this into files in ephemeral. See
|
||||
# https://github.com/flutter/flutter/issues/57146.
|
||||
set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
|
||||
|
||||
# Set fallback configurations for older versions of the flutter tool.
|
||||
if (NOT DEFINED FLUTTER_TARGET_PLATFORM)
|
||||
set(FLUTTER_TARGET_PLATFORM "windows-x64")
|
||||
endif()
|
||||
|
||||
# === Flutter Library ===
|
||||
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
|
||||
|
||||
# Published to parent scope for install step.
|
||||
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
|
||||
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
|
||||
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
|
||||
set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)
|
||||
|
||||
list(APPEND FLUTTER_LIBRARY_HEADERS
|
||||
"flutter_export.h"
|
||||
"flutter_windows.h"
|
||||
"flutter_messenger.h"
|
||||
"flutter_plugin_registrar.h"
|
||||
"flutter_texture_registrar.h"
|
||||
)
|
||||
list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
|
||||
add_library(flutter INTERFACE)
|
||||
target_include_directories(flutter INTERFACE
|
||||
"${EPHEMERAL_DIR}"
|
||||
)
|
||||
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
|
||||
add_dependencies(flutter flutter_assemble)
|
||||
|
||||
# === Wrapper ===
|
||||
list(APPEND CPP_WRAPPER_SOURCES_CORE
|
||||
"core_implementations.cc"
|
||||
"standard_codec.cc"
|
||||
)
|
||||
list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
|
||||
list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
|
||||
"plugin_registrar.cc"
|
||||
)
|
||||
list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
|
||||
list(APPEND CPP_WRAPPER_SOURCES_APP
|
||||
"flutter_engine.cc"
|
||||
"flutter_view_controller.cc"
|
||||
)
|
||||
list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
|
||||
|
||||
# Wrapper sources needed for a plugin.
|
||||
add_library(flutter_wrapper_plugin STATIC
|
||||
${CPP_WRAPPER_SOURCES_CORE}
|
||||
${CPP_WRAPPER_SOURCES_PLUGIN}
|
||||
)
|
||||
apply_standard_settings(flutter_wrapper_plugin)
|
||||
set_target_properties(flutter_wrapper_plugin PROPERTIES
|
||||
POSITION_INDEPENDENT_CODE ON)
|
||||
set_target_properties(flutter_wrapper_plugin PROPERTIES
|
||||
CXX_VISIBILITY_PRESET hidden)
|
||||
target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
|
||||
target_include_directories(flutter_wrapper_plugin PUBLIC
|
||||
"${WRAPPER_ROOT}/include"
|
||||
)
|
||||
add_dependencies(flutter_wrapper_plugin flutter_assemble)
|
||||
|
||||
# Wrapper sources needed for the runner.
|
||||
add_library(flutter_wrapper_app STATIC
|
||||
${CPP_WRAPPER_SOURCES_CORE}
|
||||
${CPP_WRAPPER_SOURCES_APP}
|
||||
)
|
||||
apply_standard_settings(flutter_wrapper_app)
|
||||
target_link_libraries(flutter_wrapper_app PUBLIC flutter)
|
||||
target_include_directories(flutter_wrapper_app PUBLIC
|
||||
"${WRAPPER_ROOT}/include"
|
||||
)
|
||||
add_dependencies(flutter_wrapper_app flutter_assemble)
|
||||
|
||||
# === Flutter tool backend ===
|
||||
# _phony_ is a non-existent file to force this command to run every time,
|
||||
# since currently there's no way to get a full input/output list from the
|
||||
# flutter tool.
|
||||
set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
|
||||
set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
|
||||
add_custom_command(
|
||||
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
|
||||
${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
|
||||
${CPP_WRAPPER_SOURCES_APP}
|
||||
${PHONY_OUTPUT}
|
||||
COMMAND ${CMAKE_COMMAND} -E env
|
||||
${FLUTTER_TOOL_ENVIRONMENT}
|
||||
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
|
||||
${FLUTTER_TARGET_PLATFORM} $<CONFIG>
|
||||
VERBATIM
|
||||
)
|
||||
add_custom_target(flutter_assemble DEPENDS
|
||||
"${FLUTTER_LIBRARY}"
|
||||
${FLUTTER_LIBRARY_HEADERS}
|
||||
${CPP_WRAPPER_SOURCES_CORE}
|
||||
${CPP_WRAPPER_SOURCES_PLUGIN}
|
||||
${CPP_WRAPPER_SOURCES_APP}
|
||||
)
|
|
@ -0,0 +1,14 @@
|
|||
//
|
||||
// Generated file. Do not edit.
|
||||
//
|
||||
|
||||
// clang-format off
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <flutter_inappwebview_windows/flutter_inappwebview_windows_plugin_c_api.h>
|
||||
|
||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||
FlutterInappwebviewWindowsPluginCApiRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("FlutterInappwebviewWindowsPluginCApi"));
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
//
|
||||
// Generated file. Do not edit.
|
||||
//
|
||||
|
||||
// clang-format off
|
||||
|
||||
#ifndef GENERATED_PLUGIN_REGISTRANT_
|
||||
#define GENERATED_PLUGIN_REGISTRANT_
|
||||
|
||||
#include <flutter/plugin_registry.h>
|
||||
|
||||
// Registers Flutter plugins.
|
||||
void RegisterPlugins(flutter::PluginRegistry* registry);
|
||||
|
||||
#endif // GENERATED_PLUGIN_REGISTRANT_
|
|
@ -0,0 +1,24 @@
|
|||
#
|
||||
# Generated file, do not edit.
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
flutter_inappwebview_windows
|
||||
)
|
||||
|
||||
list(APPEND FLUTTER_FFI_PLUGIN_LIST
|
||||
)
|
||||
|
||||
set(PLUGIN_BUNDLED_LIBRARIES)
|
||||
|
||||
foreach(plugin ${FLUTTER_PLUGIN_LIST})
|
||||
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin})
|
||||
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
|
||||
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
|
||||
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
|
||||
endforeach(plugin)
|
||||
|
||||
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
|
||||
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin})
|
||||
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
|
||||
endforeach(ffi_plugin)
|
|
@ -0,0 +1,40 @@
|
|||
cmake_minimum_required(VERSION 3.14)
|
||||
project(runner LANGUAGES CXX)
|
||||
|
||||
# Define the application target. To change its name, change BINARY_NAME in the
|
||||
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
|
||||
# work.
|
||||
#
|
||||
# Any new source files that you add to the application should be added here.
|
||||
add_executable(${BINARY_NAME} WIN32
|
||||
"flutter_window.cpp"
|
||||
"main.cpp"
|
||||
"utils.cpp"
|
||||
"win32_window.cpp"
|
||||
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
|
||||
"Runner.rc"
|
||||
"runner.exe.manifest"
|
||||
)
|
||||
|
||||
# Apply the standard set of build settings. This can be removed for applications
|
||||
# that need different build settings.
|
||||
apply_standard_settings(${BINARY_NAME})
|
||||
|
||||
# Add preprocessor definitions for the build version.
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")
|
||||
|
||||
# Disable Windows macros that collide with C++ standard library functions.
|
||||
target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
|
||||
|
||||
# Add dependency libraries and include directories. Add any application-specific
|
||||
# dependencies here.
|
||||
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
|
||||
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
|
||||
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
|
||||
|
||||
# Run the Flutter tool portions of the build. This must not be removed.
|
||||
add_dependencies(${BINARY_NAME} flutter_assemble)
|
|
@ -0,0 +1,121 @@
|
|||
// Microsoft Visual C++ generated resource script.
|
||||
//
|
||||
#pragma code_page(65001)
|
||||
#include "resource.h"
|
||||
|
||||
#define APSTUDIO_READONLY_SYMBOLS
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Generated from the TEXTINCLUDE 2 resource.
|
||||
//
|
||||
#include "winres.h"
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
#undef APSTUDIO_READONLY_SYMBOLS
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// English (United States) resources
|
||||
|
||||
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
|
||||
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
|
||||
|
||||
#ifdef APSTUDIO_INVOKED
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// TEXTINCLUDE
|
||||
//
|
||||
|
||||
1 TEXTINCLUDE
|
||||
BEGIN
|
||||
"resource.h\0"
|
||||
END
|
||||
|
||||
2 TEXTINCLUDE
|
||||
BEGIN
|
||||
"#include ""winres.h""\r\n"
|
||||
"\0"
|
||||
END
|
||||
|
||||
3 TEXTINCLUDE
|
||||
BEGIN
|
||||
"\r\n"
|
||||
"\0"
|
||||
END
|
||||
|
||||
#endif // APSTUDIO_INVOKED
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Icon
|
||||
//
|
||||
|
||||
// Icon with lowest ID value placed first to ensure application icon
|
||||
// remains consistent on all systems.
|
||||
IDI_APP_ICON ICON "resources\\app_icon.ico"
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Version
|
||||
//
|
||||
|
||||
#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)
|
||||
#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD
|
||||
#else
|
||||
#define VERSION_AS_NUMBER 1,0,0,0
|
||||
#endif
|
||||
|
||||
#if defined(FLUTTER_VERSION)
|
||||
#define VERSION_AS_STRING FLUTTER_VERSION
|
||||
#else
|
||||
#define VERSION_AS_STRING "1.0.0"
|
||||
#endif
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION VERSION_AS_NUMBER
|
||||
PRODUCTVERSION VERSION_AS_NUMBER
|
||||
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
|
||||
#ifdef _DEBUG
|
||||
FILEFLAGS VS_FF_DEBUG
|
||||
#else
|
||||
FILEFLAGS 0x0L
|
||||
#endif
|
||||
FILEOS VOS__WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
FILESUBTYPE 0x0L
|
||||
BEGIN
|
||||
BLOCK "StringFileInfo"
|
||||
BEGIN
|
||||
BLOCK "040904e4"
|
||||
BEGIN
|
||||
VALUE "CompanyName", "com.pichillilorenzo" "\0"
|
||||
VALUE "FileDescription", "flutter_inappwebview_windows_example" "\0"
|
||||
VALUE "FileVersion", VERSION_AS_STRING "\0"
|
||||
VALUE "InternalName", "flutter_inappwebview_windows_example" "\0"
|
||||
VALUE "LegalCopyright", "Copyright (C) 2023 com.pichillilorenzo. All rights reserved." "\0"
|
||||
VALUE "OriginalFilename", "flutter_inappwebview_windows_example.exe" "\0"
|
||||
VALUE "ProductName", "flutter_inappwebview_windows_example" "\0"
|
||||
VALUE "ProductVersion", VERSION_AS_STRING "\0"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
BEGIN
|
||||
VALUE "Translation", 0x409, 1252
|
||||
END
|
||||
END
|
||||
|
||||
#endif // English (United States) resources
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
#ifndef APSTUDIO_INVOKED
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Generated from the TEXTINCLUDE 3 resource.
|
||||
//
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
#endif // not APSTUDIO_INVOKED
|
|
@ -0,0 +1,71 @@
|
|||
#include "flutter_window.h"
|
||||
|
||||
#include <optional>
|
||||
|
||||
#include "flutter/generated_plugin_registrant.h"
|
||||
|
||||
FlutterWindow::FlutterWindow(const flutter::DartProject& project)
|
||||
: project_(project) {}
|
||||
|
||||
FlutterWindow::~FlutterWindow() {}
|
||||
|
||||
bool FlutterWindow::OnCreate() {
|
||||
if (!Win32Window::OnCreate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
RECT frame = GetClientArea();
|
||||
|
||||
// The size here must match the window dimensions to avoid unnecessary surface
|
||||
// creation / destruction in the startup path.
|
||||
flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
|
||||
frame.right - frame.left, frame.bottom - frame.top, project_);
|
||||
// Ensure that basic setup of the controller was successful.
|
||||
if (!flutter_controller_->engine() || !flutter_controller_->view()) {
|
||||
return false;
|
||||
}
|
||||
RegisterPlugins(flutter_controller_->engine());
|
||||
SetChildContent(flutter_controller_->view()->GetNativeWindow());
|
||||
|
||||
flutter_controller_->engine()->SetNextFrameCallback([&]() {
|
||||
this->Show();
|
||||
});
|
||||
|
||||
// Flutter can complete the first frame before the "show window" callback is
|
||||
// registered. The following call ensures a frame is pending to ensure the
|
||||
// window is shown. It is a no-op if the first frame hasn't completed yet.
|
||||
flutter_controller_->ForceRedraw();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void FlutterWindow::OnDestroy() {
|
||||
if (flutter_controller_) {
|
||||
flutter_controller_ = nullptr;
|
||||
}
|
||||
|
||||
Win32Window::OnDestroy();
|
||||
}
|
||||
|
||||
LRESULT
|
||||
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept {
|
||||
// Give Flutter, including plugins, an opportunity to handle window messages.
|
||||
if (flutter_controller_) {
|
||||
std::optional<LRESULT> result =
|
||||
flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
|
||||
lparam);
|
||||
if (result) {
|
||||
return *result;
|
||||
}
|
||||
}
|
||||
|
||||
switch (message) {
|
||||
case WM_FONTCHANGE:
|
||||
flutter_controller_->engine()->ReloadSystemFonts();
|
||||
break;
|
||||
}
|
||||
|
||||
return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
#ifndef RUNNER_FLUTTER_WINDOW_H_
|
||||
#define RUNNER_FLUTTER_WINDOW_H_
|
||||
|
||||
#include <flutter/dart_project.h>
|
||||
#include <flutter/flutter_view_controller.h>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "win32_window.h"
|
||||
|
||||
// A window that does nothing but host a Flutter view.
|
||||
class FlutterWindow : public Win32Window {
|
||||
public:
|
||||
// Creates a new FlutterWindow hosting a Flutter view running |project|.
|
||||
explicit FlutterWindow(const flutter::DartProject& project);
|
||||
virtual ~FlutterWindow();
|
||||
|
||||
protected:
|
||||
// Win32Window:
|
||||
bool OnCreate() override;
|
||||
void OnDestroy() override;
|
||||
LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept override;
|
||||
|
||||
private:
|
||||
// The project to run.
|
||||
flutter::DartProject project_;
|
||||
|
||||
// The Flutter instance hosted by this window.
|
||||
std::unique_ptr<flutter::FlutterViewController> flutter_controller_;
|
||||
};
|
||||
|
||||
#endif // RUNNER_FLUTTER_WINDOW_H_
|
|
@ -0,0 +1,43 @@
|
|||
#include <flutter/dart_project.h>
|
||||
#include <flutter/flutter_view_controller.h>
|
||||
#include <windows.h>
|
||||
|
||||
#include "flutter_window.h"
|
||||
#include "utils.h"
|
||||
|
||||
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
||||
_In_ wchar_t *command_line, _In_ int show_command) {
|
||||
// Attach to console when present (e.g., 'flutter run') or create a
|
||||
// new console when running with a debugger.
|
||||
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
|
||||
CreateAndAttachConsole();
|
||||
}
|
||||
|
||||
// Initialize COM, so that it is available for use in the library and/or
|
||||
// plugins.
|
||||
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
|
||||
flutter::DartProject project(L"data");
|
||||
|
||||
std::vector<std::string> command_line_arguments =
|
||||
GetCommandLineArguments();
|
||||
|
||||
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
|
||||
|
||||
FlutterWindow window(project);
|
||||
Win32Window::Point origin(10, 10);
|
||||
Win32Window::Size size(1280, 720);
|
||||
if (!window.Create(L"flutter_inappwebview_windows_example", origin, size)) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
window.SetQuitOnClose(true);
|
||||
|
||||
::MSG msg;
|
||||
while (::GetMessage(&msg, nullptr, 0, 0)) {
|
||||
::TranslateMessage(&msg);
|
||||
::DispatchMessage(&msg);
|
||||
}
|
||||
|
||||
::CoUninitialize();
|
||||
return EXIT_SUCCESS;
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
//{{NO_DEPENDENCIES}}
|
||||
// Microsoft Visual C++ generated include file.
|
||||
// Used by Runner.rc
|
||||
//
|
||||
#define IDI_APP_ICON 101
|
||||
|
||||
// Next default values for new objects
|
||||
//
|
||||
#ifdef APSTUDIO_INVOKED
|
||||
#ifndef APSTUDIO_READONLY_SYMBOLS
|
||||
#define _APS_NEXT_RESOURCE_VALUE 102
|
||||
#define _APS_NEXT_COMMAND_VALUE 40001
|
||||
#define _APS_NEXT_CONTROL_VALUE 1001
|
||||
#define _APS_NEXT_SYMED_VALUE 101
|
||||
#endif
|
||||
#endif
|
Binary file not shown.
After Width: | Height: | Size: 33 KiB |
|
@ -0,0 +1,20 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<!-- Windows 10 and Windows 11 -->
|
||||
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
|
||||
<!-- Windows 8.1 -->
|
||||
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
|
||||
<!-- Windows 8 -->
|
||||
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
|
||||
<!-- Windows 7 -->
|
||||
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
|
||||
</application>
|
||||
</compatibility>
|
||||
</assembly>
|
|
@ -0,0 +1,65 @@
|
|||
#include "utils.h"
|
||||
|
||||
#include <flutter_windows.h>
|
||||
#include <io.h>
|
||||
#include <stdio.h>
|
||||
#include <windows.h>
|
||||
|
||||
#include <iostream>
|
||||
|
||||
void CreateAndAttachConsole() {
|
||||
if (::AllocConsole()) {
|
||||
FILE *unused;
|
||||
if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
|
||||
_dup2(_fileno(stdout), 1);
|
||||
}
|
||||
if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
|
||||
_dup2(_fileno(stdout), 2);
|
||||
}
|
||||
std::ios::sync_with_stdio();
|
||||
FlutterDesktopResyncOutputStreams();
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> GetCommandLineArguments() {
|
||||
// Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
|
||||
int argc;
|
||||
wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
|
||||
if (argv == nullptr) {
|
||||
return std::vector<std::string>();
|
||||
}
|
||||
|
||||
std::vector<std::string> command_line_arguments;
|
||||
|
||||
// Skip the first argument as it's the binary name.
|
||||
for (int i = 1; i < argc; i++) {
|
||||
command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
|
||||
}
|
||||
|
||||
::LocalFree(argv);
|
||||
|
||||
return command_line_arguments;
|
||||
}
|
||||
|
||||
std::string Utf8FromUtf16(const wchar_t* utf16_string) {
|
||||
if (utf16_string == nullptr) {
|
||||
return std::string();
|
||||
}
|
||||
int target_length = ::WideCharToMultiByte(
|
||||
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
|
||||
-1, nullptr, 0, nullptr, nullptr)
|
||||
-1; // remove the trailing null character
|
||||
int input_length = (int)wcslen(utf16_string);
|
||||
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,
|
||||
input_length, utf8_string.data(), target_length, nullptr, nullptr);
|
||||
if (converted_length == 0) {
|
||||
return std::string();
|
||||
}
|
||||
return utf8_string;
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
#ifndef RUNNER_UTILS_H_
|
||||
#define RUNNER_UTILS_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// Creates a console for the process, and redirects stdout and stderr to
|
||||
// it for both the runner and the Flutter library.
|
||||
void CreateAndAttachConsole();
|
||||
|
||||
// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
|
||||
// encoded in UTF-8. Returns an empty std::string on failure.
|
||||
std::string Utf8FromUtf16(const wchar_t* utf16_string);
|
||||
|
||||
// Gets the command line arguments passed in as a std::vector<std::string>,
|
||||
// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.
|
||||
std::vector<std::string> GetCommandLineArguments();
|
||||
|
||||
#endif // RUNNER_UTILS_H_
|
|
@ -0,0 +1,288 @@
|
|||
#include "win32_window.h"
|
||||
|
||||
#include <dwmapi.h>
|
||||
#include <flutter_windows.h>
|
||||
|
||||
#include "resource.h"
|
||||
|
||||
namespace {
|
||||
|
||||
/// Window attribute that enables dark mode window decorations.
|
||||
///
|
||||
/// Redefined in case the developer's machine has a Windows SDK older than
|
||||
/// version 10.0.22000.0.
|
||||
/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
|
||||
#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
|
||||
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
|
||||
#endif
|
||||
|
||||
constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";
|
||||
|
||||
/// Registry key for app theme preference.
|
||||
///
|
||||
/// A value of 0 indicates apps should use dark mode. A non-zero or missing
|
||||
/// value indicates apps should use light mode.
|
||||
constexpr const wchar_t kGetPreferredBrightnessRegKey[] =
|
||||
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
|
||||
constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";
|
||||
|
||||
// The number of Win32Window objects that currently exist.
|
||||
static int g_active_window_count = 0;
|
||||
|
||||
using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);
|
||||
|
||||
// Scale helper to convert logical scaler values to physical using passed in
|
||||
// scale factor
|
||||
int Scale(int source, double scale_factor) {
|
||||
return static_cast<int>(source * scale_factor);
|
||||
}
|
||||
|
||||
// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.
|
||||
// This API is only needed for PerMonitor V1 awareness mode.
|
||||
void EnableFullDpiSupportIfAvailable(HWND hwnd) {
|
||||
HMODULE user32_module = LoadLibraryA("User32.dll");
|
||||
if (!user32_module) {
|
||||
return;
|
||||
}
|
||||
auto enable_non_client_dpi_scaling =
|
||||
reinterpret_cast<EnableNonClientDpiScaling*>(
|
||||
GetProcAddress(user32_module, "EnableNonClientDpiScaling"));
|
||||
if (enable_non_client_dpi_scaling != nullptr) {
|
||||
enable_non_client_dpi_scaling(hwnd);
|
||||
}
|
||||
FreeLibrary(user32_module);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Manages the Win32Window's window class registration.
|
||||
class WindowClassRegistrar {
|
||||
public:
|
||||
~WindowClassRegistrar() = default;
|
||||
|
||||
// Returns the singleton registrar instance.
|
||||
static WindowClassRegistrar* GetInstance() {
|
||||
if (!instance_) {
|
||||
instance_ = new WindowClassRegistrar();
|
||||
}
|
||||
return instance_;
|
||||
}
|
||||
|
||||
// Returns the name of the window class, registering the class if it hasn't
|
||||
// previously been registered.
|
||||
const wchar_t* GetWindowClass();
|
||||
|
||||
// Unregisters the window class. Should only be called if there are no
|
||||
// instances of the window.
|
||||
void UnregisterWindowClass();
|
||||
|
||||
private:
|
||||
WindowClassRegistrar() = default;
|
||||
|
||||
static WindowClassRegistrar* instance_;
|
||||
|
||||
bool class_registered_ = false;
|
||||
};
|
||||
|
||||
WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;
|
||||
|
||||
const wchar_t* WindowClassRegistrar::GetWindowClass() {
|
||||
if (!class_registered_) {
|
||||
WNDCLASS window_class{};
|
||||
window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
|
||||
window_class.lpszClassName = kWindowClassName;
|
||||
window_class.style = CS_HREDRAW | CS_VREDRAW;
|
||||
window_class.cbClsExtra = 0;
|
||||
window_class.cbWndExtra = 0;
|
||||
window_class.hInstance = GetModuleHandle(nullptr);
|
||||
window_class.hIcon =
|
||||
LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
|
||||
window_class.hbrBackground = 0;
|
||||
window_class.lpszMenuName = nullptr;
|
||||
window_class.lpfnWndProc = Win32Window::WndProc;
|
||||
RegisterClass(&window_class);
|
||||
class_registered_ = true;
|
||||
}
|
||||
return kWindowClassName;
|
||||
}
|
||||
|
||||
void WindowClassRegistrar::UnregisterWindowClass() {
|
||||
UnregisterClass(kWindowClassName, nullptr);
|
||||
class_registered_ = false;
|
||||
}
|
||||
|
||||
Win32Window::Win32Window() {
|
||||
++g_active_window_count;
|
||||
}
|
||||
|
||||
Win32Window::~Win32Window() {
|
||||
--g_active_window_count;
|
||||
Destroy();
|
||||
}
|
||||
|
||||
bool Win32Window::Create(const std::wstring& title,
|
||||
const Point& origin,
|
||||
const Size& size) {
|
||||
Destroy();
|
||||
|
||||
const wchar_t* window_class =
|
||||
WindowClassRegistrar::GetInstance()->GetWindowClass();
|
||||
|
||||
const POINT target_point = {static_cast<LONG>(origin.x),
|
||||
static_cast<LONG>(origin.y)};
|
||||
HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);
|
||||
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
|
||||
double scale_factor = dpi / 96.0;
|
||||
|
||||
HWND window = CreateWindow(
|
||||
window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
|
||||
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
|
||||
Scale(size.width, scale_factor), Scale(size.height, scale_factor),
|
||||
nullptr, nullptr, GetModuleHandle(nullptr), this);
|
||||
|
||||
if (!window) {
|
||||
return false;
|
||||
}
|
||||
|
||||
UpdateTheme(window);
|
||||
|
||||
return OnCreate();
|
||||
}
|
||||
|
||||
bool Win32Window::Show() {
|
||||
return ShowWindow(window_handle_, SW_SHOWNORMAL);
|
||||
}
|
||||
|
||||
// static
|
||||
LRESULT CALLBACK Win32Window::WndProc(HWND const window,
|
||||
UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept {
|
||||
if (message == WM_NCCREATE) {
|
||||
auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
|
||||
SetWindowLongPtr(window, GWLP_USERDATA,
|
||||
reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));
|
||||
|
||||
auto that = static_cast<Win32Window*>(window_struct->lpCreateParams);
|
||||
EnableFullDpiSupportIfAvailable(window);
|
||||
that->window_handle_ = window;
|
||||
} else if (Win32Window* that = GetThisFromHandle(window)) {
|
||||
return that->MessageHandler(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
return DefWindowProc(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
LRESULT
|
||||
Win32Window::MessageHandler(HWND hwnd,
|
||||
UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept {
|
||||
switch (message) {
|
||||
case WM_DESTROY:
|
||||
window_handle_ = nullptr;
|
||||
Destroy();
|
||||
if (quit_on_close_) {
|
||||
PostQuitMessage(0);
|
||||
}
|
||||
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 rect = GetClientArea();
|
||||
if (child_content_ != nullptr) {
|
||||
// Size and position the child window.
|
||||
MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,
|
||||
rect.bottom - rect.top, TRUE);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
case WM_ACTIVATE:
|
||||
if (child_content_ != nullptr) {
|
||||
SetFocus(child_content_);
|
||||
}
|
||||
return 0;
|
||||
|
||||
case WM_DWMCOLORIZATIONCOLORCHANGED:
|
||||
UpdateTheme(hwnd);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return DefWindowProc(window_handle_, message, wparam, lparam);
|
||||
}
|
||||
|
||||
void Win32Window::Destroy() {
|
||||
OnDestroy();
|
||||
|
||||
if (window_handle_) {
|
||||
DestroyWindow(window_handle_);
|
||||
window_handle_ = nullptr;
|
||||
}
|
||||
if (g_active_window_count == 0) {
|
||||
WindowClassRegistrar::GetInstance()->UnregisterWindowClass();
|
||||
}
|
||||
}
|
||||
|
||||
Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {
|
||||
return reinterpret_cast<Win32Window*>(
|
||||
GetWindowLongPtr(window, GWLP_USERDATA));
|
||||
}
|
||||
|
||||
void Win32Window::SetChildContent(HWND content) {
|
||||
child_content_ = content;
|
||||
SetParent(content, window_handle_);
|
||||
RECT frame = GetClientArea();
|
||||
|
||||
MoveWindow(content, frame.left, frame.top, frame.right - frame.left,
|
||||
frame.bottom - frame.top, true);
|
||||
|
||||
SetFocus(child_content_);
|
||||
}
|
||||
|
||||
RECT Win32Window::GetClientArea() {
|
||||
RECT frame;
|
||||
GetClientRect(window_handle_, &frame);
|
||||
return frame;
|
||||
}
|
||||
|
||||
HWND Win32Window::GetHandle() {
|
||||
return window_handle_;
|
||||
}
|
||||
|
||||
void Win32Window::SetQuitOnClose(bool quit_on_close) {
|
||||
quit_on_close_ = quit_on_close;
|
||||
}
|
||||
|
||||
bool Win32Window::OnCreate() {
|
||||
// No-op; provided for subclasses.
|
||||
return true;
|
||||
}
|
||||
|
||||
void Win32Window::OnDestroy() {
|
||||
// No-op; provided for subclasses.
|
||||
}
|
||||
|
||||
void Win32Window::UpdateTheme(HWND const window) {
|
||||
DWORD light_mode;
|
||||
DWORD light_mode_size = sizeof(light_mode);
|
||||
LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
|
||||
kGetPreferredBrightnessRegValue,
|
||||
RRF_RT_REG_DWORD, nullptr, &light_mode,
|
||||
&light_mode_size);
|
||||
|
||||
if (result == ERROR_SUCCESS) {
|
||||
BOOL enable_dark_mode = light_mode == 0;
|
||||
DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,
|
||||
&enable_dark_mode, sizeof(enable_dark_mode));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
#ifndef RUNNER_WIN32_WINDOW_H_
|
||||
#define RUNNER_WIN32_WINDOW_H_
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
// A class abstraction for a high DPI-aware Win32 Window. Intended to be
|
||||
// inherited from by classes that wish to specialize with custom
|
||||
// rendering and input handling
|
||||
class Win32Window {
|
||||
public:
|
||||
struct Point {
|
||||
unsigned int x;
|
||||
unsigned int y;
|
||||
Point(unsigned int x, unsigned int y) : x(x), y(y) {}
|
||||
};
|
||||
|
||||
struct Size {
|
||||
unsigned int width;
|
||||
unsigned int height;
|
||||
Size(unsigned int width, unsigned int height)
|
||||
: width(width), height(height) {}
|
||||
};
|
||||
|
||||
Win32Window();
|
||||
virtual ~Win32Window();
|
||||
|
||||
// Creates a win32 window with |title| that is positioned and sized using
|
||||
// |origin| and |size|. New windows are created on the default monitor. Window
|
||||
// sizes are specified to the OS in physical pixels, hence to ensure a
|
||||
// consistent size this function will scale the inputted width and height as
|
||||
// as appropriate for the default monitor. The window is invisible until
|
||||
// |Show| is called. Returns true if the window was created successfully.
|
||||
bool Create(const std::wstring& title, const Point& origin, const Size& size);
|
||||
|
||||
// Show the current window. Returns true if the window was successfully shown.
|
||||
bool Show();
|
||||
|
||||
// Release OS resources associated with window.
|
||||
void Destroy();
|
||||
|
||||
// Inserts |content| into the window tree.
|
||||
void SetChildContent(HWND content);
|
||||
|
||||
// Returns the backing Window handle to enable clients to set icon and other
|
||||
// window properties. Returns nullptr if the window has been destroyed.
|
||||
HWND GetHandle();
|
||||
|
||||
// If true, closing this window will quit the application.
|
||||
void SetQuitOnClose(bool quit_on_close);
|
||||
|
||||
// Return a RECT representing the bounds of the current client area.
|
||||
RECT GetClientArea();
|
||||
|
||||
protected:
|
||||
// Processes and route salient window messages for mouse handling,
|
||||
// size change and DPI. Delegates handling of these to member overloads that
|
||||
// inheriting classes can handle.
|
||||
virtual LRESULT MessageHandler(HWND window,
|
||||
UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept;
|
||||
|
||||
// Called when CreateAndShow is called, allowing subclass window-related
|
||||
// setup. Subclasses should return false if setup fails.
|
||||
virtual bool OnCreate();
|
||||
|
||||
// Called when Destroy is called.
|
||||
virtual void OnDestroy();
|
||||
|
||||
private:
|
||||
friend class WindowClassRegistrar;
|
||||
|
||||
// OS callback called by message pump. Handles the WM_NCCREATE message which
|
||||
// is passed when the non-client area is being created and enables automatic
|
||||
// non-client DPI scaling so that the non-client area automatically
|
||||
// responds to changes in DPI. All other messages are handled by
|
||||
// MessageHandler.
|
||||
static LRESULT CALLBACK WndProc(HWND const window,
|
||||
UINT const message,
|
||||
WPARAM const wparam,
|
||||
LPARAM const lparam) noexcept;
|
||||
|
||||
// Retrieves a class instance pointer for |window|
|
||||
static Win32Window* GetThisFromHandle(HWND const window) noexcept;
|
||||
|
||||
// Update the window frame's theme to match the system theme.
|
||||
static void UpdateTheme(HWND const window);
|
||||
|
||||
bool quit_on_close_ = false;
|
||||
|
||||
// window handle for top level window.
|
||||
HWND window_handle_ = nullptr;
|
||||
|
||||
// window handle for hosted content.
|
||||
HWND child_content_ = nullptr;
|
||||
};
|
||||
|
||||
#endif // RUNNER_WIN32_WINDOW_H_
|
|
@ -0,0 +1,3 @@
|
|||
library flutter_inappwebview_windows;
|
||||
|
||||
export 'src/main.dart';
|
|
@ -0,0 +1,433 @@
|
|||
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 'in_app_webview/headless_in_app_webview.dart';
|
||||
import 'platform_util.dart';
|
||||
|
||||
/// Object specifying creation parameters for creating a [MacOSCookieManager].
|
||||
///
|
||||
/// 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 MacOSCookieManagerCreationParams
|
||||
extends PlatformCookieManagerCreationParams {
|
||||
/// Creates a new [MacOSCookieManagerCreationParams] instance.
|
||||
const MacOSCookieManagerCreationParams(
|
||||
// This parameter prevents breaking changes later.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformCookieManagerCreationParams params,
|
||||
) : super();
|
||||
|
||||
/// Creates a [MacOSCookieManagerCreationParams] instance based on [PlatformCookieManagerCreationParams].
|
||||
factory MacOSCookieManagerCreationParams.fromPlatformCookieManagerCreationParams(
|
||||
PlatformCookieManagerCreationParams params) {
|
||||
return MacOSCookieManagerCreationParams(params);
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformCookieManager}
|
||||
class MacOSCookieManager extends PlatformCookieManager with ChannelController {
|
||||
/// Creates a new [MacOSCookieManager].
|
||||
MacOSCookieManager(PlatformCookieManagerCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSCookieManagerCreationParams
|
||||
? params
|
||||
: MacOSCookieManagerCreationParams
|
||||
.fromPlatformCookieManagerCreationParams(params),
|
||||
) {
|
||||
channel = const MethodChannel(
|
||||
'com.pichillilorenzo/flutter_inappwebview_cookiemanager');
|
||||
handler = handleMethod;
|
||||
initMethodCallHandler();
|
||||
}
|
||||
|
||||
static MacOSCookieManager? _instance;
|
||||
|
||||
///Gets the [MacOSCookieManager] shared instance.
|
||||
static MacOSCookieManager instance() {
|
||||
return (_instance != null) ? _instance! : _init();
|
||||
}
|
||||
|
||||
static MacOSCookieManager _init() {
|
||||
_instance = MacOSCookieManager(MacOSCookieManagerCreationParams(
|
||||
const PlatformCookieManagerCreationParams()));
|
||||
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 {
|
||||
webViewController = webViewController ?? iosBelow11WebViewController;
|
||||
|
||||
assert(url.toString().isNotEmpty);
|
||||
assert(name.isNotEmpty);
|
||||
assert(value.isNotEmpty);
|
||||
assert(path.isNotEmpty);
|
||||
|
||||
if (await _shouldUseJavascript()) {
|
||||
await _setCookieWithJavaScript(
|
||||
url: url,
|
||||
name: name,
|
||||
value: value,
|
||||
domain: domain,
|
||||
path: path,
|
||||
expiresDate: expiresDate,
|
||||
maxAge: maxAge,
|
||||
isSecure: isSecure,
|
||||
sameSite: sameSite,
|
||||
webViewController: webViewController);
|
||||
return true;
|
||||
}
|
||||
|
||||
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?.toString());
|
||||
args.putIfAbsent('maxAge', () => maxAge);
|
||||
args.putIfAbsent('isSecure', () => isSecure);
|
||||
args.putIfAbsent('isHttpOnly', () => isHttpOnly);
|
||||
args.putIfAbsent('sameSite', () => sameSite?.toNativeValue());
|
||||
|
||||
return await channel?.invokeMethod<bool>('setCookie', args) ?? false;
|
||||
}
|
||||
|
||||
Future<void> _setCookieWithJavaScript(
|
||||
{required WebUri url,
|
||||
required String name,
|
||||
required String value,
|
||||
String path = "/",
|
||||
String? domain,
|
||||
int? expiresDate,
|
||||
int? maxAge,
|
||||
bool? isSecure,
|
||||
HTTPCookieSameSitePolicy? sameSite,
|
||||
PlatformInAppWebViewController? webViewController}) async {
|
||||
var cookieValue = name + "=" + value + "; Path=" + path;
|
||||
|
||||
if (domain != null) cookieValue += "; Domain=" + domain;
|
||||
|
||||
if (expiresDate != null)
|
||||
cookieValue += "; Expires=" + await _getCookieExpirationDate(expiresDate);
|
||||
|
||||
if (maxAge != null) cookieValue += "; Max-Age=" + maxAge.toString();
|
||||
|
||||
if (isSecure != null && isSecure) cookieValue += "; Secure";
|
||||
|
||||
if (sameSite != null)
|
||||
cookieValue += "; SameSite=" + sameSite.toNativeValue();
|
||||
|
||||
cookieValue += ";";
|
||||
|
||||
if (webViewController != null) {
|
||||
final javaScriptEnabled =
|
||||
(await webViewController.getSettings())?.javaScriptEnabled ?? false;
|
||||
if (javaScriptEnabled) {
|
||||
await webViewController.evaluateJavascript(
|
||||
source: 'document.cookie="$cookieValue"');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
final setCookieCompleter = Completer<void>();
|
||||
final headlessWebView =
|
||||
MacOSHeadlessInAppWebView(MacOSHeadlessInAppWebViewCreationParams(
|
||||
initialUrlRequest: URLRequest(url: url),
|
||||
onLoadStop: (controller, url) async {
|
||||
await controller.evaluateJavascript(
|
||||
source: 'document.cookie="$cookieValue"');
|
||||
setCookieCompleter.complete();
|
||||
}));
|
||||
await headlessWebView.run();
|
||||
await setCookieCompleter.future;
|
||||
await headlessWebView.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<Cookie>> getCookies(
|
||||
{required WebUri url,
|
||||
@Deprecated("Use webViewController instead")
|
||||
PlatformInAppWebViewController? iosBelow11WebViewController,
|
||||
PlatformInAppWebViewController? webViewController}) async {
|
||||
assert(url.toString().isNotEmpty);
|
||||
|
||||
webViewController = webViewController ?? iosBelow11WebViewController;
|
||||
|
||||
if (await _shouldUseJavascript()) {
|
||||
return await _getCookiesWithJavaScript(
|
||||
url: url, webViewController: webViewController);
|
||||
}
|
||||
|
||||
List<Cookie> cookies = [];
|
||||
|
||||
Map<String, dynamic> args = <String, dynamic>{};
|
||||
args.putIfAbsent('url', () => url.toString());
|
||||
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;
|
||||
}
|
||||
|
||||
Future<List<Cookie>> _getCookiesWithJavaScript(
|
||||
{required WebUri url,
|
||||
PlatformInAppWebViewController? webViewController}) async {
|
||||
assert(url.toString().isNotEmpty);
|
||||
|
||||
List<Cookie> cookies = [];
|
||||
|
||||
if (webViewController != null) {
|
||||
final javaScriptEnabled =
|
||||
(await webViewController.getSettings())?.javaScriptEnabled ?? false;
|
||||
if (javaScriptEnabled) {
|
||||
List<String> documentCookies = (await webViewController
|
||||
.evaluateJavascript(source: 'document.cookie') as String)
|
||||
.split(';')
|
||||
.map((documentCookie) => documentCookie.trim())
|
||||
.toList();
|
||||
documentCookies.forEach((documentCookie) {
|
||||
List<String> cookie = documentCookie.split('=');
|
||||
if (cookie.length > 1) {
|
||||
cookies.add(Cookie(
|
||||
name: cookie[0],
|
||||
value: cookie[1],
|
||||
));
|
||||
}
|
||||
});
|
||||
return cookies;
|
||||
}
|
||||
}
|
||||
|
||||
final pageLoaded = Completer<void>();
|
||||
final headlessWebView =
|
||||
MacOSHeadlessInAppWebView(MacOSHeadlessInAppWebViewCreationParams(
|
||||
initialUrlRequest: URLRequest(url: url),
|
||||
onLoadStop: (controller, url) async {
|
||||
pageLoaded.complete();
|
||||
},
|
||||
));
|
||||
await headlessWebView.run();
|
||||
await pageLoaded.future;
|
||||
|
||||
List<String> documentCookies = (await headlessWebView.webViewController!
|
||||
.evaluateJavascript(source: 'document.cookie') as String)
|
||||
.split(';')
|
||||
.map((documentCookie) => documentCookie.trim())
|
||||
.toList();
|
||||
documentCookies.forEach((documentCookie) {
|
||||
List<String> cookie = documentCookie.split('=');
|
||||
if (cookie.length > 1) {
|
||||
cookies.add(Cookie(
|
||||
name: cookie[0],
|
||||
value: cookie[1],
|
||||
));
|
||||
}
|
||||
});
|
||||
await headlessWebView.dispose();
|
||||
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);
|
||||
|
||||
webViewController = webViewController ?? iosBelow11WebViewController;
|
||||
|
||||
if (await _shouldUseJavascript()) {
|
||||
List<Cookie> cookies = await _getCookiesWithJavaScript(
|
||||
url: url, webViewController: webViewController);
|
||||
return cookies
|
||||
.cast<Cookie?>()
|
||||
.firstWhere((cookie) => cookie!.name == name, orElse: () => null);
|
||||
}
|
||||
|
||||
Map<String, dynamic> args = <String, dynamic>{};
|
||||
args.putIfAbsent('url', () => url.toString());
|
||||
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);
|
||||
|
||||
webViewController = webViewController ?? iosBelow11WebViewController;
|
||||
|
||||
if (await _shouldUseJavascript()) {
|
||||
await _setCookieWithJavaScript(
|
||||
url: url,
|
||||
name: name,
|
||||
value: "",
|
||||
path: path,
|
||||
domain: domain,
|
||||
maxAge: -1,
|
||||
webViewController: webViewController);
|
||||
return true;
|
||||
}
|
||||
|
||||
Map<String, dynamic> args = <String, dynamic>{};
|
||||
args.putIfAbsent('url', () => url.toString());
|
||||
args.putIfAbsent('name', () => name);
|
||||
args.putIfAbsent('domain', () => domain);
|
||||
args.putIfAbsent('path', () => path);
|
||||
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);
|
||||
|
||||
webViewController = webViewController ?? iosBelow11WebViewController;
|
||||
|
||||
if (await _shouldUseJavascript()) {
|
||||
List<Cookie> cookies = await _getCookiesWithJavaScript(
|
||||
url: url, webViewController: webViewController);
|
||||
for (var i = 0; i < cookies.length; i++) {
|
||||
await _setCookieWithJavaScript(
|
||||
url: url,
|
||||
name: cookies[i].name,
|
||||
value: "",
|
||||
path: path,
|
||||
domain: domain,
|
||||
maxAge: -1,
|
||||
webViewController: webViewController);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Map<String, dynamic> args = <String, dynamic>{};
|
||||
args.putIfAbsent('url', () => url.toString());
|
||||
args.putIfAbsent('domain', () => domain);
|
||||
args.putIfAbsent('path', () => path);
|
||||
return await channel?.invokeMethod<bool>('deleteCookies', args) ?? false;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> deleteAllCookies() async {
|
||||
Map<String, dynamic> args = <String, dynamic>{};
|
||||
return await channel?.invokeMethod<bool>('deleteAllCookies', args) ?? false;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<Cookie>> getAllCookies() async {
|
||||
List<Cookie> cookies = [];
|
||||
|
||||
Map<String, dynamic> args = <String, dynamic>{};
|
||||
List<dynamic> cookieListMap =
|
||||
await channel?.invokeMethod<List>('getAllCookies', 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;
|
||||
}
|
||||
|
||||
Future<String> _getCookieExpirationDate(int expiresDate) async {
|
||||
var platformUtil = PlatformUtil.instance();
|
||||
var dateTime = DateTime.fromMillisecondsSinceEpoch(expiresDate).toUtc();
|
||||
return !kIsWeb
|
||||
? await platformUtil.formatDate(
|
||||
date: dateTime,
|
||||
format: 'EEE, dd MMM yyyy hh:mm:ss z',
|
||||
locale: 'en_US',
|
||||
timezone: 'GMT')
|
||||
: await platformUtil.getWebCookieExpirationDate(date: dateTime);
|
||||
}
|
||||
|
||||
Future<bool> _shouldUseJavascript() async {
|
||||
final platformUtil = PlatformUtil.instance();
|
||||
final systemVersion = await platformUtil.getSystemVersion();
|
||||
return systemVersion.compareTo("11") == -1;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// empty
|
||||
}
|
||||
}
|
||||
|
||||
extension InternalCookieManager on MacOSCookieManager {
|
||||
get handleMethod => _handleMethod;
|
||||
}
|
|
@ -0,0 +1,124 @@
|
|||
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 [MacOSFindInteractionController].
|
||||
///
|
||||
/// 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 MacOSFindInteractionControllerCreationParams
|
||||
extends PlatformFindInteractionControllerCreationParams {
|
||||
/// Creates a new [MacOSFindInteractionControllerCreationParams] instance.
|
||||
const MacOSFindInteractionControllerCreationParams(
|
||||
{super.onFindResultReceived});
|
||||
|
||||
/// Creates a [MacOSFindInteractionControllerCreationParams] instance based on [PlatformFindInteractionControllerCreationParams].
|
||||
factory MacOSFindInteractionControllerCreationParams.fromPlatformFindInteractionControllerCreationParams(
|
||||
// Recommended placeholder to prevent being broken by platform interface.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformFindInteractionControllerCreationParams params) {
|
||||
return MacOSFindInteractionControllerCreationParams(
|
||||
onFindResultReceived: params.onFindResultReceived);
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController}
|
||||
class MacOSFindInteractionController extends PlatformFindInteractionController
|
||||
with ChannelController {
|
||||
/// Constructs a [MacOSFindInteractionController].
|
||||
MacOSFindInteractionController(
|
||||
PlatformFindInteractionControllerCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSFindInteractionControllerCreationParams
|
||||
? params
|
||||
: MacOSFindInteractionControllerCreationParams
|
||||
.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 MacOSFindInteractionController {
|
||||
void init(dynamic id) {
|
||||
channel = MethodChannel(
|
||||
'com.pichillilorenzo/flutter_inappwebview_find_interaction_$id');
|
||||
handler = _handleMethod;
|
||||
initMethodCallHandler();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
export 'find_interaction_controller.dart'
|
||||
hide InternalFindInteractionController;
|
|
@ -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 [MacOSHttpAuthCredentialDatabase].
|
||||
///
|
||||
/// 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 MacOSHttpAuthCredentialDatabaseCreationParams
|
||||
extends PlatformHttpAuthCredentialDatabaseCreationParams {
|
||||
/// Creates a new [MacOSHttpAuthCredentialDatabaseCreationParams] instance.
|
||||
const MacOSHttpAuthCredentialDatabaseCreationParams(
|
||||
// This parameter prevents breaking changes later.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformHttpAuthCredentialDatabaseCreationParams params,
|
||||
) : super();
|
||||
|
||||
/// Creates a [MacOSHttpAuthCredentialDatabaseCreationParams] instance based on [PlatformHttpAuthCredentialDatabaseCreationParams].
|
||||
factory MacOSHttpAuthCredentialDatabaseCreationParams.fromPlatformHttpAuthCredentialDatabaseCreationParams(
|
||||
PlatformHttpAuthCredentialDatabaseCreationParams params) {
|
||||
return MacOSHttpAuthCredentialDatabaseCreationParams(params);
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformHttpAuthCredentialDatabase}
|
||||
class MacOSHttpAuthCredentialDatabase extends PlatformHttpAuthCredentialDatabase
|
||||
with ChannelController {
|
||||
/// Creates a new [MacOSHttpAuthCredentialDatabase].
|
||||
MacOSHttpAuthCredentialDatabase(
|
||||
PlatformHttpAuthCredentialDatabaseCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSHttpAuthCredentialDatabaseCreationParams
|
||||
? params
|
||||
: MacOSHttpAuthCredentialDatabaseCreationParams
|
||||
.fromPlatformHttpAuthCredentialDatabaseCreationParams(params),
|
||||
) {
|
||||
channel = const MethodChannel(
|
||||
'com.pichillilorenzo/flutter_inappwebview_credential_database');
|
||||
handler = handleMethod;
|
||||
initMethodCallHandler();
|
||||
}
|
||||
|
||||
static MacOSHttpAuthCredentialDatabase? _instance;
|
||||
|
||||
///Gets the database shared instance.
|
||||
static MacOSHttpAuthCredentialDatabase instance() {
|
||||
return (_instance != null) ? _instance! : _init();
|
||||
}
|
||||
|
||||
static MacOSHttpAuthCredentialDatabase _init() {
|
||||
_instance = MacOSHttpAuthCredentialDatabase(
|
||||
MacOSHttpAuthCredentialDatabaseCreationParams(
|
||||
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 MacOSHttpAuthCredentialDatabase {
|
||||
get handleMethod => _handleMethod;
|
||||
}
|
|
@ -0,0 +1,373 @@
|
|||
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';
|
||||
|
||||
/// 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});
|
||||
|
||||
/// 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 MacOSFindInteractionController?,
|
||||
initialUserScripts: params.initialUserScripts,
|
||||
windowId: params.windowId);
|
||||
}
|
||||
|
||||
@override
|
||||
final MacOSFindInteractionController? findInteractionController;
|
||||
}
|
||||
|
||||
///{@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 _macosParams =>
|
||||
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);
|
||||
_macosParams.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);
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
export 'in_app_browser.dart' hide InternalInAppBrowser;
|
|
@ -0,0 +1,4 @@
|
|||
import 'package:flutter/services.dart';
|
||||
|
||||
const IN_APP_WEBVIEW_STATIC_CHANNEL =
|
||||
MethodChannel('com.pichillilorenzo/flutter_inappwebview_manager');
|
|
@ -0,0 +1,433 @@
|
|||
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 'in_app_webview_controller.dart';
|
||||
|
||||
/// Object specifying creation parameters for creating a [MacOSHeadlessInAppWebView].
|
||||
///
|
||||
/// 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 MacOSHeadlessInAppWebViewCreationParams
|
||||
extends PlatformHeadlessInAppWebViewCreationParams {
|
||||
/// Creates a new [MacOSHeadlessInAppWebViewCreationParams] instance.
|
||||
MacOSHeadlessInAppWebViewCreationParams(
|
||||
{super.controllerFromPlatform,
|
||||
super.initialSize,
|
||||
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 [MacOSHeadlessInAppWebViewCreationParams] instance based on [PlatformHeadlessInAppWebViewCreationParams].
|
||||
MacOSHeadlessInAppWebViewCreationParams.fromPlatformHeadlessInAppWebViewCreationParams(
|
||||
PlatformHeadlessInAppWebViewCreationParams params)
|
||||
: this(
|
||||
controllerFromPlatform: params.controllerFromPlatform,
|
||||
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 MacOSFindInteractionController?);
|
||||
|
||||
@override
|
||||
final MacOSFindInteractionController? findInteractionController;
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformHeadlessInAppWebView}
|
||||
class MacOSHeadlessInAppWebView 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 [MacOSHeadlessInAppWebView].
|
||||
MacOSHeadlessInAppWebView(PlatformHeadlessInAppWebViewCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSHeadlessInAppWebViewCreationParams
|
||||
? params
|
||||
: MacOSHeadlessInAppWebViewCreationParams
|
||||
.fromPlatformHeadlessInAppWebViewCreationParams(params),
|
||||
) {
|
||||
id = IdGenerator.generate();
|
||||
}
|
||||
|
||||
@override
|
||||
WindowsInAppWebViewController? get webViewController => _webViewController;
|
||||
|
||||
dynamic _controllerFromPlatform;
|
||||
|
||||
MacOSHeadlessInAppWebViewCreationParams get _macosParams =>
|
||||
params as MacOSHeadlessInAppWebViewCreationParams;
|
||||
|
||||
_init() {
|
||||
_webViewController = WindowsInAppWebViewController(
|
||||
WindowsInAppWebViewControllerCreationParams(id: id, webviewParams: params),
|
||||
);
|
||||
_controllerFromPlatform =
|
||||
params.controllerFromPlatform?.call(_webViewController!) ??
|
||||
_webViewController!;
|
||||
_macosParams.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 =
|
||||
_macosParams.pullToRefreshController?.params.settings.toMap() ??
|
||||
_macosParams.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()
|
||||
});
|
||||
await _sharedChannel.invokeMethod('run', args);
|
||||
_running = true;
|
||||
}
|
||||
|
||||
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;
|
||||
_macosParams.pullToRefreshController?.dispose();
|
||||
_macosParams.findInteractionController?.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
extension InternalHeadlessInAppWebView on MacOSHeadlessInAppWebView {
|
||||
Future<void> internalDispose() async {
|
||||
_started = false;
|
||||
_running = false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,408 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
|
||||
import 'headless_in_app_webview.dart';
|
||||
|
||||
import '../find_interaction/find_interaction_controller.dart';
|
||||
import 'in_app_webview_controller.dart';
|
||||
|
||||
/// Object specifying creation parameters for creating a [PlatformInAppWebViewWidget].
|
||||
///
|
||||
/// Platform specific implementations can add additional fields by extending
|
||||
/// this class.
|
||||
class MacOSInAppWebViewWidgetCreationParams
|
||||
extends PlatformInAppWebViewWidgetCreationParams {
|
||||
MacOSInAppWebViewWidgetCreationParams(
|
||||
{super.controllerFromPlatform,
|
||||
super.key,
|
||||
super.layoutDirection,
|
||||
super.gestureRecognizers,
|
||||
super.headlessWebView,
|
||||
super.keepAlive,
|
||||
super.preventGestureDelay,
|
||||
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});
|
||||
|
||||
/// Constructs a [MacOSInAppWebViewWidgetCreationParams] using a
|
||||
/// [PlatformInAppWebViewWidgetCreationParams].
|
||||
MacOSInAppWebViewWidgetCreationParams.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,
|
||||
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 MacOSFindInteractionController?);
|
||||
|
||||
@override
|
||||
final MacOSFindInteractionController? findInteractionController;
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformInAppWebViewWidget}
|
||||
class MacOSInAppWebViewWidget extends PlatformInAppWebViewWidget {
|
||||
/// Constructs a [MacOSInAppWebViewWidget].
|
||||
///
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformInAppWebViewWidget}
|
||||
MacOSInAppWebViewWidget(PlatformInAppWebViewWidgetCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSInAppWebViewWidgetCreationParams
|
||||
? params
|
||||
: MacOSInAppWebViewWidgetCreationParams
|
||||
.fromPlatformInAppWebViewWidgetCreationParams(params),
|
||||
);
|
||||
|
||||
MacOSInAppWebViewWidgetCreationParams get _macosParams =>
|
||||
params as MacOSInAppWebViewWidgetCreationParams;
|
||||
|
||||
WindowsInAppWebViewController? _controller;
|
||||
|
||||
MacOSHeadlessInAppWebView? get _macosHeadlessInAppWebView =>
|
||||
params.headlessWebView as MacOSHeadlessInAppWebView?;
|
||||
|
||||
@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 UiKitView(
|
||||
viewType: 'com.pichillilorenzo/flutter_inappwebview',
|
||||
onPlatformViewCreated: _onPlatformViewCreated,
|
||||
gestureRecognizers: params.gestureRecognizers,
|
||||
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() ?? [],
|
||||
'pullToRefreshSettings': pullToRefreshSettings,
|
||||
'keepAliveId': params.keepAlive?.id,
|
||||
'preventGestureDelay': params.preventGestureDelay
|
||||
},
|
||||
creationParamsCodec: const StandardMessageCodec(),
|
||||
);
|
||||
}
|
||||
|
||||
void _onPlatformViewCreated(int id) {
|
||||
dynamic viewId = id;
|
||||
if (params.headlessWebView?.isRunning() ?? false) {
|
||||
viewId = params.headlessWebView?.id;
|
||||
}
|
||||
viewId = params.keepAlive?.id ?? viewId ?? id;
|
||||
_macosHeadlessInAppWebView?.internalDispose();
|
||||
_controller = WindowsInAppWebViewController(
|
||||
PlatformInAppWebViewControllerCreationParams(
|
||||
id: viewId, webviewParams: params));
|
||||
_macosParams.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();
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -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;
|
|
@ -0,0 +1,32 @@
|
|||
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
|
||||
|
||||
import 'in_app_browser/in_app_browser.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 [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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
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';
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
export '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 [MacOSPrintJobController].
|
||||
///
|
||||
/// 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 MacOSPrintJobControllerCreationParams
|
||||
extends PlatformPrintJobControllerCreationParams {
|
||||
/// Creates a new [MacOSPrintJobControllerCreationParams] instance.
|
||||
const MacOSPrintJobControllerCreationParams(
|
||||
{required super.id, super.onComplete});
|
||||
|
||||
/// Creates a [MacOSPrintJobControllerCreationParams] instance based on [PlatformPrintJobControllerCreationParams].
|
||||
factory MacOSPrintJobControllerCreationParams.fromPlatformPrintJobControllerCreationParams(
|
||||
// Recommended placeholder to prevent being broken by platform interface.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformPrintJobControllerCreationParams params) {
|
||||
return MacOSPrintJobControllerCreationParams(
|
||||
id: params.id, onComplete: params.onComplete);
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformPrintJobController}
|
||||
class MacOSPrintJobController extends PlatformPrintJobController
|
||||
with ChannelController {
|
||||
/// Constructs a [MacOSPrintJobController].
|
||||
MacOSPrintJobController(PlatformPrintJobControllerCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSPrintJobControllerCreationParams
|
||||
? params
|
||||
: MacOSPrintJobControllerCreationParams
|
||||
.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();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
export 'web_message_port.dart' hide InternalWebMessagePort;
|
||||
export 'web_message_channel.dart' hide InternalWebMessageChannel;
|
||||
export 'web_message_listener.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 [MacOSWebMessageChannel].
|
||||
///
|
||||
/// 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 MacOSWebMessageChannelCreationParams
|
||||
extends PlatformWebMessageChannelCreationParams {
|
||||
/// Creates a new [MacOSWebMessageChannelCreationParams] instance.
|
||||
const MacOSWebMessageChannelCreationParams(
|
||||
{required super.id, required super.port1, required super.port2});
|
||||
|
||||
/// Creates a [MacOSWebMessageChannelCreationParams] instance based on [PlatformWebMessageChannelCreationParams].
|
||||
factory MacOSWebMessageChannelCreationParams.fromPlatformWebMessageChannelCreationParams(
|
||||
// Recommended placeholder to prevent being broken by platform interface.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformWebMessageChannelCreationParams params) {
|
||||
return MacOSWebMessageChannelCreationParams(
|
||||
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 MacOSWebMessageChannel extends PlatformWebMessageChannel
|
||||
with ChannelController {
|
||||
/// Constructs a [MacOSWebMessageChannel].
|
||||
MacOSWebMessageChannel(PlatformWebMessageChannelCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSWebMessageChannelCreationParams
|
||||
? params
|
||||
: MacOSWebMessageChannelCreationParams
|
||||
.fromPlatformWebMessageChannelCreationParams(params),
|
||||
) {
|
||||
channel = MethodChannel(
|
||||
'com.pichillilorenzo/flutter_inappwebview_web_message_channel_${params.id}');
|
||||
handler = _handleMethod;
|
||||
initMethodCallHandler();
|
||||
}
|
||||
|
||||
static final MacOSWebMessageChannel _staticValue = MacOSWebMessageChannel(
|
||||
MacOSWebMessageChannelCreationParams(
|
||||
id: '',
|
||||
port1:
|
||||
MacOSWebMessagePort(MacOSWebMessagePortCreationParams(index: 0)),
|
||||
port2: MacOSWebMessagePort(
|
||||
MacOSWebMessagePortCreationParams(index: 1))));
|
||||
|
||||
/// Provide static access.
|
||||
factory MacOSWebMessageChannel.static() {
|
||||
return _staticValue;
|
||||
}
|
||||
|
||||
MacOSWebMessagePort get _macosPort1 => port1 as MacOSWebMessagePort;
|
||||
|
||||
MacOSWebMessagePort get _macosPort2 => port2 as MacOSWebMessagePort;
|
||||
|
||||
static MacOSWebMessageChannel? _fromMap(Map<String, dynamic>? map) {
|
||||
if (map == null) {
|
||||
return null;
|
||||
}
|
||||
var webMessageChannel = MacOSWebMessageChannel(
|
||||
MacOSWebMessageChannelCreationParams(
|
||||
id: map["id"],
|
||||
port1: MacOSWebMessagePort(
|
||||
MacOSWebMessagePortCreationParams(index: 0)),
|
||||
port2: MacOSWebMessagePort(
|
||||
MacOSWebMessagePortCreationParams(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
|
||||
MacOSWebMessageChannel? 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 MacOSWebMessageChannel {
|
||||
MethodChannel? get internalChannel => channel;
|
||||
}
|
|
@ -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 [MacOSWebMessageListener].
|
||||
///
|
||||
/// 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 MacOSWebMessageListenerCreationParams
|
||||
extends PlatformWebMessageListenerCreationParams {
|
||||
/// Creates a new [MacOSWebMessageListenerCreationParams] instance.
|
||||
const MacOSWebMessageListenerCreationParams(
|
||||
{required this.allowedOriginRules,
|
||||
required super.jsObjectName,
|
||||
super.onPostMessage});
|
||||
|
||||
/// Creates a [MacOSWebMessageListenerCreationParams] instance based on [PlatformWebMessageListenerCreationParams].
|
||||
factory MacOSWebMessageListenerCreationParams.fromPlatformWebMessageListenerCreationParams(
|
||||
// Recommended placeholder to prevent being broken by platform interface.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformWebMessageListenerCreationParams params) {
|
||||
return MacOSWebMessageListenerCreationParams(
|
||||
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 MacOSWebMessageListener extends PlatformWebMessageListener
|
||||
with ChannelController {
|
||||
/// Constructs a [MacOSWebMessageListener].
|
||||
MacOSWebMessageListener(PlatformWebMessageListenerCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSWebMessageListenerCreationParams
|
||||
? params
|
||||
: MacOSWebMessageListenerCreationParams
|
||||
.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;
|
||||
|
||||
MacOSWebMessageListenerCreationParams get _macosParams =>
|
||||
params as MacOSWebMessageListenerCreationParams;
|
||||
|
||||
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 [MacOSWebMessageListener].
|
||||
MacOSJavaScriptReplyProxy(PlatformJavaScriptReplyProxyCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSJavaScriptReplyProxyCreationParams
|
||||
? params
|
||||
: MacOSJavaScriptReplyProxyCreationParams
|
||||
.fromPlatformJavaScriptReplyProxyCreationParams(params),
|
||||
);
|
||||
|
||||
MacOSWebMessageListener get _macosWebMessageListener =>
|
||||
params.webMessageListener as MacOSWebMessageListener;
|
||||
|
||||
@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{}';
|
||||
}
|
||||
}
|
|
@ -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 [MacOSWebMessagePort].
|
||||
///
|
||||
/// 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 MacOSWebMessagePortCreationParams
|
||||
extends PlatformWebMessagePortCreationParams {
|
||||
/// Creates a new [MacOSWebMessagePortCreationParams] instance.
|
||||
const MacOSWebMessagePortCreationParams({required super.index});
|
||||
|
||||
/// Creates a [MacOSWebMessagePortCreationParams] instance based on [PlatformWebMessagePortCreationParams].
|
||||
factory MacOSWebMessagePortCreationParams.fromPlatformWebMessagePortCreationParams(
|
||||
// Recommended placeholder to prevent being broken by platform interface.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformWebMessagePortCreationParams params) {
|
||||
return MacOSWebMessagePortCreationParams(index: params.index);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'MacOSWebMessagePortCreationParams{index: $index}';
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformWebMessagePort}
|
||||
class MacOSWebMessagePort extends PlatformWebMessagePort {
|
||||
WebMessageCallback? _onMessage;
|
||||
late MacOSWebMessageChannel _webMessageChannel;
|
||||
|
||||
/// Constructs a [MacOSWebMessagePort].
|
||||
MacOSWebMessagePort(PlatformWebMessagePortCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSWebMessagePortCreationParams
|
||||
? params
|
||||
: MacOSWebMessagePortCreationParams
|
||||
.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 MacOSWebMessagePort {
|
||||
WebMessageCallback? get onMessage => _onMessage;
|
||||
void set onMessage(WebMessageCallback? value) => _onMessage = value;
|
||||
|
||||
MacOSWebMessageChannel get webMessageChannel => _webMessageChannel;
|
||||
void set webMessageChannel(MacOSWebMessageChannel value) =>
|
||||
_webMessageChannel = value;
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
export 'web_storage.dart';
|
||||
export 'web_storage_manager.dart' hide InternalWebStorageManager;
|
|
@ -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 [MacOSWebStorage].
|
||||
///
|
||||
/// 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 MacOSWebStorageCreationParams extends PlatformWebStorageCreationParams {
|
||||
/// Creates a new [MacOSWebStorageCreationParams] instance.
|
||||
MacOSWebStorageCreationParams(
|
||||
{required super.localStorage, required super.sessionStorage});
|
||||
|
||||
/// Creates a [MacOSWebStorageCreationParams] instance based on [PlatformWebStorageCreationParams].
|
||||
factory MacOSWebStorageCreationParams.fromPlatformWebStorageCreationParams(
|
||||
// Recommended placeholder to prevent being broken by platform interface.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformWebStorageCreationParams params) {
|
||||
return MacOSWebStorageCreationParams(
|
||||
localStorage: params.localStorage,
|
||||
sessionStorage: params.sessionStorage);
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformWebStorage}
|
||||
class MacOSWebStorage extends PlatformWebStorage {
|
||||
/// Constructs a [MacOSWebStorage].
|
||||
MacOSWebStorage(PlatformWebStorageCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSWebStorageCreationParams
|
||||
? params
|
||||
: MacOSWebStorageCreationParams
|
||||
.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 [MacOSStorage].
|
||||
///
|
||||
/// 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 MacOSStorageCreationParams extends PlatformStorageCreationParams {
|
||||
/// Creates a new [MacOSStorageCreationParams] instance.
|
||||
MacOSStorageCreationParams(
|
||||
{required super.controller, required super.webStorageType});
|
||||
|
||||
/// Creates a [MacOSStorageCreationParams] instance based on [PlatformStorageCreationParams].
|
||||
factory MacOSStorageCreationParams.fromPlatformStorageCreationParams(
|
||||
// Recommended placeholder to prevent being broken by platform interface.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformStorageCreationParams params) {
|
||||
return MacOSStorageCreationParams(
|
||||
controller: params.controller, webStorageType: params.webStorageType);
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformStorage}
|
||||
abstract class MacOSStorage 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 [MacOSLocalStorage].
|
||||
///
|
||||
/// 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 MacOSLocalStorageCreationParams
|
||||
extends PlatformLocalStorageCreationParams {
|
||||
/// Creates a new [MacOSLocalStorageCreationParams] instance.
|
||||
MacOSLocalStorageCreationParams(super.params);
|
||||
|
||||
/// Creates a [MacOSLocalStorageCreationParams] instance based on [PlatformLocalStorageCreationParams].
|
||||
factory MacOSLocalStorageCreationParams.fromPlatformLocalStorageCreationParams(
|
||||
// Recommended placeholder to prevent being broken by platform interface.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformLocalStorageCreationParams params) {
|
||||
return MacOSLocalStorageCreationParams(params);
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformLocalStorage}
|
||||
class MacOSLocalStorage extends PlatformLocalStorage with MacOSStorage {
|
||||
/// Constructs a [MacOSLocalStorage].
|
||||
MacOSLocalStorage(PlatformLocalStorageCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSLocalStorageCreationParams
|
||||
? params
|
||||
: MacOSLocalStorageCreationParams
|
||||
.fromPlatformLocalStorageCreationParams(params),
|
||||
);
|
||||
|
||||
/// Default storage
|
||||
factory MacOSLocalStorage.defaultStorage(
|
||||
{required PlatformInAppWebViewController? controller}) {
|
||||
return MacOSLocalStorage(MacOSLocalStorageCreationParams(
|
||||
PlatformLocalStorageCreationParams(PlatformStorageCreationParams(
|
||||
controller: controller,
|
||||
webStorageType: WebStorageType.LOCAL_STORAGE))));
|
||||
}
|
||||
|
||||
@override
|
||||
WindowsInAppWebViewController? get controller =>
|
||||
params.controller as WindowsInAppWebViewController?;
|
||||
}
|
||||
|
||||
/// Object specifying creation parameters for creating a [MacOSSessionStorage].
|
||||
///
|
||||
/// 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 MacOSSessionStorageCreationParams
|
||||
extends PlatformSessionStorageCreationParams {
|
||||
/// Creates a new [MacOSSessionStorageCreationParams] instance.
|
||||
MacOSSessionStorageCreationParams(super.params);
|
||||
|
||||
/// Creates a [MacOSSessionStorageCreationParams] instance based on [PlatformSessionStorageCreationParams].
|
||||
factory MacOSSessionStorageCreationParams.fromPlatformSessionStorageCreationParams(
|
||||
// Recommended placeholder to prevent being broken by platform interface.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformSessionStorageCreationParams params) {
|
||||
return MacOSSessionStorageCreationParams(params);
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformSessionStorage}
|
||||
class MacOSSessionStorage extends PlatformSessionStorage with MacOSStorage {
|
||||
/// Constructs a [MacOSSessionStorage].
|
||||
MacOSSessionStorage(PlatformSessionStorageCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSSessionStorageCreationParams
|
||||
? params
|
||||
: MacOSSessionStorageCreationParams
|
||||
.fromPlatformSessionStorageCreationParams(params),
|
||||
);
|
||||
|
||||
/// Default storage
|
||||
factory MacOSSessionStorage.defaultStorage(
|
||||
{required PlatformInAppWebViewController? controller}) {
|
||||
return MacOSSessionStorage(MacOSSessionStorageCreationParams(
|
||||
PlatformSessionStorageCreationParams(PlatformStorageCreationParams(
|
||||
controller: controller,
|
||||
webStorageType: WebStorageType.SESSION_STORAGE))));
|
||||
}
|
||||
|
||||
@override
|
||||
WindowsInAppWebViewController? get controller =>
|
||||
params.controller as WindowsInAppWebViewController?;
|
||||
}
|
|
@ -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 [MacOSWebStorageManager].
|
||||
///
|
||||
/// 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 MacOSWebStorageManagerCreationParams
|
||||
extends PlatformWebStorageManagerCreationParams {
|
||||
/// Creates a new [MacOSWebStorageManagerCreationParams] instance.
|
||||
const MacOSWebStorageManagerCreationParams(
|
||||
// This parameter prevents breaking changes later.
|
||||
// ignore: avoid_unused_constructor_parameters
|
||||
PlatformWebStorageManagerCreationParams params,
|
||||
) : super();
|
||||
|
||||
/// Creates a [MacOSWebStorageManagerCreationParams] instance based on [PlatformWebStorageManagerCreationParams].
|
||||
factory MacOSWebStorageManagerCreationParams.fromPlatformWebStorageManagerCreationParams(
|
||||
PlatformWebStorageManagerCreationParams params) {
|
||||
return MacOSWebStorageManagerCreationParams(params);
|
||||
}
|
||||
}
|
||||
|
||||
///{@macro flutter_inappwebview_platform_interface.PlatformWebStorageManager}
|
||||
class MacOSWebStorageManager extends PlatformWebStorageManager
|
||||
with ChannelController {
|
||||
/// Creates a new [MacOSWebStorageManager].
|
||||
MacOSWebStorageManager(PlatformWebStorageManagerCreationParams params)
|
||||
: super.implementation(
|
||||
params is MacOSWebStorageManagerCreationParams
|
||||
? params
|
||||
: MacOSWebStorageManagerCreationParams
|
||||
.fromPlatformWebStorageManagerCreationParams(params),
|
||||
) {
|
||||
channel = const MethodChannel(
|
||||
'com.pichillilorenzo/flutter_inappwebview_webstoragemanager');
|
||||
handler = handleMethod;
|
||||
initMethodCallHandler();
|
||||
}
|
||||
|
||||
static MacOSWebStorageManager? _instance;
|
||||
|
||||
///Gets the WebStorage manager shared instance.
|
||||
static MacOSWebStorageManager instance() {
|
||||
return (_instance != null) ? _instance! : _init();
|
||||
}
|
||||
|
||||
static MacOSWebStorageManager _init() {
|
||||
_instance = MacOSWebStorageManager(MacOSWebStorageManagerCreationParams(
|
||||
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 MacOSWebStorageManager {
|
||||
get handleMethod => _handleMethod;
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
name: flutter_inappwebview_windows
|
||||
description: Windows implementation of the flutter_inappwebview plugin.
|
||||
version: 1.0.11
|
||||
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
|
||||
topics:
|
||||
- html
|
||||
- webview
|
||||
- webview-flutter
|
||||
- inappwebview
|
||||
- browser
|
||||
|
||||
environment:
|
||||
sdk: ">=2.17.0 <4.0.0"
|
||||
flutter: ">=3.0.0"
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
flutter_inappwebview_platform_interface: ^1.0.10
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
flutter_lints: ^2.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-packages
|
|
@ -0,0 +1,19 @@
|
|||
flutter/
|
||||
|
||||
# Visual Studio user-specific files.
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# Visual Studio build-related files.
|
||||
x64/
|
||||
x86/
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!*.[Cc]ache/
|
||||
|
||||
packages/
|
|
@ -0,0 +1,151 @@
|
|||
# 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.2210.55")
|
||||
|
||||
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")
|
||||
|
||||
set(NUGET_URL https://dist.nuget.org/win-x86-commandline/latest/nuget.exe)
|
||||
set(NUGET_SHA256 852b71cc8c8c2d40d09ea49d321ff56fd2397b9d6ea9f96e532530307bbbafd3)
|
||||
|
||||
find_program(NUGET nuget)
|
||||
if(NOT NUGET)
|
||||
message(NOTICE "Nuget is not installed.")
|
||||
set(NUGET ${CMAKE_BINARY_DIR}/nuget.exe)
|
||||
if (NOT EXISTS ${NUGET})
|
||||
message(NOTICE "Attempting to download nuget.")
|
||||
file(DOWNLOAD ${NUGET_URL} ${NUGET})
|
||||
endif()
|
||||
|
||||
file(SHA256 ${NUGET} NUGET_DL_HASH)
|
||||
if (NOT NUGET_DL_HASH STREQUAL NUGET_SHA256)
|
||||
message(FATAL_ERROR "Integrity check for ${NUGET} failed.")
|
||||
endif()
|
||||
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
|
||||
DEPENDS ${NUGET}
|
||||
)
|
||||
|
||||
# Any new source files that you add to the plugin should be added here.
|
||||
list(APPEND PLUGIN_SOURCES
|
||||
"flutter_inappwebview_windows_base_plugin.h"
|
||||
"flutter_inappwebview_windows_base_plugin.cpp"
|
||||
"flutter_inappwebview_windows_plugin.cpp"
|
||||
"flutter_inappwebview_windows_plugin.h"
|
||||
"utils/strconv.h"
|
||||
"utils/util.h"
|
||||
"types/channel_delegate.cpp"
|
||||
"types/channel_delegate.h"
|
||||
"types/url_request.cpp"
|
||||
"types/url_request.h"
|
||||
"in_app_webview/in_app_webview.cpp"
|
||||
"in_app_webview/in_app_webview.h"
|
||||
"in_app_webview/webview_channel_delegate.cpp"
|
||||
"in_app_webview/webview_channel_delegate.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"
|
||||
)
|
||||
|
||||
# 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}
|
||||
)
|
||||
|
||||
# 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})
|
||||
|
||||
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)
|
||||
|
||||
# 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()
|
|
@ -0,0 +1,14 @@
|
|||
#include "flutter_inappwebview_windows_base_plugin.h"
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
FlutterInappwebviewWindowsBasePlugin::FlutterInappwebviewWindowsBasePlugin(flutter::PluginRegistrarWindows* registrar) : registrar(registrar)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
FlutterInappwebviewWindowsBasePlugin::~FlutterInappwebviewWindowsBasePlugin()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_BASE_PLUGIN_H_
|
||||
#define FLUTTER_INAPPWEBVIEW_PLUGIN_BASE_PLUGIN_H_
|
||||
|
||||
#include <flutter/plugin_registrar_windows.h>
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
class FlutterInappwebviewWindowsBasePlugin : public flutter::Plugin, public std::enable_shared_from_this<FlutterInappwebviewWindowsBasePlugin> {
|
||||
public:
|
||||
flutter::PluginRegistrarWindows* registrar;
|
||||
|
||||
FlutterInappwebviewWindowsBasePlugin(flutter::PluginRegistrarWindows* registrar);
|
||||
|
||||
virtual ~FlutterInappwebviewWindowsBasePlugin();
|
||||
};
|
||||
}
|
||||
|
||||
#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_BASE_PLUGIN_H_
|
|
@ -0,0 +1,35 @@
|
|||
#include "flutter_inappwebview_windows_plugin.h"
|
||||
|
||||
// This must be included before many other Windows headers.
|
||||
#include <windows.h>
|
||||
|
||||
// For getPlatformVersion; remove unless needed for your plugin implementation.
|
||||
#include <VersionHelpers.h>
|
||||
|
||||
#include <flutter/method_channel.h>
|
||||
#include <flutter/plugin_registrar_windows.h>
|
||||
#include <flutter/standard_method_codec.h>
|
||||
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
|
||||
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)
|
||||
: FlutterInappwebviewWindowsBasePlugin(registrar)
|
||||
{
|
||||
inAppBrowserManager = std::make_unique<InAppBrowserManager>(this);
|
||||
}
|
||||
|
||||
FlutterInappwebviewWindowsPlugin::~FlutterInappwebviewWindowsPlugin()
|
||||
{
|
||||
inAppBrowserManager.release();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
#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>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "flutter_inappwebview_windows_base_plugin.h"
|
||||
|
||||
#include "in_app_browser/in_app_browser_manager.h"
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
class FlutterInappwebviewWindowsPlugin : public FlutterInappwebviewWindowsBasePlugin {
|
||||
public:
|
||||
std::unique_ptr<InAppBrowserManager> inAppBrowserManager;
|
||||
|
||||
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_
|
|
@ -0,0 +1,12 @@
|
|||
#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));
|
||||
}
|
|
@ -0,0 +1,238 @@
|
|||
#include <Windows.h>
|
||||
#include "in_app_browser.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
|
||||
#include "flutter/event_channel.h"
|
||||
#include "flutter/plugin_registrar.h"
|
||||
#include "flutter/plugin_registrar_windows.h"
|
||||
#include "flutter/method_channel.h"
|
||||
#include "flutter/encodable_value.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string>
|
||||
#include <tchar.h>
|
||||
#include <wil/wrl.h>
|
||||
#include <wil/com.h>
|
||||
#include "../utils/strconv.h"
|
||||
|
||||
#include <WebView2.h>
|
||||
#include <WebView2EnvironmentOptions.h>
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
using namespace Microsoft::WRL;
|
||||
|
||||
const wchar_t* CLASS_NAME = L"InAppBrowser";
|
||||
|
||||
InAppBrowser::InAppBrowser(FlutterInappwebviewWindowsBasePlugin* plugin, const InAppBrowserCreationParams& params)
|
||||
: plugin(plugin),
|
||||
m_hInstance(GetModuleHandle(nullptr)),
|
||||
id(params.id),
|
||||
initialUrlRequest(params.urlRequest),
|
||||
channelDelegate(std::make_unique<InAppBrowserChannelDelegate>(id, plugin->registrar->messenger()))
|
||||
{
|
||||
WNDCLASS wndClass = {};
|
||||
wndClass.lpszClassName = CLASS_NAME;
|
||||
wndClass.hInstance = m_hInstance;
|
||||
wndClass.hIcon = LoadIcon(NULL, IDI_WINLOGO);
|
||||
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
|
||||
wndClass.lpfnWndProc = InAppBrowser::WndProc;
|
||||
|
||||
RegisterClass(&wndClass);
|
||||
|
||||
m_hWnd = CreateWindowEx(
|
||||
0, // Optional window styles.
|
||||
CLASS_NAME, // Window class
|
||||
L"Learn to Program Windows", // Window text
|
||||
WS_OVERLAPPEDWINDOW, // Window style
|
||||
|
||||
// Size and position
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
|
||||
|
||||
NULL, // Parent window
|
||||
NULL, // Menu
|
||||
m_hInstance,// Instance handle
|
||||
this // Additional application data
|
||||
);
|
||||
|
||||
ShowWindow(m_hWnd, SW_SHOW);
|
||||
|
||||
webView = std::make_unique<InAppWebView>(plugin, id, m_hWnd, InAppBrowser::METHOD_CHANNEL_NAME_PREFIX + id, [this]() -> void {
|
||||
if (channelDelegate) {
|
||||
channelDelegate->onBrowserCreated();
|
||||
}
|
||||
|
||||
if (initialUrlRequest.has_value()) {
|
||||
webView->loadUrl(initialUrlRequest.value());
|
||||
}
|
||||
});
|
||||
|
||||
// <-- WebView2 sample code starts here -->
|
||||
// Step 3 - Create a single WebView within the parent window
|
||||
// Locate the browser and set up the environment for WebView
|
||||
//CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
|
||||
// Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
|
||||
// [hWnd = m_hWnd, inAppBrowser = this](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {
|
||||
|
||||
// // Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd
|
||||
// env->CreateCoreWebView2Controller(hWnd, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
|
||||
// [hWnd, inAppBrowser](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
|
||||
// if (controller != nullptr) {
|
||||
// inAppBrowser->webviewController = controller;
|
||||
// inAppBrowser->webviewController->get_CoreWebView2(&inAppBrowser->webview);
|
||||
// }
|
||||
|
||||
// // Add a few settings for the webview
|
||||
// // The demo step is redundant since the values are the default settings
|
||||
// wil::com_ptr<ICoreWebView2Settings> settings;
|
||||
// inAppBrowser->webview->get_Settings(&settings);
|
||||
// settings->put_IsScriptEnabled(TRUE);
|
||||
// settings->put_AreDefaultScriptDialogsEnabled(TRUE);
|
||||
// settings->put_IsWebMessageEnabled(TRUE);
|
||||
|
||||
// // Resize WebView to fit the bounds of the parent window
|
||||
// RECT bounds;
|
||||
// GetClientRect(hWnd, &bounds);
|
||||
// inAppBrowser->webviewController->put_Bounds(bounds);
|
||||
|
||||
// auto url = inAppBrowser->initialUrlRequest.value().url.value();
|
||||
// std::wstring stemp = ansi_to_wide(url);
|
||||
|
||||
// // Schedule an async task to navigate to Bing
|
||||
// inAppBrowser->webview->Navigate(stemp.c_str());
|
||||
|
||||
// // <NavigationEvents>
|
||||
// // Step 4 - Navigation events
|
||||
// // register an ICoreWebView2NavigationStartingEventHandler to cancel any non-https navigation
|
||||
// EventRegistrationToken token;
|
||||
// inAppBrowser->webview->add_NavigationStarting(Callback<ICoreWebView2NavigationStartingEventHandler>(
|
||||
// [](ICoreWebView2* webview, ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT {
|
||||
// wil::unique_cotaskmem_string uri;
|
||||
// args->get_Uri(&uri);
|
||||
// std::wstring source(uri.get());
|
||||
// if (source.substr(0, 5) != L"https") {
|
||||
// args->put_Cancel(true);
|
||||
// }
|
||||
// return S_OK;
|
||||
// }).Get(), &token);
|
||||
// // </NavigationEvents>
|
||||
|
||||
// // <Scripting>
|
||||
// // Step 5 - Scripting
|
||||
// // Schedule an async task to add initialization script that freezes the Object object
|
||||
// inAppBrowser->webview->AddScriptToExecuteOnDocumentCreated(L"Object.freeze(Object);", nullptr);
|
||||
// // Schedule an async task to get the document URL
|
||||
// inAppBrowser->webview->ExecuteScript(L"window.document.URL;", Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
|
||||
// [](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT {
|
||||
// LPCWSTR URL = resultObjectAsJson;
|
||||
// OutputDebugStringW(URL);
|
||||
// //doSomethingWithURL(URL);
|
||||
// return S_OK;
|
||||
// }).Get());
|
||||
// // </Scripting>
|
||||
|
||||
// // <CommunicationHostWeb>
|
||||
// // Step 6 - Communication between host and web content
|
||||
// // Set an event handler for the host to return received message back to the web content
|
||||
// inAppBrowser->webview->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(
|
||||
// [](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT {
|
||||
// wil::unique_cotaskmem_string message;
|
||||
// args->TryGetWebMessageAsString(&message);
|
||||
// // processMessage(&message);
|
||||
// webview->PostWebMessageAsString(message.get());
|
||||
// return S_OK;
|
||||
// }).Get(), &token);
|
||||
|
||||
// // Schedule an async task to add initialization script that
|
||||
// // 1) Add an listener to print message from the host
|
||||
// // 2) Post document URL to the host
|
||||
// inAppBrowser->webview->AddScriptToExecuteOnDocumentCreated(
|
||||
// L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \
|
||||
// L"window.chrome.webview.postMessage(window.document.URL);",
|
||||
// nullptr);
|
||||
// // </CommunicationHostWeb>
|
||||
|
||||
// return S_OK;
|
||||
// }).Get());
|
||||
// return S_OK;
|
||||
// }).Get());
|
||||
}
|
||||
|
||||
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: {
|
||||
webView.reset();
|
||||
|
||||
// might receive multiple WM_DESTROY messages.
|
||||
if (!destroyed_) {
|
||||
destroyed_ = true;
|
||||
|
||||
if (channelDelegate) {
|
||||
channelDelegate->onExit();
|
||||
}
|
||||
}
|
||||
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()
|
||||
{
|
||||
std::cout << "dealloc InAppBrowser\n";
|
||||
webView.reset();
|
||||
SetWindowLongPtr(m_hWnd, GWLP_USERDATA, 0);
|
||||
plugin = nullptr;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_H_
|
||||
#define FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_H_
|
||||
|
||||
#include <Windows.h>
|
||||
#include <string>
|
||||
#include <optional>
|
||||
|
||||
#include <wil/com.h>
|
||||
#include "../flutter_inappwebview_windows_base_plugin.h"
|
||||
#include "../in_app_webview/in_app_webview.h"
|
||||
#include "../types/url_request.h"
|
||||
#include "in_app_browser_channel_delegate.h"
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
struct InAppBrowserCreationParams
|
||||
{
|
||||
std::string id;
|
||||
std::optional<URLRequest> urlRequest;
|
||||
};
|
||||
|
||||
class InAppBrowser {
|
||||
public:
|
||||
static inline const std::string METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_inappbrowser_";
|
||||
|
||||
static LRESULT CALLBACK WndProc(HWND window,
|
||||
UINT message,
|
||||
WPARAM wparam,
|
||||
LPARAM lparam) noexcept;
|
||||
|
||||
FlutterInappwebviewWindowsBasePlugin* plugin;
|
||||
std::string id;
|
||||
std::optional<URLRequest> initialUrlRequest;
|
||||
std::unique_ptr<InAppWebView> webView;
|
||||
std::unique_ptr<InAppBrowserChannelDelegate> channelDelegate;
|
||||
|
||||
InAppBrowser(FlutterInappwebviewWindowsBasePlugin* plugin, const InAppBrowserCreationParams& params);
|
||||
~InAppBrowser();
|
||||
|
||||
private:
|
||||
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_
|
|
@ -0,0 +1,40 @@
|
|||
#include "in_app_browser.h"
|
||||
#include "in_app_browser_channel_delegate.h"
|
||||
|
||||
#include "../utils/util.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()
|
||||
{
|
||||
std::cout << "dealloc InAppBrowserChannelDelegate\n";
|
||||
}
|
||||
}
|
|
@ -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_
|
|
@ -0,0 +1,56 @@
|
|||
#include <memory>
|
||||
#include <flutter/method_channel.h>
|
||||
#include <flutter/standard_method_codec.h>
|
||||
|
||||
#include "in_app_browser_manager.h"
|
||||
|
||||
#include "../types/url_request.h"
|
||||
|
||||
#include "../utils/util.h"
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
InAppBrowserManager::InAppBrowserManager(FlutterInappwebviewWindowsBasePlugin* 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)
|
||||
{
|
||||
if (method_call.method_name().compare("open") == 0) {
|
||||
auto* arguments = std::get_if<flutter::EncodableMap>(method_call.arguments());
|
||||
open(arguments);
|
||||
result->Success(flutter::EncodableValue(true));
|
||||
}
|
||||
else {
|
||||
result->NotImplemented();
|
||||
}
|
||||
}
|
||||
|
||||
void InAppBrowserManager::open(const flutter::EncodableMap* arguments)
|
||||
{
|
||||
auto id = std::get<std::string>(arguments->at(flutter::EncodableValue("id")));
|
||||
auto urlRequestMap = std::get_if<flutter::EncodableMap>(&arguments->at(flutter::EncodableValue("urlRequest")));
|
||||
auto urlRequest = make_pointer_optional<URLRequest>(new URLRequest(*urlRequestMap));
|
||||
|
||||
InAppBrowserCreationParams params = {
|
||||
id,
|
||||
urlRequest
|
||||
};
|
||||
auto inAppBrowser = std::make_unique<InAppBrowser>(plugin, params);
|
||||
browsers[id] = std::move(inAppBrowser);
|
||||
}
|
||||
|
||||
InAppBrowserManager::~InAppBrowserManager()
|
||||
{
|
||||
std::cout << "dealloc InAppBrowserManager\n";
|
||||
for (std::map<std::string, std::unique_ptr<InAppBrowser>>::iterator itr = browsers.begin(); itr != browsers.end(); itr++)
|
||||
{
|
||||
browsers.erase(itr->first);
|
||||
}
|
||||
browsers.clear();
|
||||
plugin = nullptr;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
#ifndef FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_MANAGER_H_
|
||||
#define FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_MANAGER_H_
|
||||
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <flutter/method_channel.h>
|
||||
#include <flutter/standard_message_codec.h>
|
||||
|
||||
#include "../flutter_inappwebview_windows_base_plugin.h"
|
||||
|
||||
#include "in_app_browser.h"
|
||||
|
||||
#include "../types/channel_delegate.h"
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
class InAppBrowserManager : public ChannelDelegate
|
||||
{
|
||||
public:
|
||||
static inline const std::string METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappbrowser";
|
||||
|
||||
FlutterInappwebviewWindowsBasePlugin* plugin;
|
||||
std::map<std::string, std::unique_ptr<InAppBrowser>> browsers;
|
||||
|
||||
InAppBrowserManager(FlutterInappwebviewWindowsBasePlugin* plugin);
|
||||
~InAppBrowserManager();
|
||||
|
||||
void HandleMethodCall(
|
||||
const flutter::MethodCall<flutter::EncodableValue>& method_call,
|
||||
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
|
||||
|
||||
void open(const flutter::EncodableMap* arguments);
|
||||
};
|
||||
}
|
||||
#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_BROWSER_MANAGER_H_
|
|
@ -0,0 +1,114 @@
|
|||
#include "in_app_webview.h"
|
||||
#include <WebView2EnvironmentOptions.h>
|
||||
#include <wil/wrl.h>
|
||||
#include "../utils/strconv.h"
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
using namespace Microsoft::WRL;
|
||||
|
||||
InAppWebView::InAppWebView(FlutterInappwebviewWindowsBasePlugin* plugin, std::variant<std::string, int> id, const HWND parentWindow, const std::function<void()> completionHandler)
|
||||
: plugin(plugin), id(id), channelDelegate(std::make_unique<WebViewChannelDelegate>(this, plugin->registrar->messenger()))
|
||||
{
|
||||
createWebView(parentWindow, completionHandler);
|
||||
}
|
||||
|
||||
InAppWebView::InAppWebView(FlutterInappwebviewWindowsBasePlugin* plugin, std::variant<std::string, int> id, const HWND parentWindow, const std::string& channelName, const std::function<void()> completionHandler)
|
||||
: plugin(plugin), id(id), channelDelegate(std::make_unique<WebViewChannelDelegate>(this, plugin->registrar->messenger(), channelName))
|
||||
{
|
||||
createWebView(parentWindow, completionHandler);
|
||||
}
|
||||
|
||||
void InAppWebView::createWebView(const HWND parentWindow, const std::function<void()> completionHandler)
|
||||
{
|
||||
CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
|
||||
Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
|
||||
[parentWindow, completionHandler, this](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {
|
||||
// Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd
|
||||
env->CreateCoreWebView2Controller(parentWindow, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
|
||||
[parentWindow, completionHandler, this](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
|
||||
if (controller != nullptr) {
|
||||
webViewController = controller;
|
||||
webViewController->get_CoreWebView2(webView.put());
|
||||
}
|
||||
|
||||
// Resize WebView to fit the bounds of the parent window
|
||||
RECT bounds;
|
||||
GetClientRect(parentWindow, &bounds);
|
||||
webViewController->put_Bounds(bounds);
|
||||
|
||||
registerEventHandlers();
|
||||
|
||||
completionHandler();
|
||||
|
||||
return S_OK;
|
||||
}).Get());
|
||||
return S_OK;
|
||||
}).Get());
|
||||
}
|
||||
|
||||
void InAppWebView::registerEventHandlers()
|
||||
{
|
||||
if (!webView) {
|
||||
return;
|
||||
}
|
||||
|
||||
webView->add_NavigationStarting(
|
||||
Callback<ICoreWebView2NavigationStartingEventHandler>(
|
||||
[this](ICoreWebView2* sender, ICoreWebView2NavigationStartingEventArgs* args) {
|
||||
if (channelDelegate) {
|
||||
LPWSTR uri = nullptr;
|
||||
std::optional<std::string> url = SUCCEEDED(args->get_Uri(&uri)) ? wide_to_utf8(std::wstring(uri)) : std::optional<std::string>{};
|
||||
channelDelegate->onLoadStart(url);
|
||||
}
|
||||
|
||||
args->put_Cancel(false);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
).Get(), nullptr);
|
||||
|
||||
webView->add_NavigationCompleted(
|
||||
Callback<ICoreWebView2NavigationCompletedEventHandler>(
|
||||
[this](ICoreWebView2* sender, ICoreWebView2NavigationCompletedEventArgs* args) {
|
||||
if (channelDelegate) {
|
||||
LPWSTR uri = nullptr;
|
||||
std::optional<std::string> url = SUCCEEDED(webView->get_Source(&uri)) ? wide_to_utf8(std::wstring(uri)) : std::optional<std::string>{};
|
||||
channelDelegate->onLoadStop(url);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
).Get(), nullptr);
|
||||
}
|
||||
|
||||
std::optional<std::string> InAppWebView::getUrl() const
|
||||
{
|
||||
LPWSTR uri = nullptr;
|
||||
return SUCCEEDED(webView->get_Source(&uri)) ? wide_to_utf8(std::wstring(uri)) : std::optional<std::string>{};
|
||||
}
|
||||
|
||||
void InAppWebView::loadUrl(const URLRequest urlRequest) const
|
||||
{
|
||||
if (!webView) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto url = urlRequest.url.value();
|
||||
std::wstring stemp = ansi_to_wide(url);
|
||||
|
||||
// Schedule an async task to navigate to Bing
|
||||
webView->Navigate(stemp.c_str());
|
||||
}
|
||||
|
||||
InAppWebView::~InAppWebView()
|
||||
{
|
||||
std::cout << "dealloc InAppWebView\n";
|
||||
if (webView) {
|
||||
webView->Stop();
|
||||
}
|
||||
if (webViewController) {
|
||||
webViewController->Close();
|
||||
}
|
||||
plugin = nullptr;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
#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 "../types/url_request.h"
|
||||
#include "webview_channel_delegate.h"
|
||||
#include "../flutter_inappwebview_windows_base_plugin.h"
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
using namespace Microsoft::WRL;
|
||||
|
||||
class InAppWebView
|
||||
{
|
||||
public:
|
||||
static inline const std::string METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_inappwebview_";
|
||||
|
||||
FlutterInappwebviewWindowsBasePlugin* plugin;
|
||||
std::variant<std::string, int> id;
|
||||
wil::com_ptr<ICoreWebView2Controller> webViewController;
|
||||
wil::com_ptr<ICoreWebView2> webView;
|
||||
std::unique_ptr<WebViewChannelDelegate> channelDelegate;
|
||||
|
||||
InAppWebView(FlutterInappwebviewWindowsBasePlugin* plugin, std::variant<std::string, int> id, const HWND parentWindow, const std::function<void()> completionHandler);
|
||||
InAppWebView(FlutterInappwebviewWindowsBasePlugin* plugin, std::variant<std::string, int> id, const HWND parentWindow, const std::string& channelName, const std::function<void()> completionHandler);
|
||||
~InAppWebView();
|
||||
|
||||
std::optional<std::string> getUrl() const;
|
||||
void loadUrl(const URLRequest urlRequest) const;
|
||||
|
||||
private:
|
||||
void createWebView(const HWND parentWindow, const std::function<void()> completionHandler);
|
||||
void InAppWebView::registerEventHandlers();
|
||||
};
|
||||
}
|
||||
#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_IN_APP_WEBVIEW_H_
|
|
@ -0,0 +1,67 @@
|
|||
#include "in_app_webview.h"
|
||||
#include "webview_channel_delegate.h"
|
||||
|
||||
#include "../utils/util.h"
|
||||
#include "../utils/strconv.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)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void WebViewChannelDelegate::HandleMethodCall(const flutter::MethodCall<flutter::EncodableValue>& method_call,
|
||||
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)
|
||||
{
|
||||
if (!webView) {
|
||||
result->Success();
|
||||
return;
|
||||
}
|
||||
|
||||
if (method_call.method_name().compare("getUrl") == 0) {
|
||||
std::optional<std::string> url = webView->getUrl();
|
||||
result->Success(url.has_value() ? flutter::EncodableValue(url.value()) : flutter::EncodableValue());
|
||||
}
|
||||
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 {
|
||||
{flutter::EncodableValue("url"), url.has_value() ? flutter::EncodableValue(url.value()) : flutter::EncodableValue()},
|
||||
});
|
||||
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{
|
||||
{flutter::EncodableValue("url"), url.has_value() ? flutter::EncodableValue(url.value()) : flutter::EncodableValue()},
|
||||
});
|
||||
channel->InvokeMethod("onLoadStop", std::move(arguments));
|
||||
}
|
||||
|
||||
WebViewChannelDelegate::~WebViewChannelDelegate()
|
||||
{
|
||||
std::cout << "dealloc WebViewChannelDelegate\n";
|
||||
webView = nullptr;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
#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/channel_delegate.h"
|
||||
|
||||
namespace flutter_inappwebview_plugin
|
||||
{
|
||||
class InAppWebView;
|
||||
|
||||
class WebViewChannelDelegate : public ChannelDelegate
|
||||
{
|
||||
public:
|
||||
InAppWebView* webView;
|
||||
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
#endif //FLUTTER_INAPPWEBVIEW_PLUGIN_WEBVIEW_CHANNEL_DELEGATE_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_
|
|
@ -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_windows
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue