diff --git a/packages/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt index db85ca71b11f..a18d1c3f6291 100644 --- a/packages/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/windows/CMakeLists.txt @@ -65,6 +65,7 @@ list(APPEND PLUGIN_SOURCES "firebase_core_plugin.h" "messages.g.cpp" "messages.g.h" + "firebase_plugin_registry.cpp" ) # Read version from pubspec.yaml @@ -89,6 +90,7 @@ include_directories(${CMAKE_BINARY_DIR}/generated/) # on PLUGIN_NAME above). add_library(${PLUGIN_NAME} STATIC "include/firebase_core/firebase_core_plugin_c_api.h" + "include/firebase_core/firebase_plugin_registry.h" "firebase_core_plugin_c_api.cpp" ${PLUGIN_SOURCES} ${CMAKE_BINARY_DIR}/generated/firebase_core/plugin_version.h @@ -120,7 +122,7 @@ add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) target_include_directories(${PLUGIN_NAME} INTERFACE "${FIREBASE_CPP_SDK_DIR}/include") -set(FIREBASE_RELEASE_PATH_LIBS firebase_app firebase_auth firebase_storage firebase_firestore) +set(FIREBASE_RELEASE_PATH_LIBS firebase_app firebase_auth firebase_storage firebase_firestore firebase_remote_config) foreach(firebase_lib IN ITEMS ${FIREBASE_RELEASE_PATH_LIBS}) get_target_property(firebase_lib_path ${firebase_lib} IMPORTED_LOCATION) string(REPLACE "Debug" "Release" firebase_lib_release_path ${firebase_lib_path}) diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index f6c9ded368f5..6c235dba0cce 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -16,6 +16,7 @@ #include #include #include +#include "include/firebase_core/firebase_plugin_registry.h" #include #include @@ -95,12 +96,40 @@ CoreFirebaseOptions optionsFromFIROptions(const firebase::AppOptions &options) { // Convert a firebase::App to CoreInitializeResponse CoreInitializeResponse AppToCoreInitializeResponse(const App &app) { + + auto firebaseRegistry = FirebasePluginRegistry::GetInstance(); + std::vector>& values = firebaseRegistry->p_constants(); + flutter::EncodableMap plugin_constants; + + for (const std::shared_ptr &val: values) { + flutter::EncodableMap constants = val->get_plugin_constants(app); + plugin_constants[flutter::EncodableValue(val->plugin_name().c_str())] = flutter::EncodableValue(constants); + } + CoreInitializeResponse response = CoreInitializeResponse( app.name(), optionsFromFIROptions(app.options()), plugin_constants); return response; } +// PigeonInitializeResponse AppToPigeonInitializeResponse(const App &app) { +// PigeonInitializeResponse response = PigeonInitializeResponse(); + +// auto firebaseRegistry = FirebasePluginRegistry::GetInstance(); +// std::vector>& values = firebaseRegistry->p_constants(); + +// response.set_name(app.name()); +// response.set_options(optionsFromFIROptions(app.options())); + +// flutter::EncodableMap result; + +// for (const std::shared_ptr &val: values) { +// flutter::EncodableMap constants = val->get_plugin_constants(app); +// result[flutter::EncodableValue(val->plugin_name().c_str())] = flutter::EncodableValue(constants); +// } + +// response.set_plugin_constants(result); + void FirebaseCorePlugin::InitializeApp( const std::string &app_name, const CoreFirebaseOptions &initialize_app_request, diff --git a/packages/firebase_core/firebase_core/windows/firebase_plugin_registry.cpp b/packages/firebase_core/firebase_core/windows/firebase_plugin_registry.cpp new file mode 100644 index 000000000000..68cead007b84 --- /dev/null +++ b/packages/firebase_core/firebase_core/windows/firebase_plugin_registry.cpp @@ -0,0 +1,27 @@ +// +// Created by Andrii on 13.01.2024. +// + +#include "include/firebase_core/firebase_plugin_registry.h" +#include "firebase/app.h" + +extern firebase_core_windows::FirebasePluginRegistry* registry_instance_ = nullptr; + +namespace firebase_core_windows { + + FirebasePluginRegistry* FirebasePluginRegistry::GetInstance() { + if (registry_instance_ == nullptr) { + registry_instance_ = new FirebasePluginRegistry(); + } + + return registry_instance_; + } + + void FirebasePluginRegistry::put_plugin_ref(std::shared_ptr plugin) { + this->pConstants_.push_back(plugin); + } + + std::vector>& FirebasePluginRegistry::p_constants() { + return pConstants_; + } +} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_plugin_registry.h b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_plugin_registry.h new file mode 100644 index 000000000000..c6a6482b0602 --- /dev/null +++ b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_plugin_registry.h @@ -0,0 +1,46 @@ +// +// Created by Andrii on 13.01.2024. +// + +#ifndef TODO_POINTS_FIREBASE_PLUGIN_REGISTRY_H +#define TODO_POINTS_FIREBASE_PLUGIN_REGISTRY_H + +#ifdef BUILDING_SHARED_DLL +#define DLL_EXPORT __declspec(dllexport) +#else +#define DLL_EXPORT __declspec(dllimport) +#endif + +#include "../../messages.g.h" +#include "firebase/app.h" +#include +#include +#include "flutter_firebase_plugin.h" +#include +#include +#include +#include + +namespace firebase_core_windows { + + class FirebasePluginRegistry { + public: + + static FirebasePluginRegistry *GetInstance(); + + void put_plugin_ref(std::shared_ptr ); + + std::vector > &p_constants(); + + std::string app_name; + + private: + FirebasePluginRegistry() { + pConstants_ = {}; + } + std::vector > pConstants_; + friend class FirebaseCorePlugin; + }; + +} +#endif //TODO_POINTS_FIREBASE_PLUGIN_REGISTRY_H \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/windows/include/firebase_core/flutter_firebase_plugin.h b/packages/firebase_core/firebase_core/windows/include/firebase_core/flutter_firebase_plugin.h new file mode 100644 index 000000000000..ee13e9631249 --- /dev/null +++ b/packages/firebase_core/firebase_core/windows/include/firebase_core/flutter_firebase_plugin.h @@ -0,0 +1,21 @@ +// +// Created by Andrii on 13.01.2024. +// + +#ifndef TODO_POINTS_FLUTTER_FIREBASE_PLUGIN_H +#define TODO_POINTS_FLUTTER_FIREBASE_PLUGIN_H + +#include +#include +#include "firebase/app.h" + +namespace firebase_core_windows { + + class FlutterFirebasePlugin { + public: + virtual std::string plugin_name() = 0; + virtual flutter::EncodableMap get_plugin_constants(const ::firebase::App&) = 0; + }; +} + +#endif //TODO_POINTS_FLUTTER_FIREBASE_PLUGIN_H diff --git a/packages/firebase_remote_config/firebase_remote_config/example/lib/firebase_options.dart b/packages/firebase_remote_config/firebase_remote_config/example/lib/firebase_options.dart index af4b4130e962..5cd10447d8c3 100644 --- a/packages/firebase_remote_config/firebase_remote_config/example/lib/firebase_options.dart +++ b/packages/firebase_remote_config/firebase_remote_config/example/lib/firebase_options.dart @@ -31,10 +31,7 @@ class DefaultFirebaseOptions { case TargetPlatform.macOS: return macos; case TargetPlatform.windows: - throw UnsupportedError( - 'DefaultFirebaseOptions have not been configured for windows - ' - 'you can reconfigure this by running the FlutterFire CLI again.', - ); + return android; case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' diff --git a/packages/firebase_remote_config/firebase_remote_config/example/lib/home_page.dart b/packages/firebase_remote_config/firebase_remote_config/example/lib/home_page.dart index 4e0e7e5b8a9d..35191a7c7a47 100644 --- a/packages/firebase_remote_config/firebase_remote_config/example/lib/home_page.dart +++ b/packages/firebase_remote_config/firebase_remote_config/example/lib/home_page.dart @@ -32,6 +32,7 @@ class _HomePageState extends State { onPressed: () async { final FirebaseRemoteConfig remoteConfig = FirebaseRemoteConfig.instance; + // await remoteConfig.ensureInitialized(); await remoteConfig.setConfigSettings( RemoteConfigSettings( fetchTimeout: const Duration(seconds: 10), diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/.gitignore b/packages/firebase_remote_config/firebase_remote_config/example/windows/.gitignore new file mode 100644 index 000000000000..d492d0d98c8f --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/.gitignore @@ -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/ diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/CMakeLists.txt b/packages/firebase_remote_config/firebase_remote_config/example/windows/CMakeLists.txt new file mode 100644 index 000000000000..c435cf713539 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/CMakeLists.txt @@ -0,0 +1,101 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(firebase_core_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 "firebase_remote_config_example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# 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 "$<$:_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 "$") +# 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() + +# 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) diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/CMakeLists.txt b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000000..903f4899d6fc --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/CMakeLists.txt @@ -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} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/CMakeLists.txt b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/CMakeLists.txt new file mode 100644 index 000000000000..394917c053a0 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/CMakeLists.txt @@ -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) diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/Runner.rc b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/Runner.rc new file mode 100644 index 000000000000..c0d7fe21c712 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/Runner.rc @@ -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.example" "\0" + VALUE "FileDescription", "firebase_core_example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "firebase_core_example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "firebase_core_example.exe" "\0" + VALUE "ProductName", "firebase_core_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 diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp new file mode 100644 index 000000000000..227a248924bf --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp @@ -0,0 +1,68 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#include "flutter_window.h" + +#include + +#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( + 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(); }); + + 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 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); +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.h b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.h new file mode 100644 index 000000000000..2b30f421692a --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.h @@ -0,0 +1,39 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#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_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/main.cpp b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/main.cpp new file mode 100644 index 000000000000..0bba0da0102d --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/main.cpp @@ -0,0 +1,46 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#include +#include +#include + +#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 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"firebase_remote_config_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; +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resource.h b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resource.h new file mode 100644 index 000000000000..3b8e4da19d6f --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resource.h @@ -0,0 +1,22 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +//{{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 diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resources/app_icon.ico b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resources/app_icon.ico new file mode 100644 index 000000000000..c04e20caf637 Binary files /dev/null and b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resources/app_icon.ico differ diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/runner.exe.manifest b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/runner.exe.manifest new file mode 100644 index 000000000000..a42ea7687cb6 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.cpp b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.cpp new file mode 100644 index 000000000000..605494e6c81c --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.cpp @@ -0,0 +1,67 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#include "utils.h" + +#include +#include +#include +#include + +#include + +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 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::vector 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); + 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, -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.h b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.h new file mode 100644 index 000000000000..67b5c48b8d3d --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.h @@ -0,0 +1,25 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// 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, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.cpp b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.cpp new file mode 100644 index 000000000000..2d3709236bd4 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.cpp @@ -0,0 +1,284 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#include "win32_window.h" + +#include +#include + +#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(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( + 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 registar 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(origin.x), + static_cast(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(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(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(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( + 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)); + } +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.h b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.h new file mode 100644 index 000000000000..4e15bbde1058 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.h @@ -0,0 +1,106 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// 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 + // responsponds 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_ diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt b/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt new file mode 100644 index 000000000000..8b4c402fa9cc --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt @@ -0,0 +1,138 @@ +# 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) + +# Project-level configuration. +set(PROJECT_NAME "firebase_remote_config") +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 "firebase_remote_config_plugin") + +# Any new source files that you add to the plugin should be added here. +list(APPEND PLUGIN_SOURCES + "firebase_remote_config_plugin.cpp" + "firebase_remote_config_plugin.h" + "firebase_remote_config_plugin_constants.h" + "firebase_remote_config_plugin_constants.cpp" + # "messages.g.h" + # "messages.g.cpp" + # "FirebaseRemoteConfigImplementation.h" + # "FirebaseRemoteConfigImplementation.cpp" + # "remote_config_pigeon_implemetation.h" + # "remote_config_pigeon_implemetation.cpp" +) + +# Read version from pubspec.yaml +file(STRINGS "../pubspec.yaml" pubspec_content) +foreach(line ${pubspec_content}) + string(FIND ${line} "version: " has_version) + + if("${has_version}" STREQUAL "0") + string(FIND ${line} ": " version_start_pos) + math(EXPR version_start_pos "${version_start_pos} + 2") + string(LENGTH ${line} version_end_pos) + math(EXPR len "${version_end_pos} - ${version_start_pos}") + string(SUBSTRING ${line} ${version_start_pos} ${len} PLUGIN_VERSION) + break() + endif() +endforeach(line) + +configure_file(plugin_version.h.in ${CMAKE_BINARY_DIR}/generated/firebase_remote_config/plugin_version.h) +include_directories(${CMAKE_BINARY_DIR}/generated/) + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +add_library(${PLUGIN_NAME} STATIC + "include/firebase_remote_config/firebase_remote_config_plugin_c_api.h" + "firebase_remote_config_plugin_c_api.cpp" + ${PLUGIN_SOURCES} + ${CMAKE_BINARY_DIR}/generated/firebase_remote_config/plugin_version.h + firebase_remote_config_plugin_constants.cpp + firebase_remote_config_plugin_constants.h +) + +# 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}) + +# 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} PUBLIC FLUTTER_PLUGIN_IMPL) +# Enable firebase-cpp-sdk's platform logging api. +target_compile_definitions(${PLUGIN_NAME} PRIVATE -DINTERNAL_EXPERIMENTAL=1) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +set(MSVC_RUNTIME_MODE MD) +set(firebase_libs firebase_core_plugin firebase_remote_config) +set(ADDITIONAL_LIBS advapi32 ws2_32 crypt32 rpcrt4 ole32) +target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}" "${ADDITIONAL_LIBS}") + +# 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(firebase_remote_config_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/firebase_remote_config_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}" $ + ) + + # Enable automatic test discovery. + include(GoogleTest) + gtest_discover_tests(${TEST_RUNNER}) +endif () diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp new file mode 100644 index 000000000000..13cbdc78c72e --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp @@ -0,0 +1,592 @@ +#include "firebase_remote_config_plugin.h" + +// This must be included before many other Windows headers. +#include + +// For getPlatformVersion; remove unless needed for your plugin implementation. +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "firebase/app.h" +#include "firebase/remote_config.h" +#include "firebase_core/firebase_plugin_registry.h" +#include "firebase_remote_config/plugin_version.h" +#include "firebase_remote_config_plugin_constants.h" + +// #include "messages.g.h" +// #include "remote_config_pigeon_implemetation.h" + +using namespace firebase::remote_config; +using namespace firebase; + +extern "C" firebase_core_windows::FirebasePluginRegistry* +GetFlutterFirebaseRegistry(); + +namespace firebase_remote_config_windows { +const char* kEventChannelName = + "plugins.flutter.io/firebase_remote_config_updated"; +const char* kMethodChannelName = "plugins.flutter.io/firebase_remote_config"; +const char* kRemoteConfigLibrary = "firebase_remote_config_windows"; +std::unique_ptr> sink_; + +const char* kSetConfigSettingsMethodName = "RemoteConfig#setConfigSettings"; +const char* kSetDefaultsMethodName = "RemoteConfig#setDefaults"; +const char* kEnsureInitializedMethodName = "RemoteConfig#ensureInitialized"; +const char* kFetchMethodName = "RemoteConfig#fetch"; +const char* kActivateMethodName = "RemoteConfig#activate"; +const char* kGetAllMethodName = "RemoteConfig#getAll"; +const char* kGetPropertiesMethodName = "RemoteConfig#getProperties"; +const char* kFetchAndActivateMethodName = "RemoteConfig#fetchAndActivate"; + +void FirebaseRemoteConfigPlugin::RegisterWithRegistrar( + flutter::PluginRegistrarWindows* registrar) { + auto plugin = std::make_unique(); + + const auto method_channel = + std::make_unique>( + registrar->messenger(), kMethodChannelName, + &flutter::StandardMethodCodec::GetInstance()); + + method_channel->SetMethodCallHandler( + [plugin_pointer = plugin.get()](const auto& call, auto result) { + plugin_pointer->HandleMethodCall(call, std::move(result)); + }); + + const auto firebase_registry = + firebase_core_windows::FirebasePluginRegistry::GetInstance(); + const auto shared_plugin = + std::make_shared(); + ::firebase::App::RegisterLibrary(kRemoteConfigLibrary, + getPluginVersion().c_str(), nullptr); + firebase_registry->put_plugin_ref(shared_plugin); + + const auto event_channel = + std::make_unique>( + registrar->messenger(), kEventChannelName, + &flutter::StandardMethodCodec::GetInstance()); + + auto eventChannelHandler = std::make_unique< + flutter::StreamHandlerFunctions>( + [&, plugin_pointer = plugin.get()]( + const flutter::EncodableValue* arguments, + std::unique_ptr> sink) + -> std::unique_ptr< + flutter::StreamHandlerError> { + // sink_ = std::move(sink); + const auto args = plugin_pointer->try_get_arguments_(arguments); + + // Getting app name + const auto app_name = plugin_pointer->get_app_name_(args); + + const auto firebaseApp = ::firebase::App::GetInstance(app_name.c_str()); + const auto remoteConfig = + ::firebase::remote_config::RemoteConfig::GetInstance(firebaseApp); + auto registration = remoteConfig->AddOnConfigUpdateListener( + [&sink, this](ConfigUpdate&& config_update, + RemoteConfigError error) { + const auto updatedKeys = config_update.updated_keys; + flutter::EncodableList keys{}; + + for (const auto& key : updatedKeys) { + keys.push_back(flutter::EncodableValue(key)); + } + sink->Success(flutter::EncodableValue(keys)); + }); + + return nullptr; + }, + [](const flutter::EncodableValue* arguments) + -> std::unique_ptr< + flutter::StreamHandlerError> { + return nullptr; + }); + + event_channel->SetStreamHandler(std::move(eventChannelHandler)); + + registrar->AddPlugin(std::move(plugin)); +} + +FirebaseRemoteConfigPlugin::FirebaseRemoteConfigPlugin() {} + +FirebaseRemoteConfigPlugin::~FirebaseRemoteConfigPlugin() {} + +void FirebaseRemoteConfigPlugin::HandleMethodCall( + const flutter::MethodCall& method_call, + std::unique_ptr> result) { + std::cout << "Method call: " << method_call.method_name() << std::endl; + + const auto& method_name = method_call.method_name(); + try { + auto shared_result = + std::shared_ptr>( + std::move(result)); + + if (method_name == kSetConfigSettingsMethodName) { + set_config_settings_( + method_call.arguments(), + [shared_result](const std::optional& + response_result) { + if (response_result.has_value()) { + shared_result->Error(kSetConfigSettingsMethodName, + response_result->what()); + } else { + shared_result->Success(); + } + }); + } else if (method_name == kSetDefaultsMethodName) { + set_defaults_(method_call.arguments(), [shared_result]( + const auto& response_result) { + if (response_result.has_value()) { + shared_result->Error(kSetDefaultsMethodName, response_result->what()); + } else { + shared_result->Success(); + } + }); + } else if (method_name == kGetPropertiesMethodName) { + auto properties = get_properties_(method_call.arguments()); + shared_result->Success(flutter::EncodableValue(properties)); + } else if (method_name == kGetAllMethodName) { + // const auto args = try_get_arguments_(method_call.arguments()); + const auto all = get_all_(method_call.arguments()); + shared_result->Success(flutter::EncodableValue(all)); + } else if (method_name == kEnsureInitializedMethodName) { + ensure_initialized_(method_call.arguments(), + [shared_result](const auto& callback_result) { + if (callback_result.has_value()) { + shared_result->Error(kEnsureInitializedMethodName, + callback_result->what()); + } else { + shared_result->Success(); + } + }); + } else if (method_name == kActivateMethodName) { + activate_(method_call.arguments(), [shared_result]( + const auto& callback_result) { + if (std::holds_alternative( + callback_result)) { + shared_result->Error( + kActivateMethodName, + std::get(callback_result).what()); + } else { + shared_result->Success( + flutter::EncodableValue(std::get(callback_result))); + } + }); + } else if (method_name == kFetchMethodName) { + fetch_(method_call.arguments(), [shared_result]( + const auto& callback_result) { + if (callback_result.has_value()) { + shared_result->Error(kFetchMethodName, callback_result->what()); + } else { + shared_result->Success(); + } + }); + } else if (method_name == kFetchAndActivateMethodName) { + fetch_and_activate_( + method_call.arguments(), + [shared_result](const auto& callback_result) { + if (std::holds_alternative( + callback_result)) { + shared_result->Error( + kFetchAndActivateMethodName, + std::get(callback_result) + .what()); + } else { + shared_result->Success( + flutter::EncodableValue(std::get(callback_result))); + } + }); + } else { + result->NotImplemented(); + } + } catch (const FirebaseRemoteConfigException& e) { + result->Error(kSetConfigSettingsMethodName, e.what()); + } catch (const std::exception& e) { + result->Error(kSetConfigSettingsMethodName, e.what()); + } +} + +void FirebaseRemoteConfigPlugin::get_method_channel_arguments_( + flutter::EncodableMap* args) const { + for (const auto& [key, value] : *args) { + std::cout << "Key: " << std::get(key) << std::endl; + } +} + +std::vector +FirebaseRemoteConfigPlugin::set_defaults_convert_to_native_( + const flutter::EncodableMap& default_parameters) const { + std::vector parameters; + std::vector> storage; + + for (const auto& items : default_parameters) { + if (std::holds_alternative(items.first)) { + std::string key_str = std::get(items.first); + + ConfigKeyValueVariant kv; + char* key = new char[key_str.size() + 1]; + // strcpy(key, key_str.c_str()); + strcpy_s(key, sizeof(char) * key_str.size() + 1, key_str.c_str()); + kv.key = key; + kv.value = set_defaults_to_variant_(items.second); + parameters.push_back(kv); + } + } + + return parameters; +} +firebase::Variant FirebaseRemoteConfigPlugin::set_defaults_to_variant_( + flutter::EncodableValue encodableValue) const { + if (std::holds_alternative(encodableValue)) { + auto value = std::get(encodableValue); + return {value}; + } + + if (std::holds_alternative(encodableValue)) { + auto value = std::get(encodableValue); + return {value}; + } + + if (std::holds_alternative(encodableValue)) { + auto value = std::get(encodableValue); + return {value}; + } + + if (std::holds_alternative(encodableValue)) { + auto value = std::get(encodableValue); + return {value}; + } + + return {}; +} +std::string FirebaseRemoteConfigPlugin::map_last_fetch_status_( + firebase::remote_config::LastFetchStatus lastFetchStatus) const { + if (lastFetchStatus == kLastFetchStatusSuccess) { + return "success"; + } else if (lastFetchStatus == kLastFetchStatusFailure) { + return "failure"; + } else if (lastFetchStatus == kLastFetchStatusPending) { + return "noFetchYet"; + } else { + return "failure"; + } +} +flutter::EncodableMap* FirebaseRemoteConfigPlugin::try_get_arguments_( + const flutter::EncodableValue* arguments) const { + const auto args = std::get_if(arguments); + return args ? const_cast(args) : nullptr; +} + +std::string FirebaseRemoteConfigPlugin::get_app_name_( + flutter::EncodableMap* args) const { + const auto& encodable_app_name_arg = + args->find(flutter::EncodableValue("appName")); + if (encodable_app_name_arg == args->end()) { + throw std::exception("Arguments does not contains appName"); + } + const auto& app_name_arg = + std::get(encodable_app_name_arg->second); + + return app_name_arg; +} + +std::string FirebaseRemoteConfigPlugin::map_source_(ValueSource source) const { + if (source == kValueSourceStaticValue) { + return "static"; + } else if (source == kValueSourceDefaultValue) { + return "default"; + } else if (source == kValueSourceRemoteValue) { + return "remote"; + } else { + return "static"; + } +} + +flutter::EncodableMap +FirebaseRemoteConfigPlugin::create_remote_config_values_map_( + std::string key, RemoteConfig* remote_config) const { + flutter::EncodableMap parsed_parameters; + + ValueInfo value_info{}; + auto data = remote_config->GetData(key.c_str(), &value_info); + + parsed_parameters.insert( + {flutter::EncodableValue("value"), flutter::EncodableValue(data)}); + const auto source_mapped = map_source_(value_info.source); + parsed_parameters.insert({flutter::EncodableValue("source"), + flutter::EncodableValue(source_mapped.c_str())}); + return parsed_parameters; +} + +flutter::EncodableMap FirebaseRemoteConfigPlugin::map_parameters_( + std::map parameters, + RemoteConfig* remote_config) const { + flutter::EncodableMap map_; + + for (const auto& val : parameters) { + auto param = val.second; + auto name = val.first; + + map_.insert({name, create_remote_config_values_map_(name, remote_config)}); + } + + return map_; +} + +void FirebaseRemoteConfigPlugin::set_config_settings_( + const flutter::EncodableValue* arguments, + std::function)> + completion) { + const auto& args = try_get_arguments_(arguments); + + if (!args) { + completion(FirebaseRemoteConfigException("Cannot decode arguments")); + return; + } + + const auto app_name = get_app_name_(args); + + const auto& encodable_fetch_timeout_arg = + args->find(flutter::EncodableValue("fetchTimeout")); + if (encodable_fetch_timeout_arg == args->end()) { + completion(FirebaseRemoteConfigException("Cannot decode fetch timeout")); + return; + } + const int64_t fetch_timeout_arg = + encodable_fetch_timeout_arg->second.LongValue(); + + const auto& encodable_minimum_fetch_interval_arg = + args->find(flutter::EncodableValue("minimumFetchInterval")); + if (encodable_minimum_fetch_interval_arg == args->end()) { + completion( + FirebaseRemoteConfigException("Cannot decode minimum fetch interval")); + return; + } + const int64_t minimum_fetch_interval_arg = + encodable_minimum_fetch_interval_arg->second.LongValue(); + + const auto firebaseApp = App::GetInstance(app_name.c_str()); + const auto remoteConfig = RemoteConfig::GetInstance(firebaseApp); + + const ConfigSettings config_setting{ + static_cast(fetch_timeout_arg), + static_cast(minimum_fetch_interval_arg)}; + + auto future = remoteConfig->SetConfigSettings(config_setting); + + future.OnCompletion([completion](const Future& futureResult) { + if (futureResult.error() == kFutureStatusComplete) { + completion({}); + } else { + completion(FirebaseRemoteConfigException("Cannot set config settings")); + } + }); +} + +void FirebaseRemoteConfigPlugin::set_defaults_( + const flutter::EncodableValue* arguments, + std::function)> + completion) { + const auto& args = try_get_arguments_(arguments); + + if (!args) { + completion(FirebaseRemoteConfigException("Cannot decode arguments")); + return; + } + + const auto app_name = get_app_name_(args); + + const auto& encodable_defaults_arg = + args->find(flutter::EncodableValue("defaults")); + if (encodable_defaults_arg == args->end()) { + completion(FirebaseRemoteConfigException("Cannot decode defaults")); + return; + } + const auto& defaults_arg = + std::get(encodable_defaults_arg->second); + + App* firebaseApp = App::GetInstance(app_name.c_str()); + RemoteConfig* remoteConfig = RemoteConfig::GetInstance(firebaseApp); + + const auto& default_args_native = + set_defaults_convert_to_native_(defaults_arg); + + auto future = remoteConfig->SetDefaults(default_args_native.data(), + default_args_native.size()); + + future.OnCompletion([completion](const Future& futureResult) { + if (futureResult.error() == kFutureStatusComplete) { + completion({}); + } else { + completion(FirebaseRemoteConfigException("Cannot set defaults")); + } + }); +} +flutter::EncodableMap FirebaseRemoteConfigPlugin::get_properties_( + const flutter::EncodableValue* arguments) { + const auto& args = try_get_arguments_(arguments); + + if (!args) { + throw FirebaseRemoteConfigException("Cannot decode arguments"); + } + + const auto app_name = get_app_name_(args); + + App* firebaseApp = App::GetInstance(app_name.c_str()); + RemoteConfig* remote_config = RemoteConfig::GetInstance(firebaseApp); + + const auto configSettings = remote_config->GetConfigSettings(); + auto fetchTimeout = + static_cast(configSettings.fetch_timeout_in_milliseconds); + auto minFetchTimeout = static_cast( + configSettings.minimum_fetch_interval_in_milliseconds); + + const auto configInfo = remote_config->GetInfo(); + const auto lastFetch = static_cast(configInfo.fetch_time); + const auto lastFetchStatus = configInfo.last_fetch_status; + const auto lastFetchStatusMapped = map_last_fetch_status_(lastFetchStatus); + // + flutter::EncodableMap values; + + values.insert({flutter::EncodableValue("fetchTimeout"), + flutter::EncodableValue(fetchTimeout)}); + values.insert({flutter::EncodableValue("minimumFetchInterval"), + flutter::EncodableValue(minFetchTimeout)}); + values.insert({flutter::EncodableValue("lastFetchTime"), + flutter::EncodableValue(lastFetch)}); + values.insert({flutter::EncodableValue("lastFetchStatus"), + flutter::EncodableValue(lastFetchStatusMapped.c_str())}); + + return values; +} + +void FirebaseRemoteConfigPlugin::ensure_initialized_( + const flutter::EncodableValue* arguments, + std::function)> + completion) { + const auto& args = try_get_arguments_(arguments); + + auto app_name = get_app_name_(args); + + const auto firebaseApp = ::firebase::App::GetInstance(app_name.c_str()); + const auto remote_config = RemoteConfig::GetInstance(firebaseApp); + + const auto future = remote_config->EnsureInitialized(); + + future.OnCompletion([completion](const Future& futureResult) { + if (futureResult.status() == kFutureStatusComplete) { + completion({}); + } else { + completion( + FirebaseRemoteConfigException("Cannot initialize remote config")); + } + }); +} + +void FirebaseRemoteConfigPlugin::activate_( + const flutter::EncodableValue* arguments, + std::function)> + completion) { + const auto& args = try_get_arguments_(arguments); + if (!args) { + throw FirebaseRemoteConfigException("Cannot decode arguments"); + } + + const auto app_name = get_app_name_(args); + + const auto firebaseApp = ::firebase::App::GetInstance(app_name.c_str()); + const auto remote_config = RemoteConfig::GetInstance(firebaseApp); + + auto future = remote_config->Activate(); + + future.OnCompletion([completion](const Future& futureResult) { + if (futureResult.status() == kFutureStatusComplete) { + auto result = *futureResult.result(); + completion(std::variant(result)); + } else { + completion( + FirebaseRemoteConfigException("Cannot activate remote config")); + } + }); +} + +void FirebaseRemoteConfigPlugin::fetch_( + const flutter::EncodableValue* arguments, + std::function)> + completion) { + const auto& args = try_get_arguments_(arguments); + + if (!args) { + throw FirebaseRemoteConfigException("Cannot decode arguments"); + } + + const auto app_name = get_app_name_(args); + + const auto firebaseApp = ::firebase::App::GetInstance(app_name.c_str()); + const auto remote_config = RemoteConfig::GetInstance(firebaseApp); + + auto future = remote_config->Fetch(); + + future.OnCompletion([completion](const Future& futureResult) { + if (futureResult.status() == kFutureStatusComplete) { + completion({}); + } else { + completion(FirebaseRemoteConfigException("Cannot fetch remote config")); + } + }); +} + +void FirebaseRemoteConfigPlugin::fetch_and_activate_( + const flutter::EncodableValue* arguments, + std::function)> + completion) { + const auto& args = try_get_arguments_(arguments); + if (!args) { + throw FirebaseRemoteConfigException("Cannot decode arguments"); + } + + const auto app_name = get_app_name_(args); + + const auto firebaseApp = ::firebase::App::GetInstance(app_name.c_str()); + const auto remote_config = RemoteConfig::GetInstance(firebaseApp); + + auto future = remote_config->FetchAndActivate(); + + future.OnCompletion([completion](const Future& futureResult) { + if (futureResult.status() == kFutureStatusComplete) { + auto result = *futureResult.result(); + completion(std::variant(result)); + } else { + completion( + FirebaseRemoteConfigException("Cannot activate remote config")); + } + }); +} + +flutter::EncodableMap FirebaseRemoteConfigPlugin::get_all_( + const flutter::EncodableValue* arguments) const { + const auto& args = try_get_arguments_(arguments); + + if (!args) { + throw FirebaseRemoteConfigException("Cannot decode arguments"); + } + + const auto app_name = get_app_name_(args); + + const auto firebaseApp = ::firebase::App::GetInstance(app_name.c_str()); + const auto remote_config = RemoteConfig::GetInstance(firebaseApp); + + const auto get_all = remote_config->GetAll(); + // + auto all_mapped = map_parameters_(get_all, remote_config); + + return all_mapped; +} +} // namespace firebase_remote_config_windows diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.h b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.h new file mode 100644 index 000000000000..4ca9fc807a6e --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.h @@ -0,0 +1,94 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_H_ +#define FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_H_ + +#include +#include +#include +#include + +#include + +#include "firebase_core/flutter_firebase_plugin.h" + +namespace firebase { +namespace remote_config { +struct ConfigKeyValueVariant; +} +} + +namespace firebase_remote_config_windows { + +class FirebaseRemoteConfigException : public std::exception { + public: + explicit FirebaseRemoteConfigException(std::string message) + : message_(std::move(message)) {} + + const char *what() const noexcept override { return message_.c_str(); } + + private: + std::string message_; +}; + +class FirebaseRemoteConfigPlugin : public flutter::Plugin { + public: + static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); + + FirebaseRemoteConfigPlugin(); + + virtual ~FirebaseRemoteConfigPlugin(); + + // Disallow copy and assign. + FirebaseRemoteConfigPlugin(const FirebaseRemoteConfigPlugin &) = delete; + + FirebaseRemoteConfigPlugin &operator=(const FirebaseRemoteConfigPlugin &) = + delete; + + // Called when a method is called on this plugin's channel from Dart. + void HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result); + + private: + void get_method_channel_arguments_(flutter::EncodableMap *args) const; + // bool set_defaults_(const std::string &app_name, + // const flutter::EncodableMap &args) const; + std::vector set_defaults_convert_to_native_( + const flutter::EncodableMap &default_parameters) const; + firebase::Variant set_defaults_to_variant_(flutter::EncodableValue encodableValue) const; + std::string map_last_fetch_status_(firebase::remote_config::LastFetchStatus lastFetchStatus) const; + flutter::EncodableMap *try_get_arguments_(const flutter::EncodableValue *arguments) const; + std::string get_app_name_(flutter::EncodableMap *encodable_map) const; + flutter::EncodableMap get_all_( + const flutter::EncodableValue *arguments) const; + std::string map_source_(firebase::remote_config::ValueSource source) const; + flutter::EncodableMap create_remote_config_values_map_( + std::string key, firebase::remote_config::RemoteConfig *remote_config) const; + flutter::EncodableMap map_parameters_( + std::map parameters, + firebase::remote_config::RemoteConfig *remote_config) const; + void set_config_settings_( + const flutter::EncodableValue *arguments, + std::function)> + completion); + void set_defaults_(const flutter::EncodableValue *arguments, + std::function)> + completion); + flutter::EncodableMap get_properties_(const flutter::EncodableValue *arguments); + void ensure_initialized_(const flutter::EncodableValue *arguments, + std::function)> + completion); + void activate_(const flutter::EncodableValue *arguments, + std::function)> completion); + void fetch_( + const flutter::EncodableValue *arguments, + std::function)> + completion); + void fetch_and_activate_( + const flutter::EncodableValue *arguments, + std::function)> + completion); +}; + +} // namespace firebase_remote_config_windows + +#endif // FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_c_api.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_c_api.cpp new file mode 100644 index 000000000000..94580265d73d --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_c_api.cpp @@ -0,0 +1,12 @@ +#include "include/firebase_remote_config/firebase_remote_config_plugin_c_api.h" + +#include + +#include "firebase_remote_config_plugin.h" + +void FirebaseRemoteConfigPluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar) { + firebase_remote_config_windows::FirebaseRemoteConfigPlugin::RegisterWithRegistrar( + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar)); +} diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_constants.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_constants.cpp new file mode 100644 index 000000000000..638aaa1e3de7 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_constants.cpp @@ -0,0 +1,139 @@ +// +// Created by Andrii on 29.10.2024. +// + +#include "firebase_remote_config_plugin_constants.h" + +// This must be included before many other Windows headers. +#include + +// For getPlatformVersion; remove unless needed for your plugin implementation. +#include + +#include +#include +#include +#include "firebase_core/firebase_plugin_registry.h" +#include "firebase/remote_config.h" +#include "firebase/app.h" +#include +#include +// #include "firebase_remote_config/plugin_version.h" + +//#include "FirebaseRemoteConfigImplementation.h" +#include +#include + +using namespace firebase::remote_config; +using namespace firebase; +using namespace flutter; + +namespace firebase_remote_config_windows { +// virtual std::string plugin_name() override; +// +// virtual flutter::EncodableMap get_plugin_constants(const ::firebase::App &) override; + + + std::string mapLastFetchStatus(LastFetchStatus lastFetchStatus) + { + if (lastFetchStatus == kLastFetchStatusSuccess) { + return "success"; + } + else if (lastFetchStatus == kLastFetchStatusFailure) + return "failure"; + else if (lastFetchStatus == kLastFetchStatusPending) { + return "noFetchYet"; + } + else { + return "failure"; + } + } + + std::string map_source(ValueSource source) + { + if (source == kValueSourceStaticValue) + { + return "static"; + } + else if (source == kValueSourceDefaultValue) + { + return "default"; + } + else if (source == kValueSourceRemoteValue) + { + return "remote"; + } + else + { + return "static"; + } + } + + flutter::EncodableMap createRemoteConfigValuesMap(std::string key, RemoteConfig* remote_config) { + flutter::EncodableMap parsed_parameters; + + ValueInfo value_info{}; + auto data = remote_config->GetData(key.c_str(), &value_info); + + parsed_parameters.insert({ EncodableValue("value"), EncodableValue(data) }); + const auto source_mapped = map_source(value_info.source); + parsed_parameters.insert({ EncodableValue("source"), EncodableValue(source_mapped.c_str()) }); + return parsed_parameters; + + } + + flutter::EncodableMap mapParameters(const std::map& parameters, RemoteConfig* remote_config) + { + flutter::EncodableMap map_; + + for (const auto& val : parameters) + { + auto param = val.second; + auto name = val.first; + + map_.insert({ name, createRemoteConfigValuesMap(name, remote_config) }); + + } + + return map_; + } + + void get_all_parameters(RemoteConfig* remote_config) + { + } + + flutter::EncodableMap FlutterFirebaseRemoteConfigPlugin::get_plugin_constants(const ::firebase::App& firebaseApp) + { + auto app = const_cast<::firebase::App*>(&firebaseApp); + //app->SetDefaultConfigPath() + const auto remoteConfig = RemoteConfig::GetInstance(app); + const auto configSettings = remoteConfig->GetConfigSettings(); + auto fetchTimeout = static_cast(configSettings.fetch_timeout_in_milliseconds); + auto minFetchTimeout = static_cast(configSettings.minimum_fetch_interval_in_milliseconds); + + const auto configInfo = remoteConfig->GetInfo(); + const auto lastFetch = static_cast(configInfo.fetch_time); + const auto lastFetchStatus = configInfo.last_fetch_status; + const auto lastFetchStatusMapped = mapLastFetchStatus(lastFetchStatus); + + flutter::EncodableMap values; + + values.insert({ EncodableValue("fetchTimeout"), EncodableValue(fetchTimeout) }); + values.insert({ EncodableValue("minimumFetchInterval"), EncodableValue(minFetchTimeout) }); + values.insert({ EncodableValue("lastFetchTime"), EncodableValue(lastFetch) }); + values.insert({ EncodableValue("lastFetchStatus"), EncodableValue(lastFetchStatusMapped.c_str()) }); + + const auto allItems = remoteConfig->GetAll(); + + auto converted = mapParameters(allItems, remoteConfig); + + values.insert({ EncodableValue("parameters"), converted }); + + return values; + } + + std::string FlutterFirebaseRemoteConfigPlugin::plugin_name() + { + return "plugins.flutter.io/firebase_remote_config"; + } +} diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_constants.h b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_constants.h new file mode 100644 index 000000000000..6e47ae55d2a4 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_constants.h @@ -0,0 +1,25 @@ +// +// Created by Andrii on 29.10.2024. +// + +#ifndef WINDOWS_FIREBASE_REMOTE_CONFIG_PLUGIN_CONSTANTS_H +#define WINDOWS_FIREBASE_REMOTE_CONFIG_PLUGIN_CONSTANTS_H + +#include "firebase_core/flutter_firebase_plugin.h" + +namespace firebase_remote_config_windows { + class FlutterFirebaseRemoteConfigPlugin : public firebase_core_windows::FlutterFirebasePlugin { + public: + FlutterFirebaseRemoteConfigPlugin() {} + // virtual ~FirebaseRemoteConfigImplementation() override {} + + virtual std::string plugin_name() override; + + virtual flutter::EncodableMap get_plugin_constants(const ::firebase::App &) override; + + private: + std::string app_name_; + }; + +} +#endif //WINDOWS_FIREBASE_REMOTE_CONFIG_PLUGIN_CONSTANTS_H diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/include/firebase_remote_config/firebase_remote_config_plugin_c_api.h b/packages/firebase_remote_config/firebase_remote_config/windows/include/firebase_remote_config/firebase_remote_config_plugin_c_api.h new file mode 100644 index 000000000000..2e4ab090234a --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/include/firebase_remote_config/firebase_remote_config_plugin_c_api.h @@ -0,0 +1,23 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_C_API_H_ +#define FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_C_API_H_ + +#include + +#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 FirebaseRemoteConfigPluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_C_API_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/plugin_version.h.in b/packages/firebase_remote_config/firebase_remote_config/windows/plugin_version.h.in new file mode 100644 index 000000000000..e57a86f7af82 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/plugin_version.h.in @@ -0,0 +1,13 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#ifndef PLUGIN_VERSION_CONFIG_H +#define PLUGIN_VERSION_CONFIG_H + +namespace firebase_remote_config_windows { + +std::string getPluginVersion() { return "@PLUGIN_VERSION@"; } +} // namespace firebase_auth_windows + +#endif // PLUGIN_VERSION_CONFIG_H diff --git a/tests/windows/flutter/generated_plugin_registrant.cc b/tests/windows/flutter/generated_plugin_registrant.cc index 6013891f132f..2fda6bf3095a 100644 --- a/tests/windows/flutter/generated_plugin_registrant.cc +++ b/tests/windows/flutter/generated_plugin_registrant.cc @@ -8,6 +8,7 @@ #include #include +#include #include void RegisterPlugins(flutter::PluginRegistry* registry) { @@ -15,6 +16,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) { registry->GetRegistrarForPlugin("FirebaseAuthPluginCApi")); FirebaseCorePluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); + FirebaseRemoteConfigPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseRemoteConfigPluginCApi")); FirebaseStoragePluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("FirebaseStoragePluginCApi")); } diff --git a/tests/windows/flutter/generated_plugins.cmake b/tests/windows/flutter/generated_plugins.cmake index 3976ac4622ed..7a8854af51e0 100644 --- a/tests/windows/flutter/generated_plugins.cmake +++ b/tests/windows/flutter/generated_plugins.cmake @@ -5,6 +5,7 @@ list(APPEND FLUTTER_PLUGIN_LIST firebase_auth firebase_core + firebase_remote_config firebase_storage )