diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 26fbf00..96f3086 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -6,40 +6,49 @@ on: name: Release Builds jobs: linux: - name: Android & Linux & Web + name: Linux runs-on: ubuntu-latest steps: - run: | git clone https://github.com/flutter/flutter.git cd flutter - git checkout 4df8fdb7df + git checkout 5663e02645 - run: echo ::add-path::`pwd`"/flutter/bin" - - - uses: actions/setup-java@v1 - with: - java-version: '12.x' - - uses: actions/checkout@v2 with: path: 'app' - - run: | cd app flutter config --enable-linux-desktop - flutter config --enable-web flutter pub get flutter build linux --release - flutter build apk -t lib/main.mobile.dart --release - flutter build web -t lib/main.mobile.dart --release cd build/linux/ zip -r linux-release.zip release + - name: Create Android & linux Release + uses: ncipollo/release-action@v1 + with: + artifacts: 'app/build/linux/linux-release.zip' + token: ${{ secrets.TOKEN }} + allowUpdates: true - # - run: | - # cd app - # npm i - # npm run upload apk ${{ secrets.ACCOUNT }} - # npm run upload linux ${{ secrets.ACCOUNT }} + web: + name: Web + runs-on: ubuntu-latest + steps: + - run: | + git clone https://github.com/flutter/flutter.git + cd flutter + git checkout 5663e02645 + - run: echo ::add-path::`pwd`"/flutter/bin" + - uses: actions/checkout@v2 + with: + path: 'app' + - run: | + cd app + flutter config --enable-web + flutter pub get + flutter build web -t lib/main.mobile.dart --release - name: Deploy to Firebase uses: w9jds/firebase-action@v1.3.0 with: @@ -48,10 +57,29 @@ jobs: PROJECT_PATH: 'app' FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }} + android: + name: Android + runs-on: ubuntu-latest + steps: + - run: | + git clone https://github.com/flutter/flutter.git + cd flutter + git checkout 5663e02645 + - run: echo ::add-path::`pwd`"/flutter/bin" + - uses: actions/setup-java@v1 + with: + java-version: '12.x' + - uses: actions/checkout@v2 + with: + path: 'app' + - run: | + cd app + flutter pub get + flutter build apk -t lib/main.mobile.dart --release - name: Create Android & linux Release uses: ncipollo/release-action@v1 with: - artifacts: 'app/build/app/outputs/apk/release/app-release.apk,app/build/linux/linux-release.zip' + artifacts: 'app/build/app/outputs/apk/release/app-release.apk' token: ${{ secrets.TOKEN }} allowUpdates: true @@ -62,13 +90,11 @@ jobs: - run: | git clone https://github.com/flutter/flutter.git cd flutter - git checkout 4df8fdb7df + git checkout 5663e02645 - run: echo ::add-path::`pwd`"/flutter/bin" - - uses: actions/checkout@v2 with: path: 'app' - - run: | cd app flutter config --enable-macos-desktop @@ -76,12 +102,6 @@ jobs: flutter build macos --release cd build/macos/Build/Products/Release ditto -c -k --sequesterRsrc --keepParent flutter_uis.app macos-release.zip - - # - run: | - # cd app - # npm i - # npm run upload macos ${{ secrets.ACCOUNT }} - - uses: ncipollo/release-action@v1 with: artifacts: 'app/build/macOS/Build/Products/Release/macos-release.zip' @@ -95,13 +115,11 @@ jobs: - run: | git clone https://github.com/flutter/flutter.git cd flutter - git checkout 4df8fdb7df + git checkout 5663e02645 - run: echo ::add-path::"$(pwd)\flutter\bin" - - uses: actions/checkout@v2 with: path: 'app' - - run: | cd app flutter config --enable-windows-desktop @@ -109,13 +127,6 @@ jobs: flutter build windows --release cd build\windows\x64\Release Compress-Archive -Path Runner -DestinationPath windows-release.zip - - # Windows prints the secret variable in log taht's why It's disabled for now - # - run: | - # cd app - # npm i - # npm run upload windows ${{ secrets.ACCOUNT }} - - name: Windows release build for github uses: ncipollo/release-action@v1 with: diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..4aa8926 --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,77 @@ +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +set(BINARY_NAME "flutter_uis") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "\$ORIGIN") + +# Configure build options. +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() + +# Compilation settings that should be applied to most targets. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") + +# Flutter library and tool build rules. +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build +add_executable(${BINARY_NAME} + "main.cc" + "window_configuration.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) +apply_standard_settings(${BINARY_NAME}) +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${PROJECT_BINARY_DIR}/bundle" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +file(GLOB FLUTTER_PLUGIN_DIRS "${PROJECT_BINARY_DIR}/plugins/*") + +INSTALL(CODE " + include(BundleUtilities) + fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/${BINARY_NAME}\" \"\" + \"${FLUTTER_PLUGIN_DIRS};${FLUTTER_LIBRARY_DIR}\") + " COMPONENT Runtime) + +INSTALL(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_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) diff --git a/linux/Makefile b/linux/Makefile deleted file mode 100644 index c86f1ad..0000000 --- a/linux/Makefile +++ /dev/null @@ -1,157 +0,0 @@ -# Copyright 2018 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Executable name. -BINARY_NAME=flutter_desktop_example -# Any extra source files to build. -EXTRA_SOURCES= -# Paths of any additional libraries to be bundled in the output directory. -EXTRA_BUNDLED_LIBRARIES= -# Extra flags (e.g., for library dependencies). -SYSTEM_LIBRARIES= -EXTRA_CXXFLAGS= -EXTRA_CPPFLAGS= -EXTRA_LDFLAGS= - -# Default build type. For a release build, set BUILD=release. -# Currently this only sets NDEBUG, which is used to control the flags passed -# to the Flutter engine in the example shell, and not the complation settings -# (e.g., optimization level) of the C++ code. -BUILD=debug - -FLUTTER_EPHEMERAL_DIR=flutter/ephemeral - -# Configuration provided via flutter tool. -FLUTTER_CONFIG_FILE=$(FLUTTER_EPHEMERAL_DIR)/generated_config.mk -include $(FLUTTER_CONFIG_FILE) - -# Dependency locations -FLUTTER_APP_DIR=$(CURDIR)/.. -FLUTTER_APP_BUILD_DIR=$(FLUTTER_APP_DIR)/build - -OUT_DIR=$(FLUTTER_APP_BUILD_DIR)/linux -OBJ_DIR=$(OUT_DIR)/obj/$(BUILD) - -# Libraries -FLUTTER_LIB_NAME=flutter_linux_glfw -FLUTTER_LIB=$(FLUTTER_EPHEMERAL_DIR)/lib$(FLUTTER_LIB_NAME).so - -# Tools -FLUTTER_BIN=$(FLUTTER_ROOT)/bin/flutter -LINUX_BUILD=$(FLUTTER_ROOT)/packages/flutter_tools/bin/tool_backend.sh - -# Resources -ICU_DATA_NAME=icudtl.dat -ICU_DATA_SOURCE=$(FLUTTER_EPHEMERAL_DIR)/$(ICU_DATA_NAME) -FLUTTER_ASSETS_NAME=flutter_assets -FLUTTER_ASSETS_SOURCE=$(FLUTTER_APP_BUILD_DIR)/$(FLUTTER_ASSETS_NAME) - -# Bundle structure -BUNDLE_OUT_DIR=$(OUT_DIR)/$(BUILD) -BUNDLE_DATA_DIR=$(BUNDLE_OUT_DIR)/data -BUNDLE_LIB_DIR=$(BUNDLE_OUT_DIR)/lib - -BIN_OUT=$(BUNDLE_OUT_DIR)/$(BINARY_NAME) -ICU_DATA_OUT=$(BUNDLE_DATA_DIR)/$(ICU_DATA_NAME) -FLUTTER_LIB_OUT=$(BUNDLE_LIB_DIR)/$(notdir $(FLUTTER_LIB)) -ALL_LIBS_OUT=$(FLUTTER_LIB_OUT) \ - $(foreach lib,$(EXTRA_BUNDLED_LIBRARIES),$(BUNDLE_LIB_DIR)/$(notdir $(lib))) - -# Add relevant code from the wrapper library, which is intended to be statically -# built into the client. -# Use abspath for the wrapper root, which can contain relative paths; the -# intermediate build files will be based on the source path, which will cause -# issues if they start with one or more '../'s. -WRAPPER_ROOT=$(abspath $(FLUTTER_EPHEMERAL_DIR)/cpp_client_wrapper_glfw) -WRAPPER_SOURCES= \ - $(WRAPPER_ROOT)/flutter_window_controller.cc \ - $(WRAPPER_ROOT)/plugin_registrar.cc \ - $(WRAPPER_ROOT)/engine_method_result.cc - -# Use abspath for extra sources, which may also contain relative paths (see -# note above about WRAPPER_ROOT). -SOURCES=main.cc flutter/generated_plugin_registrant.cc $(WRAPPER_SOURCES) \ - $(abspath $(EXTRA_SOURCES)) - -# Headers -WRAPPER_INCLUDE_DIR=$(WRAPPER_ROOT)/include -INCLUDE_DIRS=$(FLUTTER_EPHEMERAL_DIR) $(WRAPPER_INCLUDE_DIR) - -# Build settings -ifneq ($(strip $(SYSTEM_LIBRARIES)),) -EXTRA_CPPFLAGS+=$(patsubst -I%,-isystem%,$(shell pkg-config --cflags $(SYSTEM_LIBRARIES))) -EXTRA_LDFLAGS+=$(shell pkg-config --libs $(SYSTEM_LIBRARIES)) -endif -CXX=clang++ $(EXTRA_CXXFLAGS) -CXXFLAGS.release=-DNDEBUG -CXXFLAGS=-std=c++14 -Wall -Werror $(CXXFLAGS.$(BUILD)) -CPPFLAGS=$(patsubst %,-I%,$(INCLUDE_DIRS)) $(EXTRA_CPPFLAGS) -LDFLAGS=-L$(BUNDLE_LIB_DIR) \ - -l$(FLUTTER_LIB_NAME) \ - $(EXTRA_LDFLAGS) \ - -Wl,-rpath=\$$ORIGIN/lib - -# Intermediate files. -OBJ_FILES=$(SOURCES:%.cc=$(OBJ_DIR)/%.o) -DEPENDENCY_FILES=$(OBJ_FILES:%.o=%.d) - -# Targets - -.PHONY: all -all: $(BIN_OUT) bundle - -# This is a phony target because the flutter tool cannot describe -# its inputs and outputs yet. -.PHONY: sync -sync: $(FLUTTER_CONFIG_FILE) - $(LINUX_BUILD) linux-x64 $(BUILD) - -.PHONY: bundle -bundle: $(ICU_DATA_OUT) $(ALL_LIBS_OUT) bundleflutterassets - -$(BIN_OUT): $(OBJ_FILES) $(ALL_LIBS_OUT) - mkdir -p $(@D) - $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(OBJ_FILES) $(LDFLAGS) -o $@ - -$(WRAPPER_SOURCES) $(FLUTTER_LIB) $(ICU_DATA_SOURCE) $(FLUTTER_ASSETS_SOURCE): \ - | sync - -$(FLUTTER_LIB_OUT): $(FLUTTER_LIB) - mkdir -p $(@D) - cp $< $@ - -$(ICU_DATA_OUT): $(ICU_DATA_SOURCE) - mkdir -p $(@D) - cp $< $@ - --include $(DEPENDENCY_FILES) - -$(OBJ_DIR)/%.o : %.cc | sync - mkdir -p $(@D) - $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MMD -c $< -o $@ - -# Fully re-copy the assets directory on each build to avoid having to keep a -# comprehensive list of all asset files here, which would be fragile to changes -# in the Flutter example (e.g., adding a new font to pubspec.yaml would require -# changes here). -.PHONY: bundleflutterassets -bundleflutterassets: $(FLUTTER_ASSETS_SOURCE) - mkdir -p $(BUNDLE_DATA_DIR) - rsync -rpu --delete $(FLUTTER_ASSETS_SOURCE) $(BUNDLE_DATA_DIR) - -.PHONY: clean -clean: - rm -rf $(OUT_DIR); \ - cd $(FLUTTER_APP_DIR); \ - $(FLUTTER_BIN) clean diff --git a/linux/flutter/.template_version b/linux/flutter/.template_version new file mode 100644 index 0000000..d8263ee --- /dev/null +++ b/linux/flutter/.template_version @@ -0,0 +1 @@ +2 \ No newline at end of file diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..902cfa4 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,108 @@ +cmake_minimum_required(VERSION 3.10) + +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_glfw") + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_glfw.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY_DIR "${EPHEMERAL_DIR}" PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_glfw.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" +) +list_prepend(FLUTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "engine_method_result.cc" + "standard_codec.cc" +) +list_prepend(CPP_WRAPPER_SOURCES_CORE "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list_prepend(CPP_WRAPPER_SOURCES_PLUGIN "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_window_controller.cc" +) +list_prepend(CPP_WRAPPER_SOURCES_APP "${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. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + linux-x64 ${CMAKE_BUILD_TYPE} +) +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/linux/flutter/generated_plugins.mk b/linux/flutter/generated_plugins.mk deleted file mode 100644 index 63a60db..0000000 --- a/linux/flutter/generated_plugins.mk +++ /dev/null @@ -1,25 +0,0 @@ -# Plugins to include in the build. -GENERATED_PLUGINS=\ - -GENERATED_PLUGINS_DIR=flutter/ephemeral/.plugin_symlinks -# A plugin library name plugin name with _plugin appended. -GENERATED_PLUGIN_LIB_NAMES=$(foreach plugin,$(GENERATED_PLUGINS),$(plugin)_plugin) - -# Variables for use in the enclosing Makefile. Changes to these names are -# breaking changes. -PLUGIN_TARGETS=$(GENERATED_PLUGINS) -PLUGIN_LIBRARIES=$(foreach plugin,$(GENERATED_PLUGIN_LIB_NAMES),\ - $(OUT_DIR)/lib$(plugin).so) -PLUGIN_LDFLAGS=$(patsubst %,-l%,$(GENERATED_PLUGIN_LIB_NAMES)) -PLUGIN_CPPFLAGS=$(foreach plugin,$(GENERATED_PLUGINS),\ - -I$(GENERATED_PLUGINS_DIR)/$(plugin)/linux) - -# Targets - -# Implicit rules don't match phony targets, so list plugin builds explicitly. - -.PHONY: $(GENERATED_PLUGINS) -$(GENERATED_PLUGINS): - make -C $(GENERATED_PLUGINS_DIR)/$@/linux \ - OUT_DIR=$(OUT_DIR) \ - FLUTTER_EPHEMERAL_DIR="$(abspath flutter/ephemeral)" diff --git a/linux/main.cc b/linux/main.cc index 7549c0e..e92332d 100644 --- a/linux/main.cc +++ b/linux/main.cc @@ -1,16 +1,4 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +#include #include #include #include @@ -21,37 +9,26 @@ #include #include "flutter/generated_plugin_registrant.h" +#include "window_configuration.h" namespace { -// Returns the path of the directory containing this executable, or an empty -// string if the directory cannot be found. -std::string GetExecutableDirectory() { - char buffer[PATH_MAX + 1]; - ssize_t length = readlink("/proc/self/exe", buffer, sizeof(buffer)); - if (length > PATH_MAX) { - std::cerr << "Couldn't locate executable" << std::endl; - return ""; +// Runs the application in headless mode, without a window. +void RunHeadless(const std::string& icu_data_path, + const std::string& assets_path, + const std::vector& arguments) { + flutter::FlutterEngine engine; + engine.Start(icu_data_path, assets_path, arguments); + RegisterPlugins(&engine); + while (true) { + engine.RunEventLoopWithTimeout(); } - std::string executable_path(buffer, length); - size_t last_separator_position = executable_path.find_last_of('/'); - if (last_separator_position == std::string::npos) { - std::cerr << "Unabled to find parent directory of " << executable_path - << std::endl; - return ""; - } - return executable_path.substr(0, last_separator_position); } } // namespace int main(int argc, char **argv) { - // Resources are located relative to the executable. - std::string base_directory = GetExecutableDirectory(); - if (base_directory.empty()) { - base_directory = "."; - } - std::string data_directory = base_directory + "/data"; + std::string data_directory = "data"; std::string assets_path = data_directory + "/flutter_assets"; std::string icu_data_path = data_directory + "/icudtl.dat"; @@ -60,20 +37,24 @@ int main(int argc, char **argv) { flutter::FlutterWindowController flutter_controller(icu_data_path); flutter::WindowProperties window_properties = {}; - window_properties.title = "Flutter Desktop Example"; - window_properties.width = 800; - window_properties.height = 600; + window_properties.title = kFlutterWindowTitle; + window_properties.width = kFlutterWindowWidth; + window_properties.height = kFlutterWindowHeight; // Start the engine. if (!flutter_controller.CreateWindow(window_properties, assets_path, arguments)) { + if (getenv("DISPLAY") == nullptr) { + std::cout << "No DISPLAY; falling back to headless mode." << std::endl; + RunHeadless(icu_data_path, assets_path, arguments); + return EXIT_SUCCESS; + } return EXIT_FAILURE; } RegisterPlugins(&flutter_controller); // Run until the window is closed. - while (flutter_controller.RunEventLoopWithTimeout( - std::chrono::milliseconds::max())) { + while (flutter_controller.RunEventLoopWithTimeout()) { } return EXIT_SUCCESS; } diff --git a/linux/window_configuration.cc b/linux/window_configuration.cc new file mode 100644 index 0000000..f044be2 --- /dev/null +++ b/linux/window_configuration.cc @@ -0,0 +1,5 @@ +#include "window_configuration.h" + +const char *kFlutterWindowTitle = "flutter_uis"; +const unsigned int kFlutterWindowWidth = 1280; +const unsigned int kFlutterWindowHeight = 720; diff --git a/linux/window_configuration.h b/linux/window_configuration.h new file mode 100644 index 0000000..5de7011 --- /dev/null +++ b/linux/window_configuration.h @@ -0,0 +1,15 @@ +#ifndef WINDOW_CONFIGURATION_ +#define WINDOW_CONFIGURATION_ + +// This is a temporary approach to isolate common customizations from main.cpp, +// where the APIs are still in flux. This should simplify re-creating the +// runner while preserving local changes. +// +// Longer term there should be simpler configuration options for common +// customizations like this, without requiring native code changes. + +extern const char *kFlutterWindowTitle; +extern const unsigned int kFlutterWindowWidth; +extern const unsigned int kFlutterWindowHeight; + +#endif // WINDOW_CONFIGURATION_ diff --git a/windows/.gitignore b/windows/.gitignore index 3738443..d492d0d 100644 --- a/windows/.gitignore +++ b/windows/.gitignore @@ -1,333 +1,17 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# Local additions, not from the link above flutter/ephemeral/ -# User-specific files +# Visual Studio user-specific files. *.suo *.user *.userosscache *.sln.docstates -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ +# Visual Studio build-related files. x64/ x86/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# JetBrains Rider -.idea/ -*.sln.iml - -# CodeRush -.cr/ - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ -GeneratedPlugins.props \ No newline at end of file diff --git a/windows/AppConfiguration.props b/windows/AppConfiguration.props index 8707315..56f6883 100644 --- a/windows/AppConfiguration.props +++ b/windows/AppConfiguration.props @@ -1,6 +1,6 @@ - - - - Flutter Desktop Example - - + + + + flutter_uis + + diff --git a/windows/FlutterBuild.vcxproj b/windows/FlutterBuild.vcxproj index e07664d..5570a46 100644 --- a/windows/FlutterBuild.vcxproj +++ b/windows/FlutterBuild.vcxproj @@ -1,46 +1,50 @@ - - - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F} - Flutter Build - 10.0.17763.0 - - - - v141 - v142 - - - - - - - - - - - - - - "$(ProjectDir)scripts\prepare_dependencies" $(Configuration) - Running Flutter backend build - force_to_run_every_time - - - - - - - - + + + + + Debug + x64 + + + Profile + x64 + + + Release + x64 + + + + 15.0 + {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F} + Flutter Build + 10.0 + + + + v141 + v142 + + + + + + + + + + + + + + "$(ProjectDir)scripts\prepare_dependencies" $(Configuration) + Running Flutter backend build + force_to_run_every_time + + + + + + + + diff --git a/windows/FlutterPlugins.props b/windows/FlutterPlugins.props deleted file mode 100644 index acd407e..0000000 --- a/windows/FlutterPlugins.props +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - %(AdditionalDependencies) - - - diff --git a/windows/Runner.rc b/windows/Runner.rc deleted file mode 100644 index 24f0a45..0000000 Binary files a/windows/Runner.rc and /dev/null differ diff --git a/windows/Runner.sln b/windows/Runner.sln index 06e0c6f..373d0ee 100644 --- a/windows/Runner.sln +++ b/windows/Runner.sln @@ -1,38 +1,43 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.28307.645 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Runner", "Runner.vcxproj", "{5A827760-CF8B-408A-99A3-B6C0AD2271E7}" - ProjectSection(ProjectDependencies) = postProject - {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F} = {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Flutter Build", "FlutterBuild.vcxproj", "{6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}" -EndProject + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Runner", "Runner.vcxproj", "{5A827760-CF8B-408A-99A3-B6C0AD2271E7}" + ProjectSection(ProjectDependencies) = postProject + {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F} = {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Flutter Build", "FlutterBuild.vcxproj", "{6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}" +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Flutter Plugins", "Flutter Plugins", "{5C2E738A-1DD3-445A-AAC8-EEB9648DD07C}" EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Debug|x64.ActiveCfg = Debug|x64 - {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Debug|x64.Build.0 = Debug|x64 - {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Release|x64.ActiveCfg = Release|x64 - {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Release|x64.Build.0 = Release|x64 - {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Debug|x64.ActiveCfg = Debug|x64 - {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Debug|x64.Build.0 = Debug|x64 - {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Release|x64.ActiveCfg = Release|x64 - {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {B8A69CB0-A974-4774-9EBD-1E5EECACD186} - EndGlobalSection +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Profile|x64 = Profile|x64 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Debug|x64.ActiveCfg = Debug|x64 + {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Debug|x64.Build.0 = Debug|x64 + {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Profile|x64.ActiveCfg = Profile|x64 + {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Profile|x64.Build.0 = Profile|x64 + {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Release|x64.ActiveCfg = Release|x64 + {5A827760-CF8B-408A-99A3-B6C0AD2271E7}.Release|x64.Build.0 = Release|x64 + {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Debug|x64.ActiveCfg = Debug|x64 + {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Debug|x64.Build.0 = Debug|x64 + {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Profile|x64.ActiveCfg = Profile|x64 + {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Profile|x64.Build.0 = Profile|x64 + {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Release|x64.ActiveCfg = Release|x64 + {6419BF13-6ECD-4CD2-9E85-E566A1F03F8F}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B8A69CB0-A974-4774-9EBD-1E5EECACD186} + EndGlobalSection GlobalSection(NestedProjects) = preSolution EndGlobalSection EndGlobal \ No newline at end of file diff --git a/windows/Runner.vcxproj b/windows/Runner.vcxproj index 43d3559..e16b7e4 100644 --- a/windows/Runner.vcxproj +++ b/windows/Runner.vcxproj @@ -1,185 +1,262 @@ - - - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {5A827760-CF8B-408A-99A3-B6C0AD2271E7} - GLFWExample - 10.0.17763.0 - - - - Application - true - v141 - v142 - Unicode - - - Application - false - v141 - v142 - true - Unicode - - - - - - - - - - - - - - - - - - - - - $(ProjectDir)..\build\windows\$(Platform)\$(Configuration)\$(ProjectName)\ - $(ProjectDir)..\build\windows\intermediates\$(Platform)\$(Configuration)\$(ProjectName)\ - $(ProjectDir);$(FLUTTER_EPHEMERAL_DIR)\;$(FLUTTER_EPHEMERAL_DIR)\cpp_client_wrapper\include\;$(OutDir)..\Plugins;$(IncludePath) - $(FLUTTER_EPHEMERAL_DIR);$(OutDir)..\Plugins;$(LibraryPath) - - - $(ProjectDir)..\build\windows\$(Platform)\$(Configuration)\$(ProjectName)\ - $(ProjectDir)..\build\windows\intermediates\$(Platform)\$(Configuration)\$(ProjectName)\ - $(ProjectDir);$(FLUTTER_EPHEMERAL_DIR)\;$(FLUTTER_EPHEMERAL_DIR)\cpp_client_wrapper\include\;$(OutDir)..\Plugins;$(IncludePath) - $(FLUTTER_EPHEMERAL_DIR);$(OutDir)..\Plugins;$(LibraryPath) - - - - Level3 - Disabled - true - true - - - _MBCS;%(PreprocessorDefinitions) - - - flutter_windows.dll.lib;Shcore.lib;%(AdditionalDependencies) - - - - - - - - - - - - - - - - - - - - - - - "$(ProjectDir)scripts\bundle_assets_and_deps" "$(FLUTTER_EPHEMERAL_DIR)\" "$(OutputPath)" "$(OutputPath)..\Plugins\" "$(TargetFileName)" - - - Bundling dependencies - Dummy_Run_Always - - - - - - - Level3 - MaxSpeed - true - true - true - true - - - _MBCS;%(PreprocessorDefinitions) - - - true - true - flutter_windows.dll.lib;Shcore.lib;%(AdditionalDependencies) - - - - - - - - - - - - - - - - - - - - - - - "$(ProjectDir)scripts\bundle_assets_and_deps" "$(FLUTTER_EPHEMERAL_DIR)\" "$(OutputPath)" "$(OutputPath)..\Plugins\" "$(TargetFileName)" - - - Bundling dependencies - Dummy_Run_Always - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(SolutionDir) - - + + + + + Debug + x64 + + + Profile + x64 + + + Release + x64 + + + + 15.0 + {5A827760-CF8B-408A-99A3-B6C0AD2271E7} + flutter_uis + 10.0 + + + + Application + true + v141 + v142 + Unicode + + + Application + false + v141 + v142 + true + Unicode + + + Application + false + v141 + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + + + + + + $(ProjectDir)..\build\windows\$(Platform)\$(Configuration)\$(ProjectName)\ + $(ProjectDir)..\build\windows\intermediates\$(Platform)\$(Configuration)\$(ProjectName)\ + + + $(ProjectDir)..\build\windows\$(Platform)\$(Configuration)\$(ProjectName)\ + $(ProjectDir)..\build\windows\intermediates\$(Platform)\$(Configuration)\$(ProjectName)\ + + + $(ProjectDir)..\build\windows\$(Platform)\$(Configuration)\$(ProjectName)\ + $(ProjectDir)..\build\windows\intermediates\$(Platform)\$(Configuration)\$(ProjectName)\ + + + + Level4 + Disabled + true + true + $(ProjectDir);$(FLUTTER_EPHEMERAL_DIR);$(FLUTTER_EPHEMERAL_DIR)\cpp_client_wrapper\include;%(AdditionalIncludeDirectories) + _MBCS;_HAS_EXCEPTIONS=0;%(PreprocessorDefinitions) + true + 4100 + + + flutter_windows.dll.lib;%(AdditionalDependencies) + $(FLUTTER_EPHEMERAL_DIR);$(OutDir)..\Plugins;%(AdditionalLibraryDirectories) + + + + + + + + + + + + + + + + + + + + + + + "$(ProjectDir)scripts\bundle_assets_and_deps" "$(FLUTTER_EPHEMERAL_DIR)\" "$(OutputPath)" "$(OutputPath)..\Plugins\" "$(TargetFileName)" + + + Bundling dependencies + Dummy_Run_Always + + + + + + + Level4 + MaxSpeed + true + true + true + true + $(ProjectDir);$(FLUTTER_EPHEMERAL_DIR);$(FLUTTER_EPHEMERAL_DIR)\cpp_client_wrapper\include;%(AdditionalIncludeDirectories) + _MBCS;_HAS_EXCEPTIONS=0;%(PreprocessorDefinitions) + true + 4100 + + + true + true + flutter_windows.dll.lib;%(AdditionalDependencies) + $(FLUTTER_EPHEMERAL_DIR);$(OutDir)..\Plugins;%(AdditionalLibraryDirectories) + + + + + + + + + + + + + + + + + + + + + + + "$(ProjectDir)scripts\bundle_assets_and_deps" "$(FLUTTER_EPHEMERAL_DIR)\" "$(OutputPath)" "$(OutputPath)..\Plugins\" "$(TargetFileName)" + + + Bundling dependencies + Dummy_Run_Always + + + + + + + Level4 + MaxSpeed + true + true + true + true + $(ProjectDir);$(FLUTTER_EPHEMERAL_DIR);$(FLUTTER_EPHEMERAL_DIR)\cpp_client_wrapper\include;%(AdditionalIncludeDirectories) + _MBCS;_HAS_EXCEPTIONS=0;%(PreprocessorDefinitions) + true + 4100 + + + true + true + flutter_windows.dll.lib;%(AdditionalDependencies) + $(FLUTTER_EPHEMERAL_DIR);$(OutDir)..\Plugins;%(AdditionalLibraryDirectories) + + + + + + + + + + + + + + + + + + + + + + + "$(ProjectDir)scripts\bundle_assets_and_deps" "$(FLUTTER_EPHEMERAL_DIR)\" "$(OutputPath)" "$(OutputPath)..\Plugins\" "$(TargetFileName)" + + + Bundling dependencies + Dummy_Run_Always + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $(SolutionDir) + + diff --git a/windows/Runner.vcxproj.filters b/windows/Runner.vcxproj.filters index 5d3499c..d7a8b1e 100644 --- a/windows/Runner.vcxproj.filters +++ b/windows/Runner.vcxproj.filters @@ -1,70 +1,88 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - {2761a4b5-57b2-4d50-a677-d20ddc17a7f1} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files\Client Wrapper - - - Source Files\Client Wrapper - - - Source Files\Client Wrapper - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - - - - Resource Files - - - - - Resource Files - - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {2761a4b5-57b2-4d50-a677-d20ddc17a7f1} + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files\Client Wrapper + + + Source Files\Client Wrapper + + + Source Files\Client Wrapper + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + + + + Resource Files + + + + + Resource Files + + + diff --git a/windows/flutter/.template_version b/windows/flutter/.template_version new file mode 100644 index 0000000..0cfbf08 --- /dev/null +++ b/windows/flutter/.template_version @@ -0,0 +1 @@ +2 diff --git a/windows/main.cpp b/windows/main.cpp deleted file mode 100644 index 0aefa0e..0000000 --- a/windows/main.cpp +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include -#include - -#include -#include -#include -#include -#include - -#include "flutter/generated_plugin_registrant.h" -#include "win32_window.h" -#include "window_configuration.h" - -namespace { - -// Returns the path of the directory containing this executable, or an empty -// string if the directory cannot be found. -std::string GetExecutableDirectory() { - wchar_t buffer[MAX_PATH]; - if (GetModuleFileName(nullptr, buffer, MAX_PATH) == 0) { - std::cerr << "Couldn't locate executable" << std::endl; - return ""; - } - std::wstring_convert> wide_to_utf8; - std::string executable_path = wide_to_utf8.to_bytes(buffer); - size_t last_separator_position = executable_path.find_last_of('\\'); - if (last_separator_position == std::string::npos) { - std::cerr << "Unabled to find parent directory of " << executable_path - << std::endl; - return ""; - } - return executable_path.substr(0, last_separator_position); -} - -} // namespace - -int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prev, wchar_t *command_line, - 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()) { - ::AllocConsole(); - } - - // Resources are located relative to the executable. - std::string base_directory = GetExecutableDirectory(); - if (base_directory.empty()) { - base_directory = "."; - } - std::string data_directory = base_directory + "\\data"; - std::string assets_path = data_directory + "\\flutter_assets"; - std::string icu_data_path = data_directory + "\\icudtl.dat"; - - // Arguments for the Flutter Engine. - std::vector arguments; - - // Top-level window frame. - Win32Window::Point origin(kFlutterWindowOriginX, kFlutterWindowOriginY); - Win32Window::Size size(kFlutterWindowWidth, kFlutterWindowHeight); - - flutter::FlutterViewController flutter_controller( - icu_data_path, size.width, size.height, assets_path, arguments); - RegisterPlugins(&flutter_controller); - - // Create a top-level win32 window to host the Flutter view. - Win32Window window; - if (!window.CreateAndShow(kFlutterWindowTitle, origin, size)) { - return EXIT_FAILURE; - } - - // Parent and resize Flutter view into top-level window. - window.SetChildContent(flutter_controller.view()->GetNativeWindow()); - - // Run messageloop with a hook for flutter_controller to do work until - // the window is closed. - std::chrono::nanoseconds wait_duration(0); - // Run until the window is closed. - while (window.GetHandle() != nullptr) { - MsgWaitForMultipleObjects(0, NULL, FALSE, - static_cast(wait_duration.count() / 1000), - QS_ALLINPUT); - MSG message; - // All pending Windows messages must be processed; MsgWaitForMultipleObjects - // won't return again for items left in the queue after PeekMessage. - while (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { - if (message.message == WM_QUIT) { - window.Destroy(); - break; - } - TranslateMessage(&message); - DispatchMessage(&message); - } - // Allow Flutter to process its messages. - // TODO: Consider interleaving processing on a per-message basis to avoid - // the possibility of one queue starving the other. - wait_duration = flutter_controller.ProcessMessages(); - } - - return EXIT_SUCCESS; -} diff --git a/windows/resources/app_icon.ico b/windows/resources/app_icon.ico deleted file mode 100644 index ce783f3..0000000 Binary files a/windows/resources/app_icon.ico and /dev/null differ diff --git a/windows/runner.exe.manifest b/windows/runner.exe.manifest deleted file mode 100644 index 26b3834..0000000 --- a/windows/runner.exe.manifest +++ /dev/null @@ -1,8 +0,0 @@ - - - - - PerMonitorV2 - - - \ No newline at end of file diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..7d86499 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,70 @@ +// 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" + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..fe980cf --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,29 @@ +#include "flutter_window.h" + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(RunLoop* run_loop, + const flutter::DartProject& project) + : run_loop_(run_loop), project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +void FlutterWindow::OnCreate() { + Win32Window::OnCreate(); + + // The size here is arbitrary since SetChildContent will resize it. + flutter_controller_ = + std::make_unique(100, 100, project_); + RegisterPlugins(flutter_controller_.get()); + run_loop_->RegisterFlutterInstance(flutter_controller_.get()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + run_loop_->UnregisterFlutterInstance(flutter_controller_.get()); + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..4f41e16 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,37 @@ +#ifndef FLUTTER_WINDOW_H_ +#define FLUTTER_WINDOW_H_ + +#include +#include + +#include "run_loop.h" +#include "win32_window.h" + +#include + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow driven by the |run_loop|, hosting a + // Flutter view running |project|. + explicit FlutterWindow(RunLoop* run_loop, + const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + void OnCreate() override; + void OnDestroy() override; + + private: + // The run loop driving events for this window. + RunLoop* run_loop_; + + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..11b48e9 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,37 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "run_loop.h" +#include "utils.h" +#include "window_configuration.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); + + RunLoop run_loop; + + flutter::DartProject project(L"data"); + FlutterWindow window(&run_loop, project); + Win32Window::Point origin(kFlutterWindowOriginX, kFlutterWindowOriginY); + Win32Window::Size size(kFlutterWindowWidth, kFlutterWindowHeight); + if (!window.CreateAndShow(kFlutterWindowTitle, origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + run_loop.Run(); + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/resource.h b/windows/runner/resource.h similarity index 99% rename from windows/resource.h rename to windows/runner/resource.h index 54ea751..66a65d1 100644 --- a/windows/resource.h +++ b/windows/runner/resource.h @@ -5,7 +5,7 @@ #define IDI_APP_ICON 101 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 102 diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/run_loop.cpp b/windows/runner/run_loop.cpp new file mode 100644 index 0000000..f91d6d4 --- /dev/null +++ b/windows/runner/run_loop.cpp @@ -0,0 +1,70 @@ +#include "run_loop.h" + +#include +// Don't stomp std::min/std::max +#undef max +#undef min + +#include + +RunLoop::RunLoop() {} + +RunLoop::~RunLoop() {} + +void RunLoop::Run() { + bool keep_running = true; + TimePoint next_flutter_event_time = TimePoint::clock::now(); + while (keep_running) { + std::chrono::nanoseconds wait_duration = + std::max(std::chrono::nanoseconds(0), + next_flutter_event_time - TimePoint::clock::now()); + ::MsgWaitForMultipleObjects( + 0, nullptr, FALSE, static_cast(wait_duration.count() / 1000), + QS_ALLINPUT); + bool processed_events = false; + MSG message; + // All pending Windows messages must be processed; MsgWaitForMultipleObjects + // won't return again for items left in the queue after PeekMessage. + while (::PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { + processed_events = true; + if (message.message == WM_QUIT) { + keep_running = false; + break; + } + ::TranslateMessage(&message); + ::DispatchMessage(&message); + // Allow Flutter to process messages each time a Windows message is + // processed, to prevent starvation. + next_flutter_event_time = + std::min(next_flutter_event_time, ProcessFlutterMessages()); + } + // If the PeekMessage loop didn't run, process Flutter messages. + if (!processed_events) { + next_flutter_event_time = + std::min(next_flutter_event_time, ProcessFlutterMessages()); + } + } +} + +void RunLoop::RegisterFlutterInstance( + flutter::FlutterViewController* flutter_instance) { + flutter_instances_.insert(flutter_instance); +} + +void RunLoop::UnregisterFlutterInstance( + flutter::FlutterViewController* flutter_instance) { + flutter_instances_.erase(flutter_instance); +} + +RunLoop::TimePoint RunLoop::ProcessFlutterMessages() { + TimePoint next_event_time = TimePoint::max(); + for (auto flutter_controller : flutter_instances_) { + std::chrono::nanoseconds wait_duration = + flutter_controller->ProcessMessages(); + if (wait_duration != std::chrono::nanoseconds::max()) { + next_event_time = + std::min(next_event_time, TimePoint::clock::now() + wait_duration); + } + } + return next_event_time; +} diff --git a/windows/runner/run_loop.h b/windows/runner/run_loop.h new file mode 100644 index 0000000..442a58e --- /dev/null +++ b/windows/runner/run_loop.h @@ -0,0 +1,40 @@ +#ifndef RUN_LOOP_H_ +#define RUN_LOOP_H_ + +#include + +#include +#include + +// A runloop that will service events for Flutter instances as well +// as native messages. +class RunLoop { + public: + RunLoop(); + ~RunLoop(); + + // Prevent copying + RunLoop(RunLoop const&) = delete; + RunLoop& operator=(RunLoop const&) = delete; + + // Runs the run loop until the application quits. + void Run(); + + // Registers the given Flutter instance for event servicing. + void RegisterFlutterInstance( + flutter::FlutterViewController* flutter_instance); + + // Unregisters the given Flutter instance from event servicing. + void UnregisterFlutterInstance( + flutter::FlutterViewController* flutter_instance); + + private: + using TimePoint = std::chrono::steady_clock::time_point; + + // Processes all currently pending messages for registered Flutter instances. + TimePoint ProcessFlutterMessages(); + + std::set flutter_instances_; +}; + +#endif // RUN_LOOP_H_ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..c977c4a --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..37501e5 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,22 @@ +#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(); + } +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..d247a66 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,8 @@ +#ifndef CONSOLE_UTILS_H_ +#define CONSOLE_UTILS_H_ + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +#endif // CONSOLE_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..677a9a6 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,249 @@ +#include "win32_window.h" + +#include + +#include "resource.h" + +namespace { + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +// 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::CreateAndShow(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 | WS_VISIBLE, + 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); + + OnCreate(); + + return window != nullptr; +} + +// 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 { + auto window = + reinterpret_cast(GetWindowLongPtr(hwnd, GWLP_USERDATA)); + + if (window == nullptr) { + return 0; + } + + 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; + GetClientRect(hwnd, &rect); + 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; + + // Messages that are directly forwarded to embedding. + case WM_FONTCHANGE: + SendMessage(child_content_, WM_FONTCHANGE, NULL, NULL); + 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; + GetClientRect(window_handle_, &frame); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +void Win32Window::OnCreate() { + // No-op; provided for subclasses. +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} diff --git a/windows/win32_window.h b/windows/runner/win32_window.h similarity index 70% rename from windows/win32_window.h rename to windows/runner/win32_window.h index c6cf1bb..5cbb5d5 100644 --- a/windows/win32_window.h +++ b/windows/runner/win32_window.h @@ -1,7 +1,3 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - #ifndef WIN32_WINDOW_H_ #define WIN32_WINDOW_H_ @@ -31,7 +27,7 @@ class Win32Window { }; Win32Window(); - ~Win32Window(); + virtual ~Win32Window(); // Creates and shows a win32 window with |title| and position and size using // |origin| and |size|. New windows are created on the default monitor. Window @@ -39,10 +35,11 @@ class Win32Window { // consistent size to will treat the width height passed in to this function // as logical pixels and scale to appropriate for the default monitor. Returns // true if the window was created successfully. - bool CreateAndShow(const std::wstring &title, const Point &origin, - const Size &size); + bool CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size); - // Release OS resources asociated with window. + // Release OS resources associated with window. void Destroy(); // Inserts |content| into the window tree. @@ -52,33 +49,42 @@ class Win32Window { // 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); + protected: - // Registers a window class with default style attributes, cursor and - // icon. - WNDCLASS RegisterWindowClass(); + // 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. + virtual void 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, + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; - // 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. - LRESULT - MessageHandler(HWND window, UINT const message, WPARAM const wparam, - LPARAM const lparam) noexcept; - - private: - // should message loop keep running - bool messageloop_running_ = true; - // Retrieves a class instance pointer for |window| - static Win32Window *GetThisFromHandle(HWND const window) noexcept; + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + bool quit_on_close_ = false; // window handle for top level window. HWND window_handle_ = nullptr; diff --git a/windows/runner/window_configuration.cpp b/windows/runner/window_configuration.cpp new file mode 100644 index 0000000..514a691 --- /dev/null +++ b/windows/runner/window_configuration.cpp @@ -0,0 +1,7 @@ +#include "window_configuration.h" + +const wchar_t* kFlutterWindowTitle = L"flutter_uis"; +const unsigned int kFlutterWindowOriginX = 10; +const unsigned int kFlutterWindowOriginY = 10; +const unsigned int kFlutterWindowWidth = 1280; +const unsigned int kFlutterWindowHeight = 720; diff --git a/windows/runner/window_configuration.h b/windows/runner/window_configuration.h new file mode 100644 index 0000000..ea5cead --- /dev/null +++ b/windows/runner/window_configuration.h @@ -0,0 +1,18 @@ +#ifndef WINDOW_CONFIGURATION_ +#define WINDOW_CONFIGURATION_ + +// This is a temporary approach to isolate changes that people are likely to +// make to main.cpp, where the APIs are still in flux. This will reduce the +// need to resolve conflicts or re-create changes slightly differently every +// time the Windows Flutter API surface changes. +// +// Longer term there should be simpler configuration options for common +// customizations like this, without requiring native code changes. + +extern const wchar_t* kFlutterWindowTitle; +extern const unsigned int kFlutterWindowOriginX; +extern const unsigned int kFlutterWindowOriginY; +extern const unsigned int kFlutterWindowWidth; +extern const unsigned int kFlutterWindowHeight; + +#endif // WINDOW_CONFIGURATION_ diff --git a/windows/scripts/bundle_assets_and_deps.bat b/windows/scripts/bundle_assets_and_deps.bat index 86ecfd9..87c3b6f 100644 --- a/windows/scripts/bundle_assets_and_deps.bat +++ b/windows/scripts/bundle_assets_and_deps.bat @@ -1,50 +1,37 @@ -:: Copyright 2018 Google LLC -:: -:: Licensed under the Apache License, Version 2.0 (the "License"); -:: you may not use this file except in compliance with the License. -:: You may obtain a copy of the License at -:: -:: http://www.apache.org/licenses/LICENSE-2.0 -:: -:: Unless required by applicable law or agreed to in writing, software -:: distributed under the License is distributed on an "AS IS" BASIS, -:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -:: See the License for the specific language governing permissions and -:: limitations under the License. -@echo off - -set FLUTTER_CACHE_DIR=%~1 -set BUNDLE_DIR=%~2 -set PLUGIN_DIR=%~3 -set EXE_NAME=%~4 - -set DATA_DIR=%BUNDLE_DIR%data - -if not exist "%DATA_DIR%" call mkdir "%DATA_DIR%" -if %errorlevel% neq 0 exit /b %errorlevel% - -:: Write the executable name to the location expected by the Flutter tool. -echo %EXE_NAME%>"%FLUTTER_CACHE_DIR%exe_filename" - -:: Copy the Flutter assets to the data directory. -set FLUTTER_APP_DIR=%~dp0..\.. -set ASSET_DIR_NAME=flutter_assets -set TARGET_ASSET_DIR=%DATA_DIR%\%ASSET_DIR_NAME% -if exist "%TARGET_ASSET_DIR%" call rmdir /s /q "%TARGET_ASSET_DIR%" -if %errorlevel% neq 0 exit /b %errorlevel% -call xcopy /s /e /i /q "%FLUTTER_APP_DIR%\build\%ASSET_DIR_NAME%" "%TARGET_ASSET_DIR%" -if %errorlevel% neq 0 exit /b %errorlevel% - -:: Copy the icudtl.dat file from the Flutter tree to the data directory. -call xcopy /y /d /q "%FLUTTER_CACHE_DIR%icudtl.dat" "%DATA_DIR%" -if %errorlevel% neq 0 exit /b %errorlevel% - -:: Copy the Flutter DLL to the target location. -call xcopy /y /d /q "%FLUTTER_CACHE_DIR%flutter_windows.dll" "%BUNDLE_DIR%" -if %errorlevel% neq 0 exit /b %errorlevel% - -:: Copy any Plugin DLLs to the target location. -if exist "%PLUGIN_DIR%" ( - call xcopy /y /d /q "%PLUGIN_DIR%"*.dll "%BUNDLE_DIR%" - if %errorlevel% neq 0 exit /b %errorlevel% -) +@echo off + +set FLUTTER_CACHE_DIR=%~1 +set BUNDLE_DIR=%~2 +set PLUGIN_DIR=%~3 +set EXE_NAME=%~4 + +set DATA_DIR=%BUNDLE_DIR%data + +if not exist "%DATA_DIR%" call mkdir "%DATA_DIR%" +if %errorlevel% neq 0 exit /b %errorlevel% + +:: Write the executable name to the location expected by the Flutter tool. +echo %EXE_NAME%>"%FLUTTER_CACHE_DIR%exe_filename" + +:: Copy the Flutter assets to the data directory. +set FLUTTER_APP_DIR=%~dp0..\.. +set ASSET_DIR_NAME=flutter_assets +set TARGET_ASSET_DIR=%DATA_DIR%\%ASSET_DIR_NAME% +if exist "%TARGET_ASSET_DIR%" call rmdir /s /q "%TARGET_ASSET_DIR%" +if %errorlevel% neq 0 exit /b %errorlevel% +call xcopy /s /e /i /q "%FLUTTER_APP_DIR%\build\%ASSET_DIR_NAME%" "%TARGET_ASSET_DIR%" +if %errorlevel% neq 0 exit /b %errorlevel% + +:: Copy the icudtl.dat file from the Flutter tree to the data directory. +call xcopy /y /d /q "%FLUTTER_CACHE_DIR%icudtl.dat" "%DATA_DIR%" +if %errorlevel% neq 0 exit /b %errorlevel% + +:: Copy the Flutter DLL to the target location. +call xcopy /y /d /q "%FLUTTER_CACHE_DIR%flutter_windows.dll" "%BUNDLE_DIR%" +if %errorlevel% neq 0 exit /b %errorlevel% + +:: Copy any Plugin DLLs to the target location. +if exist "%PLUGIN_DIR%" ( + call xcopy /y /d /q "%PLUGIN_DIR%"*.dll "%BUNDLE_DIR%" + if %errorlevel% neq 0 exit /b %errorlevel% +) diff --git a/windows/scripts/prepare_dependencies.bat b/windows/scripts/prepare_dependencies.bat index d36b5a8..b2d161c 100644 --- a/windows/scripts/prepare_dependencies.bat +++ b/windows/scripts/prepare_dependencies.bat @@ -1,18 +1,5 @@ -:: Copyright 2018 Google LLC -:: -:: Licensed under the Apache License, Version 2.0 (the "License"); -:: you may not use this file except in compliance with the License. -:: You may obtain a copy of the License at -:: -:: http://www.apache.org/licenses/LICENSE-2.0 -:: -:: Unless required by applicable law or agreed to in writing, software -:: distributed under the License is distributed on an "AS IS" BASIS, -:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -:: See the License for the specific language governing permissions and -:: limitations under the License. -@echo off - -:: Run flutter tool backend. -set BUILD_MODE=%~1 -"%FLUTTER_ROOT%\packages\flutter_tools\bin\tool_backend" windows-x64 %BUILD_MODE% +@echo off + +:: Run flutter tool backend. +set BUILD_MODE=%~1 +"%FLUTTER_ROOT%\packages\flutter_tools\bin\tool_backend" windows-x64 %BUILD_MODE% diff --git a/windows/win32_window.cc b/windows/win32_window.cc deleted file mode 100644 index 2c53584..0000000 --- a/windows/win32_window.cc +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2013 The Flutter Authors. 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 "resource.h" -#include "shellscalingapi.h" - -namespace { - -// the Windows DPI system is based on this -// constant for machines running at 100% scaling. -constexpr int kBaseDpi = 96; - -constexpr LPCWSTR kClassName = L"CLASSNAME"; - -// 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); -} - -} // namespace - -Win32Window::Win32Window() {} - -Win32Window::~Win32Window() { Destroy(); } - -bool Win32Window::CreateAndShow(const std::wstring &title, const Point &origin, - const Size &size) { - Destroy(); - - WNDCLASS window_class = RegisterWindowClass(); - - HMONITOR defaut_monitor = - MonitorFromWindow(nullptr, MONITOR_DEFAULTTOPRIMARY); - UINT dpi_x = 0, dpi_y = 0; - GetDpiForMonitor(defaut_monitor, MDT_EFFECTIVE_DPI, &dpi_x, &dpi_y); - - double scale_factor = static_cast(dpi_x) / kBaseDpi; - - HWND window = CreateWindow( - window_class.lpszClassName, title.c_str(), - WS_OVERLAPPEDWINDOW | WS_VISIBLE, Scale(origin.x, scale_factor), - Scale(origin.y, scale_factor), Scale(size.width, scale_factor), - Scale(size.height, scale_factor), nullptr, nullptr, - window_class.hInstance, this); - return window != nullptr; -} - -WNDCLASS Win32Window::RegisterWindowClass() { - WNDCLASS window_class{}; - window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); - window_class.lpszClassName = kClassName; - 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 = WndProc; - RegisterClass(&window_class); - return window_class; -} - -LRESULT CALLBACK Win32Window::WndProc(HWND const window, UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - if (message == WM_NCCREATE) { - auto cs = reinterpret_cast(lparam); - SetWindowLongPtr(window, GWLP_USERDATA, - reinterpret_cast(cs->lpCreateParams)); - - auto that = static_cast(cs->lpCreateParams); - - 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 { - auto window = - reinterpret_cast(GetWindowLongPtr(hwnd, GWLP_USERDATA)); - - if (window == nullptr) { - return 0; - } - - switch (message) { - case WM_DESTROY: - window_handle_ = nullptr; - Destroy(); - return 0; - - case WM_SIZE: - RECT rect; - GetClientRect(hwnd, &rect); - 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; - - // Messages that are directly forwarded to embedding. - case WM_FONTCHANGE: - SendMessage(child_content_, WM_FONTCHANGE, NULL, NULL); - return 0; - } - - return DefWindowProc(window_handle_, message, wparam, lparam); -} - -void Win32Window::Destroy() { - if (window_handle_) { - DestroyWindow(window_handle_); - window_handle_ = nullptr; - } - - UnregisterClass(kClassName, nullptr); -} - -Win32Window *Win32Window::GetThisFromHandle(HWND const window) noexcept { - return reinterpret_cast( - GetWindowLongPtr(window, GWLP_USERDATA)); -} - -void Win32Window::SetChildContent(HWND content) { - child_content_ = content; - auto res = SetParent(content, window_handle_); - RECT frame; - GetClientRect(window_handle_, &frame); - - MoveWindow(content, frame.left, frame.top, frame.right - frame.left, - frame.bottom - frame.top, true); - - SetFocus(child_content_); -} - -HWND Win32Window::GetHandle() { return window_handle_; } diff --git a/windows/window_configuration.cpp b/windows/window_configuration.cpp deleted file mode 100644 index 27975d3..0000000 --- a/windows/window_configuration.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "window_configuration.h" - -const wchar_t *kFlutterWindowTitle = L"Flutter Desktop Example"; -const unsigned int kFlutterWindowOriginX = 10; -const unsigned int kFlutterWindowOriginY = 10; -const unsigned int kFlutterWindowWidth = 800; -const unsigned int kFlutterWindowHeight = 600; diff --git a/windows/window_configuration.h b/windows/window_configuration.h deleted file mode 100644 index 5ee5586..0000000 --- a/windows/window_configuration.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef WINDOW_CONFIGURATION_ -#define WINDOW_CONFIGURATION_ - -// This is a temporary approach to isolate changes that people are likely to -// make to the example project from main.cpp, where the APIs are still in flux. -// This will avoid people needing to resolve conflicts or re-create changes -// slightly different every time the Windows Flutter API surface changes just -// because of, e.g., a local change to the window title. -// -// Longer term there should be simpler configuration options for common -// customizations like this, without requiring native code changes. - -extern const wchar_t *kFlutterWindowTitle; -extern const unsigned int kFlutterWindowOriginX; -extern const unsigned int kFlutterWindowOriginY; -extern const unsigned int kFlutterWindowWidth; -extern const unsigned int kFlutterWindowHeight; - -#endif // WINDOW_CONFIGURATION_