text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
# 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. assert(is_fuchsia) import("//flutter/tools/fuchsia/fuchsia_archive.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") group("tests") { testonly = true deps = [ ":touch-input-test" ] } executable("touch-input-test-bin") { testonly = true output_name = "touch-input-test" sources = [ "touch-input-test.cc" ] # This is needed for //flutter/third_party/googletest for linking zircon # symbols. libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] deps = [ "${fuchsia_sdk}/fidl/fuchsia.accessibility.semantics", "${fuchsia_sdk}/fidl/fuchsia.buildinfo", "${fuchsia_sdk}/fidl/fuchsia.component", "${fuchsia_sdk}/fidl/fuchsia.fonts", "${fuchsia_sdk}/fidl/fuchsia.intl", "${fuchsia_sdk}/fidl/fuchsia.kernel", "${fuchsia_sdk}/fidl/fuchsia.memorypressure", "${fuchsia_sdk}/fidl/fuchsia.metrics", "${fuchsia_sdk}/fidl/fuchsia.net.interfaces", "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", "${fuchsia_sdk}/fidl/fuchsia.ui.app", "${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton", "${fuchsia_sdk}/fidl/fuchsia.ui.input", "${fuchsia_sdk}/fidl/fuchsia.ui.pointerinjector", "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", "${fuchsia_sdk}/fidl/fuchsia.ui.test.scene", "${fuchsia_sdk}/fidl/fuchsia.web", "${fuchsia_sdk}/pkg/async", "${fuchsia_sdk}/pkg/async-loop-testing", "${fuchsia_sdk}/pkg/fidl_cpp", "${fuchsia_sdk}/pkg/sys_component_cpp_testing", "${fuchsia_sdk}/pkg/zx", "embedding-flutter-view:package", "touch-input-view:package", "//flutter/fml", "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:portable_ui_test", "//flutter/third_party/googletest:gtest", "//flutter/third_party/googletest:gtest_main", ] } fuchsia_test_archive("touch-input-test") { testonly = true deps = [ ":touch-input-test-bin", # "OOT" copies of the runners used by tests, to avoid conflicting with the # runners in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. "//flutter/shell/platform/fuchsia/flutter:oot_flutter_jit_runner", ] binary = "$target_name" cml_file = rebase_path("meta/$target_name.cml") }
engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/BUILD.gn", "repo_id": "engine", "token_count": 1110 }
386
// 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 FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_PORTABLE_UI_TEST_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_PORTABLE_UI_TEST_H_ #include <fuchsia/sysmem/cpp/fidl.h> #include <fuchsia/ui/app/cpp/fidl.h> #include <fuchsia/ui/composition/cpp/fidl.h> #include <fuchsia/ui/display/singleton/cpp/fidl.h> #include <fuchsia/ui/input/cpp/fidl.h> #include <fuchsia/ui/test/input/cpp/fidl.h> #include <fuchsia/ui/test/scene/cpp/fidl.h> #include <lib/async-loop/testing/cpp/real_loop.h> #include <lib/sys/component/cpp/testing/realm_builder.h> #include <lib/sys/component/cpp/testing/realm_builder_types.h> #include <zircon/status.h> #include <optional> #include <vector> namespace fuchsia_test_utils { class PortableUITest : public ::loop_fixture::RealLoop { public: // The FIDL bindings for these services are not exposed in the Fuchsia SDK so // we must encode the names manually here. static constexpr auto kVulkanLoaderServiceName = "fuchsia.vulkan.loader.Loader"; static constexpr auto kPosixSocketProviderName = "fuchsia.posix.socket.Provider"; static constexpr auto kPointerInjectorRegistryName = "fuchsia.ui.pointerinjector.Registry"; // The naming and references used by Realm Builder static constexpr auto kTestUIStack = "ui"; static constexpr auto kTestUIStackRef = component_testing::ChildRef{kTestUIStack}; static constexpr auto kFlutterJitRunner = "flutter_jit_runner"; static constexpr auto kFlutterJitRunnerRef = component_testing::ChildRef{kFlutterJitRunner}; static constexpr auto kFlutterJitRunnerUrl = "fuchsia-pkg://fuchsia.com/oot_flutter_jit_runner#meta/" "flutter_jit_runner.cm"; static constexpr auto kFlutterRunnerEnvironment = "flutter_runner_env"; void SetUp(bool build_realm = true); // Calls the Build method for Realm Builder to build the realm // Can only be called once, panics otherwise void BuildRealm(); // Attaches a client view to the scene, and waits for it to render. void LaunchClient(); // Attaches a view with an embedded child view to the scene, and waits for it // to render. void LaunchClientWithEmbeddedView(); // Returns true when the specified view is fully connected to the scene AND // has presented at least one frame of content. bool HasViewConnected(zx_koid_t view_ref_koid); // Registers a fake touch screen device with an injection coordinate space // spanning [-1000, 1000] on both axes. void RegisterTouchScreen(); // Registers a fake mouse device, for which mouse movement is measured on a // scale of [-1000, 1000] on both axes and scroll is measured from [-100, 100] // on both axes. void RegisterMouse(); // Register a fake keyboard void RegisterKeyboard(); // Simulates a tap at location (x, y). void InjectTap(int32_t x, int32_t y); // Helper method to simulate combinations of button presses/releases and/or // mouse movements. void SimulateMouseEvent( std::vector<fuchsia::ui::test::input::MouseButton> pressed_buttons, int movement_x, int movement_y); // Helper method to simulate a mouse scroll event. // // Set `use_physical_units` to true to specify scroll in physical pixels and // false to specify scroll in detents. void SimulateMouseScroll( std::vector<fuchsia::ui::test::input::MouseButton> pressed_buttons, int scroll_x, int scroll_y, bool use_physical_units = false); // Helper method to simluate text input void SimulateTextEntry(std::string text); protected: component_testing::RealmBuilder* realm_builder() { return &realm_builder_; } component_testing::RealmRoot* realm_root() { return realm_.get(); } uint32_t display_width_ = 0; uint32_t display_height_ = 0; int touch_injection_request_count() const { return touch_injection_request_count_; } private: void SetUpRealmBase(); // Configures the test-specific component topology. virtual void ExtendRealm() = 0; // Returns the test-specific test-ui-stack component url to use. // Usually overridden to return a value from gtest GetParam() virtual std::string GetTestUIStackUrl() = 0; // Helper method to watch for view geometry updates. void WatchViewGeometry(); // Helper method to process a view geometry update. void ProcessViewGeometryResponse( fuchsia::ui::observation::geometry::WatchResponse response); fuchsia::ui::test::input::RegistryPtr input_registry_; fuchsia::ui::test::input::TouchScreenPtr fake_touchscreen_; fuchsia::ui::test::input::MousePtr fake_mouse_; fuchsia::ui::test::input::KeyboardPtr fake_keyboard_; fuchsia::ui::test::scene::ControllerPtr scene_provider_; fuchsia::ui::observation::geometry::ViewTreeWatcherPtr view_tree_watcher_; component_testing::RealmBuilder realm_builder_ = component_testing::RealmBuilder::Create(); std::unique_ptr<component_testing::RealmRoot> realm_; // Counts the number of completed requests to inject touch reports into input // pipeline. int touch_injection_request_count_ = 0; // The KOID of the client root view's `ViewRef`. std::optional<zx_koid_t> client_root_view_ref_koid_; // Holds the most recent view tree snapshot received from the view tree // watcher. // // From this snapshot, we can retrieve relevant view tree state on demand, // e.g. if the client view is rendering content. std::optional<fuchsia::ui::observation::geometry::ViewTreeSnapshot> last_view_tree_snapshot_; }; } // namespace fuchsia_test_utils #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_PORTABLE_UI_TEST_H_
engine/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h", "repo_id": "engine", "token_count": 1918 }
387
// 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 FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VSYNC_WAITER_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VSYNC_WAITER_H_ #include <lib/async/cpp/wait.h> #include "flutter/fml/macros.h" #include "flutter/fml/memory/weak_ptr.h" #include "flutter/fml/time/time_delta.h" #include "flutter/fml/time/time_point.h" #include "flutter/shell/common/vsync_waiter.h" #include "flutter_runner_product_configuration.h" namespace flutter_runner { using FireCallbackCallback = std::function<void(fml::TimePoint, fml::TimePoint)>; using AwaitVsyncCallback = std::function<void(FireCallbackCallback)>; using AwaitVsyncForSecondaryCallbackCallback = std::function<void(FireCallbackCallback)>; class VsyncWaiter final : public flutter::VsyncWaiter { public: VsyncWaiter(AwaitVsyncCallback await_vsync_callback, AwaitVsyncForSecondaryCallbackCallback await_vsync_for_secondary_callback_callback, flutter::TaskRunners task_runners); ~VsyncWaiter() override; private: // |flutter::VsyncWaiter| void AwaitVSync() override; // |flutter::VsyncWaiter| void AwaitVSyncForSecondaryCallback() override; FireCallbackCallback fire_callback_callback_; AwaitVsyncCallback await_vsync_callback_; AwaitVsyncForSecondaryCallbackCallback await_vsync_for_secondary_callback_callback_; fml::WeakPtr<VsyncWaiter> weak_ui_; std::unique_ptr<fml::WeakPtrFactory<VsyncWaiter>> weak_factory_ui_; fml::WeakPtrFactory<VsyncWaiter> weak_factory_; FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiter); }; } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VSYNC_WAITER_H_
engine/shell/platform/fuchsia/flutter/vsync_waiter.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/vsync_waiter.h", "repo_id": "engine", "token_count": 689 }
388
// 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 "files.h" #include <fcntl.h> #include <unistd.h> #include <cstdint> #include "flutter/fml/logging.h" namespace dart_utils { namespace { bool ReadFileDescriptor(int fd, std::string* result) { FML_DCHECK(result); result->clear(); if (fd < 0) { return false; } constexpr size_t kBufferSize = 1 << 16; size_t offset = 0; ssize_t bytes_read = 0; do { offset += bytes_read; result->resize(offset + kBufferSize); bytes_read = read(fd, &(*result)[offset], kBufferSize); } while (bytes_read > 0); if (bytes_read < 0) { result->clear(); return false; } result->resize(offset + bytes_read); return true; } bool WriteFileDescriptor(int fd, const char* data, ssize_t size) { ssize_t total = 0; for (ssize_t partial = 0; total < size; total += partial) { partial = write(fd, data + total, size - total); if (partial < 0) return false; } return true; } } // namespace bool ReadFileToString(const std::string& path, std::string* result) { return ReadFileToStringAt(AT_FDCWD, path, result); } bool ReadFileToStringAt(int dirfd, const std::string& path, std::string* result) { int fd = openat(dirfd, path.c_str(), O_RDONLY); bool status = ReadFileDescriptor(fd, result); close(fd); return status; } bool WriteFile(const std::string& path, const char* data, ssize_t size) { int fd = openat(AT_FDCWD, path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0666); if (fd < 0) { return false; } bool status = WriteFileDescriptor(fd, data, size); close(fd); return status; } } // namespace dart_utils
engine/shell/platform/fuchsia/runtime/dart/utils/files.cc/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/files.cc", "repo_id": "engine", "token_count": 712 }
389
// 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 FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMSERVICE_OBJECT_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMSERVICE_OBJECT_H_ #include <lib/vfs/cpp/lazy_dir.h> namespace dart_utils { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" class VMServiceObject : public vfs::LazyDir { public: static constexpr const char* kDirName = "DartVM"; static constexpr const char* kPortDirName = "vmservice-port"; static constexpr const char* kPortDir = "/tmp/dart.services"; void GetContents(LazyEntryVector* out_vector) const override; zx_status_t GetFile(Node** out_node, uint64_t id, std::string name) const override; }; #pragma clang diagnostic pop } // namespace dart_utils #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMSERVICE_OBJECT_H_
engine/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.h/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.h", "repo_id": "engine", "token_count": 410 }
390
# 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. declare_args() { # Whether to build the GLFW shell for the host platform, if available. # # By default, the GLFW shell is not built if there is a native toolkit shell, # but it can be enabled for supported platforms (Windows, macOS, and Linux) # as an extra build artifact with this flag. The native toolkit shell will # still be built as well. build_glfw_shell = is_linux && current_toolchain == host_toolchain }
engine/shell/platform/glfw/config.gni/0
{ "file_path": "engine/shell/platform/glfw/config.gni", "repo_id": "engine", "token_count": 163 }
391
// 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 "flutter/shell/platform/glfw/system_utils.h" #include <cstdlib> #include "gtest/gtest.h" namespace flutter { namespace { // This is a helper for setting up the different environment variables to // specific strings, calling GetPreferredLanguageInfo, and then restoring those // environment variables to any previously existing values. std::vector<LanguageInfo> SetAndRestoreLanguageAroundGettingLanguageInfo( const char* language, const char* lc_all, const char* lc_messages, const char* lang) { std::vector<const char*> env_vars{ "LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG", }; std::map<const char*, const char*> new_values{ {env_vars[0], language}, {env_vars[1], lc_all}, {env_vars[2], lc_messages}, {env_vars[3], lang}, }; std::map<const char*, const char*> prior_values; for (auto var : env_vars) { const char* value = getenv(var); if (value != nullptr) { prior_values.emplace(var, value); } const char* new_value = new_values.at(var); if (new_value != nullptr) { setenv(var, new_value, 1); } else { unsetenv(var); } } std::vector<LanguageInfo> languages = GetPreferredLanguageInfo(); for (auto [var, value] : prior_values) { setenv(var, value, 1); } return languages; } TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoFull) { const char* locale_string = "en_GB.ISO-8859-1@euro:en_US:sv:zh_CN.UTF-8"; std::vector<LanguageInfo> languages = SetAndRestoreLanguageAroundGettingLanguageInfo(locale_string, nullptr, nullptr, nullptr); EXPECT_EQ(languages.size(), 15UL); EXPECT_STREQ(languages[0].language.c_str(), "en"); EXPECT_STREQ(languages[0].territory.c_str(), "GB"); EXPECT_STREQ(languages[0].codeset.c_str(), "ISO-8859-1"); EXPECT_STREQ(languages[0].modifier.c_str(), "euro"); EXPECT_STREQ(languages[1].language.c_str(), "en"); EXPECT_STREQ(languages[1].territory.c_str(), "GB"); EXPECT_STREQ(languages[1].codeset.c_str(), ""); EXPECT_STREQ(languages[1].modifier.c_str(), "euro"); EXPECT_STREQ(languages[2].language.c_str(), "en"); EXPECT_STREQ(languages[2].territory.c_str(), ""); EXPECT_STREQ(languages[2].codeset.c_str(), "ISO-8859-1"); EXPECT_STREQ(languages[2].modifier.c_str(), "euro"); EXPECT_STREQ(languages[3].language.c_str(), "en"); EXPECT_STREQ(languages[3].territory.c_str(), ""); EXPECT_STREQ(languages[3].codeset.c_str(), ""); EXPECT_STREQ(languages[3].modifier.c_str(), "euro"); EXPECT_STREQ(languages[4].language.c_str(), "en"); EXPECT_STREQ(languages[4].territory.c_str(), "GB"); EXPECT_STREQ(languages[4].codeset.c_str(), "ISO-8859-1"); EXPECT_STREQ(languages[4].modifier.c_str(), ""); EXPECT_STREQ(languages[5].language.c_str(), "en"); EXPECT_STREQ(languages[5].territory.c_str(), "GB"); EXPECT_STREQ(languages[5].codeset.c_str(), ""); EXPECT_STREQ(languages[5].modifier.c_str(), ""); EXPECT_STREQ(languages[6].language.c_str(), "en"); EXPECT_STREQ(languages[6].territory.c_str(), ""); EXPECT_STREQ(languages[6].codeset.c_str(), "ISO-8859-1"); EXPECT_STREQ(languages[6].modifier.c_str(), ""); EXPECT_STREQ(languages[7].language.c_str(), "en"); EXPECT_STREQ(languages[7].territory.c_str(), ""); EXPECT_STREQ(languages[7].codeset.c_str(), ""); EXPECT_STREQ(languages[7].modifier.c_str(), ""); EXPECT_STREQ(languages[8].language.c_str(), "en"); EXPECT_STREQ(languages[8].territory.c_str(), "US"); EXPECT_STREQ(languages[8].codeset.c_str(), ""); EXPECT_STREQ(languages[8].modifier.c_str(), ""); EXPECT_STREQ(languages[9].language.c_str(), "en"); EXPECT_STREQ(languages[9].territory.c_str(), ""); EXPECT_STREQ(languages[9].codeset.c_str(), ""); EXPECT_STREQ(languages[9].modifier.c_str(), ""); EXPECT_STREQ(languages[10].language.c_str(), "sv"); EXPECT_STREQ(languages[10].territory.c_str(), ""); EXPECT_STREQ(languages[10].codeset.c_str(), ""); EXPECT_STREQ(languages[10].modifier.c_str(), ""); EXPECT_STREQ(languages[11].language.c_str(), "zh"); EXPECT_STREQ(languages[11].territory.c_str(), "CN"); EXPECT_STREQ(languages[11].codeset.c_str(), "UTF-8"); EXPECT_STREQ(languages[11].modifier.c_str(), ""); EXPECT_STREQ(languages[12].language.c_str(), "zh"); EXPECT_STREQ(languages[12].territory.c_str(), "CN"); EXPECT_STREQ(languages[12].codeset.c_str(), ""); EXPECT_STREQ(languages[12].modifier.c_str(), ""); EXPECT_STREQ(languages[13].language.c_str(), "zh"); EXPECT_STREQ(languages[13].territory.c_str(), ""); EXPECT_STREQ(languages[13].codeset.c_str(), "UTF-8"); EXPECT_STREQ(languages[13].modifier.c_str(), ""); EXPECT_STREQ(languages[14].language.c_str(), "zh"); EXPECT_STREQ(languages[14].territory.c_str(), ""); EXPECT_STREQ(languages[14].codeset.c_str(), ""); EXPECT_STREQ(languages[14].modifier.c_str(), ""); } TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoWeird) { const char* locale_string = "[email protected]"; std::vector<LanguageInfo> languages = SetAndRestoreLanguageAroundGettingLanguageInfo(locale_string, nullptr, nullptr, nullptr); EXPECT_EQ(languages.size(), 4UL); EXPECT_STREQ(languages[0].language.c_str(), "tt"); EXPECT_STREQ(languages[0].territory.c_str(), "RU"); EXPECT_STREQ(languages[0].codeset.c_str(), ""); EXPECT_STREQ(languages[0].modifier.c_str(), "iqtelif.UTF-8"); EXPECT_STREQ(languages[1].language.c_str(), "tt"); EXPECT_STREQ(languages[1].territory.c_str(), ""); EXPECT_STREQ(languages[1].codeset.c_str(), ""); EXPECT_STREQ(languages[1].modifier.c_str(), "iqtelif.UTF-8"); EXPECT_STREQ(languages[2].language.c_str(), "tt"); EXPECT_STREQ(languages[2].territory.c_str(), "RU"); EXPECT_STREQ(languages[2].codeset.c_str(), ""); EXPECT_STREQ(languages[2].modifier.c_str(), ""); EXPECT_STREQ(languages[3].language.c_str(), "tt"); EXPECT_STREQ(languages[3].territory.c_str(), ""); EXPECT_STREQ(languages[3].codeset.c_str(), ""); EXPECT_STREQ(languages[3].modifier.c_str(), ""); } TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEmpty) { const char* locale_string = ""; std::vector<LanguageInfo> languages = SetAndRestoreLanguageAroundGettingLanguageInfo( locale_string, locale_string, locale_string, locale_string); EXPECT_EQ(languages.size(), 1UL); EXPECT_STREQ(languages[0].language.c_str(), "C"); EXPECT_TRUE(languages[0].territory.empty()); EXPECT_TRUE(languages[0].codeset.empty()); EXPECT_TRUE(languages[0].modifier.empty()); } TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering1) { const char* language = "de"; const char* lc_all = "en"; const char* lc_messages = "zh"; const char* lang = "tt"; std::vector<LanguageInfo> languages = SetAndRestoreLanguageAroundGettingLanguageInfo(language, lc_all, lc_messages, lang); EXPECT_EQ(languages.size(), 1UL); EXPECT_STREQ(languages[0].language.c_str(), language); } TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering2) { const char* lc_all = "en"; const char* lc_messages = "zh"; const char* lang = "tt"; std::vector<LanguageInfo> languages = SetAndRestoreLanguageAroundGettingLanguageInfo(nullptr, lc_all, lc_messages, lang); EXPECT_EQ(languages.size(), 1UL); EXPECT_STREQ(languages[0].language.c_str(), lc_all); } TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering3) { const char* lc_messages = "zh"; const char* lang = "tt"; std::vector<LanguageInfo> languages = SetAndRestoreLanguageAroundGettingLanguageInfo(nullptr, nullptr, lc_messages, lang); EXPECT_EQ(languages.size(), 1UL); EXPECT_STREQ(languages[0].language.c_str(), lc_messages); } TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering4) { const char* lang = "tt"; std::vector<LanguageInfo> languages = SetAndRestoreLanguageAroundGettingLanguageInfo(nullptr, nullptr, nullptr, lang); EXPECT_EQ(languages.size(), 1UL); EXPECT_STREQ(languages[0].language.c_str(), lang); } TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering5) { std::vector<LanguageInfo> languages = SetAndRestoreLanguageAroundGettingLanguageInfo(nullptr, nullptr, nullptr, nullptr); EXPECT_EQ(languages.size(), 1UL); EXPECT_STREQ(languages[0].language.c_str(), "C"); } TEST(FlutterGlfwSystemUtilsTest, ConvertToFlutterLocaleEmpty) { std::vector<LanguageInfo> languages; std::vector<FlutterLocale> locales = ConvertToFlutterLocale(languages); EXPECT_TRUE(locales.empty()); } TEST(FlutterGlfwSystemUtilsTest, ConvertToFlutterLocaleNonEmpty) { std::vector<LanguageInfo> languages; languages.push_back(LanguageInfo{"en", "US", "", ""}); languages.push_back(LanguageInfo{"tt", "RU", "", "iqtelif.UTF-8"}); languages.push_back(LanguageInfo{"sv", "", "", ""}); languages.push_back(LanguageInfo{"de", "DE", "UTF-8", "euro"}); languages.push_back(LanguageInfo{"zh", "CN", "UTF-8", ""}); std::vector<FlutterLocale> locales = ConvertToFlutterLocale(languages); EXPECT_EQ(locales.size(), 5UL); EXPECT_EQ(locales[0].struct_size, sizeof(FlutterLocale)); EXPECT_STREQ(locales[0].language_code, "en"); EXPECT_STREQ(locales[0].country_code, "US"); EXPECT_EQ(locales[0].script_code, nullptr); EXPECT_EQ(locales[0].variant_code, nullptr); EXPECT_STREQ(locales[1].language_code, "tt"); EXPECT_STREQ(locales[1].country_code, "RU"); EXPECT_EQ(locales[1].script_code, nullptr); EXPECT_STREQ(locales[1].variant_code, "iqtelif.UTF-8"); EXPECT_STREQ(locales[2].language_code, "sv"); EXPECT_EQ(locales[2].country_code, nullptr); EXPECT_EQ(locales[2].script_code, nullptr); EXPECT_EQ(locales[2].variant_code, nullptr); EXPECT_STREQ(locales[3].language_code, "de"); EXPECT_STREQ(locales[3].country_code, "DE"); EXPECT_STREQ(locales[3].script_code, "UTF-8"); EXPECT_STREQ(locales[3].variant_code, "euro"); EXPECT_STREQ(locales[4].language_code, "zh"); EXPECT_STREQ(locales[4].country_code, "CN"); EXPECT_STREQ(locales[4].script_code, "UTF-8"); EXPECT_EQ(locales[4].variant_code, nullptr); } } // namespace } // namespace flutter
engine/shell/platform/glfw/system_utils_test.cc/0
{ "file_path": "engine/shell/platform/glfw/system_utils_test.cc", "repo_id": "engine", "token_count": 4590 }
392
// 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 "flutter/shell/platform/linux/public/flutter_linux/fl_binary_codec.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "gtest/gtest.h" // Encodes a message using a FlBinaryCodec. Return a hex string with the encoded // binary output. static gchar* encode_message(FlValue* value) { g_autoptr(FlBinaryCodec) codec = fl_binary_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(GBytes) message = fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, &error); EXPECT_NE(message, nullptr); EXPECT_EQ(error, nullptr); return bytes_to_hex_string(message); } // Encodes a message using a FlBinaryCodec. Expect the given error. static void encode_message_error(FlValue* value, GQuark domain, int code) { g_autoptr(FlBinaryCodec) codec = fl_binary_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(GBytes) message = fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, &error); EXPECT_EQ(message, nullptr); EXPECT_TRUE(g_error_matches(error, domain, code)); } // Decodes a message using a FlBinaryCodec. The binary data is given in the form // of a hex string. static FlValue* decode_message(const char* hex_string) { g_autoptr(FlBinaryCodec) codec = fl_binary_codec_new(); g_autoptr(GBytes) data = hex_string_to_bytes(hex_string); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) value = fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), data, &error); EXPECT_EQ(error, nullptr); EXPECT_NE(value, nullptr); return fl_value_ref(value); } TEST(FlBinaryCodecTest, EncodeData) { uint8_t data[] = {0x00, 0x01, 0x02, 0xFD, 0xFE, 0xFF}; g_autoptr(FlValue) value = fl_value_new_uint8_list(data, 6); g_autofree gchar* hex_string = encode_message(value); EXPECT_STREQ(hex_string, "000102fdfeff"); } TEST(FlBinaryCodecTest, EncodeEmpty) { g_autoptr(FlValue) value = fl_value_new_uint8_list(nullptr, 0); g_autofree gchar* hex_string = encode_message(value); EXPECT_STREQ(hex_string, ""); } TEST(FlBinaryCodecTest, EncodeNullptr) { encode_message_error(nullptr, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE); } TEST(FlBinaryCodecTest, EncodeUnknownType) { g_autoptr(FlValue) value = fl_value_new_null(); encode_message_error(value, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE); } TEST(FlBinaryCodecTest, DecodeData) { g_autoptr(FlValue) value = decode_message("000102fdfeff"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_UINT8_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(6)); EXPECT_EQ(fl_value_get_uint8_list(value)[0], 0x00); EXPECT_EQ(fl_value_get_uint8_list(value)[1], 0x01); EXPECT_EQ(fl_value_get_uint8_list(value)[2], 0x02); EXPECT_EQ(fl_value_get_uint8_list(value)[3], 0xFD); EXPECT_EQ(fl_value_get_uint8_list(value)[4], 0xFE); EXPECT_EQ(fl_value_get_uint8_list(value)[5], 0xFF); } TEST(FlBinaryCodecTest, DecodeEmpty) { g_autoptr(FlValue) value = decode_message(""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_UINT8_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlBinaryCodecTest, EncodeDecode) { g_autoptr(FlBinaryCodec) codec = fl_binary_codec_new(); uint8_t data[] = {0x00, 0x01, 0x02, 0xFD, 0xFE, 0xFF}; g_autoptr(FlValue) input = fl_value_new_uint8_list(data, 6); g_autoptr(GError) error = nullptr; g_autoptr(GBytes) message = fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), input, &error); EXPECT_NE(message, nullptr); EXPECT_EQ(error, nullptr); g_autoptr(FlValue) output = fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), message, &error); EXPECT_EQ(error, nullptr); EXPECT_NE(output, nullptr); ASSERT_TRUE(fl_value_equal(input, output)); }
engine/shell/platform/linux/fl_binary_codec_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_binary_codec_test.cc", "repo_id": "engine", "token_count": 1698 }
393
// 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 "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h" #include "gtest/gtest.h" #include <cmath> // Encodes a message using FlJsonMessageCodec to a UTF-8 string. static gchar* encode_message(FlValue* value) { g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); g_autoptr(GError) error = nullptr; g_autofree gchar* result = fl_json_message_codec_encode(codec, value, &error); EXPECT_EQ(error, nullptr); return static_cast<gchar*>(g_steal_pointer(&result)); } // Encodes a message using FlJsonMessageCodec to a UTF-8 string. Expect the // given error. static void encode_error_message(FlValue* value, GQuark domain, gint code) { g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); g_autoptr(GError) error = nullptr; g_autofree gchar* result = fl_json_message_codec_encode(codec, value, &error); EXPECT_TRUE(g_error_matches(error, domain, code)); EXPECT_EQ(result, nullptr); } // Decodes a message using FlJsonMessageCodec from UTF-8 string. static FlValue* decode_message(const char* text) { g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) value = fl_json_message_codec_decode(codec, text, &error); EXPECT_EQ(error, nullptr); EXPECT_NE(value, nullptr); return fl_value_ref(value); } // Decodes a message using FlJsonMessageCodec from UTF-8 string. Expect the // given error. static void decode_error_message(const char* text, GQuark domain, gint code) { g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) value = fl_json_message_codec_decode(codec, text, &error); EXPECT_TRUE(g_error_matches(error, domain, code)); EXPECT_EQ(value, nullptr); } TEST(FlJsonMessageCodecTest, EncodeNullptr) { g_autofree gchar* text = encode_message(nullptr); EXPECT_STREQ(text, "null"); } TEST(FlJsonMessageCodecTest, EncodeNull) { g_autoptr(FlValue) value = fl_value_new_null(); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "null"); } TEST(FlJsonMessageCodecTest, DecodeNull) { g_autoptr(FlValue) value = decode_message("null"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_NULL); } static gchar* encode_bool(gboolean value) { g_autoptr(FlValue) v = fl_value_new_bool(value); return encode_message(v); } TEST(FlJsonMessageCodecTest, EncodeBoolFalse) { g_autofree gchar* text = encode_bool(FALSE); EXPECT_STREQ(text, "false"); } TEST(FlJsonMessageCodecTest, EncodeBoolTrue) { g_autofree gchar* text = encode_bool(TRUE); EXPECT_STREQ(text, "true"); } TEST(FlJsonMessageCodecTest, DecodeBoolFalse) { g_autoptr(FlValue) value = decode_message("false"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_BOOL); EXPECT_FALSE(fl_value_get_bool(value)); } TEST(FlJsonMessageCodecTest, DecodeBoolTrue) { g_autoptr(FlValue) value = decode_message("true"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_BOOL); EXPECT_TRUE(fl_value_get_bool(value)); } static gchar* encode_int(int64_t value) { g_autoptr(FlValue) v = fl_value_new_int(value); return encode_message(v); } TEST(FlJsonMessageCodecTest, EncodeIntZero) { g_autofree gchar* text = encode_int(0); EXPECT_STREQ(text, "0"); } TEST(FlJsonMessageCodecTest, EncodeIntOne) { g_autofree gchar* text = encode_int(1); EXPECT_STREQ(text, "1"); } TEST(FlJsonMessageCodecTest, EncodeInt12345) { g_autofree gchar* text = encode_int(12345); EXPECT_STREQ(text, "12345"); } TEST(FlJsonMessageCodecTest, EncodeIntMin) { g_autofree gchar* text = encode_int(G_MININT64); EXPECT_STREQ(text, "-9223372036854775808"); } TEST(FlJsonMessageCodecTest, EncodeIntMax) { g_autofree gchar* text = encode_int(G_MAXINT64); EXPECT_STREQ(text, "9223372036854775807"); } TEST(FlJsonMessageCodecTest, DecodeIntZero) { g_autoptr(FlValue) value = decode_message("0"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), 0); } TEST(FlJsonMessageCodecTest, DecodeIntOne) { g_autoptr(FlValue) value = decode_message("1"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), 1); } TEST(FlJsonMessageCodecTest, DecodeInt12345) { g_autoptr(FlValue) value = decode_message("12345"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), 12345); } TEST(FlJsonMessageCodecTest, DecodeIntMin) { g_autoptr(FlValue) value = decode_message("-9223372036854775808"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), G_MININT64); } TEST(FlJsonMessageCodecTest, DecodeIntMax) { g_autoptr(FlValue) value = decode_message("9223372036854775807"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), G_MAXINT64); } TEST(FlJsonMessageCodecTest, DecodeUintMax) { // This is bigger than an signed 64 bit integer, so we expect it to be // represented as a double. g_autoptr(FlValue) value = decode_message("18446744073709551615"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), 1.8446744073709551615e+19); } TEST(FlJsonMessageCodecTest, DecodeHugeNumber) { // This is bigger than an unsigned 64 bit integer, so we expect it to be // represented as a double. g_autoptr(FlValue) value = decode_message("184467440737095516150"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), 1.84467440737095516150e+20); } TEST(FlJsonMessageCodecTest, DecodeIntLeadingZero1) { decode_error_message("00", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeIntLeadingZero2) { decode_error_message("01", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeIntDoubleNegative) { decode_error_message("--1", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeIntPositiveSign) { decode_error_message("+1", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeIntHexChar) { decode_error_message("0a", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } static gchar* encode_float(double value) { g_autoptr(FlValue) v = fl_value_new_float(value); return encode_message(v); } TEST(FlJsonMessageCodecTest, EncodeFloatZero) { g_autofree gchar* text = encode_float(0); EXPECT_STREQ(text, "0.0"); } TEST(FlJsonMessageCodecTest, EncodeFloatOne) { g_autofree gchar* text = encode_float(1); EXPECT_STREQ(text, "1.0"); } TEST(FlJsonMessageCodecTest, EncodeFloatMinusOne) { g_autofree gchar* text = encode_float(-1); EXPECT_STREQ(text, "-1.0"); } TEST(FlJsonMessageCodecTest, EncodeFloatHalf) { g_autofree gchar* text = encode_float(0.5); EXPECT_STREQ(text, "0.5"); } TEST(FlJsonMessageCodecTest, EncodeFloatPi) { g_autofree gchar* text = encode_float(M_PI); EXPECT_STREQ(text, "3.141592653589793"); } TEST(FlJsonMessageCodecTest, EncodeFloatMinusZero) { g_autofree gchar* text = encode_float(-0.0); EXPECT_STREQ(text, "-0.0"); } // NOTE(robert-ancell): JSON doesn't support encoding of NAN and INFINITY, but // rapidjson doesn't seem to either encode them or treat them as an error. TEST(FlJsonMessageCodecTest, DecodeFloatZero) { g_autoptr(FlValue) value = decode_message("0.0"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), 0.0); } TEST(FlJsonMessageCodecTest, DecodeFloatOne) { g_autoptr(FlValue) value = decode_message("1.0"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), 1.0); } TEST(FlJsonMessageCodecTest, DecodeFloatMinusOne) { g_autoptr(FlValue) value = decode_message("-1.0"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), -1.0); } TEST(FlJsonMessageCodecTest, DecodeFloatHalf) { g_autoptr(FlValue) value = decode_message("0.5"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), 0.5); } TEST(FlJsonMessageCodecTest, DecodeFloatPi) { g_autoptr(FlValue) value = decode_message("3.1415926535897931"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), M_PI); } TEST(FlJsonMessageCodecTest, DecodeFloatMinusZero) { g_autoptr(FlValue) value = decode_message("-0.0"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), -0.0); } TEST(FlJsonMessageCodecTest, DecodeFloatMissingFraction) { decode_error_message("0.", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeFloatInvalidFraction) { decode_error_message("0.a", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } static gchar* encode_string(const gchar* value) { g_autoptr(FlValue) v = fl_value_new_string(value); return encode_message(v); } TEST(FlJsonMessageCodecTest, EncodeStringEmpty) { g_autofree gchar* text = encode_string(""); EXPECT_STREQ(text, "\"\""); } TEST(FlJsonMessageCodecTest, EncodeStringHello) { g_autofree gchar* text = encode_string("hello"); EXPECT_STREQ(text, "\"hello\""); } TEST(FlJsonMessageCodecTest, EncodeStringEmptySized) { g_autoptr(FlValue) value = fl_value_new_string_sized(nullptr, 0); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "\"\""); } TEST(FlJsonMessageCodecTest, EncodeStringHelloSized) { g_autoptr(FlValue) value = fl_value_new_string_sized("Hello World", 5); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "\"Hello\""); } TEST(FlJsonMessageCodecTest, EncodeStringEscapeQuote) { g_autofree gchar* text = encode_string("\""); EXPECT_STREQ(text, "\"\\\"\""); } TEST(FlJsonMessageCodecTest, EncodeStringEscapeBackslash) { g_autofree gchar* text = encode_string("\\"); EXPECT_STREQ(text, "\"\\\\\""); } TEST(FlJsonMessageCodecTest, EncodeStringEscapeBackspace) { g_autofree gchar* text = encode_string("\b"); EXPECT_STREQ(text, "\"\\b\""); } TEST(FlJsonMessageCodecTest, EncodeStringEscapeFormFeed) { g_autofree gchar* text = encode_string("\f"); EXPECT_STREQ(text, "\"\\f\""); } TEST(FlJsonMessageCodecTest, EncodeStringEscapeNewline) { g_autofree gchar* text = encode_string("\n"); EXPECT_STREQ(text, "\"\\n\""); } TEST(FlJsonMessageCodecTest, EncodeStringEscapeCarriageReturn) { g_autofree gchar* text = encode_string("\r"); EXPECT_STREQ(text, "\"\\r\""); } TEST(FlJsonMessageCodecTest, EncodeStringEscapeTab) { g_autofree gchar* text = encode_string("\t"); EXPECT_STREQ(text, "\"\\t\""); } TEST(FlJsonMessageCodecTest, EncodeStringEscapeUnicode) { g_autofree gchar* text = encode_string("\u0001"); EXPECT_STREQ(text, "\"\\u0001\""); } TEST(FlJsonMessageCodecTest, EncodeStringEmoji) { g_autofree gchar* text = encode_string("πŸ˜€"); EXPECT_STREQ(text, "\"πŸ˜€\""); } TEST(FlJsonMessageCodecTest, DecodeStringEmpty) { g_autoptr(FlValue) value = decode_message("\"\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), ""); } TEST(FlJsonMessageCodecTest, DecodeStringHello) { g_autoptr(FlValue) value = decode_message("\"hello\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "hello"); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeQuote) { g_autoptr(FlValue) value = decode_message("\"\\\"\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "\""); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeBackslash) { g_autoptr(FlValue) value = decode_message("\"\\\\\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "\\"); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeSlash) { g_autoptr(FlValue) value = decode_message("\"\\/\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "/"); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeBackspace) { g_autoptr(FlValue) value = decode_message("\"\\b\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "\b"); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeFormFeed) { g_autoptr(FlValue) value = decode_message("\"\\f\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "\f"); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeNewline) { g_autoptr(FlValue) value = decode_message("\"\\n\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "\n"); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeCarriageReturn) { g_autoptr(FlValue) value = decode_message("\"\\r\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "\r"); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeTab) { g_autoptr(FlValue) value = decode_message("\"\\t\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "\t"); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeUnicode) { g_autoptr(FlValue) value = decode_message("\"\\u0001\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "\u0001"); } TEST(FlJsonMessageCodecTest, DecodeStringEmoji) { g_autoptr(FlValue) value = decode_message("\"πŸ˜€\""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "πŸ˜€"); } TEST(FlJsonMessageCodecTest, DecodeInvalidUTF8) { decode_error_message("\xff", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_UTF8); } TEST(FlJsonMessageCodecTest, DecodeStringInvalidUTF8) { decode_error_message("\"\xff\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_UTF8); } TEST(FlJsonMessageCodecTest, DecodeStringBinary) { decode_error_message("\"Hello\x01World\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringNewline) { decode_error_message("\"Hello\nWorld\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringCarriageReturn) { decode_error_message("\"Hello\rWorld\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringTab) { decode_error_message("\"Hello\tWorld\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringUnterminatedEmpty) { decode_error_message("\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringExtraQuote) { decode_error_message("\"\"\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringEscapedClosingQuote) { decode_error_message("\"\\\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringUnknownEscape) { decode_error_message("\"\\z\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringInvalidEscapeUnicode) { decode_error_message("\"\\uxxxx\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeUnicodeNoData) { decode_error_message("\"\\u\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeStringEscapeUnicodeShortData) { decode_error_message("\"\\uxx\"", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, EncodeUint8ListEmpty) { g_autoptr(FlValue) value = fl_value_new_uint8_list(nullptr, 0); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[]"); } TEST(FlJsonMessageCodecTest, EncodeUint8List) { uint8_t data[] = {0, 1, 2, 3, 4}; g_autoptr(FlValue) value = fl_value_new_uint8_list(data, 5); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[0,1,2,3,4]"); } TEST(FlJsonMessageCodecTest, EncodeInt32ListEmpty) { g_autoptr(FlValue) value = fl_value_new_int32_list(nullptr, 0); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[]"); } TEST(FlJsonMessageCodecTest, EncodeInt32List) { int32_t data[] = {0, -1, 2, -3, 4}; g_autoptr(FlValue) value = fl_value_new_int32_list(data, 5); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[0,-1,2,-3,4]"); } TEST(FlJsonMessageCodecTest, EncodeInt64ListEmpty) { g_autoptr(FlValue) value = fl_value_new_int64_list(nullptr, 0); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[]"); } TEST(FlJsonMessageCodecTest, EncodeInt64List) { int64_t data[] = {0, -1, 2, -3, 4}; g_autoptr(FlValue) value = fl_value_new_int64_list(data, 5); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[0,-1,2,-3,4]"); } TEST(FlJsonMessageCodecTest, EncodeFloatListEmpty) { g_autoptr(FlValue) value = fl_value_new_float_list(nullptr, 0); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[]"); } TEST(FlJsonMessageCodecTest, EncodeFloatList) { double data[] = {0, -0.5, 0.25, -0.125, 0.0625}; g_autoptr(FlValue) value = fl_value_new_float_list(data, 5); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[0.0,-0.5,0.25,-0.125,0.0625]"); } TEST(FlJsonMessageCodecTest, EncodeListEmpty) { g_autoptr(FlValue) value = fl_value_new_list(); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[]"); } TEST(FlJsonMessageCodecTest, EncodeListTypes) { g_autoptr(FlValue) value = fl_value_new_list(); fl_value_append_take(value, fl_value_new_null()); fl_value_append_take(value, fl_value_new_bool(TRUE)); fl_value_append_take(value, fl_value_new_int(42)); fl_value_append_take(value, fl_value_new_float(-1.5)); fl_value_append_take(value, fl_value_new_string("hello")); fl_value_append_take(value, fl_value_new_list()); fl_value_append_take(value, fl_value_new_map()); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[null,true,42,-1.5,\"hello\",[],{}]"); } TEST(FlJsonMessageCodecTest, EncodeListNested) { g_autoptr(FlValue) even_numbers = fl_value_new_list(); g_autoptr(FlValue) odd_numbers = fl_value_new_list(); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { fl_value_append_take(even_numbers, fl_value_new_int(i)); } else { fl_value_append_take(odd_numbers, fl_value_new_int(i)); } } g_autoptr(FlValue) value = fl_value_new_list(); fl_value_append(value, even_numbers); fl_value_append(value, odd_numbers); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "[[0,2,4,6,8],[1,3,5,7,9]]"); } TEST(FlJsonMessageCodecTest, DecodeListEmpty) { g_autoptr(FlValue) value = decode_message("[]"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST); EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlJsonMessageCodecTest, DecodeListNoComma) { decode_error_message("[0,1,2,3 4]", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeListUnterminatedEmpty) { decode_error_message("[", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeListStartUnterminate) { decode_error_message("]", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeListUnterminated) { decode_error_message("[0,1,2,3,4", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeListDoubleTerminated) { decode_error_message("[0,1,2,3,4]]", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, EncodeMapEmpty) { g_autoptr(FlValue) value = fl_value_new_map(); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "{}"); } TEST(FlJsonMessageCodecTest, EncodeMapNullKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_null(), fl_value_new_string("null")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapBoolKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_bool(TRUE), fl_value_new_string("bool")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapIntKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_int(42), fl_value_new_string("int")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapFloatKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_float(M_PI), fl_value_new_string("float")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapUint8ListKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_uint8_list(nullptr, 0), fl_value_new_string("uint8_list")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapInt32ListKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_int32_list(nullptr, 0), fl_value_new_string("int32_list")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapInt64ListKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_int64_list(nullptr, 0), fl_value_new_string("int64_list")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapFloatListKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_float_list(nullptr, 0), fl_value_new_string("float_list")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapListKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_list(), fl_value_new_string("list")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapMapKey) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_map(), fl_value_new_string("map")); encode_error_message(value, FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE); } TEST(FlJsonMessageCodecTest, EncodeMapValueTypes) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_string("null"), fl_value_new_null()); fl_value_set_take(value, fl_value_new_string("bool"), fl_value_new_bool(TRUE)); fl_value_set_take(value, fl_value_new_string("int"), fl_value_new_int(42)); fl_value_set_take(value, fl_value_new_string("float"), fl_value_new_float(-1.5)); fl_value_set_take(value, fl_value_new_string("string"), fl_value_new_string("hello")); fl_value_set_take(value, fl_value_new_string("list"), fl_value_new_list()); fl_value_set_take(value, fl_value_new_string("map"), fl_value_new_map()); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "{\"null\":null,\"bool\":true,\"int\":42,\"float\":-" "1.5,\"string\":\"hello\",\"list\":[],\"map\":{}}"); } TEST(FlJsonMessageCodecTest, EncodeMapNested) { g_autoptr(FlValue) str_to_int = fl_value_new_map(); const char* numbers[] = {"zero", "one", "two", "three", nullptr}; for (int i = 0; numbers[i] != nullptr; i++) { fl_value_set_take(str_to_int, fl_value_new_string(numbers[i]), fl_value_new_int(i)); } g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_string(value, "str-to-int", str_to_int); g_autofree gchar* text = encode_message(value); EXPECT_STREQ(text, "{\"str-to-int\":{\"zero\":0,\"one\":1,\"two\":2,\"three\":3}}"); } TEST(FlJsonMessageCodecTest, DecodeMapEmpty) { g_autoptr(FlValue) value = decode_message("{}"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP); EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlJsonMessageCodecTest, DecodeMapUnterminatedEmpty) { decode_error_message("{", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeMapStartUnterminate) { decode_error_message("}", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeMapNoComma) { decode_error_message("{\"zero\":0 \"one\":1}", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeMapNoColon) { decode_error_message("{\"zero\" 0,\"one\":1}", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeMapUnterminated) { decode_error_message("{\"zero\":0,\"one\":1", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeMapDoubleTerminated) { decode_error_message("{\"zero\":0,\"one\":1}}", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, DecodeUnknownWord) { decode_error_message("foo", FL_JSON_MESSAGE_CODEC_ERROR, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON); } TEST(FlJsonMessageCodecTest, EncodeDecode) { g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); g_autoptr(FlValue) input = fl_value_new_list(); fl_value_append_take(input, fl_value_new_null()); fl_value_append_take(input, fl_value_new_bool(TRUE)); fl_value_append_take(input, fl_value_new_int(42)); fl_value_append_take(input, fl_value_new_float(M_PI)); fl_value_append_take(input, fl_value_new_string("hello")); fl_value_append_take(input, fl_value_new_list()); fl_value_append_take(input, fl_value_new_map()); g_autoptr(GError) error = nullptr; g_autofree gchar* message = fl_json_message_codec_encode(codec, input, &error); ASSERT_NE(message, nullptr); EXPECT_EQ(error, nullptr); g_autoptr(FlValue) output = fl_json_message_codec_decode(codec, message, &error); EXPECT_EQ(error, nullptr); EXPECT_NE(output, nullptr); EXPECT_TRUE(fl_value_equal(input, output)); }
engine/shell/platform/linux/fl_json_message_codec_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_json_message_codec_test.cc", "repo_id": "engine", "token_count": 12795 }
394
// 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 "flutter/shell/platform/linux/fl_keyboard_manager.h" #include <cstring> #include <vector> #include "flutter/shell/platform/embedder/test_utils/key_codes.g.h" #include "flutter/shell/platform/linux/fl_binary_messenger_private.h" #include "flutter/shell/platform/linux/fl_method_codec_private.h" #include "flutter/shell/platform/linux/key_mapping.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "flutter/shell/platform/linux/testing/mock_binary_messenger.h" #include "flutter/shell/platform/linux/testing/mock_text_input_plugin.h" #include "flutter/testing/testing.h" #include "gmock/gmock.h" #include "gtest/gtest.h" // Define compound `expect` in macros. If they were defined in functions, the // stacktrace wouldn't print where the function is called in the unit tests. #define EXPECT_KEY_EVENT(RECORD, TYPE, PHYSICAL, LOGICAL, CHAR, SYNTHESIZED) \ EXPECT_EQ((RECORD).type, CallRecord::kKeyCallEmbedder); \ EXPECT_EQ((RECORD).event->type, (TYPE)); \ EXPECT_EQ((RECORD).event->physical, (PHYSICAL)); \ EXPECT_EQ((RECORD).event->logical, (LOGICAL)); \ EXPECT_STREQ((RECORD).event->character, (CHAR)); \ EXPECT_EQ((RECORD).event->synthesized, (SYNTHESIZED)); #define VERIFY_DOWN(OUT_LOGICAL, OUT_CHAR) \ EXPECT_EQ(call_records[0].type, CallRecord::kKeyCallEmbedder); \ EXPECT_EQ(call_records[0].event->type, kFlutterKeyEventTypeDown); \ EXPECT_EQ(call_records[0].event->logical, (OUT_LOGICAL)); \ EXPECT_STREQ(call_records[0].event->character, (OUT_CHAR)); \ EXPECT_EQ(call_records[0].event->synthesized, false); \ call_records.clear() namespace { using ::flutter::testing::keycodes::kLogicalAltLeft; using ::flutter::testing::keycodes::kLogicalBracketLeft; using ::flutter::testing::keycodes::kLogicalComma; using ::flutter::testing::keycodes::kLogicalControlLeft; using ::flutter::testing::keycodes::kLogicalDigit1; using ::flutter::testing::keycodes::kLogicalKeyA; using ::flutter::testing::keycodes::kLogicalKeyB; using ::flutter::testing::keycodes::kLogicalKeyM; using ::flutter::testing::keycodes::kLogicalKeyQ; using ::flutter::testing::keycodes::kLogicalMetaLeft; using ::flutter::testing::keycodes::kLogicalMinus; using ::flutter::testing::keycodes::kLogicalParenthesisRight; using ::flutter::testing::keycodes::kLogicalSemicolon; using ::flutter::testing::keycodes::kLogicalShiftLeft; using ::flutter::testing::keycodes::kLogicalUnderscore; using ::flutter::testing::keycodes::kPhysicalAltLeft; using ::flutter::testing::keycodes::kPhysicalControlLeft; using ::flutter::testing::keycodes::kPhysicalKeyA; using ::flutter::testing::keycodes::kPhysicalKeyB; using ::flutter::testing::keycodes::kPhysicalMetaLeft; using ::flutter::testing::keycodes::kPhysicalShiftLeft; // Hardware key codes. typedef std::function<void(bool handled)> AsyncKeyCallback; typedef std::function<void(AsyncKeyCallback callback)> ChannelCallHandler; typedef std::function<void(const FlutterKeyEvent* event, AsyncKeyCallback callback)> EmbedderCallHandler; typedef std::function<void(std::unique_ptr<FlKeyEvent>)> RedispatchHandler; // A type that can record all kinds of effects that the keyboard manager // triggers. // // An instance of `CallRecord` might not have all the fields filled. typedef struct { enum { kKeyCallEmbedder, kKeyCallChannel, } type; AsyncKeyCallback callback; std::unique_ptr<FlutterKeyEvent> event; std::unique_ptr<char[]> event_character; } CallRecord; // Clone a C-string. // // Must be deleted by delete[]. char* cloneString(const char* source) { if (source == nullptr) { return nullptr; } size_t charLen = strlen(source); char* target = new char[charLen + 1]; strncpy(target, source, charLen + 1); return target; } constexpr guint16 kKeyCodeKeyA = 0x26u; constexpr guint16 kKeyCodeKeyB = 0x38u; constexpr guint16 kKeyCodeKeyM = 0x3au; constexpr guint16 kKeyCodeDigit1 = 0x0au; constexpr guint16 kKeyCodeMinus = 0x14u; constexpr guint16 kKeyCodeSemicolon = 0x2fu; constexpr guint16 kKeyCodeKeyLeftBracket = 0x22u; static constexpr char kKeyEventChannelName[] = "flutter/keyevent"; static constexpr char kKeyboardChannelName[] = "flutter/keyboard"; static constexpr char kGetKeyboardStateMethod[] = "getKeyboardState"; static constexpr uint64_t kMockPhysicalKey = 42; static constexpr uint64_t kMockLogicalKey = 42; // All key clues for a keyboard layout. // // The index is (keyCode * 2 + hasShift), where each value is the character for // this key (GTK only supports UTF-16.) Since the maximum keycode of interest // is 128, it has a total of 256 entries.. typedef std::array<uint32_t, 256> MockGroupLayoutData; typedef std::vector<const MockGroupLayoutData*> MockLayoutData; extern const MockLayoutData kLayoutUs; extern const MockLayoutData kLayoutRussian; extern const MockLayoutData kLayoutFrench; G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlMockViewDelegate, fl_mock_view_delegate, FL, MOCK_VIEW_DELEGATE, GObject); G_DECLARE_FINAL_TYPE(FlMockKeyBinaryMessenger, fl_mock_key_binary_messenger, FL, MOCK_KEY_BINARY_MESSENGER, GObject) G_END_DECLS MATCHER_P(MethodSuccessResponse, result, "") { g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response(FL_METHOD_CODEC(codec), arg, nullptr); fl_method_response_get_result(response, nullptr); if (fl_value_equal(fl_method_response_get_result(response, nullptr), result)) { return true; } *result_listener << ::testing::PrintToString(response); return false; } /***** FlMockKeyBinaryMessenger *****/ /* Mock a binary messenger that only processes messages from the embedding on * the key event channel, and does so according to the callback set by * fl_mock_key_binary_messenger_set_callback_handler */ struct _FlMockKeyBinaryMessenger { GObject parent_instance; }; struct FlMockKeyBinaryMessengerPrivate { ChannelCallHandler callback_handler; }; static void fl_mock_key_binary_messenger_iface_init( FlBinaryMessengerInterface* iface); G_DEFINE_TYPE_WITH_CODE( FlMockKeyBinaryMessenger, fl_mock_key_binary_messenger, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE(fl_binary_messenger_get_type(), fl_mock_key_binary_messenger_iface_init); G_ADD_PRIVATE(FlMockKeyBinaryMessenger)) #define FL_MOCK_KEY_BINARY_MESSENGER_GET_PRIVATE(obj) \ static_cast<FlMockKeyBinaryMessengerPrivate*>( \ fl_mock_key_binary_messenger_get_instance_private( \ FL_MOCK_KEY_BINARY_MESSENGER(obj))) static void fl_mock_key_binary_messenger_init(FlMockKeyBinaryMessenger* self) { FlMockKeyBinaryMessengerPrivate* priv = FL_MOCK_KEY_BINARY_MESSENGER_GET_PRIVATE(self); new (priv) FlMockKeyBinaryMessengerPrivate(); } static void fl_mock_key_binary_messenger_finalize(GObject* object) { FL_MOCK_KEY_BINARY_MESSENGER_GET_PRIVATE(object) ->~FlMockKeyBinaryMessengerPrivate(); } static void fl_mock_key_binary_messenger_class_init( FlMockKeyBinaryMessengerClass* klass) { G_OBJECT_CLASS(klass)->finalize = fl_mock_key_binary_messenger_finalize; } static void fl_mock_key_binary_messenger_send_on_channel( FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data) { FlMockKeyBinaryMessenger* self = FL_MOCK_KEY_BINARY_MESSENGER(messenger); if (callback != nullptr) { EXPECT_STREQ(channel, kKeyEventChannelName); FL_MOCK_KEY_BINARY_MESSENGER_GET_PRIVATE(self)->callback_handler( [self, cancellable, callback, user_data](bool handled) { g_autoptr(GTask) task = g_task_new(self, cancellable, callback, user_data); g_autoptr(FlValue) result = fl_value_new_map(); fl_value_set_string_take(result, "handled", fl_value_new_bool(handled)); g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); g_autoptr(GError) error = nullptr; GBytes* data = fl_message_codec_encode_message( FL_MESSAGE_CODEC(codec), result, &error); g_task_return_pointer( task, data, reinterpret_cast<GDestroyNotify>(g_bytes_unref)); }); } } static GBytes* fl_mock_key_binary_messenger_send_on_channel_finish( FlBinaryMessenger* messenger, GAsyncResult* result, GError** error) { return static_cast<GBytes*>(g_task_propagate_pointer(G_TASK(result), error)); } static void fl_mock_binary_messenger_resize_channel( FlBinaryMessenger* messenger, const gchar* channel, int64_t new_size) { // Mock implementation. Do nothing. } static void fl_mock_binary_messenger_set_warns_on_channel_overflow( FlBinaryMessenger* messenger, const gchar* channel, bool warns) { // Mock implementation. Do nothing. } static void fl_mock_key_binary_messenger_iface_init( FlBinaryMessengerInterface* iface) { iface->set_message_handler_on_channel = [](FlBinaryMessenger* messenger, const gchar* channel, FlBinaryMessengerMessageHandler handler, gpointer user_data, GDestroyNotify destroy_notify) { EXPECT_STREQ(channel, kKeyEventChannelName); // No need to mock. The key event channel expects no incoming messages // from the framework. }; iface->send_response = [](FlBinaryMessenger* messenger, FlBinaryMessengerResponseHandle* response_handle, GBytes* response, GError** error) -> gboolean { // The key event channel expects no incoming messages from the framework, // hence no responses either. g_return_val_if_reached(TRUE); return TRUE; }; iface->send_on_channel = fl_mock_key_binary_messenger_send_on_channel; iface->send_on_channel_finish = fl_mock_key_binary_messenger_send_on_channel_finish; iface->resize_channel = fl_mock_binary_messenger_resize_channel; iface->set_warns_on_channel_overflow = fl_mock_binary_messenger_set_warns_on_channel_overflow; } static FlMockKeyBinaryMessenger* fl_mock_key_binary_messenger_new() { FlMockKeyBinaryMessenger* self = FL_MOCK_KEY_BINARY_MESSENGER( g_object_new(fl_mock_key_binary_messenger_get_type(), NULL)); // Added to stop compiler complaining about an unused function. FL_IS_MOCK_KEY_BINARY_MESSENGER(self); return self; } static void fl_mock_key_binary_messenger_set_callback_handler( FlMockKeyBinaryMessenger* self, ChannelCallHandler handler) { FL_MOCK_KEY_BINARY_MESSENGER_GET_PRIVATE(self)->callback_handler = std::move(handler); } /***** FlMockViewDelegate *****/ struct _FlMockViewDelegate { GObject parent_instance; }; struct FlMockViewDelegatePrivate { FlMockKeyBinaryMessenger* messenger; EmbedderCallHandler embedder_handler; bool text_filter_result; RedispatchHandler redispatch_handler; KeyboardLayoutNotifier layout_notifier; const MockLayoutData* layout_data; }; static void fl_mock_view_keyboard_delegate_iface_init( FlKeyboardViewDelegateInterface* iface); G_DEFINE_TYPE_WITH_CODE( FlMockViewDelegate, fl_mock_view_delegate, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE(fl_keyboard_view_delegate_get_type(), fl_mock_view_keyboard_delegate_iface_init); G_ADD_PRIVATE(FlMockViewDelegate)) #define FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(obj) \ static_cast<FlMockViewDelegatePrivate*>( \ fl_mock_view_delegate_get_instance_private(FL_MOCK_VIEW_DELEGATE(obj))) static void fl_mock_view_delegate_init(FlMockViewDelegate* self) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(self); new (priv) FlMockViewDelegatePrivate(); } static void fl_mock_view_delegate_finalize(GObject* object) { FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(object)->~FlMockViewDelegatePrivate(); } static void fl_mock_view_delegate_dispose(GObject* object) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(object); g_clear_object(&priv->messenger); G_OBJECT_CLASS(fl_mock_view_delegate_parent_class)->dispose(object); } static void fl_mock_view_delegate_class_init(FlMockViewDelegateClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_mock_view_delegate_dispose; G_OBJECT_CLASS(klass)->finalize = fl_mock_view_delegate_finalize; } static void fl_mock_view_keyboard_send_key_event( FlKeyboardViewDelegate* view_delegate, const FlutterKeyEvent* event, FlutterKeyEventCallback callback, void* user_data) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(view_delegate); priv->embedder_handler(event, [callback, user_data](bool handled) { if (callback != nullptr) { callback(handled, user_data); } }); } static gboolean fl_mock_view_keyboard_text_filter_key_press( FlKeyboardViewDelegate* view_delegate, FlKeyEvent* event) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(view_delegate); return priv->text_filter_result; } static FlBinaryMessenger* fl_mock_view_keyboard_get_messenger( FlKeyboardViewDelegate* view_delegate) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(view_delegate); return FL_BINARY_MESSENGER(priv->messenger); } static void fl_mock_view_keyboard_redispatch_event( FlKeyboardViewDelegate* view_delegate, std::unique_ptr<FlKeyEvent> event) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(view_delegate); if (priv->redispatch_handler) { priv->redispatch_handler(std::move(event)); } } static void fl_mock_view_keyboard_subscribe_to_layout_change( FlKeyboardViewDelegate* delegate, KeyboardLayoutNotifier notifier) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(delegate); priv->layout_notifier = std::move(notifier); } static guint fl_mock_view_keyboard_lookup_key(FlKeyboardViewDelegate* delegate, const GdkKeymapKey* key) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(delegate); guint8 group = static_cast<guint8>(key->group); EXPECT_LT(group, priv->layout_data->size()); const MockGroupLayoutData* group_layout = (*priv->layout_data)[group]; EXPECT_TRUE(group_layout != nullptr); EXPECT_TRUE(key->level == 0 || key->level == 1); bool shift = key->level == 1; return (*group_layout)[key->keycode * 2 + shift]; } static GHashTable* fl_mock_view_keyboard_get_keyboard_state( FlKeyboardViewDelegate* view_delegate) { GHashTable* result = g_hash_table_new(g_direct_hash, g_direct_equal); g_hash_table_insert(result, reinterpret_cast<gpointer>(kMockPhysicalKey), reinterpret_cast<gpointer>(kMockLogicalKey)); return result; } static void fl_mock_view_keyboard_delegate_iface_init( FlKeyboardViewDelegateInterface* iface) { iface->send_key_event = fl_mock_view_keyboard_send_key_event; iface->text_filter_key_press = fl_mock_view_keyboard_text_filter_key_press; iface->get_messenger = fl_mock_view_keyboard_get_messenger; iface->redispatch_event = fl_mock_view_keyboard_redispatch_event; iface->subscribe_to_layout_change = fl_mock_view_keyboard_subscribe_to_layout_change; iface->lookup_key = fl_mock_view_keyboard_lookup_key; iface->get_keyboard_state = fl_mock_view_keyboard_get_keyboard_state; } static FlMockViewDelegate* fl_mock_view_delegate_new() { FlMockViewDelegate* self = FL_MOCK_VIEW_DELEGATE( g_object_new(fl_mock_view_delegate_get_type(), nullptr)); // Added to stop compiler complaining about an unused function. FL_IS_MOCK_VIEW_DELEGATE(self); FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(self); priv->messenger = fl_mock_key_binary_messenger_new(); return self; } static void fl_mock_view_set_embedder_handler(FlMockViewDelegate* self, EmbedderCallHandler handler) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(self); priv->embedder_handler = std::move(handler); } static void fl_mock_view_set_text_filter_result(FlMockViewDelegate* self, bool result) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(self); priv->text_filter_result = result; } static void fl_mock_view_set_redispatch_handler(FlMockViewDelegate* self, RedispatchHandler handler) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(self); priv->redispatch_handler = std::move(handler); } static void fl_mock_view_set_layout(FlMockViewDelegate* self, const MockLayoutData* layout) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(self); priv->layout_data = layout; if (priv->layout_notifier != nullptr) { priv->layout_notifier(); } } /***** End FlMockViewDelegate *****/ // Create a new #FlKeyEvent with the given information. static FlKeyEvent* fl_key_event_new_by_mock(bool is_press, guint keyval, guint16 keycode, GdkModifierType state, gboolean is_modifier, guint8 group = 0) { FlKeyEvent* event = g_new0(FlKeyEvent, 1); event->is_press = is_press; event->time = 0; event->state = state; event->keyval = keyval; event->group = group; event->keycode = keycode; return event; } class KeyboardTester { public: KeyboardTester() { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; view_ = fl_mock_view_delegate_new(); respondToEmbedderCallsWith(false); respondToChannelCallsWith(false); respondToTextInputWith(false); setLayout(kLayoutUs); manager_ = fl_keyboard_manager_new(messenger, FL_KEYBOARD_VIEW_DELEGATE(view_)); } ~KeyboardTester() { g_clear_object(&view_); g_clear_object(&manager_); } FlKeyboardManager* manager() { return manager_; } // Block until all GdkMainLoop messages are processed, which is basically // used only for channel messages. void flushChannelMessages() { GMainLoop* loop = g_main_loop_new(nullptr, 0); g_idle_add(_flushChannelMessagesCb, loop); g_main_loop_run(loop); } // Dispatch each of the given events, expect their results to be false // (unhandled), and clear the event array. // // Returns the number of events redispatched. If any result is unexpected // (handled), return a minus number `-x` instead, where `x` is the index of // the first unexpected redispatch. int redispatchEventsAndClear( std::vector<std::unique_ptr<FlKeyEvent>>& events) { size_t event_count = events.size(); int first_error = -1; during_redispatch_ = true; for (size_t event_id = 0; event_id < event_count; event_id += 1) { bool handled = fl_keyboard_manager_handle_event( manager_, events[event_id].release()); EXPECT_FALSE(handled); if (handled) { first_error = first_error == -1 ? event_id : first_error; } } during_redispatch_ = false; events.clear(); return first_error < 0 ? event_count : -first_error; } void respondToEmbedderCallsWith(bool response) { fl_mock_view_set_embedder_handler( view_, [response, this](const FlutterKeyEvent* event, const AsyncKeyCallback& callback) { EXPECT_FALSE(during_redispatch_); callback(response); }); } void recordEmbedderCallsTo(std::vector<CallRecord>& storage) { fl_mock_view_set_embedder_handler( view_, [&storage, this](const FlutterKeyEvent* event, AsyncKeyCallback callback) { EXPECT_FALSE(during_redispatch_); auto new_event = std::make_unique<FlutterKeyEvent>(*event); char* new_event_character = cloneString(event->character); new_event->character = new_event_character; storage.push_back(CallRecord{ .type = CallRecord::kKeyCallEmbedder, .callback = std::move(callback), .event = std::move(new_event), .event_character = std::unique_ptr<char[]>(new_event_character), }); }); } void respondToEmbedderCallsWithAndRecordsTo( bool response, std::vector<CallRecord>& storage) { fl_mock_view_set_embedder_handler( view_, [&storage, response, this](const FlutterKeyEvent* event, const AsyncKeyCallback& callback) { EXPECT_FALSE(during_redispatch_); auto new_event = std::make_unique<FlutterKeyEvent>(*event); char* new_event_character = cloneString(event->character); new_event->character = new_event_character; storage.push_back(CallRecord{ .type = CallRecord::kKeyCallEmbedder, .event = std::move(new_event), .event_character = std::unique_ptr<char[]>(new_event_character), }); callback(response); }); } void respondToChannelCallsWith(bool response) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(view_); fl_mock_key_binary_messenger_set_callback_handler( priv->messenger, [response, this](const AsyncKeyCallback& callback) { EXPECT_FALSE(during_redispatch_); callback(response); }); } void recordChannelCallsTo(std::vector<CallRecord>& storage) { FlMockViewDelegatePrivate* priv = FL_MOCK_VIEW_DELEGATE_GET_PRIVATE(view_); fl_mock_key_binary_messenger_set_callback_handler( priv->messenger, [&storage, this](AsyncKeyCallback callback) { EXPECT_FALSE(during_redispatch_); storage.push_back(CallRecord{ .type = CallRecord::kKeyCallChannel, .callback = std::move(callback), }); }); } void respondToTextInputWith(bool response) { fl_mock_view_set_text_filter_result(view_, response); } void recordRedispatchedEventsTo( std::vector<std::unique_ptr<FlKeyEvent>>& storage) { fl_mock_view_set_redispatch_handler( view_, [&storage](std::unique_ptr<FlKeyEvent> key) { storage.push_back(std::move(key)); }); } void setLayout(const MockLayoutData& layout) { fl_mock_view_set_layout(view_, &layout); } private: FlMockViewDelegate* view_; FlKeyboardManager* manager_; bool during_redispatch_ = false; static gboolean _flushChannelMessagesCb(gpointer data) { g_autoptr(GMainLoop) loop = reinterpret_cast<GMainLoop*>(data); g_main_loop_quit(loop); return FALSE; } }; // Make sure that the keyboard can be disposed without crashes when there are // unresolved pending events. TEST(FlKeyboardManagerTest, DisposeWithUnresolvedPends) { KeyboardTester tester; std::vector<CallRecord> call_records; // Record calls so that they aren't responded. tester.recordEmbedderCallsTo(call_records); fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(true, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); tester.respondToEmbedderCallsWith(true); fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(false, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); tester.flushChannelMessages(); // Passes if the cleanup does not crash. } TEST(FlKeyboardManagerTest, SingleDelegateWithAsyncResponds) { KeyboardTester tester; std::vector<CallRecord> call_records; std::vector<std::unique_ptr<FlKeyEvent>> redispatched; gboolean manager_handled = false; /// Test 1: One event that is handled by the framework tester.recordEmbedderCallsTo(call_records); tester.recordRedispatchedEventsTo(redispatched); // Dispatch a key event manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(true, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); tester.flushChannelMessages(); EXPECT_EQ(manager_handled, true); EXPECT_EQ(redispatched.size(), 0u); EXPECT_EQ(call_records.size(), 1u); EXPECT_KEY_EVENT(call_records[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", false); call_records[0].callback(true); tester.flushChannelMessages(); EXPECT_EQ(redispatched.size(), 0u); EXPECT_TRUE(fl_keyboard_manager_is_state_clear(tester.manager())); call_records.clear(); /// Test 2: Two events that are unhandled by the framework manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(false, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); tester.flushChannelMessages(); EXPECT_EQ(manager_handled, true); EXPECT_EQ(redispatched.size(), 0u); EXPECT_EQ(call_records.size(), 1u); EXPECT_KEY_EVENT(call_records[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, nullptr, false); // Dispatch another key event manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(true, GDK_KEY_b, kKeyCodeKeyB, static_cast<GdkModifierType>(0), false)); tester.flushChannelMessages(); EXPECT_EQ(manager_handled, true); EXPECT_EQ(redispatched.size(), 0u); EXPECT_EQ(call_records.size(), 2u); EXPECT_KEY_EVENT(call_records[1], kFlutterKeyEventTypeDown, kPhysicalKeyB, kLogicalKeyB, "b", false); // Resolve the second event first to test out-of-order response call_records[1].callback(false); EXPECT_EQ(redispatched.size(), 1u); EXPECT_EQ(redispatched[0]->keyval, 0x62u); call_records[0].callback(false); tester.flushChannelMessages(); EXPECT_EQ(redispatched.size(), 2u); EXPECT_EQ(redispatched[1]->keyval, 0x61u); EXPECT_FALSE(fl_keyboard_manager_is_state_clear(tester.manager())); call_records.clear(); // Resolve redispatches EXPECT_EQ(tester.redispatchEventsAndClear(redispatched), 2); tester.flushChannelMessages(); EXPECT_EQ(call_records.size(), 0u); EXPECT_TRUE(fl_keyboard_manager_is_state_clear(tester.manager())); /// Test 3: Dispatch the same event again to ensure that prevention from /// redispatching only works once. manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(false, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); tester.flushChannelMessages(); EXPECT_EQ(manager_handled, true); EXPECT_EQ(redispatched.size(), 0u); EXPECT_EQ(call_records.size(), 1u); call_records[0].callback(true); EXPECT_TRUE(fl_keyboard_manager_is_state_clear(tester.manager())); } TEST(FlKeyboardManagerTest, SingleDelegateWithSyncResponds) { KeyboardTester tester; gboolean manager_handled = false; std::vector<CallRecord> call_records; std::vector<std::unique_ptr<FlKeyEvent>> redispatched; /// Test 1: One event that is handled by the framework tester.respondToEmbedderCallsWithAndRecordsTo(true, call_records); tester.recordRedispatchedEventsTo(redispatched); // Dispatch a key event manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(true, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); tester.flushChannelMessages(); EXPECT_EQ(manager_handled, true); EXPECT_EQ(call_records.size(), 1u); EXPECT_KEY_EVENT(call_records[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", false); EXPECT_EQ(redispatched.size(), 0u); call_records.clear(); EXPECT_TRUE(fl_keyboard_manager_is_state_clear(tester.manager())); redispatched.clear(); /// Test 2: An event unhandled by the framework tester.respondToEmbedderCallsWithAndRecordsTo(false, call_records); manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(false, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); tester.flushChannelMessages(); EXPECT_EQ(manager_handled, true); EXPECT_EQ(call_records.size(), 1u); EXPECT_KEY_EVENT(call_records[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, nullptr, false); EXPECT_EQ(redispatched.size(), 1u); call_records.clear(); EXPECT_FALSE(fl_keyboard_manager_is_state_clear(tester.manager())); EXPECT_EQ(tester.redispatchEventsAndClear(redispatched), 1); EXPECT_EQ(call_records.size(), 0u); EXPECT_TRUE(fl_keyboard_manager_is_state_clear(tester.manager())); } TEST(FlKeyboardManagerTest, WithTwoAsyncDelegates) { KeyboardTester tester; std::vector<CallRecord> call_records; std::vector<std::unique_ptr<FlKeyEvent>> redispatched; gboolean manager_handled = false; tester.recordEmbedderCallsTo(call_records); tester.recordChannelCallsTo(call_records); tester.recordRedispatchedEventsTo(redispatched); /// Test 1: One delegate responds true, the other false manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(true, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); EXPECT_EQ(manager_handled, true); EXPECT_EQ(redispatched.size(), 0u); EXPECT_EQ(call_records.size(), 2u); EXPECT_EQ(call_records[0].type, CallRecord::kKeyCallEmbedder); EXPECT_EQ(call_records[1].type, CallRecord::kKeyCallChannel); call_records[0].callback(true); call_records[1].callback(false); tester.flushChannelMessages(); EXPECT_EQ(redispatched.size(), 0u); EXPECT_TRUE(fl_keyboard_manager_is_state_clear(tester.manager())); call_records.clear(); /// Test 2: All delegates respond false manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(false, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); EXPECT_EQ(manager_handled, true); EXPECT_EQ(redispatched.size(), 0u); EXPECT_EQ(call_records.size(), 2u); EXPECT_EQ(call_records[0].type, CallRecord::kKeyCallEmbedder); EXPECT_EQ(call_records[1].type, CallRecord::kKeyCallChannel); call_records[0].callback(false); call_records[1].callback(false); call_records.clear(); // Resolve redispatch tester.flushChannelMessages(); EXPECT_EQ(redispatched.size(), 1u); EXPECT_EQ(tester.redispatchEventsAndClear(redispatched), 1); EXPECT_EQ(call_records.size(), 0u); EXPECT_TRUE(fl_keyboard_manager_is_state_clear(tester.manager())); } TEST(FlKeyboardManagerTest, TextInputPluginReturnsFalse) { KeyboardTester tester; std::vector<std::unique_ptr<FlKeyEvent>> redispatched; gboolean manager_handled = false; tester.recordRedispatchedEventsTo(redispatched); tester.respondToTextInputWith(false); // Dispatch a key event. manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(true, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); tester.flushChannelMessages(); EXPECT_EQ(manager_handled, true); // The event was redispatched because no one handles it. EXPECT_EQ(redispatched.size(), 1u); // Resolve redispatched event. EXPECT_EQ(tester.redispatchEventsAndClear(redispatched), 1); EXPECT_TRUE(fl_keyboard_manager_is_state_clear(tester.manager())); } TEST(FlKeyboardManagerTest, TextInputPluginReturnsTrue) { KeyboardTester tester; std::vector<std::unique_ptr<FlKeyEvent>> redispatched; gboolean manager_handled = false; tester.recordRedispatchedEventsTo(redispatched); tester.respondToTextInputWith(true); // Dispatch a key event. manager_handled = fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(true, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); tester.flushChannelMessages(); EXPECT_EQ(manager_handled, true); // The event was not redispatched because text input plugin handles it. EXPECT_EQ(redispatched.size(), 0u); EXPECT_TRUE(fl_keyboard_manager_is_state_clear(tester.manager())); } TEST(FlKeyboardManagerTest, CorrectLogicalKeyForLayouts) { KeyboardTester tester; std::vector<CallRecord> call_records; tester.recordEmbedderCallsTo(call_records); auto sendTap = [&](guint8 keycode, guint keyval, guint8 group) { fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock( true, keyval, keycode, static_cast<GdkModifierType>(0), false, group)); fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock( false, keyval, keycode, static_cast<GdkModifierType>(0), false, group)); }; /* US keyboard layout */ sendTap(kKeyCodeKeyA, GDK_KEY_a, 0); // KeyA VERIFY_DOWN(kLogicalKeyA, "a"); sendTap(kKeyCodeKeyA, GDK_KEY_A, 0); // Shift-KeyA VERIFY_DOWN(kLogicalKeyA, "A"); sendTap(kKeyCodeDigit1, GDK_KEY_1, 0); // Digit1 VERIFY_DOWN(kLogicalDigit1, "1"); sendTap(kKeyCodeDigit1, GDK_KEY_exclam, 0); // Shift-Digit1 VERIFY_DOWN(kLogicalDigit1, "!"); sendTap(kKeyCodeMinus, GDK_KEY_minus, 0); // Minus VERIFY_DOWN(kLogicalMinus, "-"); sendTap(kKeyCodeMinus, GDK_KEY_underscore, 0); // Shift-Minus VERIFY_DOWN(kLogicalUnderscore, "_"); /* French keyboard layout, group 3, which is when the input method is showing * "Fr" */ tester.setLayout(kLayoutFrench); sendTap(kKeyCodeKeyA, GDK_KEY_q, 3); // KeyA VERIFY_DOWN(kLogicalKeyQ, "q"); sendTap(kKeyCodeKeyA, GDK_KEY_Q, 3); // Shift-KeyA VERIFY_DOWN(kLogicalKeyQ, "Q"); sendTap(kKeyCodeSemicolon, GDK_KEY_m, 3); // ; but prints M VERIFY_DOWN(kLogicalKeyM, "m"); sendTap(kKeyCodeKeyM, GDK_KEY_comma, 3); // M but prints , VERIFY_DOWN(kLogicalComma, ","); sendTap(kKeyCodeDigit1, GDK_KEY_ampersand, 3); // Digit1 VERIFY_DOWN(kLogicalDigit1, "&"); sendTap(kKeyCodeDigit1, GDK_KEY_1, 3); // Shift-Digit1 VERIFY_DOWN(kLogicalDigit1, "1"); sendTap(kKeyCodeMinus, GDK_KEY_parenright, 3); // Minus VERIFY_DOWN(kLogicalParenthesisRight, ")"); sendTap(kKeyCodeMinus, GDK_KEY_degree, 3); // Shift-Minus VERIFY_DOWN(static_cast<uint32_t>(L'Β°'), "Β°"); /* French keyboard layout, group 0, which is pressing the "extra key for * triggering input method" key once after switching to French IME. */ sendTap(kKeyCodeKeyA, GDK_KEY_a, 0); // KeyA VERIFY_DOWN(kLogicalKeyA, "a"); sendTap(kKeyCodeDigit1, GDK_KEY_1, 0); // Digit1 VERIFY_DOWN(kLogicalDigit1, "1"); /* Russian keyboard layout, group 2 */ tester.setLayout(kLayoutRussian); sendTap(kKeyCodeKeyA, GDK_KEY_Cyrillic_ef, 2); // KeyA VERIFY_DOWN(kLogicalKeyA, "Ρ„"); sendTap(kKeyCodeDigit1, GDK_KEY_1, 2); // Shift-Digit1 VERIFY_DOWN(kLogicalDigit1, "1"); sendTap(kKeyCodeKeyLeftBracket, GDK_KEY_Cyrillic_ha, 2); VERIFY_DOWN(kLogicalBracketLeft, "Ρ…"); /* Russian keyboard layout, group 0 */ sendTap(kKeyCodeKeyA, GDK_KEY_a, 0); // KeyA VERIFY_DOWN(kLogicalKeyA, "a"); sendTap(kKeyCodeKeyLeftBracket, GDK_KEY_bracketleft, 0); VERIFY_DOWN(kLogicalBracketLeft, "["); } TEST(FlKeyboardManagerTest, SynthesizeModifiersIfNeeded) { KeyboardTester tester; std::vector<CallRecord> call_records; tester.recordEmbedderCallsTo(call_records); auto verifyModifierIsSynthesized = [&](GdkModifierType mask, uint64_t physical, uint64_t logical) { // Modifier is pressed. guint state = mask; fl_keyboard_manager_sync_modifier_if_needed(tester.manager(), state, 1000); EXPECT_EQ(call_records.size(), 1u); EXPECT_KEY_EVENT(call_records[0], kFlutterKeyEventTypeDown, physical, logical, NULL, true); // Modifier is released. state = state ^ mask; fl_keyboard_manager_sync_modifier_if_needed(tester.manager(), state, 1001); EXPECT_EQ(call_records.size(), 2u); EXPECT_KEY_EVENT(call_records[1], kFlutterKeyEventTypeUp, physical, logical, NULL, true); call_records.clear(); }; // No modifiers pressed. guint state = 0; fl_keyboard_manager_sync_modifier_if_needed(tester.manager(), state, 1000); EXPECT_EQ(call_records.size(), 0u); call_records.clear(); // Press and release each modifier once. verifyModifierIsSynthesized(GDK_CONTROL_MASK, kPhysicalControlLeft, kLogicalControlLeft); verifyModifierIsSynthesized(GDK_META_MASK, kPhysicalMetaLeft, kLogicalMetaLeft); verifyModifierIsSynthesized(GDK_MOD1_MASK, kPhysicalAltLeft, kLogicalAltLeft); verifyModifierIsSynthesized(GDK_SHIFT_MASK, kPhysicalShiftLeft, kLogicalShiftLeft); } TEST(FlKeyboardManagerTest, GetPressedState) { KeyboardTester tester; tester.respondToTextInputWith(true); // Dispatch a key event. fl_keyboard_manager_handle_event( tester.manager(), fl_key_event_new_by_mock(true, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), false)); GHashTable* pressedState = fl_keyboard_manager_get_pressed_state(tester.manager()); EXPECT_EQ(g_hash_table_size(pressedState), 1u); gpointer physical_key = g_hash_table_lookup(pressedState, uint64_to_gpointer(kPhysicalKeyA)); EXPECT_EQ(gpointer_to_uint64(physical_key), kLogicalKeyA); } TEST(FlKeyboardPluginTest, KeyboardChannelGetPressedState) { ::testing::NiceMock<flutter::testing::MockBinaryMessenger> messenger; g_autoptr(FlKeyboardManager) manager = fl_keyboard_manager_new( messenger, FL_KEYBOARD_VIEW_DELEGATE(fl_mock_view_delegate_new())); EXPECT_NE(manager, nullptr); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(GBytes) message = fl_method_codec_encode_method_call( FL_METHOD_CODEC(codec), kGetKeyboardStateMethod, nullptr, nullptr); g_autoptr(FlValue) response = fl_value_new_map(); fl_value_set_take(response, fl_value_new_int(kMockPhysicalKey), fl_value_new_int(kMockLogicalKey)); EXPECT_CALL(messenger, fl_binary_messenger_send_response( ::testing::Eq<FlBinaryMessenger*>(messenger), ::testing::_, MethodSuccessResponse(response), ::testing::_)) .WillOnce(::testing::Return(true)); messenger.ReceiveMessage(kKeyboardChannelName, message); } // The following layout data is generated using DEBUG_PRINT_LAYOUT. const MockGroupLayoutData kLayoutUs0{{ // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x00 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x04 0xffff, 0x0031, 0xffff, 0x0031, 0x0031, 0x0021, 0x0032, 0x0040, // 0x08 0x0033, 0x0023, 0x0034, 0x0024, 0x0035, 0x0025, 0x0036, 0x005e, // 0x0c 0x0037, 0x0026, 0x0038, 0x002a, 0x0039, 0x0028, 0x0030, 0x0029, // 0x10 0x002d, 0x005f, 0x003d, 0x002b, 0xffff, 0xffff, 0xffff, 0xffff, // 0x14 0x0071, 0x0051, 0x0077, 0x0057, 0x0065, 0x0045, 0x0072, 0x0052, // 0x18 0x0074, 0x0054, 0x0079, 0x0059, 0x0075, 0x0055, 0x0069, 0x0049, // 0x1c 0x006f, 0x004f, 0x0070, 0x0050, 0x005b, 0x007b, 0x005d, 0x007d, // 0x20 0xffff, 0xffff, 0xffff, 0x0061, 0x0061, 0x0041, 0x0073, 0x0053, // 0x24 0x0064, 0x0044, 0x0066, 0x0046, 0x0067, 0x0047, 0x0068, 0x0048, // 0x28 0x006a, 0x004a, 0x006b, 0x004b, 0x006c, 0x004c, 0x003b, 0x003a, // 0x2c 0x0027, 0x0022, 0x0060, 0x007e, 0xffff, 0x005c, 0x005c, 0x007c, // 0x30 0x007a, 0x005a, 0x0078, 0x0058, 0x0063, 0x0043, 0x0076, 0x0056, // 0x34 0x0062, 0x0042, 0x006e, 0x004e, 0x006d, 0x004d, 0x002c, 0x003c, // 0x38 0x002e, 0x003e, 0x002f, 0x003f, 0xffff, 0xffff, 0xffff, 0xffff, // 0x3c 0xffff, 0xffff, 0x0020, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x40 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x44 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x48 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x4c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x50 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x54 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x58 0xffff, 0xffff, 0x003c, 0x003e, 0x003c, 0x003e, 0xffff, 0xffff, // 0x5c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x60 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x64 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x68 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x6c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x70 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x74 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x78 0xffff, 0xffff, 0xffff, 0x00b1, 0x00b1, 0xffff, 0xffff, 0xffff, // 0x7c }}; const MockGroupLayoutData kLayoutRussian0{ // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x00 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x04 0x0000, 0xffff, 0xffff, 0x0031, 0x0031, 0x0021, 0x0032, 0x0040, // 0x08 0x0033, 0x0023, 0x0034, 0x0024, 0x0035, 0x0025, 0x0036, 0x005e, // 0x0c 0x0037, 0x0026, 0x0038, 0x002a, 0x0039, 0x0028, 0x0030, 0x0029, // 0x10 0x002d, 0x005f, 0x003d, 0x002b, 0xffff, 0xffff, 0xffff, 0xffff, // 0x14 0x0071, 0x0051, 0x0077, 0x0057, 0x0065, 0x0045, 0x0072, 0x0052, // 0x18 0x0074, 0x0054, 0x0079, 0x0059, 0x0075, 0x0055, 0x0069, 0x0049, // 0x1c 0x006f, 0x004f, 0x0070, 0x0050, 0x005b, 0x007b, 0x005d, 0x007d, // 0x20 0xffff, 0xffff, 0xffff, 0x0061, 0x0061, 0x0041, 0x0073, 0x0053, // 0x24 0x0064, 0x0044, 0x0066, 0x0046, 0x0067, 0x0047, 0x0068, 0x0048, // 0x28 0x006a, 0x004a, 0x006b, 0x004b, 0x006c, 0x004c, 0x003b, 0x003a, // 0x2c 0x0027, 0x0022, 0x0060, 0x007e, 0xffff, 0x005c, 0x005c, 0x007c, // 0x30 0x007a, 0x005a, 0x0078, 0x0058, 0x0063, 0x0043, 0x0076, 0x0056, // 0x34 0x0062, 0x0042, 0x006e, 0x004e, 0x006d, 0x004d, 0x002c, 0x003c, // 0x38 0x002e, 0x003e, 0x002f, 0x003f, 0xffff, 0xffff, 0xffff, 0xffff, // 0x3c 0xffff, 0xffff, 0x0020, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x40 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x44 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x48 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x4c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x50 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x54 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x58 0xffff, 0xffff, 0x0000, 0xffff, 0x003c, 0x003e, 0xffff, 0xffff, // 0x5c 0xffff, 0xffff, 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x60 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0xffff, // 0x64 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x68 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x6c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x70 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x74 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x78 0xffff, 0xffff, 0xffff, 0x00b1, 0x00b1, 0xffff, 0xffff, 0xffff, // 0x7c }; const MockGroupLayoutData kLayoutRussian2{{ // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x00 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x04 0xffff, 0x0031, 0x0021, 0x0000, 0x0031, 0x0021, 0x0032, 0x0022, // 0x08 0x0033, 0x06b0, 0x0034, 0x003b, 0x0035, 0x0025, 0x0036, 0x003a, // 0x0c 0x0037, 0x003f, 0x0038, 0x002a, 0x0039, 0x0028, 0x0030, 0x0029, // 0x10 0x002d, 0x005f, 0x003d, 0x002b, 0x0071, 0x0051, 0x0000, 0x0000, // 0x14 0x06ca, 0x06ea, 0x06c3, 0x06e3, 0x06d5, 0x06f5, 0x06cb, 0x06eb, // 0x18 0x06c5, 0x06e5, 0x06ce, 0x06ee, 0x06c7, 0x06e7, 0x06db, 0x06fb, // 0x1c 0x06dd, 0x06fd, 0x06da, 0x06fa, 0x06c8, 0x06e8, 0x06df, 0x06ff, // 0x20 0x0061, 0x0041, 0x0041, 0x0000, 0x06c6, 0x06e6, 0x06d9, 0x06f9, // 0x24 0x06d7, 0x06f7, 0x06c1, 0x06e1, 0x06d0, 0x06f0, 0x06d2, 0x06f2, // 0x28 0x06cf, 0x06ef, 0x06cc, 0x06ec, 0x06c4, 0x06e4, 0x06d6, 0x06f6, // 0x2c 0x06dc, 0x06fc, 0x06a3, 0x06b3, 0x007c, 0x0000, 0x005c, 0x002f, // 0x30 0x06d1, 0x06f1, 0x06de, 0x06fe, 0x06d3, 0x06f3, 0x06cd, 0x06ed, // 0x34 0x06c9, 0x06e9, 0x06d4, 0x06f4, 0x06d8, 0x06f8, 0x06c2, 0x06e2, // 0x38 0x06c0, 0x06e0, 0x002e, 0x002c, 0xffff, 0xffff, 0xffff, 0xffff, // 0x3c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x40 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x44 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x48 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x4c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x50 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x54 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x58 0xffff, 0xffff, 0x003c, 0x003e, 0x002f, 0x007c, 0xffff, 0xffff, // 0x5c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x60 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x64 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0xffff, 0xffff, 0x0000, // 0x68 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x6c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x70 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x74 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x00b1, // 0x78 0x00b1, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x7c }}; const MockGroupLayoutData kLayoutFrench0 = { // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x00 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x04 0x0000, 0xffff, 0xffff, 0x0031, 0x0031, 0x0021, 0x0032, 0x0040, // 0x08 0x0033, 0x0023, 0x0034, 0x0024, 0x0035, 0x0025, 0x0036, 0x005e, // 0x0c 0x0037, 0x0026, 0x0038, 0x002a, 0x0039, 0x0028, 0x0030, 0x0029, // 0x10 0x002d, 0x005f, 0x003d, 0x002b, 0xffff, 0xffff, 0xffff, 0xffff, // 0x14 0x0071, 0x0051, 0x0077, 0x0057, 0x0065, 0x0045, 0x0072, 0x0052, // 0x18 0x0074, 0x0054, 0x0079, 0x0059, 0x0075, 0x0055, 0x0069, 0x0049, // 0x1c 0x006f, 0x004f, 0x0070, 0x0050, 0x005b, 0x007b, 0x005d, 0x007d, // 0x20 0xffff, 0xffff, 0xffff, 0x0061, 0x0061, 0x0041, 0x0073, 0x0053, // 0x24 0x0064, 0x0044, 0x0066, 0x0046, 0x0067, 0x0047, 0x0068, 0x0048, // 0x28 0x006a, 0x004a, 0x006b, 0x004b, 0x006c, 0x004c, 0x003b, 0x003a, // 0x2c 0x0027, 0x0022, 0x0060, 0x007e, 0xffff, 0x005c, 0x005c, 0x007c, // 0x30 0x007a, 0x005a, 0x0078, 0x0058, 0x0063, 0x0043, 0x0076, 0x0056, // 0x34 0x0062, 0x0042, 0x006e, 0x004e, 0x006d, 0x004d, 0x002c, 0x003c, // 0x38 0x002e, 0x003e, 0x002f, 0x003f, 0xffff, 0xffff, 0xffff, 0xffff, // 0x3c 0xffff, 0xffff, 0x0020, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x40 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x44 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x48 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x4c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x50 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x54 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x58 0xffff, 0xffff, 0x0000, 0xffff, 0x003c, 0x003e, 0xffff, 0xffff, // 0x5c 0xffff, 0xffff, 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x60 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0xffff, // 0x64 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x68 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x6c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x70 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x74 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x78 0xffff, 0xffff, 0xffff, 0x00b1, 0x00b1, 0xffff, 0xffff, 0xffff, // 0x7c }; const MockGroupLayoutData kLayoutFrench3 = { // +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x00 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, 0x0000, 0xffff, // 0x04 0x0000, 0xffff, 0x0000, 0x0000, 0x0026, 0x0031, 0x00e9, 0x0032, // 0x08 0x0022, 0x0033, 0x0027, 0x0034, 0x0028, 0x0035, 0x002d, 0x0036, // 0x0c 0x00e8, 0x0037, 0x005f, 0x0038, 0x00e7, 0x0039, 0x00e0, 0x0030, // 0x10 0x0029, 0x00b0, 0x003d, 0x002b, 0x0000, 0x0000, 0x0061, 0x0041, // 0x14 0x0061, 0x0041, 0x007a, 0x005a, 0x0065, 0x0045, 0x0072, 0x0052, // 0x18 0x0074, 0x0054, 0x0079, 0x0059, 0x0075, 0x0055, 0x0069, 0x0049, // 0x1c 0x006f, 0x004f, 0x0070, 0x0050, 0xffff, 0xffff, 0x0024, 0x00a3, // 0x20 0x0041, 0x0000, 0x0000, 0x0000, 0x0071, 0x0051, 0x0073, 0x0053, // 0x24 0x0064, 0x0044, 0x0066, 0x0046, 0x0067, 0x0047, 0x0068, 0x0048, // 0x28 0x006a, 0x004a, 0x006b, 0x004b, 0x006c, 0x004c, 0x006d, 0x004d, // 0x2c 0x00f9, 0x0025, 0x00b2, 0x007e, 0x0000, 0x0000, 0x002a, 0x00b5, // 0x30 0x0077, 0x0057, 0x0078, 0x0058, 0x0063, 0x0043, 0x0076, 0x0056, // 0x34 0x0062, 0x0042, 0x006e, 0x004e, 0x002c, 0x003f, 0x003b, 0x002e, // 0x38 0x003a, 0x002f, 0x0021, 0x00a7, 0xffff, 0xffff, 0xffff, 0xffff, // 0x3c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x40 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x44 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x48 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x4c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x50 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x54 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x58 0xffff, 0x003c, 0x0000, 0xffff, 0x003c, 0x003e, 0xffff, 0xffff, // 0x5c 0xffff, 0xffff, 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x60 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0xffff, // 0x64 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x68 0xffff, 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x6c 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x70 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x74 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0x00b1, 0x00b1, 0xffff, // 0x78 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, // 0x7c }; const MockLayoutData kLayoutUs{&kLayoutUs0}; const MockLayoutData kLayoutRussian{&kLayoutRussian0, nullptr, &kLayoutRussian2}; const MockLayoutData kLayoutFrench{&kLayoutFrench0, nullptr, nullptr, &kLayoutFrench3}; } // namespace
engine/shell/platform/linux/fl_keyboard_manager_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_keyboard_manager_test.cc", "repo_id": "engine", "token_count": 24097 }
395
// 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 FLUTTER_SHELL_PLATFORM_LINUX_FL_MOUSE_CURSOR_PLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_MOUSE_CURSOR_PLUGIN_H_ #include <gdk/gdk.h> #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_view.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlMouseCursorPlugin, fl_mouse_cursor_plugin, FL, MOUSE_CURSOR_PLUGIN, GObject); /** * FlMouseCursorPlugin: * * #FlMouseCursorPlugin is a mouse_cursor channel that implements the shell side * of SystemChannels.mouseCursor from the Flutter services library. */ /** * fl_mouse_cursor_plugin_new: * @messenger: an #FlBinaryMessenger. * @view: an #FlView to control. * * Creates a new plugin that implements SystemChannels.mouseCursor from the * Flutter services library. * * Returns: a new #FlMouseCursorPlugin. */ FlMouseCursorPlugin* fl_mouse_cursor_plugin_new(FlBinaryMessenger* messenger, FlView* view); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_MOUSE_CURSOR_PLUGIN_H_
engine/shell/platform/linux/fl_mouse_cursor_plugin.h/0
{ "file_path": "engine/shell/platform/linux/fl_mouse_cursor_plugin.h", "repo_id": "engine", "token_count": 582 }
396
// 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 FLUTTER_SHELL_PLATFORM_LINUX_FL_RENDERER_HEADLESS_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_RENDERER_HEADLESS_H_ #include "flutter/shell/platform/linux/fl_renderer.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlRendererHeadless, fl_renderer_headless, FL, RENDERER_HEADLESS, FlRenderer) /** * FlRendererHeadless: * * #FlRendererHeadless is an implementation of #FlRenderer that works without a * display. */ /** * fl_renderer_headless_new: * * Creates an object that allows Flutter to operate without a display. * * Returns: a new #FlRendererHeadless. */ FlRendererHeadless* fl_renderer_headless_new(); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_RENDERER_HEADLESS_H_
engine/shell/platform/linux/fl_renderer_headless.h/0
{ "file_path": "engine/shell/platform/linux/fl_renderer_headless.h", "repo_id": "engine", "token_count": 410 }
397
// 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 "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h" #include <gmodule.h> #include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h" // See lib/src/services/message_codecs.dart in Flutter source for description of // encoding. // Envelope codes. static constexpr guint8 kEnvelopeTypeSuccess = 0; static constexpr guint8 kEnvelopeTypeError = 1; struct _FlStandardMethodCodec { FlMethodCodec parent_instance; FlStandardMessageCodec* codec; }; G_DEFINE_TYPE(FlStandardMethodCodec, fl_standard_method_codec, fl_method_codec_get_type()) static void fl_standard_method_codec_dispose(GObject* object) { FlStandardMethodCodec* self = FL_STANDARD_METHOD_CODEC(object); g_clear_object(&self->codec); G_OBJECT_CLASS(fl_standard_method_codec_parent_class)->dispose(object); } // Implements FlMethodCodec::encode_method_call. static GBytes* fl_standard_method_codec_encode_method_call(FlMethodCodec* codec, const gchar* name, FlValue* args, GError** error) { FlStandardMethodCodec* self = FL_STANDARD_METHOD_CODEC(codec); g_autoptr(GByteArray) buffer = g_byte_array_new(); g_autoptr(FlValue) name_value = fl_value_new_string(name); if (!fl_standard_message_codec_write_value(self->codec, buffer, name_value, error)) { return nullptr; } if (!fl_standard_message_codec_write_value(self->codec, buffer, args, error)) { return nullptr; } return g_byte_array_free_to_bytes( static_cast<GByteArray*>(g_steal_pointer(&buffer))); } // Implements FlMethodCodec::decode_method_call. static gboolean fl_standard_method_codec_decode_method_call( FlMethodCodec* codec, GBytes* message, gchar** name, FlValue** args, GError** error) { FlStandardMethodCodec* self = FL_STANDARD_METHOD_CODEC(codec); size_t offset = 0; g_autoptr(FlValue) name_value = fl_standard_message_codec_read_value( self->codec, message, &offset, error); if (name_value == nullptr) { return FALSE; } if (fl_value_get_type(name_value) != FL_VALUE_TYPE_STRING) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Method call name wrong type"); return FALSE; } g_autoptr(FlValue) args_value = fl_standard_message_codec_read_value( self->codec, message, &offset, error); if (args_value == nullptr) { return FALSE; } if (offset != g_bytes_get_size(message)) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Unexpected extra data"); return FALSE; } *name = g_strdup(fl_value_get_string(name_value)); *args = fl_value_ref(args_value); return TRUE; } // Implements FlMethodCodec::encode_success_envelope. static GBytes* fl_standard_method_codec_encode_success_envelope( FlMethodCodec* codec, FlValue* result, GError** error) { FlStandardMethodCodec* self = FL_STANDARD_METHOD_CODEC(codec); g_autoptr(GByteArray) buffer = g_byte_array_new(); guint8 type = kEnvelopeTypeSuccess; g_byte_array_append(buffer, &type, 1); if (!fl_standard_message_codec_write_value(self->codec, buffer, result, error)) { return nullptr; } return g_byte_array_free_to_bytes( static_cast<GByteArray*>(g_steal_pointer(&buffer))); } // Implements FlMethodCodec::encode_error_envelope. static GBytes* fl_standard_method_codec_encode_error_envelope( FlMethodCodec* codec, const gchar* code, const gchar* message, FlValue* details, GError** error) { FlStandardMethodCodec* self = FL_STANDARD_METHOD_CODEC(codec); g_autoptr(GByteArray) buffer = g_byte_array_new(); guint8 type = kEnvelopeTypeError; g_byte_array_append(buffer, &type, 1); g_autoptr(FlValue) code_value = fl_value_new_string(code); if (!fl_standard_message_codec_write_value(self->codec, buffer, code_value, error)) { return nullptr; } g_autoptr(FlValue) message_value = message != nullptr ? fl_value_new_string(message) : nullptr; if (!fl_standard_message_codec_write_value(self->codec, buffer, message_value, error)) { return nullptr; } if (!fl_standard_message_codec_write_value(self->codec, buffer, details, error)) { return nullptr; } return g_byte_array_free_to_bytes( static_cast<GByteArray*>(g_steal_pointer(&buffer))); } // Implements FlMethodCodec::encode_decode_response. static FlMethodResponse* fl_standard_method_codec_decode_response( FlMethodCodec* codec, GBytes* message, GError** error) { FlStandardMethodCodec* self = FL_STANDARD_METHOD_CODEC(codec); if (g_bytes_get_size(message) == 0) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA, "Empty response"); return nullptr; } // First byte is response type. const guint8* data = static_cast<const guint8*>(g_bytes_get_data(message, nullptr)); guint8 type = data[0]; size_t offset = 1; g_autoptr(FlMethodResponse) response = nullptr; if (type == kEnvelopeTypeError) { g_autoptr(FlValue) code = fl_standard_message_codec_read_value( self->codec, message, &offset, error); if (code == nullptr) { return nullptr; } if (fl_value_get_type(code) != FL_VALUE_TYPE_STRING) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Error code wrong type"); return nullptr; } g_autoptr(FlValue) error_message = fl_standard_message_codec_read_value( self->codec, message, &offset, error); if (error_message == nullptr) { return nullptr; } if (fl_value_get_type(error_message) != FL_VALUE_TYPE_STRING && fl_value_get_type(error_message) != FL_VALUE_TYPE_NULL) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Error message wrong type"); return nullptr; } g_autoptr(FlValue) details = fl_standard_message_codec_read_value( self->codec, message, &offset, error); if (details == nullptr) { return nullptr; } response = FL_METHOD_RESPONSE(fl_method_error_response_new( fl_value_get_string(code), fl_value_get_type(error_message) == FL_VALUE_TYPE_STRING ? fl_value_get_string(error_message) : nullptr, fl_value_get_type(details) != FL_VALUE_TYPE_NULL ? details : nullptr)); } else if (type == kEnvelopeTypeSuccess) { g_autoptr(FlValue) result = fl_standard_message_codec_read_value( self->codec, message, &offset, error); if (result == nullptr) { return nullptr; } response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); } else { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Unknown envelope type %02x", type); return nullptr; } if (offset != g_bytes_get_size(message)) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Unexpected extra data"); return nullptr; } return FL_METHOD_RESPONSE(g_object_ref(response)); } static void fl_standard_method_codec_class_init( FlStandardMethodCodecClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_standard_method_codec_dispose; FL_METHOD_CODEC_CLASS(klass)->encode_method_call = fl_standard_method_codec_encode_method_call; FL_METHOD_CODEC_CLASS(klass)->decode_method_call = fl_standard_method_codec_decode_method_call; FL_METHOD_CODEC_CLASS(klass)->encode_success_envelope = fl_standard_method_codec_encode_success_envelope; FL_METHOD_CODEC_CLASS(klass)->encode_error_envelope = fl_standard_method_codec_encode_error_envelope; FL_METHOD_CODEC_CLASS(klass)->decode_response = fl_standard_method_codec_decode_response; } static void fl_standard_method_codec_init(FlStandardMethodCodec* self) { self->codec = fl_standard_message_codec_new(); } G_MODULE_EXPORT FlStandardMethodCodec* fl_standard_method_codec_new() { return FL_STANDARD_METHOD_CODEC( g_object_new(fl_standard_method_codec_get_type(), nullptr)); }
engine/shell/platform/linux/fl_standard_method_codec.cc/0
{ "file_path": "engine/shell/platform/linux/fl_standard_method_codec.cc", "repo_id": "engine", "token_count": 3837 }
398
// 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 "flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h" #include <gmodule.h> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/fl_pixel_buffer_texture_private.h" #include "flutter/shell/platform/linux/fl_texture_gl_private.h" #include "flutter/shell/platform/linux/fl_texture_private.h" #include "flutter/shell/platform/linux/fl_texture_registrar_private.h" G_DECLARE_FINAL_TYPE(FlTextureRegistrarImpl, fl_texture_registrar_impl, FL, TEXTURE_REGISTRAR_IMPL, GObject) struct _FlTextureRegistrarImpl { GObject parent_instance; // Weak reference to the engine this texture registrar is created for. FlEngine* engine; // ID to assign to the next new texture. int64_t next_id; // Internal record for registered textures. // // It is a map from Flutter texture ID to #FlTexture instance created by // plugins. The keys are directly stored int64s. The values are stored // pointer to #FlTexture. This table is freed by the responder. GHashTable* textures; // The mutex guard to make `textures` thread-safe. GMutex textures_mutex; }; static void fl_texture_registrar_impl_iface_init( FlTextureRegistrarInterface* iface); G_DEFINE_INTERFACE(FlTextureRegistrar, fl_texture_registrar, G_TYPE_OBJECT) G_DEFINE_TYPE_WITH_CODE( FlTextureRegistrarImpl, fl_texture_registrar_impl, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE(fl_texture_registrar_get_type(), fl_texture_registrar_impl_iface_init)) static void fl_texture_registrar_default_init( FlTextureRegistrarInterface* iface) {} static void engine_weak_notify_cb(gpointer user_data, GObject* where_the_object_was) { FlTextureRegistrarImpl* self = FL_TEXTURE_REGISTRAR_IMPL(user_data); self->engine = nullptr; // Unregister any textures. g_mutex_lock(&self->textures_mutex); g_autoptr(GHashTable) textures = self->textures; self->textures = g_hash_table_new_full(g_direct_hash, g_direct_equal, nullptr, g_object_unref); g_hash_table_remove_all(textures); g_mutex_unlock(&self->textures_mutex); } static void fl_texture_registrar_impl_dispose(GObject* object) { FlTextureRegistrarImpl* self = FL_TEXTURE_REGISTRAR_IMPL(object); g_mutex_lock(&self->textures_mutex); g_clear_pointer(&self->textures, g_hash_table_unref); g_mutex_unlock(&self->textures_mutex); if (self->engine != nullptr) { g_object_weak_unref(G_OBJECT(self->engine), engine_weak_notify_cb, self); self->engine = nullptr; } g_mutex_clear(&self->textures_mutex); G_OBJECT_CLASS(fl_texture_registrar_impl_parent_class)->dispose(object); } static void fl_texture_registrar_impl_class_init( FlTextureRegistrarImplClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_texture_registrar_impl_dispose; } static gboolean register_texture(FlTextureRegistrar* registrar, FlTexture* texture) { FlTextureRegistrarImpl* self = FL_TEXTURE_REGISTRAR_IMPL(registrar); if (FL_IS_TEXTURE_GL(texture) || FL_IS_PIXEL_BUFFER_TEXTURE(texture)) { if (self->engine == nullptr) { return FALSE; } // We ideally would use numeric IDs, but for backwards compatibility with // existing code use the address of the texture. Once all code uses // fl_texture_get_id we can re-enable this method. See // https://github.com/flutter/flutter/issues/124009 int64_t id = // self->next_id++; int64_t id = reinterpret_cast<int64_t>(texture); if (fl_engine_register_external_texture(self->engine, id)) { fl_texture_set_id(texture, id); g_mutex_lock(&self->textures_mutex); g_hash_table_insert(self->textures, GINT_TO_POINTER(id), g_object_ref(texture)); g_mutex_unlock(&self->textures_mutex); return TRUE; } else { return FALSE; } } else { // We currently only support #FlTextureGL and #FlPixelBufferTexture. return FALSE; } } static FlTexture* lookup_texture(FlTextureRegistrar* registrar, int64_t texture_id) { FlTextureRegistrarImpl* self = FL_TEXTURE_REGISTRAR_IMPL(registrar); g_mutex_lock(&self->textures_mutex); FlTexture* texture = reinterpret_cast<FlTexture*>( g_hash_table_lookup(self->textures, GINT_TO_POINTER(texture_id))); g_mutex_unlock(&self->textures_mutex); return texture; } static gboolean mark_texture_frame_available(FlTextureRegistrar* registrar, FlTexture* texture) { FlTextureRegistrarImpl* self = FL_TEXTURE_REGISTRAR_IMPL(registrar); if (self->engine == nullptr) { return FALSE; } return fl_engine_mark_texture_frame_available(self->engine, fl_texture_get_id(texture)); } static gboolean unregister_texture(FlTextureRegistrar* registrar, FlTexture* texture) { FlTextureRegistrarImpl* self = FL_TEXTURE_REGISTRAR_IMPL(registrar); if (self->engine == nullptr) { return FALSE; } gboolean result = fl_engine_unregister_external_texture( self->engine, fl_texture_get_id(texture)); g_mutex_lock(&self->textures_mutex); if (!g_hash_table_remove(self->textures, GINT_TO_POINTER(fl_texture_get_id(texture)))) { g_warning("Unregistering a non-existent texture %p", texture); } g_mutex_unlock(&self->textures_mutex); return result; } static void fl_texture_registrar_impl_iface_init( FlTextureRegistrarInterface* iface) { iface->register_texture = register_texture; iface->lookup_texture = lookup_texture; iface->mark_texture_frame_available = mark_texture_frame_available; iface->unregister_texture = unregister_texture; } static void fl_texture_registrar_impl_init(FlTextureRegistrarImpl* self) { self->next_id = 1; self->textures = g_hash_table_new_full(g_direct_hash, g_direct_equal, nullptr, g_object_unref); // Initialize the mutex for textures. g_mutex_init(&self->textures_mutex); } G_MODULE_EXPORT gboolean fl_texture_registrar_register_texture( FlTextureRegistrar* self, FlTexture* texture) { g_return_val_if_fail(FL_IS_TEXTURE_REGISTRAR(self), FALSE); g_return_val_if_fail(FL_IS_TEXTURE(texture), FALSE); return FL_TEXTURE_REGISTRAR_GET_IFACE(self)->register_texture(self, texture); } FlTexture* fl_texture_registrar_lookup_texture(FlTextureRegistrar* self, int64_t texture_id) { g_return_val_if_fail(FL_IS_TEXTURE_REGISTRAR(self), NULL); return FL_TEXTURE_REGISTRAR_GET_IFACE(self)->lookup_texture(self, texture_id); } G_MODULE_EXPORT gboolean fl_texture_registrar_mark_texture_frame_available( FlTextureRegistrar* self, FlTexture* texture) { g_return_val_if_fail(FL_IS_TEXTURE_REGISTRAR(self), FALSE); return FL_TEXTURE_REGISTRAR_GET_IFACE(self)->mark_texture_frame_available( self, texture); } G_MODULE_EXPORT gboolean fl_texture_registrar_unregister_texture( FlTextureRegistrar* self, FlTexture* texture) { g_return_val_if_fail(FL_IS_TEXTURE_REGISTRAR(self), FALSE); return FL_TEXTURE_REGISTRAR_GET_IFACE(self)->unregister_texture(self, texture); } FlTextureRegistrar* fl_texture_registrar_new(FlEngine* engine) { FlTextureRegistrarImpl* self = FL_TEXTURE_REGISTRAR_IMPL( g_object_new(fl_texture_registrar_impl_get_type(), nullptr)); // Added to stop compiler complaining about an unused function. FL_IS_TEXTURE_REGISTRAR_IMPL(self); self->engine = engine; g_object_weak_ref(G_OBJECT(engine), engine_weak_notify_cb, self); return FL_TEXTURE_REGISTRAR(self); }
engine/shell/platform/linux/fl_texture_registrar.cc/0
{ "file_path": "engine/shell/platform/linux/fl_texture_registrar.cc", "repo_id": "engine", "token_count": 3358 }
399
// 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 FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_MESSENGER_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_MESSENGER_H_ #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif #include "fl_value.h" #include <gio/gio.h> #include <glib-object.h> #include <gmodule.h> G_BEGIN_DECLS /** * FlBinaryMessengerError: * @FL_BINARY_MESSENGER_ERROR_ALREADY_RESPONDED: unable to send response, this * message has already been responded to. * * Errors for #FlBinaryMessenger objects to set on failures. */ #define FL_BINARY_MESSENGER_ERROR fl_binary_messenger_codec_error_quark() typedef enum { // Part of the public API, so fixing the name is a breaking change. // NOLINTNEXTLINE(readability-identifier-naming) FL_BINARY_MESSENGER_ERROR_ALREADY_RESPONDED, } FlBinaryMessengerError; G_MODULE_EXPORT GQuark fl_binary_messenger_codec_error_quark(void) G_GNUC_CONST; G_MODULE_EXPORT G_DECLARE_INTERFACE(FlBinaryMessenger, fl_binary_messenger, FL, BINARY_MESSENGER, GObject) G_MODULE_EXPORT G_DECLARE_DERIVABLE_TYPE(FlBinaryMessengerResponseHandle, fl_binary_messenger_response_handle, FL, BINARY_MESSENGER_RESPONSE_HANDLE, GObject) /** * FlBinaryMessengerMessageHandler: * @messenger: an #FlBinaryMessenger. * @channel: channel message received on. * @message: message content received from Dart. * @response_handle: a handle to respond to the message with. * @user_data: (closure): data provided when registering this handler. * * Function called when platform messages are received. Call * fl_binary_messenger_send_response() to respond to this message. If the * response is not occurring in this callback take a reference to * @response_handle and release that once it has been responded to. Failing to * respond before the last reference to @response_handle is dropped is a * programming error. */ typedef void (*FlBinaryMessengerMessageHandler)( FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, FlBinaryMessengerResponseHandle* response_handle, gpointer user_data); struct _FlBinaryMessengerInterface { GTypeInterface parent_iface; void (*set_message_handler_on_channel)( FlBinaryMessenger* messenger, const gchar* channel, FlBinaryMessengerMessageHandler handler, gpointer user_data, GDestroyNotify destroy_notify); gboolean (*send_response)(FlBinaryMessenger* messenger, FlBinaryMessengerResponseHandle* response_handle, GBytes* response, GError** error); void (*send_on_channel)(FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data); GBytes* (*send_on_channel_finish)(FlBinaryMessenger* messenger, GAsyncResult* result, GError** error); void (*resize_channel)(FlBinaryMessenger* messenger, const gchar* channel, int64_t new_size); void (*set_warns_on_channel_overflow)(FlBinaryMessenger* messenger, const gchar* channel, bool warns); }; struct _FlBinaryMessengerResponseHandleClass { GObjectClass parent_class; }; /** * FlBinaryMessenger: * * #FlBinaryMessenger is an object that allows sending and receiving of platform * messages with an #FlEngine. */ /** * FlBinaryMessengerResponseHandle: * * #FlBinaryMessengerResponseHandle is an object used to send responses with. */ /** * fl_binary_messenger_set_platform_message_handler: * @binary_messenger: an #FlBinaryMessenger. * @channel: channel to listen on. * @handler: (allow-none): function to call when a message is received on this * channel or %NULL to disable a handler * @user_data: (closure): user data to pass to @handler. * @destroy_notify: (allow-none): a function which gets called to free * @user_data, or %NULL. * * Sets the function called when a platform message is received on the given * channel. See #FlBinaryMessengerMessageHandler for details on how to respond * to messages. * * The handler is removed if the channel is closed or is replaced by another * handler, set @destroy_notify if you want to detect this. */ void fl_binary_messenger_set_message_handler_on_channel( FlBinaryMessenger* messenger, const gchar* channel, FlBinaryMessengerMessageHandler handler, gpointer user_data, GDestroyNotify destroy_notify); /** * fl_binary_messenger_send_response: * @binary_messenger: an #FlBinaryMessenger. * @response_handle: handle that was provided in a * #FlBinaryMessengerMessageHandler. * @response: (allow-none): response to send or %NULL for an empty response. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. * * Responds to a platform message. This function is thread-safe. * * Returns: %TRUE on success. */ gboolean fl_binary_messenger_send_response( FlBinaryMessenger* messenger, FlBinaryMessengerResponseHandle* response_handle, GBytes* response, GError** error); /** * fl_binary_messenger_send_on_channel: * @binary_messenger: an #FlBinaryMessenger. * @channel: channel to send to. * @message: (allow-none): message buffer to send or %NULL for an empty message. * @cancellable: (allow-none): a #GCancellable or %NULL. * @callback: (scope async): a #GAsyncReadyCallback to call when the request is * satisfied. * @user_data: (closure): user data to pass to @callback. * * Asynchronously sends a platform message. */ void fl_binary_messenger_send_on_channel(FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data); /** * fl_binary_messenger_send_on_channel_finish: * @messenger: an #FlBinaryMessenger. * @result: a #GAsyncResult. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. * * Completes request started with fl_binary_messenger_send_on_channel(). * * Returns: (transfer full): message response on success or %NULL on error. */ GBytes* fl_binary_messenger_send_on_channel_finish(FlBinaryMessenger* messenger, GAsyncResult* result, GError** error); /** * fl_binary_messenger_resize_channel: * @binary_messenger: an #FlBinaryMessenger. * @channel: channel to be resize. * @new_size: the new size for the channel buffer. * * Sends a message to the control channel asking to resize a channel buffer. */ void fl_binary_messenger_resize_channel(FlBinaryMessenger* messenger, const gchar* channel, int64_t new_size); /** * fl_binary_messenger_set_warns_on_channel_overflow: * @messenger: an #FlBinaryMessenger. * @channel: channel to be allowed to overflow silently. * @warns: when false, the channel is expected to overflow and warning messages * will not be shown. * * Sends a message to the control channel asking to allow or disallow a channel * to overflow silently. */ void fl_binary_messenger_set_warns_on_channel_overflow( FlBinaryMessenger* messenger, const gchar* channel, bool warns); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_MESSENGER_H_
engine/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h", "repo_id": "engine", "token_count": 3339 }
400
// 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 FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STRING_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STRING_CODEC_H_ #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif #include <gmodule.h> #include "fl_message_codec.h" G_BEGIN_DECLS G_MODULE_EXPORT G_DECLARE_FINAL_TYPE(FlStringCodec, fl_string_codec, FL, STRING_CODEC, FlMessageCodec) /** * FlStringCodec: * * #FlStringCodec is an #FlMessageCodec that implements the Flutter string * message encoding. This only encodes and decodes #FlValue of type * #FL_VALUE_TYPE_STRING, other types #FlValues will generate an error during * encoding. * * #FlStringCodec matches the StringCodec class in the Flutter services library. */ /** * fl_string_codec_new: * * Creates an #FlStringCodec. * * Returns: a new #FlStringCodec. */ FlStringCodec* fl_string_codec_new(); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STRING_CODEC_H_
engine/shell/platform/linux/public/flutter_linux/fl_string_codec.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_string_codec.h", "repo_id": "engine", "token_count": 551 }
401
// 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 FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_BINARY_MESSENGER_RESPONSE_HANDLE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_BINARY_MESSENGER_RESPONSE_HANDLE_H_ #include "flutter/shell/platform/linux/fl_binary_messenger_private.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlMockBinaryMessengerResponseHandle, fl_mock_binary_messenger_response_handle, FL, MOCK_BINARY_MESSENGER_RESPONSE_HANDLE, FlBinaryMessengerResponseHandle) FlMockBinaryMessengerResponseHandle* fl_mock_binary_messenger_response_handle_new(); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_BINARY_MESSENGER_RESPONSE_HANDLE_H_
engine/shell/platform/linux/testing/mock_binary_messenger_response_handle.h/0
{ "file_path": "engine/shell/platform/linux/testing/mock_binary_messenger_response_handle.h", "repo_id": "engine", "token_count": 402 }
402
// 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 FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXT_INPUT_VIEW_DELEGATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXT_INPUT_VIEW_DELEGATE_H_ #include <unordered_map> #include "flutter/shell/platform/linux/fl_text_input_view_delegate.h" #include "gmock/gmock.h" namespace flutter { namespace testing { // Mock for FlTextInputVuewDelegate. class MockTextInputViewDelegate { public: MockTextInputViewDelegate(); ~MockTextInputViewDelegate(); // NOLINTNEXTLINE(google-explicit-constructor) operator FlTextInputViewDelegate*(); MOCK_METHOD(void, fl_text_input_view_delegate_translate_coordinates, (FlTextInputViewDelegate * delegate, gint view_x, gint view_y, gint* window_x, gint* window_y)); private: FlTextInputViewDelegate* instance_ = nullptr; }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXT_INPUT_VIEW_DELEGATE_H_
engine/shell/platform/linux/testing/mock_text_input_view_delegate.h/0
{ "file_path": "engine/shell/platform/linux/testing/mock_text_input_view_delegate.h", "repo_id": "engine", "token_count": 482 }
403
// 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 <memory> #include <string> #include "flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view.h" #include "flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h" #include "gtest/gtest.h" namespace flutter { namespace { // Stub implementation to validate calls to the API. class TestWindowsApi : public testing::StubFlutterWindowsApi { HWND ViewGetHWND() override { return reinterpret_cast<HWND>(7); } IDXGIAdapter* ViewGetGraphicsAdapter() override { return reinterpret_cast<IDXGIAdapter*>(8); } }; } // namespace TEST(FlutterViewTest, HwndAccessPassesThrough) { testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestWindowsApi>()); auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub()); FlutterView view(reinterpret_cast<FlutterDesktopViewRef>(2)); EXPECT_EQ(view.GetNativeWindow(), reinterpret_cast<HWND>(7)); } TEST(FlutterViewTest, GraphicsAdapterAccessPassesThrough) { testing::ScopedStubFlutterWindowsApi scoped_api_stub( std::make_unique<TestWindowsApi>()); auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub()); FlutterView view(reinterpret_cast<FlutterDesktopViewRef>(2)); IDXGIAdapter* adapter = view.GetGraphicsAdapter(); EXPECT_EQ(adapter, reinterpret_cast<IDXGIAdapter*>(8)); } } // namespace flutter
engine/shell/platform/windows/client_wrapper/flutter_view_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/client_wrapper/flutter_view_unittests.cc", "repo_id": "engine", "token_count": 524 }
404
// 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 "flutter/shell/platform/windows/cursor_handler.h" #include <windows.h> #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" static constexpr char kChannelName[] = "flutter/mousecursor"; static constexpr char kActivateSystemCursorMethod[] = "activateSystemCursor"; static constexpr char kKindKey[] = "kind"; // This method allows creating a custom cursor with rawBGRA buffer, returns a // string to identify the cursor. static constexpr char kCreateCustomCursorMethod[] = "createCustomCursor/windows"; // A string, the custom cursor's name. static constexpr char kCustomCursorNameKey[] = "name"; // A list of bytes, the custom cursor's rawBGRA buffer. static constexpr char kCustomCursorBufferKey[] = "buffer"; // A double, the x coordinate of the custom cursor's hotspot, starting from // left. static constexpr char kCustomCursorHotXKey[] = "hotX"; // A double, the y coordinate of the custom cursor's hotspot, starting from top. static constexpr char kCustomCursorHotYKey[] = "hotY"; // An int value for the width of the custom cursor. static constexpr char kCustomCursorWidthKey[] = "width"; // An int value for the height of the custom cursor. static constexpr char kCustomCursorHeightKey[] = "height"; // This method also has an argument `kCustomCursorNameKey` for the name // of the cursor to activate. static constexpr char kSetCustomCursorMethod[] = "setCustomCursor/windows"; // This method also has an argument `kCustomCursorNameKey` for the name // of the cursor to delete. static constexpr char kDeleteCustomCursorMethod[] = "deleteCustomCursor/windows"; // Error codes used for responses. static constexpr char kCursorError[] = "Cursor error"; namespace flutter { CursorHandler::CursorHandler(BinaryMessenger* messenger, FlutterWindowsEngine* engine) : channel_(std::make_unique<MethodChannel<EncodableValue>>( messenger, kChannelName, &StandardMethodCodec::GetInstance())), engine_(engine) { channel_->SetMethodCallHandler( [this](const MethodCall<EncodableValue>& call, std::unique_ptr<MethodResult<EncodableValue>> result) { HandleMethodCall(call, std::move(result)); }); } void CursorHandler::HandleMethodCall( const MethodCall<EncodableValue>& method_call, std::unique_ptr<MethodResult<EncodableValue>> result) { const std::string& method = method_call.method_name(); if (method.compare(kActivateSystemCursorMethod) == 0) { const auto& arguments = std::get<EncodableMap>(*method_call.arguments()); auto kind_iter = arguments.find(EncodableValue(std::string(kKindKey))); if (kind_iter == arguments.end()) { result->Error("Argument error", "Missing argument while trying to activate system cursor"); return; } const auto& kind = std::get<std::string>(kind_iter->second); // TODO(loicsharma): Remove implicit view assumption. // https://github.com/flutter/flutter/issues/142845 FlutterWindowsView* view = engine_->view(kImplicitViewId); if (view == nullptr) { result->Error(kCursorError, "Cursor is not available in Windows headless mode"); return; } view->UpdateFlutterCursor(kind); result->Success(); } else if (method.compare(kCreateCustomCursorMethod) == 0) { const auto& arguments = std::get<EncodableMap>(*method_call.arguments()); auto name_iter = arguments.find(EncodableValue(std::string(kCustomCursorNameKey))); if (name_iter == arguments.end()) { result->Error( "Argument error", "Missing argument name while trying to customize system cursor"); return; } auto name = std::get<std::string>(name_iter->second); auto buffer_iter = arguments.find(EncodableValue(std::string(kCustomCursorBufferKey))); if (buffer_iter == arguments.end()) { result->Error( "Argument error", "Missing argument buffer while trying to customize system cursor"); return; } auto buffer = std::get<std::vector<uint8_t>>(buffer_iter->second); auto width_iter = arguments.find(EncodableValue(std::string(kCustomCursorWidthKey))); if (width_iter == arguments.end()) { result->Error( "Argument error", "Missing argument width while trying to customize system cursor"); return; } auto width = std::get<int>(width_iter->second); auto height_iter = arguments.find(EncodableValue(std::string(kCustomCursorHeightKey))); if (height_iter == arguments.end()) { result->Error( "Argument error", "Missing argument height while trying to customize system cursor"); return; } auto height = std::get<int>(height_iter->second); auto hot_x_iter = arguments.find(EncodableValue(std::string(kCustomCursorHotXKey))); if (hot_x_iter == arguments.end()) { result->Error( "Argument error", "Missing argument hotX while trying to customize system cursor"); return; } auto hot_x = std::get<double>(hot_x_iter->second); auto hot_y_iter = arguments.find(EncodableValue(std::string(kCustomCursorHotYKey))); if (hot_y_iter == arguments.end()) { result->Error( "Argument error", "Missing argument hotY while trying to customize system cursor"); return; } auto hot_y = std::get<double>(hot_y_iter->second); HCURSOR cursor = GetCursorFromBuffer(buffer, hot_x, hot_y, width, height); if (cursor == nullptr) { result->Error("Argument error", "Argument must contains a valid rawBGRA bitmap"); return; } // Push the cursor into the cache map. custom_cursors_.emplace(name, std::move(cursor)); result->Success(flutter::EncodableValue(std::move(name))); } else if (method.compare(kSetCustomCursorMethod) == 0) { const auto& arguments = std::get<EncodableMap>(*method_call.arguments()); auto name_iter = arguments.find(EncodableValue(std::string(kCustomCursorNameKey))); if (name_iter == arguments.end()) { result->Error("Argument error", "Missing argument key while trying to set a custom cursor"); return; } auto name = std::get<std::string>(name_iter->second); if (custom_cursors_.find(name) == custom_cursors_.end()) { result->Error( "Argument error", "The custom cursor identified by the argument key cannot be found"); return; } HCURSOR cursor = custom_cursors_[name]; // TODO(loicsharma): Remove implicit view assumption. // https://github.com/flutter/flutter/issues/142845 FlutterWindowsView* view = engine_->view(kImplicitViewId); if (view == nullptr) { result->Error(kCursorError, "Cursor is not available in Windows headless mode"); return; } view->SetFlutterCursor(cursor); result->Success(); } else if (method.compare(kDeleteCustomCursorMethod) == 0) { const auto& arguments = std::get<EncodableMap>(*method_call.arguments()); auto name_iter = arguments.find(EncodableValue(std::string(kCustomCursorNameKey))); if (name_iter == arguments.end()) { result->Error( "Argument error", "Missing argument key while trying to delete a custom cursor"); return; } auto name = std::get<std::string>(name_iter->second); auto it = custom_cursors_.find(name); // If the specified cursor name is not found, the deletion is a noop and // returns success. if (it != custom_cursors_.end()) { DeleteObject(it->second); custom_cursors_.erase(it); } result->Success(); } else { result->NotImplemented(); } } HCURSOR GetCursorFromBuffer(const std::vector<uint8_t>& buffer, double hot_x, double hot_y, int width, int height) { HCURSOR cursor = nullptr; HDC display_dc = GetDC(NULL); // Flutter should returns rawBGRA, which has 8bits * 4channels. BITMAPINFO bmi; memset(&bmi, 0, sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = -height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = width * height * 4; // Create the pixmap DIB section uint8_t* pixels = 0; HBITMAP bitmap = CreateDIBSection(display_dc, &bmi, DIB_RGB_COLORS, (void**)&pixels, 0, 0); ReleaseDC(0, display_dc); if (!bitmap || !pixels) { return nullptr; } int bytes_per_line = width * 4; for (int y = 0; y < height; ++y) { memcpy(pixels + y * bytes_per_line, &buffer[bytes_per_line * y], bytes_per_line); } HBITMAP mask; GetMaskBitmaps(bitmap, mask); ICONINFO icon_info; icon_info.fIcon = 0; icon_info.xHotspot = hot_x; icon_info.yHotspot = hot_y; icon_info.hbmMask = mask; icon_info.hbmColor = bitmap; cursor = CreateIconIndirect(&icon_info); DeleteObject(mask); DeleteObject(bitmap); return cursor; } void GetMaskBitmaps(HBITMAP bitmap, HBITMAP& mask_bitmap) { HDC h_dc = ::GetDC(NULL); HDC h_main_dc = ::CreateCompatibleDC(h_dc); HDC h_and_mask_dc = ::CreateCompatibleDC(h_dc); // Get the dimensions of the source bitmap BITMAP bm; ::GetObject(bitmap, sizeof(BITMAP), &bm); mask_bitmap = ::CreateCompatibleBitmap(h_dc, bm.bmWidth, bm.bmHeight); // Select the bitmaps to DC HBITMAP h_old_main_bitmap = (HBITMAP)::SelectObject(h_main_dc, bitmap); HBITMAP h_old_and_mask_bitmap = (HBITMAP)::SelectObject(h_and_mask_dc, mask_bitmap); // Scan each pixel of the souce bitmap and create the masks COLORREF main_bit_pixel; for (int x = 0; x < bm.bmWidth; ++x) { for (int y = 0; y < bm.bmHeight; ++y) { main_bit_pixel = ::GetPixel(h_main_dc, x, y); if (main_bit_pixel == RGB(0, 0, 0)) { ::SetPixel(h_and_mask_dc, x, y, RGB(255, 255, 255)); } else { ::SetPixel(h_and_mask_dc, x, y, RGB(0, 0, 0)); } } } ::SelectObject(h_main_dc, h_old_main_bitmap); ::SelectObject(h_and_mask_dc, h_old_and_mask_bitmap); ::DeleteDC(h_and_mask_dc); ::DeleteDC(h_main_dc); ::ReleaseDC(NULL, h_dc); } } // namespace flutter
engine/shell/platform/windows/cursor_handler.cc/0
{ "file_path": "engine/shell/platform/windows/cursor_handler.cc", "repo_id": "engine", "token_count": 4152 }
405
// 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 FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_PROC_TABLE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_PROC_TABLE_H_ #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <functional> #include <memory> #include "flutter/fml/macros.h" namespace flutter { namespace egl { // Lookup table for GLES functions. class ProcTable { public: static std::shared_ptr<ProcTable> Create(); virtual ~ProcTable(); virtual void GenTextures(GLsizei n, GLuint* textures) const; virtual void DeleteTextures(GLsizei n, const GLuint* textures) const; virtual void BindTexture(GLenum target, GLuint texture) const; virtual void TexParameteri(GLenum target, GLenum pname, GLint param) const; virtual void TexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* data) const; protected: ProcTable(); private: using GenTexturesProc = void(__stdcall*)(GLsizei n, GLuint* textures); using DeleteTexturesProc = void(__stdcall*)(GLsizei n, const GLuint* textures); using BindTextureProc = void(__stdcall*)(GLenum target, GLuint texture); using TexParameteriProc = void(__stdcall*)(GLenum target, GLenum pname, GLint param); using TexImage2DProc = void(__stdcall*)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* data); GenTexturesProc gen_textures_; DeleteTexturesProc delete_textures_; BindTextureProc bind_texture_; TexParameteriProc tex_parameteri_; TexImage2DProc tex_image_2d_; FML_DISALLOW_COPY_AND_ASSIGN(ProcTable); }; } // namespace egl } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_PROC_TABLE_H_
engine/shell/platform/windows/egl/proc_table.h/0
{ "file_path": "engine/shell/platform/windows/egl/proc_table.h", "repo_id": "engine", "token_count": 1319 }
406
// 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 FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_PLATFORM_NODE_DELEGATE_WINDOWS_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_PLATFORM_NODE_DELEGATE_WINDOWS_H_ #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/flutter_platform_node_delegate.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" #include "flutter/third_party/accessibility/ax/platform/ax_platform_node.h" #include "flutter/third_party/accessibility/ax/platform/ax_unique_id.h" namespace flutter { // The Windows implementation of FlutterPlatformNodeDelegate. // // This class implements a wrapper around the Windows accessibility objects // that compose the accessibility tree. class FlutterPlatformNodeDelegateWindows : public FlutterPlatformNodeDelegate { public: FlutterPlatformNodeDelegateWindows(std::weak_ptr<AccessibilityBridge> bridge, FlutterWindowsView* view); virtual ~FlutterPlatformNodeDelegateWindows(); // |ui::AXPlatformNodeDelegate| void Init(std::weak_ptr<OwnerBridge> bridge, ui::AXNode* node) override; // |ui::AXPlatformNodeDelegate| gfx::NativeViewAccessible GetNativeViewAccessible() override; // |ui::AXPlatformNodeDelegate| gfx::NativeViewAccessible HitTestSync( int screen_physical_pixel_x, int screen_physical_pixel_y) const override; // |FlutterPlatformNodeDelegate| gfx::Rect GetBoundsRect( const ui::AXCoordinateSystem coordinate_system, const ui::AXClippingBehavior clipping_behavior, ui::AXOffscreenResult* offscreen_result) const override; // Dispatches a Windows accessibility event of the specified type, generated // by the accessibility node associated with this object. This is a // convenience wrapper around |NotifyWinEvent|. virtual void DispatchWinAccessibilityEvent(ax::mojom::Event event_type); // Sets the accessibility focus to the accessibility node associated with // this object. void SetFocus(); // | AXPlatformNodeDelegate | gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() override; // | FlutterPlatformNodeDelegate | ui::AXPlatformNode* GetPlatformNode() const override; private: ui::AXPlatformNode* ax_platform_node_; std::weak_ptr<AccessibilityBridge> bridge_; FlutterWindowsView* view_; FML_DISALLOW_COPY_AND_ASSIGN(FlutterPlatformNodeDelegateWindows); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_PLATFORM_NODE_DELEGATE_WINDOWS_H_
engine/shell/platform/windows/flutter_platform_node_delegate_windows.h/0
{ "file_path": "engine/shell/platform/windows/flutter_platform_node_delegate_windows.h", "repo_id": "engine", "token_count": 842 }
407
// 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 "flutter/shell/platform/windows/flutter_windows_view.h" #include <chrono> #include "flutter/common/constants.h" #include "flutter/fml/platform/win/wstring_conversion.h" #include "flutter/shell/platform/common/accessibility_bridge.h" #include "flutter/shell/platform/windows/keyboard_key_channel_handler.h" #include "flutter/shell/platform/windows/text_input_plugin.h" #include "flutter/third_party/accessibility/ax/platform/ax_platform_node_win.h" namespace flutter { namespace { // The maximum duration to block the platform thread for while waiting // for a window resize operation to complete. constexpr std::chrono::milliseconds kWindowResizeTimeout{100}; /// Returns true if the surface will be updated as part of the resize process. /// /// This is called on window resize to determine if the platform thread needs /// to be blocked until the frame with the right size has been rendered. It /// should be kept in-sync with how the engine deals with a new surface request /// as seen in `CreateOrUpdateSurface` in `GPUSurfaceGL`. bool SurfaceWillUpdate(size_t cur_width, size_t cur_height, size_t target_width, size_t target_height) { // TODO (https://github.com/flutter/flutter/issues/65061) : Avoid special // handling for zero dimensions. bool non_zero_target_dims = target_height > 0 && target_width > 0; bool not_same_size = (cur_height != target_height) || (cur_width != target_width); return non_zero_target_dims && not_same_size; } /// Update the surface's swap interval to block until the v-blank iff /// the system compositor is disabled. void UpdateVsync(const FlutterWindowsEngine& engine, egl::WindowSurface* surface, bool needs_vsync) { egl::Manager* egl_manager = engine.egl_manager(); if (!egl_manager) { return; } auto update_vsync = [egl_manager, surface, needs_vsync]() { if (!surface || !surface->IsValid()) { return; } if (!surface->MakeCurrent()) { FML_LOG(ERROR) << "Unable to make the render surface current to update " "the swap interval"; return; } if (!surface->SetVSyncEnabled(needs_vsync)) { FML_LOG(ERROR) << "Unable to update the render surface's swap interval"; } if (!egl_manager->render_context()->ClearCurrent()) { FML_LOG(ERROR) << "Unable to clear current surface after updating " "the swap interval"; } }; // Updating the vsync makes the EGL context and render surface current. // If the engine is running, the render surface should only be made current on // the raster thread. If the engine is initializing, the raster thread doesn't // exist yet and the render surface can be made current on the platform // thread. if (engine.running()) { engine.PostRasterThreadTask(update_vsync); } else { update_vsync(); } } } // namespace FlutterWindowsView::FlutterWindowsView( FlutterViewId view_id, FlutterWindowsEngine* engine, std::unique_ptr<WindowBindingHandler> window_binding, std::shared_ptr<WindowsProcTable> windows_proc_table) : view_id_(view_id), engine_(engine), windows_proc_table_(std::move(windows_proc_table)) { if (windows_proc_table_ == nullptr) { windows_proc_table_ = std::make_shared<WindowsProcTable>(); } // Take the binding handler, and give it a pointer back to self. binding_handler_ = std::move(window_binding); binding_handler_->SetView(this); } FlutterWindowsView::~FlutterWindowsView() { // The view owns the child window. // Notify the engine the view's child window will no longer be visible. engine_->OnWindowStateEvent(GetWindowHandle(), WindowStateEvent::kHide); // The engine renders into the view's surface. The engine must be // shutdown before the view's resources can be destroyed. engine_->Stop(); DestroyRenderSurface(); } bool FlutterWindowsView::OnEmptyFrameGenerated() { // Called on the raster thread. std::unique_lock<std::mutex> lock(resize_mutex_); if (surface_ == nullptr || !surface_->IsValid()) { return false; } if (resize_status_ != ResizeState::kResizeStarted) { return true; } if (!ResizeRenderSurface(resize_target_height_, resize_target_width_)) { return false; } // Platform thread is blocked for the entire duration until the // resize_status_ is set to kDone by |OnFramePresented|. resize_status_ = ResizeState::kFrameGenerated; return true; } bool FlutterWindowsView::OnFrameGenerated(size_t width, size_t height) { // Called on the raster thread. std::unique_lock<std::mutex> lock(resize_mutex_); if (surface_ == nullptr || !surface_->IsValid()) { return false; } if (resize_status_ != ResizeState::kResizeStarted) { return true; } if (resize_target_width_ != width || resize_target_height_ != height) { return false; } if (!ResizeRenderSurface(resize_target_width_, resize_target_height_)) { return false; } // Platform thread is blocked for the entire duration until the // resize_status_ is set to kDone by |OnFramePresented|. resize_status_ = ResizeState::kFrameGenerated; return true; } void FlutterWindowsView::UpdateFlutterCursor(const std::string& cursor_name) { binding_handler_->UpdateFlutterCursor(cursor_name); } void FlutterWindowsView::SetFlutterCursor(HCURSOR cursor) { binding_handler_->SetFlutterCursor(cursor); } void FlutterWindowsView::ForceRedraw() { if (resize_status_ == ResizeState::kDone) { // Request new frame. engine_->ScheduleFrame(); } } bool FlutterWindowsView::OnWindowSizeChanged(size_t width, size_t height) { // Called on the platform thread. std::unique_lock<std::mutex> lock(resize_mutex_); if (!engine_->egl_manager()) { SendWindowMetrics(width, height, binding_handler_->GetDpiScale()); return true; } if (!surface_ || !surface_->IsValid()) { SendWindowMetrics(width, height, binding_handler_->GetDpiScale()); return true; } // We're using OpenGL rendering. Resizing the surface must happen on the // raster thread. bool surface_will_update = SurfaceWillUpdate(surface_->width(), surface_->height(), width, height); if (!surface_will_update) { SendWindowMetrics(width, height, binding_handler_->GetDpiScale()); return true; } resize_status_ = ResizeState::kResizeStarted; resize_target_width_ = width; resize_target_height_ = height; SendWindowMetrics(width, height, binding_handler_->GetDpiScale()); // Block the platform thread until a frame is presented with the target // size. See |OnFrameGenerated|, |OnEmptyFrameGenerated|, and // |OnFramePresented|. return resize_cv_.wait_for(lock, kWindowResizeTimeout, [&resize_status = resize_status_] { return resize_status == ResizeState::kDone; }); } void FlutterWindowsView::OnWindowRepaint() { ForceRedraw(); } void FlutterWindowsView::OnPointerMove(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id, int modifiers_state) { engine_->keyboard_key_handler()->SyncModifiersIfNeeded(modifiers_state); SendPointerMove(x, y, GetOrCreatePointerState(device_kind, device_id)); } void FlutterWindowsView::OnPointerDown( double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id, FlutterPointerMouseButtons flutter_button) { if (flutter_button != 0) { auto state = GetOrCreatePointerState(device_kind, device_id); state->buttons |= flutter_button; SendPointerDown(x, y, state); } } void FlutterWindowsView::OnPointerUp( double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id, FlutterPointerMouseButtons flutter_button) { if (flutter_button != 0) { auto state = GetOrCreatePointerState(device_kind, device_id); state->buttons &= ~flutter_button; SendPointerUp(x, y, state); } } void FlutterWindowsView::OnPointerLeave(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id) { SendPointerLeave(x, y, GetOrCreatePointerState(device_kind, device_id)); } void FlutterWindowsView::OnPointerPanZoomStart(int32_t device_id) { PointerLocation point = binding_handler_->GetPrimaryPointerLocation(); SendPointerPanZoomStart(device_id, point.x, point.y); } void FlutterWindowsView::OnPointerPanZoomUpdate(int32_t device_id, double pan_x, double pan_y, double scale, double rotation) { SendPointerPanZoomUpdate(device_id, pan_x, pan_y, scale, rotation); } void FlutterWindowsView::OnPointerPanZoomEnd(int32_t device_id) { SendPointerPanZoomEnd(device_id); } void FlutterWindowsView::OnText(const std::u16string& text) { SendText(text); } void FlutterWindowsView::OnKey(int key, int scancode, int action, char32_t character, bool extended, bool was_down, KeyEventCallback callback) { SendKey(key, scancode, action, character, extended, was_down, callback); } void FlutterWindowsView::OnComposeBegin() { SendComposeBegin(); } void FlutterWindowsView::OnComposeCommit() { SendComposeCommit(); } void FlutterWindowsView::OnComposeEnd() { SendComposeEnd(); } void FlutterWindowsView::OnComposeChange(const std::u16string& text, int cursor_pos) { SendComposeChange(text, cursor_pos); } void FlutterWindowsView::OnScroll(double x, double y, double delta_x, double delta_y, int scroll_offset_multiplier, FlutterPointerDeviceKind device_kind, int32_t device_id) { SendScroll(x, y, delta_x, delta_y, scroll_offset_multiplier, device_kind, device_id); } void FlutterWindowsView::OnScrollInertiaCancel(int32_t device_id) { PointerLocation point = binding_handler_->GetPrimaryPointerLocation(); SendScrollInertiaCancel(device_id, point.x, point.y); } void FlutterWindowsView::OnUpdateSemanticsEnabled(bool enabled) { engine_->UpdateSemanticsEnabled(enabled); } gfx::NativeViewAccessible FlutterWindowsView::GetNativeViewAccessible() { if (!accessibility_bridge_) { return nullptr; } return accessibility_bridge_->GetChildOfAXFragmentRoot(); } void FlutterWindowsView::OnCursorRectUpdated(const Rect& rect) { binding_handler_->OnCursorRectUpdated(rect); } void FlutterWindowsView::OnResetImeComposing() { binding_handler_->OnResetImeComposing(); } // Sends new size information to FlutterEngine. void FlutterWindowsView::SendWindowMetrics(size_t width, size_t height, double dpiScale) const { FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = width; event.height = height; event.pixel_ratio = dpiScale; event.view_id = view_id_; engine_->SendWindowMetricsEvent(event); } void FlutterWindowsView::SendInitialBounds() { PhysicalWindowBounds bounds = binding_handler_->GetPhysicalWindowBounds(); SendWindowMetrics(bounds.width, bounds.height, binding_handler_->GetDpiScale()); } FlutterWindowsView::PointerState* FlutterWindowsView::GetOrCreatePointerState( FlutterPointerDeviceKind device_kind, int32_t device_id) { // Create a virtual pointer ID that is unique across all device types // to prevent pointers from clashing in the engine's converter // (lib/ui/window/pointer_data_packet_converter.cc) int32_t pointer_id = (static_cast<int32_t>(device_kind) << 28) | device_id; auto [it, added] = pointer_states_.try_emplace(pointer_id, nullptr); if (added) { auto state = std::make_unique<PointerState>(); state->device_kind = device_kind; state->pointer_id = pointer_id; it->second = std::move(state); } return it->second.get(); } // Set's |event_data|'s phase to either kMove or kHover depending on the current // primary mouse button state. void FlutterWindowsView::SetEventPhaseFromCursorButtonState( FlutterPointerEvent* event_data, const PointerState* state) const { // For details about this logic, see FlutterPointerPhase in the embedder.h // file. if (state->buttons == 0) { event_data->phase = state->flutter_state_is_down ? FlutterPointerPhase::kUp : FlutterPointerPhase::kHover; } else { event_data->phase = state->flutter_state_is_down ? FlutterPointerPhase::kMove : FlutterPointerPhase::kDown; } } void FlutterWindowsView::SendPointerMove(double x, double y, PointerState* state) { FlutterPointerEvent event = {}; event.x = x; event.y = y; SetEventPhaseFromCursorButtonState(&event, state); SendPointerEventWithData(event, state); } void FlutterWindowsView::SendPointerDown(double x, double y, PointerState* state) { FlutterPointerEvent event = {}; event.x = x; event.y = y; SetEventPhaseFromCursorButtonState(&event, state); SendPointerEventWithData(event, state); state->flutter_state_is_down = true; } void FlutterWindowsView::SendPointerUp(double x, double y, PointerState* state) { FlutterPointerEvent event = {}; event.x = x; event.y = y; SetEventPhaseFromCursorButtonState(&event, state); SendPointerEventWithData(event, state); if (event.phase == FlutterPointerPhase::kUp) { state->flutter_state_is_down = false; } } void FlutterWindowsView::SendPointerLeave(double x, double y, PointerState* state) { FlutterPointerEvent event = {}; event.x = x; event.y = y; event.phase = FlutterPointerPhase::kRemove; SendPointerEventWithData(event, state); } void FlutterWindowsView::SendPointerPanZoomStart(int32_t device_id, double x, double y) { auto state = GetOrCreatePointerState(kFlutterPointerDeviceKindTrackpad, device_id); state->pan_zoom_start_x = x; state->pan_zoom_start_y = y; FlutterPointerEvent event = {}; event.x = x; event.y = y; event.phase = FlutterPointerPhase::kPanZoomStart; SendPointerEventWithData(event, state); } void FlutterWindowsView::SendPointerPanZoomUpdate(int32_t device_id, double pan_x, double pan_y, double scale, double rotation) { auto state = GetOrCreatePointerState(kFlutterPointerDeviceKindTrackpad, device_id); FlutterPointerEvent event = {}; event.x = state->pan_zoom_start_x; event.y = state->pan_zoom_start_y; event.pan_x = pan_x; event.pan_y = pan_y; event.scale = scale; event.rotation = rotation; event.phase = FlutterPointerPhase::kPanZoomUpdate; SendPointerEventWithData(event, state); } void FlutterWindowsView::SendPointerPanZoomEnd(int32_t device_id) { auto state = GetOrCreatePointerState(kFlutterPointerDeviceKindTrackpad, device_id); FlutterPointerEvent event = {}; event.x = state->pan_zoom_start_x; event.y = state->pan_zoom_start_y; event.phase = FlutterPointerPhase::kPanZoomEnd; SendPointerEventWithData(event, state); } void FlutterWindowsView::SendText(const std::u16string& text) { engine_->text_input_plugin()->TextHook(text); } void FlutterWindowsView::SendKey(int key, int scancode, int action, char32_t character, bool extended, bool was_down, KeyEventCallback callback) { engine_->keyboard_key_handler()->KeyboardHook( key, scancode, action, character, extended, was_down, [=, callback = std::move(callback)](bool handled) { if (!handled) { engine_->text_input_plugin()->KeyboardHook( key, scancode, action, character, extended, was_down); } callback(handled); }); } void FlutterWindowsView::SendComposeBegin() { engine_->text_input_plugin()->ComposeBeginHook(); } void FlutterWindowsView::SendComposeCommit() { engine_->text_input_plugin()->ComposeCommitHook(); } void FlutterWindowsView::SendComposeEnd() { engine_->text_input_plugin()->ComposeEndHook(); } void FlutterWindowsView::SendComposeChange(const std::u16string& text, int cursor_pos) { engine_->text_input_plugin()->ComposeChangeHook(text, cursor_pos); } void FlutterWindowsView::SendScroll(double x, double y, double delta_x, double delta_y, int scroll_offset_multiplier, FlutterPointerDeviceKind device_kind, int32_t device_id) { auto state = GetOrCreatePointerState(device_kind, device_id); FlutterPointerEvent event = {}; event.x = x; event.y = y; event.signal_kind = FlutterPointerSignalKind::kFlutterPointerSignalKindScroll; event.scroll_delta_x = delta_x * scroll_offset_multiplier; event.scroll_delta_y = delta_y * scroll_offset_multiplier; SetEventPhaseFromCursorButtonState(&event, state); SendPointerEventWithData(event, state); } void FlutterWindowsView::SendScrollInertiaCancel(int32_t device_id, double x, double y) { auto state = GetOrCreatePointerState(kFlutterPointerDeviceKindTrackpad, device_id); FlutterPointerEvent event = {}; event.x = x; event.y = y; event.signal_kind = FlutterPointerSignalKind::kFlutterPointerSignalKindScrollInertiaCancel; SetEventPhaseFromCursorButtonState(&event, state); SendPointerEventWithData(event, state); } void FlutterWindowsView::SendPointerEventWithData( const FlutterPointerEvent& event_data, PointerState* state) { // If sending anything other than an add, and the pointer isn't already added, // synthesize an add to satisfy Flutter's expectations about events. if (!state->flutter_state_is_added && event_data.phase != FlutterPointerPhase::kAdd) { FlutterPointerEvent event = {}; event.phase = FlutterPointerPhase::kAdd; event.x = event_data.x; event.y = event_data.y; event.buttons = 0; SendPointerEventWithData(event, state); } // Don't double-add (e.g., if events are delivered out of order, so an add has // already been synthesized). if (state->flutter_state_is_added && event_data.phase == FlutterPointerPhase::kAdd) { return; } FlutterPointerEvent event = event_data; event.device_kind = state->device_kind; event.device = state->pointer_id; event.buttons = state->buttons; event.view_id = view_id_; // Set metadata that's always the same regardless of the event. event.struct_size = sizeof(event); event.timestamp = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()) .count(); engine_->SendPointerEvent(event); if (event_data.phase == FlutterPointerPhase::kAdd) { state->flutter_state_is_added = true; } else if (event_data.phase == FlutterPointerPhase::kRemove) { auto it = pointer_states_.find(state->pointer_id); if (it != pointer_states_.end()) { pointer_states_.erase(it); } } } void FlutterWindowsView::OnFramePresented() { // Called on the engine's raster thread. std::unique_lock<std::mutex> lock(resize_mutex_); switch (resize_status_) { case ResizeState::kResizeStarted: // The caller must first call |OnFrameGenerated| or // |OnEmptyFrameGenerated| before calling this method. This // indicates one of the following: // // 1. The caller did not call these methods. // 2. The caller ignored these methods' result. // 3. The platform thread started a resize after the caller called these // methods. We might have presented a frame of the wrong size to the // view. return; case ResizeState::kFrameGenerated: { // A frame was generated for a pending resize. // Unblock the platform thread. resize_status_ = ResizeState::kDone; lock.unlock(); resize_cv_.notify_all(); // Blocking the raster thread until DWM flushes alleviates glitches where // previous size surface is stretched over current size view. windows_proc_table_->DwmFlush(); } case ResizeState::kDone: return; } } bool FlutterWindowsView::ClearSoftwareBitmap() { return binding_handler_->OnBitmapSurfaceCleared(); } bool FlutterWindowsView::PresentSoftwareBitmap(const void* allocation, size_t row_bytes, size_t height) { return binding_handler_->OnBitmapSurfaceUpdated(allocation, row_bytes, height); } FlutterViewId FlutterWindowsView::view_id() const { return view_id_; } void FlutterWindowsView::CreateRenderSurface() { FML_DCHECK(surface_ == nullptr); if (engine_->egl_manager()) { PhysicalWindowBounds bounds = binding_handler_->GetPhysicalWindowBounds(); surface_ = engine_->egl_manager()->CreateWindowSurface( GetWindowHandle(), bounds.width, bounds.height); UpdateVsync(*engine_, surface_.get(), NeedsVsync()); resize_target_width_ = bounds.width; resize_target_height_ = bounds.height; } } bool FlutterWindowsView::ResizeRenderSurface(size_t width, size_t height) { FML_DCHECK(surface_ != nullptr); // No-op if the surface is already the desired size. if (width == surface_->width() && height == surface_->height()) { return true; } auto const existing_vsync = surface_->vsync_enabled(); // TODO: Destroying the surface and re-creating it is expensive. // Ideally this would use ANGLE's automatic surface sizing instead. // See: https://github.com/flutter/flutter/issues/79427 if (!surface_->Destroy()) { FML_LOG(ERROR) << "View resize failed to destroy surface"; return false; } std::unique_ptr<egl::WindowSurface> resized_surface = engine_->egl_manager()->CreateWindowSurface(GetWindowHandle(), width, height); if (!resized_surface) { FML_LOG(ERROR) << "View resize failed to create surface"; return false; } if (!resized_surface->MakeCurrent() || !resized_surface->SetVSyncEnabled(existing_vsync)) { // Surfaces block until the v-blank by default. // Failing to update the vsync might result in unnecessary blocking. // This regresses performance but not correctness. FML_LOG(ERROR) << "View resize failed to set vsync"; } surface_ = std::move(resized_surface); return true; } void FlutterWindowsView::DestroyRenderSurface() { if (surface_) { surface_->Destroy(); } } egl::WindowSurface* FlutterWindowsView::surface() const { return surface_.get(); } void FlutterWindowsView::OnHighContrastChanged() { engine_->UpdateHighContrastMode(); } HWND FlutterWindowsView::GetWindowHandle() const { return binding_handler_->GetWindowHandle(); } FlutterWindowsEngine* FlutterWindowsView::GetEngine() const { return engine_; } void FlutterWindowsView::AnnounceAlert(const std::wstring& text) { auto alert_delegate = binding_handler_->GetAlertDelegate(); if (!alert_delegate) { return; } alert_delegate->SetText(fml::WideStringToUtf16(text)); ui::AXPlatformNodeWin* alert_node = binding_handler_->GetAlert(); NotifyWinEventWrapper(alert_node, ax::mojom::Event::kAlert); } void FlutterWindowsView::NotifyWinEventWrapper(ui::AXPlatformNodeWin* node, ax::mojom::Event event) { if (node) { node->NotifyAccessibilityEvent(event); } } ui::AXFragmentRootDelegateWin* FlutterWindowsView::GetAxFragmentRootDelegate() { return accessibility_bridge_.get(); } ui::AXPlatformNodeWin* FlutterWindowsView::AlertNode() const { return binding_handler_->GetAlert(); } std::shared_ptr<AccessibilityBridgeWindows> FlutterWindowsView::CreateAccessibilityBridge() { return std::make_shared<AccessibilityBridgeWindows>(this); } void FlutterWindowsView::UpdateSemanticsEnabled(bool enabled) { if (semantics_enabled_ != enabled) { semantics_enabled_ = enabled; if (!semantics_enabled_ && accessibility_bridge_) { accessibility_bridge_.reset(); } else if (semantics_enabled_ && !accessibility_bridge_) { accessibility_bridge_ = CreateAccessibilityBridge(); } } } void FlutterWindowsView::OnDwmCompositionChanged() { UpdateVsync(*engine_, surface_.get(), NeedsVsync()); } void FlutterWindowsView::OnWindowStateEvent(HWND hwnd, WindowStateEvent event) { engine_->OnWindowStateEvent(hwnd, event); } bool FlutterWindowsView::NeedsVsync() const { // If the Desktop Window Manager composition is enabled, // the system itself synchronizes with vsync. // See: https://learn.microsoft.com/windows/win32/dwm/composition-ovw return !windows_proc_table_->DwmIsCompositionEnabled(); } } // namespace flutter
engine/shell/platform/windows/flutter_windows_view.cc/0
{ "file_path": "engine/shell/platform/windows/flutter_windows_view.cc", "repo_id": "engine", "token_count": 10831 }
408
// 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 "flutter/fml/logging.h" #include "flutter/shell/platform/common/json_message_codec.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/test_utils/key_codes.g.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" #include "flutter/shell/platform/windows/keyboard_key_channel_handler.h" #include "flutter/shell/platform/windows/keyboard_key_embedder_handler.h" #include "flutter/shell/platform/windows/keyboard_key_handler.h" #include "flutter/shell/platform/windows/keyboard_manager.h" #include "flutter/shell/platform/windows/testing/engine_modifier.h" #include "flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h" #include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h" #include "flutter/shell/platform/windows/testing/test_keyboard.h" #include "flutter/shell/platform/windows/testing/windows_test.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include <functional> #include <list> #include <vector> using testing::_; using testing::Invoke; using testing::Return; using namespace ::flutter::testing::keycodes; namespace flutter { namespace testing { namespace { constexpr SHORT kStateMaskToggled = 0x01; constexpr SHORT kStateMaskPressed = 0x80; constexpr uint64_t kScanCodeBackquote = 0x29; constexpr uint64_t kScanCodeKeyA = 0x1e; constexpr uint64_t kScanCodeKeyB = 0x30; constexpr uint64_t kScanCodeKeyE = 0x12; constexpr uint64_t kScanCodeKeyF = 0x21; constexpr uint64_t kScanCodeKeyO = 0x18; constexpr uint64_t kScanCodeKeyQ = 0x10; constexpr uint64_t kScanCodeKeyW = 0x11; constexpr uint64_t kScanCodeDigit1 = 0x02; constexpr uint64_t kScanCodeDigit2 = 0x03; constexpr uint64_t kScanCodeDigit6 = 0x07; // constexpr uint64_t kScanCodeNumpad1 = 0x4f; // constexpr uint64_t kScanCodeNumLock = 0x45; constexpr uint64_t kScanCodeControl = 0x1d; constexpr uint64_t kScanCodeMetaLeft = 0x5b; constexpr uint64_t kScanCodeMetaRight = 0x5c; constexpr uint64_t kScanCodeAlt = 0x38; constexpr uint64_t kScanCodeShiftLeft = 0x2a; constexpr uint64_t kScanCodeShiftRight = 0x36; constexpr uint64_t kScanCodeBracketLeft = 0x1a; constexpr uint64_t kScanCodeArrowLeft = 0x4b; constexpr uint64_t kScanCodeEnter = 0x1c; constexpr uint64_t kScanCodeBackspace = 0x0e; constexpr uint64_t kVirtualDigit1 = 0x31; constexpr uint64_t kVirtualKeyA = 0x41; constexpr uint64_t kVirtualKeyB = 0x42; constexpr uint64_t kVirtualKeyE = 0x45; constexpr uint64_t kVirtualKeyF = 0x46; constexpr uint64_t kVirtualKeyO = 0x4f; constexpr uint64_t kVirtualKeyQ = 0x51; constexpr uint64_t kVirtualKeyW = 0x57; constexpr bool kSynthesized = true; constexpr bool kNotSynthesized = false; typedef UINT (*MapVirtualKeyLayout)(UINT uCode, UINT uMapType); typedef std::function<UINT(UINT)> MapVirtualKeyToChar; UINT LayoutDefault(UINT uCode, UINT uMapType) { return MapVirtualKey(uCode, uMapType); } UINT LayoutFrench(UINT uCode, UINT uMapType) { switch (uMapType) { case MAPVK_VK_TO_CHAR: switch (uCode) { case 0xDD: return 0x8000005E; default: return MapVirtualKey(uCode, MAPVK_VK_TO_CHAR); } default: return MapVirtualKey(uCode, uMapType); } } class TestKeyboardManager : public KeyboardManager { public: explicit TestKeyboardManager(WindowDelegate* delegate) : KeyboardManager(delegate) {} bool DuringRedispatch() { return during_redispatch_; } protected: void RedispatchEvent(std::unique_ptr<PendingEvent> event) override { FML_DCHECK(!during_redispatch_) << "RedispatchEvent called while already redispatching an event"; during_redispatch_ = true; KeyboardManager::RedispatchEvent(std::move(event)); during_redispatch_ = false; } private: bool during_redispatch_ = false; FML_DISALLOW_COPY_AND_ASSIGN(TestKeyboardManager); }; // Injecting this kind of keyboard change means that a key state (the true // state for a key, typically a modifier) should be changed. struct KeyStateChange { uint32_t key; bool pressed; bool toggled_on; }; // Injecting this kind of keyboard change does not make any changes to the // keyboard system, but indicates that a forged event is expected here, and // that `KeyStateChange`s after this will be applied only after the forged // event. // // See `IsKeyDownAltRight` for explaination for foged events. struct ExpectForgedMessage { explicit ExpectForgedMessage(Win32Message message) : message(message){}; Win32Message message; }; struct KeyboardChange { // The constructors are intentionally for implicit conversion. KeyboardChange(Win32Message message) : type(kMessage) { content.message = message; } KeyboardChange(KeyStateChange change) : type(kKeyStateChange) { content.key_state_change = change; } KeyboardChange(ExpectForgedMessage forged_message) : type(kExpectForgedMessage) { content.expected_forged_message = forged_message.message; } enum Type { kMessage, kKeyStateChange, kExpectForgedMessage, } type; union { Win32Message message; KeyStateChange key_state_change; Win32Message expected_forged_message; } content; }; class TestKeystate { public: void Set(uint32_t virtual_key, bool pressed, bool toggled_on = false) { state_[virtual_key] = (pressed ? kStateMaskPressed : 0) | (toggled_on ? kStateMaskToggled : 0); } SHORT Get(uint32_t virtual_key) { return state_[virtual_key]; } private: std::map<uint32_t, SHORT> state_; }; class MockKeyboardManagerDelegate : public KeyboardManager::WindowDelegate, protected MockMessageQueue { public: MockKeyboardManagerDelegate(WindowBindingHandlerDelegate* view, MapVirtualKeyToChar map_vk_to_char) : view_(view), map_vk_to_char_(std::move(map_vk_to_char)) { keyboard_manager_ = std::make_unique<TestKeyboardManager>(this); } virtual ~MockKeyboardManagerDelegate() {} // |KeyboardManager::WindowDelegate| void OnKey(int key, int scancode, int action, char32_t character, bool extended, bool was_down, KeyEventCallback callback) override { view_->OnKey(key, scancode, action, character, extended, was_down, callback); } // |KeyboardManager::WindowDelegate| void OnText(const std::u16string& text) override { view_->OnText(text); } SHORT GetKeyState(int virtual_key) { return key_state_.Get(virtual_key); } void InjectKeyboardChanges(std::vector<KeyboardChange> changes) { // First queue all messages to enable peeking. for (const KeyboardChange& change : changes) { switch (change.type) { case KeyboardChange::kMessage: PushBack(&change.content.message); break; default: break; } } for (const KeyboardChange& change : changes) { switch (change.type) { case KeyboardChange::kMessage: DispatchFront(); break; case KeyboardChange::kExpectForgedMessage: forged_message_expectations_.push_back(ForgedMessageExpectation{ .message = change.content.expected_forged_message, }); break; case KeyboardChange::kKeyStateChange: { const KeyStateChange& state_change = change.content.key_state_change; if (forged_message_expectations_.empty()) { key_state_.Set(state_change.key, state_change.pressed, state_change.toggled_on); } else { forged_message_expectations_.back() .state_changes_afterwards.push_back(state_change); } break; } default: FML_LOG(FATAL) << "Unhandled KeyboardChange type " << change.type; } } } std::list<Win32Message>& RedispatchedMessages() { return redispatched_messages_; } protected: BOOL Win32PeekMessage(LPMSG lpMsg, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg) override { return MockMessageQueue::Win32PeekMessage(lpMsg, wMsgFilterMin, wMsgFilterMax, wRemoveMsg); } uint32_t Win32MapVkToChar(uint32_t virtual_key) override { return map_vk_to_char_(virtual_key); } // This method is called for each message injected by test cases with // `tester.InjectMessages`. LRESULT Win32SendMessage(UINT const message, WPARAM const wparam, LPARAM const lparam) override { return keyboard_manager_->HandleMessage(message, wparam, lparam) ? 0 : kWmResultDefault; } // This method is called when the keyboard manager redispatches messages // or forges messages (such as CtrlLeft up right before AltGr up). UINT Win32DispatchMessage(UINT Msg, WPARAM wParam, LPARAM lParam) override { bool handled = keyboard_manager_->HandleMessage(Msg, wParam, lParam); if (keyboard_manager_->DuringRedispatch()) { redispatched_messages_.push_back(Win32Message{ .message = Msg, .wParam = wParam, .lParam = lParam, }); EXPECT_FALSE(handled); } else { EXPECT_FALSE(forged_message_expectations_.empty()); ForgedMessageExpectation expectation = forged_message_expectations_.front(); forged_message_expectations_.pop_front(); EXPECT_EQ(expectation.message.message, Msg); EXPECT_EQ(expectation.message.wParam, wParam); EXPECT_EQ(expectation.message.lParam, lParam); if (expectation.message.expected_result != kWmResultDontCheck) { EXPECT_EQ(expectation.message.expected_result, handled ? kWmResultZero : kWmResultDefault); } for (const KeyStateChange& change : expectation.state_changes_afterwards) { key_state_.Set(change.key, change.pressed, change.toggled_on); } } return 0; } private: struct ForgedMessageExpectation { Win32Message message; std::list<KeyStateChange> state_changes_afterwards; }; WindowBindingHandlerDelegate* view_; std::unique_ptr<TestKeyboardManager> keyboard_manager_; std::list<ForgedMessageExpectation> forged_message_expectations_; MapVirtualKeyToChar map_vk_to_char_; TestKeystate key_state_; std::list<Win32Message> redispatched_messages_; FML_DISALLOW_COPY_AND_ASSIGN(MockKeyboardManagerDelegate); }; typedef struct { enum { kKeyCallOnKey, kKeyCallOnText, kKeyCallTextMethodCall, } type; // Only one of the following fields should be assigned. FlutterKeyEvent key_event; // For kKeyCallOnKey std::u16string text; // For kKeyCallOnText std::string text_method_call; // For kKeyCallTextMethodCall } KeyCall; // A FlutterWindowsView that spies on text. class TestFlutterWindowsView : public FlutterWindowsView { public: TestFlutterWindowsView(FlutterWindowsEngine* engine, std::unique_ptr<WindowBindingHandler> window, std::function<void(KeyCall)> on_key_call) : on_key_call_(on_key_call), FlutterWindowsView(kImplicitViewId, engine, std::move(window)) {} void OnText(const std::u16string& text) override { on_key_call_(KeyCall{ .type = KeyCall::kKeyCallOnText, .text = text, }); } private: std::function<void(KeyCall)> on_key_call_; FML_DISALLOW_COPY_AND_ASSIGN(TestFlutterWindowsView); }; class KeyboardTester { public: using ResponseHandler = std::function<void(MockKeyResponseController::ResponseCallback)>; explicit KeyboardTester(WindowsTestContext& context) : callback_handler_(RespondValue(false)), map_virtual_key_layout_(LayoutDefault) { engine_ = GetTestEngine(context); view_ = std::make_unique<TestFlutterWindowsView>( engine_.get(), // The WindowBindingHandler is used for window size and such, and // doesn't affect keyboard. std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(), [this](KeyCall key_call) { key_calls.push_back(key_call); }); EngineModifier modifier{engine_.get()}; modifier.SetImplicitView(view_.get()); modifier.InitializeKeyboard(); window_ = std::make_unique<MockKeyboardManagerDelegate>( view_.get(), [this](UINT virtual_key) -> SHORT { return map_virtual_key_layout_(virtual_key, MAPVK_VK_TO_CHAR); }); } TestFlutterWindowsView& GetView() { return *view_; } MockKeyboardManagerDelegate& GetWindow() { return *window_; } // Reset the keyboard by invoking the engine restart handler. void ResetKeyboard() { EngineModifier{engine_.get()}.Restart(); } // Set all events to be handled (true) or unhandled (false). void Responding(bool response) { callback_handler_ = RespondValue(response); } // Manually handle event callback of the onKeyData embedder API. // // On every onKeyData call, the |handler| will be invoked with the target // key data and the result callback. Immediately calling the callback with // a boolean is equivalent to setting |Responding| with the boolean. However, // |LateResponding| allows storing the callback to call later. void LateResponding( MockKeyResponseController::EmbedderCallbackHandler handler) { callback_handler_ = std::move(handler); } void SetLayout(MapVirtualKeyLayout layout) { map_virtual_key_layout_ = layout == nullptr ? LayoutDefault : layout; } void InjectKeyboardChanges(std::vector<KeyboardChange> changes) { FML_DCHECK(window_ != nullptr); window_->InjectKeyboardChanges(std::move(changes)); } // Simulates receiving a platform message from the framework. void InjectPlatformMessage(const char* channel, const char* method, const char* args) { rapidjson::Document args_doc; args_doc.Parse(args); FML_DCHECK(!args_doc.HasParseError()); rapidjson::Document message_doc(rapidjson::kObjectType); auto& allocator = message_doc.GetAllocator(); message_doc.AddMember("method", rapidjson::Value(method, allocator), allocator); message_doc.AddMember("args", args_doc, allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); message_doc.Accept(writer); std::unique_ptr<std::vector<uint8_t>> data = JsonMessageCodec::GetInstance().EncodeMessage(message_doc); FlutterPlatformMessageResponseHandle response_handle; const FlutterPlatformMessage message = { sizeof(FlutterPlatformMessage), // struct_size channel, // channel data->data(), // message data->size(), // message_size &response_handle, // response_handle }; view_->GetEngine()->HandlePlatformMessage(&message); } // Get the number of redispatched messages since the last clear, then clear // the counter. size_t RedispatchedMessageCountAndClear() { auto& messages = window_->RedispatchedMessages(); size_t count = messages.size(); messages.clear(); return count; } void clear_key_calls() { for (KeyCall& key_call : key_calls) { if (key_call.type == KeyCall::kKeyCallOnKey && key_call.key_event.character != nullptr) { delete[] key_call.key_event.character; } } key_calls.clear(); } std::vector<KeyCall> key_calls; private: std::unique_ptr<FlutterWindowsEngine> engine_; std::unique_ptr<TestFlutterWindowsView> view_; std::unique_ptr<MockKeyboardManagerDelegate> window_; MockKeyResponseController::EmbedderCallbackHandler callback_handler_; MapVirtualKeyLayout map_virtual_key_layout_; // Returns an engine instance configured with dummy project path values, and // overridden methods for sending platform messages, so that the engine can // respond as if the framework were connected. std::unique_ptr<FlutterWindowsEngine> GetTestEngine( WindowsTestContext& context) { FlutterWindowsEngineBuilder builder{context}; builder.SetCreateKeyboardHandlerCallbacks( [this](int virtual_key) -> SHORT { // `window_` is not initialized yet when this callback is first // called. return window_ ? window_->GetKeyState(virtual_key) : 0; }, [this](UINT virtual_key, bool extended) -> SHORT { return map_virtual_key_layout_( virtual_key, extended ? MAPVK_VK_TO_VSC_EX : MAPVK_VK_TO_VSC); }); auto engine = builder.Build(); EngineModifier modifier(engine.get()); auto key_response_controller = std::make_shared<MockKeyResponseController>(); key_response_controller->SetEmbedderResponse( [&key_calls = key_calls, &callback_handler = callback_handler_]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { FlutterKeyEvent clone_event = *event; clone_event.character = event->character == nullptr ? nullptr : clone_string(event->character); key_calls.push_back(KeyCall{ .type = KeyCall::kKeyCallOnKey, .key_event = clone_event, }); callback_handler(event, callback); }); key_response_controller->SetTextInputResponse( [&key_calls = key_calls](std::unique_ptr<rapidjson::Document> document) { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); document->Accept(writer); key_calls.push_back(KeyCall{ .type = KeyCall::kKeyCallTextMethodCall, .text_method_call = buffer.GetString(), }); }); MockEmbedderApiForKeyboard(modifier, key_response_controller); engine->Run(); return engine; } static MockKeyResponseController::EmbedderCallbackHandler RespondValue( bool value) { return [value](const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { callback(value); }; } private: FML_DISALLOW_COPY_AND_ASSIGN(KeyboardTester); }; class KeyboardTest : public WindowsTest { public: KeyboardTest() = default; virtual ~KeyboardTest() = default; private: FML_DISALLOW_COPY_AND_ASSIGN(KeyboardTest); }; } // namespace // Define compound `expect` in macros. If they're defined in functions, the // stacktrace wouldn't print where the function is called in the unit tests. #define EXPECT_CALL_IS_EVENT(_key_call, _type, _physical, _logical, \ _character, _synthesized) \ EXPECT_EQ(_key_call.type, KeyCall::kKeyCallOnKey); \ EXPECT_EVENT_EQUALS(_key_call.key_event, _type, _physical, _logical, \ _character, _synthesized); #define EXPECT_CALL_IS_TEXT(_key_call, u16_string) \ EXPECT_EQ(_key_call.type, KeyCall::kKeyCallOnText); \ EXPECT_EQ(_key_call.text, u16_string); #define EXPECT_CALL_IS_TEXT_METHOD_CALL(_key_call, json_string) \ EXPECT_EQ(_key_call.type, KeyCall::kKeyCallTextMethodCall); \ EXPECT_STREQ(_key_call.text_method_call.c_str(), json_string); TEST_F(KeyboardTest, LowerCaseAHandled) { KeyboardTester tester{GetContext()}; tester.Responding(true); // US Keyboard layout // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST_F(KeyboardTest, LowerCaseAUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"a"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST_F(KeyboardTest, ArrowLeftHandled) { KeyboardTester tester{GetContext()}; tester.Responding(true); // US Keyboard layout // Press ArrowLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{VK_LEFT, kScanCodeArrowLeft, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalArrowLeft, kLogicalArrowLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release ArrowLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{VK_LEFT, kScanCodeArrowLeft, kExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalArrowLeft, kLogicalArrowLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST_F(KeyboardTest, ArrowLeftUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press ArrowLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{VK_LEFT, kScanCodeArrowLeft, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalArrowLeft, kLogicalArrowLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ArrowLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{VK_LEFT, kScanCodeArrowLeft, kExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalArrowLeft, kLogicalArrowLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST_F(KeyboardTest, ShiftLeftUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press ShiftLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LSHIFT, true, false}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Hold ShiftLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended, kWasDown}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeRepeat, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ShiftLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LSHIFT, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST_F(KeyboardTest, ShiftRightUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press ShiftRight tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RSHIFT, true, false}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftRight, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftRight, kLogicalShiftRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ShiftRight tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RSHIFT, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeShiftRight, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftRight, kLogicalShiftRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST_F(KeyboardTest, CtrlLeftUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press CtrlLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, true, false}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release CtrlLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST_F(KeyboardTest, CtrlRightUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press CtrlRight tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RCONTROL, true, false}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlRight, kLogicalControlRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release CtrlRight tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RCONTROL, false, true}, WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlRight, kLogicalControlRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST_F(KeyboardTest, AltLeftUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press AltLeft. AltLeft is a SysKeyDown event. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LMENU, true, false}, WmSysKeyDownInfo{VK_MENU, kScanCodeAlt, kNotExtended, kWasUp}.Build( kWmResultDefault)}); // Always pass to the default WndProc. EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalAltLeft, kLogicalAltLeft, "", kNotSynthesized); tester.clear_key_calls(); // Don't redispatch sys messages. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release AltLeft. AltLeft is a SysKeyUp event. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LMENU, false, true}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kNotExtended}.Build( kWmResultDefault)}); // Always pass to the default WndProc. EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalAltLeft, kLogicalAltLeft, "", kNotSynthesized); tester.clear_key_calls(); // Don't redispatch sys messages. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST_F(KeyboardTest, AltRightUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press AltRight. AltRight is a SysKeyDown event. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RMENU, true, false}, WmSysKeyDownInfo{VK_MENU, kScanCodeAlt, kExtended, kWasUp}.Build( kWmResultDefault)}); // Always pass to the default WndProc. EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); tester.clear_key_calls(); // Don't redispatch sys messages. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release AltRight. AltRight is a SysKeyUp event. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RMENU, false, true}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kExtended}.Build( kWmResultDefault)}); // Always pass to the default WndProc. EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); tester.clear_key_calls(); // Don't redispatch sys messages. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST_F(KeyboardTest, MetaLeftUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press MetaLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LWIN, true, false}, WmKeyDownInfo{VK_LWIN, kScanCodeMetaLeft, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalMetaLeft, kLogicalMetaLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release MetaLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LWIN, false, true}, WmKeyUpInfo{VK_LWIN, kScanCodeMetaLeft, kExtended}.Build(kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalMetaLeft, kLogicalMetaLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST_F(KeyboardTest, MetaRightUnhandled) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press MetaRight tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RWIN, true, false}, WmKeyDownInfo{VK_RWIN, kScanCodeMetaRight, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalMetaRight, kLogicalMetaRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release MetaRight tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RWIN, false, true}, WmKeyUpInfo{VK_RWIN, kScanCodeMetaRight, kExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalMetaRight, kLogicalMetaRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Press and hold A. This should generate a repeat event. TEST_F(KeyboardTest, RepeatA) { KeyboardTester tester{GetContext()}; tester.Responding(true); // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); // Hold A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasDown}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasDown}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeRepeat, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } // Press A, hot restart the engine, and hold A. // This should reset the keyboard's state and generate // two separate key down events. TEST_F(KeyboardTest, RestartClearsKeyboardState) { KeyboardTester tester{GetContext()}; tester.Responding(true); // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); // Reset the keyboard's state. tester.ResetKeyboard(); // Hold A. Notice the message declares the key is already down, however, the // the keyboard does not send a repeat event as its state was reset. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasDown}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasDown}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } // Press Shift-A. This is special because Win32 gives 'A' as character for the // KeyA press. TEST_F(KeyboardTest, ShiftLeftKeyA) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press ShiftLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LSHIFT, true, true}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'A', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "A", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"A"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release ShiftLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LSHIFT, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Press Ctrl-A. This is special because Win32 gives 0x01 as character for the // KeyA press. TEST_F(KeyboardTest, CtrlLeftKeyA) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press ControlLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, true, true}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0x01, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ControlLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, false, true}, WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Press Ctrl-1. This is special because it yields no WM_CHAR for the 1. TEST_F(KeyboardTest, CtrlLeftDigit1) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press ControlLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, true, true}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press 1 tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended, kWasUp} .Build(kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalDigit1, kLogicalDigit1, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release 1 tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalDigit1, kLogicalDigit1, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ControlLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, false, true}, WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Press 1 on a French keyboard. This is special because it yields WM_CHAR // with char_code '&'. TEST_F(KeyboardTest, Digit1OnFrenchLayout) { KeyboardTester tester{GetContext()}; tester.Responding(false); tester.SetLayout(LayoutFrench); // Press 1 tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended, kWasUp} .Build(kWmResultZero), WmCharInfo{'&', kScanCodeDigit1, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalDigit1, kLogicalDigit1, "&", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"&"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release 1 tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalDigit1, kLogicalDigit1, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests AltGr-Q on a German keyboard, which should print '@'. TEST_F(KeyboardTest, AltGrModifiedKey) { KeyboardTester tester{GetContext()}; tester.Responding(false); // German Keyboard layout // Press AltGr, which Win32 precedes with a ContrlLeft down. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, true, true}, WmKeyDownInfo{VK_LCONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero), KeyStateChange{VK_RMENU, true, true}, WmKeyDownInfo{VK_MENU, kScanCodeAlt, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeDown, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Press Q tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyQ, kScanCodeKeyQ, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'@', kScanCodeKeyQ, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyQ, kLogicalKeyQ, "@", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"@"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release Q tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyQ, kScanCodeKeyQ, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyQ, kLogicalKeyQ, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release AltGr. Win32 doesn't dispatch ControlLeft up. Instead Flutter will // forge one. The AltGr is a system key, therefore will be handled by Win32's // default WndProc. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, false, true}, ExpectForgedMessage{ WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}, KeyStateChange{VK_RMENU, false, true}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kExtended}.Build( kWmResultDefault)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeUp, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); tester.clear_key_calls(); // The sys key up must not be redispatched. The forged ControlLeft up will. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Test the following two key sequences at the same time: // // 1. Tap AltGr, then tap AltGr. // 2. Tap AltGr, hold CtrlLeft, tap AltGr, release CtrlLeft. // // The two sequences are indistinguishable until the very end when a CtrlLeft // up event might or might not follow. // // Sequence 1: CtrlLeft down, AltRight down, AltRight up // Sequence 2: CtrlLeft down, AltRight down, AltRight up, CtrlLeft up // // This is because pressing AltGr alone causes Win32 to send a fake "CtrlLeft // down" event first (see |IsKeyDownAltRight| for detailed explanation). TEST_F(KeyboardTest, AltGrTwice) { KeyboardTester tester{GetContext()}; tester.Responding(false); // 1. AltGr down. // The key down event causes a ControlLeft down and a AltRight (extended // AltLeft) down. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, true, true}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero), KeyStateChange{VK_RMENU, true, true}, WmKeyDownInfo{VK_MENU, kScanCodeAlt, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeDown, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // 2. AltGr up. // The key up event only causes a AltRight (extended AltLeft) up. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, false, true}, ExpectForgedMessage{ WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}, KeyStateChange{VK_RMENU, false, true}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kExtended}.Build( kWmResultDefault)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeUp, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); tester.clear_key_calls(); // The sys key up must not be redispatched. The forged ControlLeft up will. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // 3. AltGr down (or: ControlLeft down then AltRight down.) tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, true, false}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero), KeyStateChange{VK_RMENU, true, true}, WmKeyDownInfo{VK_MENU, kScanCodeAlt, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeDown, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // 4. AltGr up. // The key up event only causes a AltRight (extended AltLeft) up. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, false, false}, ExpectForgedMessage{ WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}, KeyStateChange{VK_RMENU, false, false}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kExtended}.Build( kWmResultDefault)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeUp, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); tester.clear_key_calls(); // The sys key up must not be redispatched. The forged ControlLeft up will. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // 5. For key sequence 2: a real ControlLeft up. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, 0, 0, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } // This tests dead key ^ then E on a French keyboard, which should be combined // into Γͺ. TEST_F(KeyboardTest, DeadKeyThatCombines) { KeyboardTester tester{GetContext()}; tester.Responding(false); tester.SetLayout(LayoutFrench); // Press ^Β¨ (US: Left bracket) tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{0xDD, kScanCodeBracketLeft, kNotExtended, kWasUp}.Build( kWmResultZero), WmDeadCharInfo{'^', kScanCodeBracketLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBracketLeft, kLogicalBracketRight, "^", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release ^Β¨ tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{0xDD, kScanCodeBracketLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalBracketLeft, kLogicalBracketRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press E tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyE, kScanCodeKeyE, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0xEA, kScanCodeKeyE, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyE, kLogicalKeyE, "Γͺ", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"Γͺ"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release E tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyE, kScanCodeKeyE, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyE, kLogicalKeyE, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests dead key ^ then E on a US INTL keyboard, which should be combined // into Γͺ. // // It is different from French AZERTY because the character that the ^ key is // mapped to does not contain the dead key character somehow. TEST_F(KeyboardTest, DeadKeyWithoutDeadMaskThatCombines) { KeyboardTester tester{GetContext()}; tester.Responding(false); // Press ShiftLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LSHIFT, true, true}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press 6^ tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{'6', kScanCodeDigit6, kNotExtended, kWasUp}.Build( kWmResultZero), WmDeadCharInfo{'^', kScanCodeDigit6, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalDigit6, kLogicalDigit6, "6", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release 6^ tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{'6', kScanCodeDigit6, kNotExtended}.Build(kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalDigit6, kLogicalDigit6, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ShiftLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LSHIFT, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press E tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyE, kScanCodeKeyE, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0xEA, kScanCodeKeyE, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyE, kLogicalKeyE, "Γͺ", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"Γͺ"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release E tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyE, kScanCodeKeyE, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyE, kLogicalKeyE, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests dead key ^ then & (US: 1) on a French keyboard, which do not // combine and should output "^&". TEST_F(KeyboardTest, DeadKeyThatDoesNotCombine) { KeyboardTester tester{GetContext()}; tester.Responding(false); tester.SetLayout(LayoutFrench); // Press ^Β¨ (US: Left bracket) tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{0xDD, kScanCodeBracketLeft, kNotExtended, kWasUp}.Build( kWmResultZero), WmDeadCharInfo{'^', kScanCodeBracketLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBracketLeft, kLogicalBracketRight, "^", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release ^Β¨ tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{0xDD, kScanCodeBracketLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalBracketLeft, kLogicalBracketRight, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press 1 tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended, kWasUp} .Build(kWmResultZero), WmCharInfo{'^', kScanCodeDigit1, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'&', kScanCodeDigit1, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 3); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalDigit1, kLogicalDigit1, "^", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"^"); EXPECT_CALL_IS_TEXT(tester.key_calls[2], u"&"); tester.clear_key_calls(); // TODO(dkwingsmt): This count should probably be 3. Currently the '^' // message is redispatched due to being part of the KeyDown session, which is // not handled by the framework, while the '&' message is not redispatched // for being a standalone message. We should resolve this inconsistency. // https://github.com/flutter/flutter/issues/98306 EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release 1 tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalDigit1, kLogicalDigit1, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests dead key `, then dead key `, then e. // // It should output ``e, instead of `Γ¨. TEST_F(KeyboardTest, DeadKeyTwiceThenLetter) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US INTL layout. // Press ` tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{0xC0, kScanCodeBackquote, kNotExtended, kWasUp}.Build( kWmResultZero), WmDeadCharInfo{'`', kScanCodeBackquote, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBackquote, kLogicalBackquote, "`", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release ` tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{0xC0, kScanCodeBackquote, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalBackquote, kLogicalBackquote, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press ` again. // The response should be slow. std::vector<MockKeyResponseController::ResponseCallback> recorded_callbacks; tester.LateResponding( [&recorded_callbacks]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { recorded_callbacks.push_back(callback); }); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{0xC0, kScanCodeBackquote, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'`', kScanCodeBackquote, kNotExtended, kWasUp, kBeingReleased, kNoContext, 1, /*bit25*/ true} .Build(kWmResultZero), WmCharInfo{'`', kScanCodeBackquote, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(recorded_callbacks.size(), 1); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBackquote, kLogicalBackquote, "`", kNotSynthesized); tester.clear_key_calls(); // Key down event responded with false. recorded_callbacks.front()(false); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_TEXT(tester.key_calls[0], u"`"); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"`"); tester.clear_key_calls(); // TODO(dkwingsmt): This count should probably be 3. See the comment above // that is marked with the same issue. // https://github.com/flutter/flutter/issues/98306 EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); tester.Responding(false); // Release ` tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{0xC0, kScanCodeBackquote, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalBackquote, kLogicalBackquote, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests when the resulting character needs to be combined with surrogates. TEST_F(KeyboardTest, MultibyteCharacter) { KeyboardTester tester{GetContext()}; tester.Responding(false); // Gothic Keyboard layout. (We need a layout that yields non-BMP characters // without IME, which is actually very rare.) // Press key W of a US keyboard, which should yield character '𐍅'. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyW, kScanCodeKeyW, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0xd800, kScanCodeKeyW, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0xdf45, kScanCodeKeyW, kNotExtended, kWasUp}.Build( kWmResultZero)}); const char* st = tester.key_calls[0].key_event.character; EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyW, kLogicalKeyW, "𐍅", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"𐍅"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 3); // Release W tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyW, kScanCodeKeyW, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyW, kLogicalKeyW, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST_F(KeyboardTest, SynthesizeModifiers) { KeyboardTester tester{GetContext()}; tester.Responding(false); // Two dummy events used to trigger synthesization. Win32Message event1 = WmKeyDownInfo{VK_BACK, kScanCodeBackspace, kNotExtended, kWasUp}.Build( kWmResultZero); Win32Message event2 = WmKeyUpInfo{VK_BACK, kScanCodeBackspace, kNotExtended}.Build( kWmResultZero); // ShiftLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LSHIFT, true, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftLeft, kLogicalShiftLeft, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LSHIFT, false, true}, event2}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftLeft, kLogicalShiftLeft, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // ShiftRight tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RSHIFT, true, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftRight, kLogicalShiftRight, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RSHIFT, false, true}, event2}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftRight, kLogicalShiftRight, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // ControlLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, true, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LCONTROL, false, true}, event2}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // ControlRight tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RCONTROL, true, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlRight, kLogicalControlRight, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RCONTROL, false, true}, event2}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlRight, kLogicalControlRight, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // AltLeft tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LMENU, true, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalAltLeft, kLogicalAltLeft, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LMENU, false, true}, event2}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalAltLeft, kLogicalAltLeft, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // AltRight tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RMENU, true, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalAltRight, kLogicalAltRight, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RMENU, false, true}, event2}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalAltRight, kLogicalAltRight, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // MetaLeft tester.InjectKeyboardChanges( std::vector<KeyboardChange>{KeyStateChange{VK_LWIN, true, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalMetaLeft, kLogicalMetaLeft, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LWIN, false, true}, event2}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalMetaLeft, kLogicalMetaLeft, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // MetaRight tester.InjectKeyboardChanges( std::vector<KeyboardChange>{KeyStateChange{VK_RWIN, true, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalMetaRight, kLogicalMetaRight, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RWIN, false, true}, event2}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalMetaRight, kLogicalMetaRight, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // CapsLock, phase 0 -> 2 -> 0. // (For phases, see |SynchronizeCriticalToggledStates|.) tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_CAPITAL, false, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 3); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalCapsLock, kLogicalCapsLock, "", kSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeUp, kPhysicalCapsLock, kLogicalCapsLock, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_CAPITAL, false, false}, event2}); EXPECT_EQ(tester.key_calls.size(), 3); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalCapsLock, kLogicalCapsLock, "", kSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeUp, kPhysicalCapsLock, kLogicalCapsLock, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // ScrollLock, phase 0 -> 1 -> 3 tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_SCROLL, true, true}, event1}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalScrollLock, kLogicalScrollLock, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_SCROLL, true, false}, event2}); EXPECT_EQ(tester.key_calls.size(), 3); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalScrollLock, kLogicalScrollLock, "", kSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeDown, kPhysicalScrollLock, kLogicalScrollLock, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // NumLock, phase 0 -> 3 -> 2 tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_NUMLOCK, true, false}, event1}); // TODO(dkwingsmt): Synthesizing from phase 0 to 3 should yield a full key // tap and a key down. Fix the algorithm so that the following result becomes // 4 keycalls with an extra pair of key down and up. // https://github.com/flutter/flutter/issues/98533 EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalNumLock, kLogicalNumLock, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_NUMLOCK, false, true}, event2}); EXPECT_EQ(tester.key_calls.size(), 4); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalNumLock, kLogicalNumLock, "", kSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeDown, kPhysicalNumLock, kLogicalNumLock, "", kSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[2], kFlutterKeyEventTypeUp, kPhysicalNumLock, kLogicalNumLock, "", kSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Pressing extended keys during IME events should work properly by not sending // any events. // // Regression test for https://github.com/flutter/flutter/issues/95888 . TEST_F(KeyboardTest, ImeExtendedEventsAreIgnored) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout. // There should be preceding key events to make the keyboard into IME mode. // Omit them in this test since they are not relavent. // Press CtrlRight in IME mode. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_RCONTROL, true, false}, WmKeyDownInfo{VK_PROCESSKEY, kScanCodeControl, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, 0, 0, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } // Ensures that synthesization works correctly when a Shift key is pressed and // (only) its up event is labeled as an IME event (VK_PROCESSKEY). // // Regression test for https://github.com/flutter/flutter/issues/104169. These // are real messages recorded when pressing Shift-2 using Microsoft Pinyin IME // on Win 10 Enterprise, which crashed the app before the fix. TEST_F(KeyboardTest, UpOnlyImeEventsAreCorrectlyHandled) { KeyboardTester tester{GetContext()}; tester.Responding(true); // US Keyboard layout. // Press CtrlRight in IME mode. tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ KeyStateChange{VK_LSHIFT, true, false}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended, kWasUp}.Build( kWmResultZero), WmKeyDownInfo{VK_PROCESSKEY, kScanCodeDigit2, kNotExtended, kWasUp}.Build( kWmResultZero), KeyStateChange{VK_LSHIFT, false, true}, WmKeyUpInfo{VK_PROCESSKEY, kScanCodeShiftLeft, kNotExtended}.Build( kWmResultZero), WmKeyUpInfo{'2', kScanCodeDigit2, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 4); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeDown, 0, 0, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[2], kFlutterKeyEventTypeUp, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[3], kFlutterKeyEventTypeDown, 0, 0, "", kNotSynthesized); tester.clear_key_calls(); } // Regression test for a crash in an earlier implementation. // // In real life, the framework responds slowly. The next real event might // arrive earlier than the framework response, and if the 2nd event has an // identical hash as the one waiting for response, an earlier implementation // will crash upon the response. TEST_F(KeyboardTest, SlowFrameworkResponse) { KeyboardTester tester{GetContext()}; std::vector<MockKeyResponseController::ResponseCallback> recorded_callbacks; // Store callbacks to manually call them. tester.LateResponding( [&recorded_callbacks]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { recorded_callbacks.push_back(callback); }); // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); // Hold A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasDown}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasDown}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_EQ(recorded_callbacks.size(), 1); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // The first response. recorded_callbacks.front()(false); EXPECT_EQ(tester.key_calls.size(), 3); EXPECT_EQ(recorded_callbacks.size(), 2); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"a"); EXPECT_CALL_IS_EVENT(tester.key_calls[2], kFlutterKeyEventTypeRepeat, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // The second response. recorded_callbacks.back()(false); EXPECT_EQ(tester.key_calls.size(), 4); EXPECT_CALL_IS_TEXT(tester.key_calls[3], u"a"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); } // Regression test for https://github.com/flutter/flutter/issues/84210. // // When the framework response is slow during a sequence of identical messages, // make sure the real messages are not mistaken as redispatched messages, // in order to not mess up the order of events. // // In this test we use: // // KeyA down, KeyA up, (down event responded with false), KeyA down, KeyA up, // // The code must not take the 2nd real key down events as a redispatched event. TEST_F(KeyboardTest, SlowFrameworkResponseForIdenticalEvents) { KeyboardTester tester{GetContext()}; std::vector<MockKeyResponseController::ResponseCallback> recorded_callbacks; // Store callbacks to manually call them. tester.LateResponding( [&recorded_callbacks]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { recorded_callbacks.push_back(callback); }); // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 0); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // The first down event responded with false. EXPECT_EQ(recorded_callbacks.size(), 1); recorded_callbacks.front()(false); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_TEXT(tester.key_calls[0], u"a"); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Press A again tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); // Nothing more was dispatched because the first up event hasn't been // responded yet. EXPECT_EQ(recorded_callbacks.size(), 2); EXPECT_EQ(tester.key_calls.size(), 0); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // The first up event responded with false, which was redispatched, and caused // the down event to be dispatched. recorded_callbacks.back()(false); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(recorded_callbacks.size(), 3); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release A again tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 0); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST_F(KeyboardTest, TextInputSubmit) { KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout tester.InjectPlatformMessage( "flutter/textinput", "TextInput.setClient", R"|([108, {"inputAction": "TextInputAction.none"}])|"); // Press Enter tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{VK_RETURN, kScanCodeEnter, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'\n', kScanCodeEnter, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalEnter, kLogicalEnter, "", kNotSynthesized); EXPECT_CALL_IS_TEXT_METHOD_CALL( tester.key_calls[1], "{" R"|("method":"TextInputClient.performAction",)|" R"|("args":[108,"TextInputAction.none"])|" "}"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release Enter tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{VK_RETURN, kScanCodeEnter, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalEnter, kLogicalEnter, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Make sure OnText is not obstructed after pressing Enter. // // Regression test for https://github.com/flutter/flutter/issues/97706. // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"a"); tester.clear_key_calls(); // Release A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); tester.clear_key_calls(); } TEST_F(KeyboardTest, VietnameseTelexAddDiacriticWithFastResponse) { // In this test, the user presses the folloing keys: // // Key Current text // =========================== // A a // F Γ  // // And the Backspace event is responded immediately. KeyboardTester tester{GetContext()}; tester.Responding(false); // US Keyboard layout // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"a"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press F, which is translated to: // // Backspace down, char & up, then VK_PACKET('Γ '). tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{VK_BACK, kScanCodeBackspace, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0x8, kScanCodeBackspace, kNotExtended, kWasUp}.Build( kWmResultZero), WmKeyUpInfo{VK_BACK, kScanCodeBackspace, kNotExtended}.Build( kWmResultZero), WmKeyDownInfo{VK_PACKET, 0, kNotExtended, kWasUp}.Build(kWmResultDefault), WmCharInfo{0xe0 /*'Γ '*/, 0, kNotExtended, kWasUp}.Build(kWmResultZero), WmKeyUpInfo{VK_PACKET, 0, kNotExtended}.Build(kWmResultDefault)}); EXPECT_EQ(tester.key_calls.size(), 3); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBackspace, kLogicalBackspace, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(tester.key_calls[1], kFlutterKeyEventTypeUp, kPhysicalBackspace, kLogicalBackspace, "", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[2], u"Γ "); tester.clear_key_calls(); // TODO(dkwingsmt): This count should probably be 4. Currently the CHAR 0x8 // message is redispatched due to being part of the KeyDown session, which is // not handled by the framework, while the 'Γ ' message is not redispatched // for being a standalone message. We should resolve this inconsistency. // https://github.com/flutter/flutter/issues/98306 EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 3); // Release F tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyF, kScanCodeKeyF, kNotExtended, /* overwrite_prev_state_0 */ true} .Build(kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, 0, 0, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } void VietnameseTelexAddDiacriticWithSlowResponse(WindowsTestContext& context, bool backspace_response) { // In this test, the user presses the following keys: // // Key Current text // =========================== // A a // F Γ  // // And the Backspace down event is responded slowly with `backspace_response`. KeyboardTester tester{context}; tester.Responding(false); // US Keyboard layout // Press A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 2); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_CALL_IS_TEXT(tester.key_calls[1], u"a"); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release A tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); std::vector<MockKeyResponseController::ResponseCallback> recorded_callbacks; tester.LateResponding( [&recorded_callbacks]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { recorded_callbacks.push_back(callback); }); // Press F, which is translated to: // // Backspace down, char & up, VK_PACKET('Γ '). tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{VK_BACK, kScanCodeBackspace, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0x8, kScanCodeBackspace, kNotExtended, kWasUp}.Build( kWmResultZero), WmKeyUpInfo{VK_BACK, kScanCodeBackspace, kNotExtended}.Build( kWmResultZero), WmKeyDownInfo{VK_PACKET, 0, kNotExtended, kWasUp}.Build(kWmResultDefault), WmCharInfo{0xe0 /*'Γ '*/, 0, kNotExtended, kWasUp}.Build(kWmResultZero), WmKeyUpInfo{VK_PACKET, 0, kNotExtended}.Build(kWmResultDefault)}); // The Backspace event has not responded yet, therefore the char message must // hold. This is because when the framework is handling the Backspace event, // it will send a setEditingState message that updates the text state that has // the last character deleted (denoted by `string1`). Processing the char // message before then will cause the final text to set to `string1`. EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBackspace, kLogicalBackspace, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); EXPECT_EQ(recorded_callbacks.size(), 1); recorded_callbacks[0](backspace_response); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeUp, kPhysicalBackspace, kLogicalBackspace, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), backspace_response ? 0 : 2); recorded_callbacks[1](false); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_TEXT(tester.key_calls[0], u"Γ "); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); tester.Responding(false); // Release F tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyUpInfo{kVirtualKeyF, kScanCodeKeyF, kNotExtended, /* overwrite_prev_state_0 */ true} .Build(kWmResultZero)}); EXPECT_EQ(tester.key_calls.size(), 1); EXPECT_CALL_IS_EVENT(tester.key_calls[0], kFlutterKeyEventTypeDown, 0, 0, "", kNotSynthesized); tester.clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST_F(KeyboardTest, VietnameseTelexAddDiacriticWithSlowFalseResponse) { VietnameseTelexAddDiacriticWithSlowResponse(GetContext(), false); } TEST_F(KeyboardTest, VietnameseTelexAddDiacriticWithSlowTrueResponse) { VietnameseTelexAddDiacriticWithSlowResponse(GetContext(), true); } // Ensure that the scancode-less key events issued by Narrator // when toggling caps lock don't violate assert statements. TEST_F(KeyboardTest, DoubleCapsLock) { KeyboardTester tester{GetContext()}; tester.Responding(false); tester.InjectKeyboardChanges(std::vector<KeyboardChange>{ WmKeyDownInfo{VK_CAPITAL, 0, kNotExtended}.Build(), WmKeyUpInfo{VK_CAPITAL, 0, kNotExtended}.Build()}); tester.clear_key_calls(); } } // namespace testing } // namespace flutter
engine/shell/platform/windows/keyboard_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/keyboard_unittests.cc", "repo_id": "engine", "token_count": 41354 }
409
// 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 FLUTTER_SHELL_PLATFORM_WINDOWS_SETTINGS_PLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_SETTINGS_PLUGIN_H_ #include <Windows.h> #include <memory> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" #include "flutter/shell/platform/windows/event_watcher.h" #include "flutter/shell/platform/windows/task_runner.h" #include "rapidjson/document.h" namespace flutter { // Abstract settings plugin. // // Used to look up and notify Flutter of user-configured system settings. // These are typically set in the control panel. class SettingsPlugin { public: enum struct PlatformBrightness { kDark, kLight }; explicit SettingsPlugin(BinaryMessenger* messenger, TaskRunner* task_runner); virtual ~SettingsPlugin(); // Sends settings (e.g., platform brightness) to the engine. void SendSettings(); // Start watching settings changes and notify the engine of the update. virtual void StartWatching(); // Stop watching settings change. The `SettingsPlugin` destructor will call // this automatically. virtual void StopWatching(); // Update the high contrast status of the system. virtual void UpdateHighContrastMode(bool is_high_contrast); protected: // Returns `true` if the user uses 24 hour time. virtual bool GetAlwaysUse24HourFormat(); // Returns the user-preferred text scale factor. virtual float GetTextScaleFactor(); // Returns the user-preferred brightness. virtual PlatformBrightness GetPreferredBrightness(); // Starts watching brightness changes. virtual void WatchPreferredBrightnessChanged(); // Starts watching text scale factor changes. virtual void WatchTextScaleFactorChanged(); bool is_high_contrast_ = false; private: std::unique_ptr<BasicMessageChannel<rapidjson::Document>> channel_; HKEY preferred_brightness_reg_hkey_ = nullptr; HKEY text_scale_factor_reg_hkey_ = nullptr; std::unique_ptr<EventWatcher> preferred_brightness_changed_watcher_; std::unique_ptr<EventWatcher> text_scale_factor_changed_watcher_; TaskRunner* task_runner_; FML_DISALLOW_COPY_AND_ASSIGN(SettingsPlugin); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_SETTINGS_PLUGIN_H_
engine/shell/platform/windows/settings_plugin.h/0
{ "file_path": "engine/shell/platform/windows/settings_plugin.h", "repo_id": "engine", "token_count": 742 }
410
// 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 FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_FLUTTER_WINDOWS_ENGINE_BUILDER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_FLUTTER_WINDOWS_ENGINE_BUILDER_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/keyboard_key_embedder_handler.h" #include "flutter/shell/platform/windows/public/flutter_windows.h" #include "flutter/shell/platform/windows/testing/windows_test_context.h" namespace flutter { namespace testing { class FlutterWindowsEngineBuilder { public: explicit FlutterWindowsEngineBuilder(WindowsTestContext& context); ~FlutterWindowsEngineBuilder(); void SetDartEntrypoint(std::string entrypoint); void AddDartEntrypointArgument(std::string arg); void SetCreateKeyboardHandlerCallbacks( KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state, KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan); void SetSwitches(std::vector<std::string> switches); void SetWindowsProcTable( std::shared_ptr<WindowsProcTable> windows_proc_table); std::unique_ptr<FlutterWindowsEngine> Build(); private: WindowsTestContext& context_; FlutterDesktopEngineProperties properties_ = {}; std::string dart_entrypoint_; std::vector<std::string> dart_entrypoint_arguments_; std::vector<std::string> switches_; KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state_; KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan_; std::shared_ptr<WindowsProcTable> windows_proc_table_; FML_DISALLOW_COPY_AND_ASSIGN(FlutterWindowsEngineBuilder); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_FLUTTER_WINDOWS_ENGINE_BUILDER_H_
engine/shell/platform/windows/testing/flutter_windows_engine_builder.h/0
{ "file_path": "engine/shell/platform/windows/testing/flutter_windows_engine_builder.h", "repo_id": "engine", "token_count": 643 }
411
// 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 "flutter/shell/platform/windows/testing/windows_test.h" #include <string> #include "flutter/shell/platform/windows/testing/windows_test_context.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { WindowsTest::WindowsTest() : context_(GetFixturesDirectory()) {} std::string WindowsTest::GetFixturesDirectory() const { return GetFixturesPath(); } WindowsTestContext& WindowsTest::GetContext() { return context_; } } // namespace testing } // namespace flutter
engine/shell/platform/windows/testing/windows_test.cc/0
{ "file_path": "engine/shell/platform/windows/testing/windows_test.cc", "repo_id": "engine", "token_count": 196 }
412
// 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 FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_PROC_DELEGATE_MANAGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_PROC_DELEGATE_MANAGER_H_ #include <Windows.h> #include <optional> #include <vector> #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/public/flutter_windows.h" namespace flutter { // Handles registration, unregistration, and dispatching for WindowProc // delegation. class WindowProcDelegateManager { public: explicit WindowProcDelegateManager(); ~WindowProcDelegateManager(); // Adds |callback| as a delegate to be called for |OnTopLevelWindowProc|. // // Multiple calls with the same |callback| will replace the previous // registration, even if |user_data| is different. void RegisterTopLevelWindowProcDelegate( FlutterDesktopWindowProcCallback callback, void* user_data); // Unregisters |callback| as a delegate for |OnTopLevelWindowProc|. void UnregisterTopLevelWindowProcDelegate( FlutterDesktopWindowProcCallback callback); // Calls any registered WindowProc delegates in the order they were // registered. // // If a result is returned, then the message was handled in such a way that // further handling should not be done. std::optional<LRESULT> OnTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) const; private: struct WindowProcDelegate { FlutterDesktopWindowProcCallback callback = nullptr; void* user_data = nullptr; }; std::vector<WindowProcDelegate> delegates_; FML_DISALLOW_COPY_AND_ASSIGN(WindowProcDelegateManager); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_PROC_DELEGATE_MANAGER_H_
engine/shell/platform/windows/window_proc_delegate_manager.h/0
{ "file_path": "engine/shell/platform/windows/window_proc_delegate_manager.h", "repo_id": "engine", "token_count": 736 }
413
// 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. import 'dart:async'; import 'dart:convert'; import 'dart:io'; class ShellProcess { final Completer<Uri> _vmServiceUriCompleter = Completer<Uri>(); final Process _process; ShellProcess(this._process) { // Scan stdout and scrape the VM Service Uri. _process.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen((String line) { final uri = _extractVMServiceUri(line); if (uri != null) { _vmServiceUriCompleter.complete(uri); } }); } Future<bool> kill() async { return _process.kill(); } Future<Uri> waitForVMService() async { return _vmServiceUriCompleter.future; } Uri? _extractVMServiceUri(String str) { final listeningMessageRegExp = RegExp( r'The Dart VM service is listening on ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)', ); final match = listeningMessageRegExp.firstMatch(str); if (match != null) { return Uri.parse(match[1]!); } return null; } } class ShellLauncher { final List<String> args = <String>[ '--vm-service-port=0', '--non-interactive', '--run-forever', '--disable-service-auth-codes', ]; final String shellExecutablePath; final String mainDartPath; final bool startPaused; ShellLauncher(this.shellExecutablePath, this.mainDartPath, this.startPaused, List<String> extraArgs) { args.addAll(extraArgs); args.add(mainDartPath); } Future<ShellProcess?> launch() async { try { final List<String> shellArguments = <String>[]; if (startPaused) { shellArguments.add('--start-paused'); } shellArguments.addAll(args); print('Launching $shellExecutablePath $shellArguments'); final Process process = await Process.start(shellExecutablePath, shellArguments); return ShellProcess(process); } catch (e) { print('Error launching shell: $e'); return null; } } }
engine/shell/testing/observatory/launcher.dart/0
{ "file_path": "engine/shell/testing/observatory/launcher.dart", "repo_id": "engine", "token_count": 826 }
414
# 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. _skia_root = "//flutter/third_party/skia" import("$_skia_root/gn/skia.gni") import("$_skia_root/modules/skshaper/skshaper.gni") if (skia_enable_skshaper) { config("public_config") { include_dirs = [ "$_skia_root/modules/skshaper/include" ] defines = [] if (skia_use_fonthost_mac) { defines += [ "SK_SHAPER_CORETEXT_AVAILABLE" ] } if (skia_use_harfbuzz) { defines += [ "SK_SHAPER_HARFBUZZ_AVAILABLE" ] } if (skia_enable_skunicode) { defines += [ "SK_SHAPER_UNICODE_AVAILABLE" ] } } component("skshaper") { # Opted out of check_includes, due to (logically) being part of skia. check_includes = false public_configs = [ ":public_config" ] public = skia_shaper_public deps = [ "../..:skia" ] defines = [ "SKSHAPER_IMPLEMENTATION=1" ] sources = skia_shaper_primitive_sources if (skia_use_fonthost_mac) { sources += skia_shaper_coretext_sources if (is_mac) { frameworks = [ "ApplicationServices.framework" ] } if (is_ios) { frameworks = [ "CoreFoundation.framework", "CoreText.framework", ] } } if (skia_enable_skunicode) { sources += skia_shaper_skunicode_sources deps += [ "../skunicode" ] } if (skia_use_harfbuzz && skia_enable_skunicode) { sources += skia_shaper_harfbuzz_sources deps += [ "../skunicode", "//flutter/third_party/harfbuzz", ] } configs += [ "../../:skia_private" ] } } else { group("skshaper") { } }
engine/skia/modules/skshaper/BUILD.gn/0
{ "file_path": "engine/skia/modules/skshaper/BUILD.gn", "repo_id": "engine", "token_count": 788 }
415
#!/usr/bin/env python3 # # 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. import argparse import platform import subprocess import shutil import sys import os from create_xcframework import create_xcframework # pylint: disable=import-error buildroot_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..')) ARCH_SUBPATH = 'mac-arm64' if platform.processor() == 'arm' else 'mac-x64' DSYMUTIL = os.path.join( os.path.dirname(__file__), '..', '..', '..', 'buildtools', ARCH_SUBPATH, 'clang', 'bin', 'dsymutil' ) out_dir = os.path.join(buildroot_dir, 'out') def main(): parser = argparse.ArgumentParser( description='Creates FlutterMacOS.framework and FlutterMacOS.xcframework for macOS' ) parser.add_argument('--dst', type=str, required=True) parser.add_argument('--arm64-out-dir', type=str, required=True) parser.add_argument('--x64-out-dir', type=str, required=True) parser.add_argument('--strip', action='store_true', default=False) parser.add_argument('--dsym', action='store_true', default=False) # TODO(godofredoc): Remove after recipes v2 have landed. parser.add_argument('--zip', action='store_true', default=False) args = parser.parse_args() dst = (args.dst if os.path.isabs(args.dst) else os.path.join(buildroot_dir, args.dst)) arm64_out_dir = ( args.arm64_out_dir if os.path.isabs(args.arm64_out_dir) else os.path.join(buildroot_dir, args.arm64_out_dir) ) x64_out_dir = ( args.x64_out_dir if os.path.isabs(args.x64_out_dir) else os.path.join(buildroot_dir, args.x64_out_dir) ) fat_framework = os.path.join(dst, 'FlutterMacOS.framework') arm64_framework = os.path.join(arm64_out_dir, 'FlutterMacOS.framework') x64_framework = os.path.join(x64_out_dir, 'FlutterMacOS.framework') arm64_dylib = os.path.join(arm64_framework, 'FlutterMacOS') x64_dylib = os.path.join(x64_framework, 'FlutterMacOS') if not os.path.isdir(arm64_framework): print('Cannot find macOS arm64 Framework at %s' % arm64_framework) return 1 if not os.path.isdir(x64_framework): print('Cannot find macOS x64 Framework at %s' % x64_framework) return 1 if not os.path.isfile(arm64_dylib): print('Cannot find macOS arm64 dylib at %s' % arm64_dylib) return 1 if not os.path.isfile(x64_dylib): print('Cannot find macOS x64 dylib at %s' % x64_dylib) return 1 if not os.path.isfile(DSYMUTIL): print('Cannot find dsymutil at %s' % DSYMUTIL) return 1 shutil.rmtree(fat_framework, True) shutil.copytree(arm64_framework, fat_framework, symlinks=True) regenerate_symlinks(fat_framework) fat_framework_binary = os.path.join(fat_framework, 'Versions', 'A', 'FlutterMacOS') # Create the arm64/x64 fat framework. subprocess.check_call([ 'lipo', arm64_dylib, x64_dylib, '-create', '-output', fat_framework_binary ]) # Add group and other readability to all files. versions_path = os.path.join(fat_framework, 'Versions') subprocess.check_call(['chmod', '-R', 'og+r', versions_path]) # Find all the files below the target dir with owner execute permission find_subprocess = subprocess.Popen(['find', versions_path, '-perm', '-100', '-print0'], stdout=subprocess.PIPE) # Add execute permission for other and group for all files that had it for owner. xargs_subprocess = subprocess.Popen(['xargs', '-0', 'chmod', 'og+x'], stdin=find_subprocess.stdout) find_subprocess.wait() xargs_subprocess.wait() process_framework(dst, args, fat_framework, fat_framework_binary) # Create XCFramework from the arm64 and x64 fat framework. xcframeworks = [fat_framework] create_xcframework(location=dst, name='FlutterMacOS', frameworks=xcframeworks) zip_framework(dst, args) return 0 def regenerate_symlinks(fat_framework): """Regenerates the symlinks structure. Recipes V2 upload artifacts in CAS before integration and CAS follows symlinks. This logic regenerates the symlinks in the expected structure. """ if os.path.islink(os.path.join(fat_framework, 'FlutterMacOS')): return os.remove(os.path.join(fat_framework, 'FlutterMacOS')) shutil.rmtree(os.path.join(fat_framework, 'Headers'), True) shutil.rmtree(os.path.join(fat_framework, 'Modules'), True) shutil.rmtree(os.path.join(fat_framework, 'Resources'), True) current_version_path = os.path.join(fat_framework, 'Versions', 'Current') shutil.rmtree(current_version_path, True) os.symlink('A', current_version_path) os.symlink( os.path.join('Versions', 'Current', 'FlutterMacOS'), os.path.join(fat_framework, 'FlutterMacOS') ) os.symlink(os.path.join('Versions', 'Current', 'Headers'), os.path.join(fat_framework, 'Headers')) os.symlink(os.path.join('Versions', 'Current', 'Modules'), os.path.join(fat_framework, 'Modules')) os.symlink( os.path.join('Versions', 'Current', 'Resources'), os.path.join(fat_framework, 'Resources') ) def embed_codesign_configuration(config_path, content): with open(config_path, 'w') as file: file.write(content) def process_framework(dst, args, fat_framework, fat_framework_binary): if args.dsym: dsym_out = os.path.splitext(fat_framework)[0] + '.dSYM' subprocess.check_call([DSYMUTIL, '-o', dsym_out, fat_framework_binary]) if args.zip: dsym_dst = os.path.join(dst, 'FlutterMacOS.dSYM') subprocess.check_call(['zip', '-r', '-y', 'FlutterMacOS.dSYM.zip', '.'], cwd=dsym_dst) # Double zip to make it consistent with legacy artifacts. # TODO(fujino): remove this once https://github.com/flutter/flutter/issues/125067 is resolved subprocess.check_call([ 'zip', '-y', 'FlutterMacOS.dSYM_.zip', 'FlutterMacOS.dSYM.zip', ], cwd=dsym_dst) # Use doubled zipped file. dsym_final_src_path = os.path.join(dsym_dst, 'FlutterMacOS.dSYM_.zip') dsym_final_dst_path = os.path.join(dst, 'FlutterMacOS.dSYM.zip') shutil.move(dsym_final_src_path, dsym_final_dst_path) if args.strip: # copy unstripped unstripped_out = os.path.join(dst, 'FlutterMacOS.unstripped') shutil.copyfile(fat_framework_binary, unstripped_out) subprocess.check_call(['strip', '-x', '-S', fat_framework_binary]) def zip_framework(dst, args): # Zip FlutterMacOS.framework. if args.zip: filepath_with_entitlements = '' framework_dst = os.path.join(dst, 'FlutterMacOS.framework') # TODO(xilaizhang): Remove the zip file from the path when outer zip is removed. filepath_without_entitlements = 'FlutterMacOS.framework.zip/Versions/A/FlutterMacOS' embed_codesign_configuration( os.path.join(framework_dst, 'entitlements.txt'), filepath_with_entitlements ) embed_codesign_configuration( os.path.join(framework_dst, 'without_entitlements.txt'), filepath_without_entitlements ) subprocess.check_call([ 'zip', '-r', '-y', 'FlutterMacOS.framework.zip', '.', ], cwd=framework_dst) # Double zip to make it consistent with legacy artifacts. # TODO(fujino): remove this once https://github.com/flutter/flutter/issues/125067 is resolved subprocess.check_call( [ 'zip', '-y', 'FlutterMacOS.framework_.zip', 'FlutterMacOS.framework.zip', # TODO(xilaizhang): Move these files to inner zip before removing the outer zip. 'entitlements.txt', 'without_entitlements.txt', ], cwd=framework_dst ) # Use doubled zipped file. final_src_path = os.path.join(framework_dst, 'FlutterMacOS.framework_.zip') final_dst_path = os.path.join(dst, 'FlutterMacOS.framework.zip') shutil.move(final_src_path, final_dst_path) zip_xcframework_archive(dst) def zip_xcframework_archive(dst): filepath_with_entitlements = '' filepath_without_entitlements = ( 'FlutterMacOS.xcframework/macos-arm64_x86_64/' 'FlutterMacOS.framework/Versions/A/FlutterMacOS' ) embed_codesign_configuration(os.path.join(dst, 'entitlements.txt'), filepath_with_entitlements) embed_codesign_configuration( os.path.join(dst, 'without_entitlements.txt'), filepath_without_entitlements ) subprocess.check_call([ 'zip', '-r', '-y', 'framework.zip', 'FlutterMacOS.xcframework', 'entitlements.txt', 'without_entitlements.txt', ], cwd=dst) if __name__ == '__main__': sys.exit(main())
engine/sky/tools/create_macos_framework.py/0
{ "file_path": "engine/sky/tools/create_macos_framework.py", "repo_id": "engine", "token_count": 3573 }
416
// 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 "flutter/testing/android/native_activity/gtest_activity.h" #include "flutter/impeller/toolkit/android/native_window.h" #include "flutter/testing/logger_listener.h" #include "flutter/testing/test_timeout_listener.h" namespace flutter { GTestActivity::GTestActivity(ANativeActivity* activity) : NativeActivity(activity) {} GTestActivity::~GTestActivity() = default; static void StartTestSuite(const impeller::android::NativeWindow& window) { auto timeout_listener = new flutter::testing::TestTimeoutListener( fml::TimeDelta::FromSeconds(120u)); auto logger_listener = new flutter::testing::LoggerListener(); auto& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Append(timeout_listener); listeners.Append(logger_listener); int result = RUN_ALL_TESTS(); delete listeners.Release(timeout_listener); delete listeners.Release(logger_listener); FML_CHECK(result == 0); } // |NativeActivity| void GTestActivity::OnNativeWindowCreated(ANativeWindow* window) { auto handle = std::make_shared<impeller::android::NativeWindow>(window); background_thread_.GetTaskRunner()->PostTask( [handle]() { StartTestSuite(*handle); }); } std::unique_ptr<NativeActivity> NativeActivityMain( ANativeActivity* activity, std::unique_ptr<fml::Mapping> saved_state) { return std::make_unique<GTestActivity>(activity); } } // namespace flutter
engine/testing/android/native_activity/gtest_activity.cc/0
{ "file_path": "engine/testing/android/native_activity/gtest_activity.cc", "repo_id": "engine", "token_count": 492 }
417
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:8.0.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = project.hasProperty('out_dir') ? project.property('out_dir') : '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir }
engine/testing/android_background_image/android/build.gradle/0
{ "file_path": "engine/testing/android_background_image/android/build.gradle", "repo_id": "engine", "token_count": 292 }
418
#!/bin/bash # # 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. # # This script expects $ENGINE_PATH to be set. It is currently used only # by automation to collect and upload metrics. set -ex $ENGINE_PATH/src/out/host_release/txt_benchmarks --benchmark_format=json > $ENGINE_PATH/src/out/host_release/txt_benchmarks.json $ENGINE_PATH/src/out/host_release/fml_benchmarks --benchmark_format=json > $ENGINE_PATH/src/out/host_release/fml_benchmarks.json $ENGINE_PATH/src/out/host_release/shell_benchmarks --benchmark_format=json > $ENGINE_PATH/src/out/host_release/shell_benchmarks.json $ENGINE_PATH/src/out/host_release/ui_benchmarks --benchmark_format=json > $ENGINE_PATH/src/out/host_release/ui_benchmarks.json $ENGINE_PATH/src/out/host_release/display_list_builder_benchmarks --benchmark_format=json > $ENGINE_PATH/src/out/host_release/display_list_builder_benchmarks.json $ENGINE_PATH/src/out/host_release/display_list_region_benchmarks --benchmark_format=json > $ENGINE_PATH/src/out/host_release/display_list_region_benchmarks.json $ENGINE_PATH/src/out/host_release/display_list_transform_benchmarks --benchmark_format=json > $ENGINE_PATH/src/out/host_release/display_list_transform_benchmarks.json $ENGINE_PATH/src/out/host_release/geometry_benchmarks --benchmark_format=json > $ENGINE_PATH/src/out/host_release/geometry_benchmarks.json $ENGINE_PATH/src/out/host_release/canvas_benchmarks --benchmark_format=json > $ENGINE_PATH/src/out/host_release/canvas_benchmarks.json
engine/testing/benchmark/generate_metrics.sh/0
{ "file_path": "engine/testing/benchmark/generate_metrics.sh", "repo_id": "engine", "token_count": 537 }
419
// 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. import 'dart:async'; import 'dart:collection'; import 'dart:convert' as convert; import 'dart:io'; import 'dart:typed_data'; import 'dart:ui'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as path; import 'impeller_enabled.dart'; import 'shader_test_file_utils.dart'; void main() async { bool assertsEnabled = false; assert(() { assertsEnabled = true; return true; }()); test('impellerc produces reasonable JSON encoded IPLR files', () async { final Directory directory = shaderDirectory('iplr-json'); final Object? rawData = convert.json.decode( File(path.join(directory.path, 'ink_sparkle.frag.iplr')).readAsStringSync()); expect(rawData is Map<String, Object?>, true); final Map<String, Object?> data = rawData! as Map<String, Object?>; expect(data.keys.toList(), <String>['sksl']); expect(data['sksl'] is Map<String, Object?>, true); final Map<String, Object?> skslData = data['sksl']! as Map<String, Object?>; expect(skslData['uniforms'] is List<Object?>, true); final Object? rawUniformData = (skslData['uniforms']! as List<Object?>)[0]; expect(rawUniformData is Map<String, Object?>, true); final Map<String, Object?> uniformData = rawUniformData! as Map<String, Object?>; expect(uniformData['location'] is int, true); }); if (impellerEnabled) { // https://github.com/flutter/flutter/issues/122823 return; } test('FragmentProgram objects are cached.', () async { final FragmentProgram programA = await FragmentProgram.fromAsset( 'blue_green_sampler.frag.iplr', ); final FragmentProgram programB = await FragmentProgram.fromAsset( 'blue_green_sampler.frag.iplr', ); expect(identical(programA, programB), true); }); test('FragmentShader setSampler throws with out-of-bounds index', () async { final FragmentProgram program = await FragmentProgram.fromAsset( 'blue_green_sampler.frag.iplr', ); final Image blueGreenImage = await _createBlueGreenImage(); final FragmentShader fragmentShader = program.fragmentShader(); try { fragmentShader.setImageSampler(1, blueGreenImage); fail('Unreachable'); } catch (e) { expect(e, contains('Sampler index out of bounds')); } finally { fragmentShader.dispose(); blueGreenImage.dispose(); } }); test('FragmentShader with sampler asserts if sampler is missing when assigned to paint', () async { if (!assertsEnabled) { return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'blue_green_sampler.frag.iplr', ); final FragmentShader fragmentShader = program.fragmentShader(); try { Paint().shader = fragmentShader; fail('Expected to throw'); } catch (err) { expect(err.toString(), contains('Invalid FragmentShader blue_green_sampler.frag.iplr')); } finally { fragmentShader.dispose(); } }); test('Disposed FragmentShader on Paint', () async { final FragmentProgram program = await FragmentProgram.fromAsset( 'blue_green_sampler.frag.iplr', ); final Image blueGreenImage = await _createBlueGreenImage(); final FragmentShader shader = program.fragmentShader() ..setImageSampler(0, blueGreenImage); shader.dispose(); try { final Paint paint = Paint()..shader = shader; // ignore: unused_local_variable if (assertsEnabled) { fail('Unreachable'); } } catch (e) { expect(e.toString(), contains('Attempted to set a disposed shader')); } blueGreenImage.dispose(); }); test('Disposed FragmentShader setFloat', () async { final FragmentProgram program = await FragmentProgram.fromAsset( 'uniforms.frag.iplr', ); final FragmentShader shader = program.fragmentShader() ..setFloat(0, 0.0); shader.dispose(); try { shader.setFloat(0, 0.0); if (assertsEnabled) { fail('Unreachable'); } } catch (e) { if (assertsEnabled) { expect( e.toString(), contains('Tried to accesss uniforms on a disposed Shader'), ); } else { expect(e is RangeError, true); } } }); test('Disposed FragmentShader setImageSampler', () async { final FragmentProgram program = await FragmentProgram.fromAsset( 'blue_green_sampler.frag.iplr', ); final Image blueGreenImage = await _createBlueGreenImage(); final FragmentShader shader = program.fragmentShader() ..setImageSampler(0, blueGreenImage); shader.dispose(); try { shader.setImageSampler(0, blueGreenImage); if (assertsEnabled) { fail('Unreachable'); } } on AssertionError catch (e) { expect( e.toString(), contains('Tried to access uniforms on a disposed Shader'), ); } on StateError catch (e) { expect( e.toString(), contains('the native peer has been collected'), ); } blueGreenImage.dispose(); }); test('Disposed FragmentShader dispose', () async { final FragmentProgram program = await FragmentProgram.fromAsset( 'uniforms.frag.iplr', ); final FragmentShader shader = program.fragmentShader() ..setFloat(0, 0.0); shader.dispose(); try { shader.dispose(); if (assertsEnabled) { fail('Unreachable'); } } catch (e) { if (assertsEnabled) { expect(e is AssertionError, true); } else { expect(e is StateError, true); } } }); test('FragmentShader simple shader renders correctly', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'functions.frag.iplr', ); final FragmentShader shader = program.fragmentShader() ..setFloat(0, 1.0); await _expectShaderRendersGreen(shader); shader.dispose(); }); test('Reused FragmentShader simple shader renders correctly', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'functions.frag.iplr', ); final FragmentShader shader = program.fragmentShader() ..setFloat(0, 1.0); await _expectShaderRendersGreen(shader); shader.setFloat(0, 0.0); await _expectShaderRendersBlack(shader); shader.dispose(); }); test('FragmentShader blue-green image renders green', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'blue_green_sampler.frag.iplr', ); final Image blueGreenImage = await _createBlueGreenImage(); final FragmentShader shader = program.fragmentShader() ..setImageSampler(0, blueGreenImage); await _expectShaderRendersGreen(shader); shader.dispose(); blueGreenImage.dispose(); }); test('FragmentShader blue-green image renders green - GPU image', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'blue_green_sampler.frag.iplr', ); final Image blueGreenImage = _createBlueGreenImageSync(); final FragmentShader shader = program.fragmentShader() ..setImageSampler(0, blueGreenImage); await _expectShaderRendersGreen(shader); shader.dispose(); blueGreenImage.dispose(); }); test('FragmentShader with uniforms renders correctly', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'uniforms.frag.iplr', ); final FragmentShader shader = program.fragmentShader() ..setFloat(0, 0.0) ..setFloat(1, 0.25) ..setFloat(2, 0.75) ..setFloat(3, 0.0) ..setFloat(4, 0.0) ..setFloat(5, 0.0) ..setFloat(6, 1.0); final ByteData renderedBytes = (await _imageByteDataFromShader( shader: shader, ))!; expect(toFloat(renderedBytes.getUint8(0)), closeTo(0.0, epsilon)); expect(toFloat(renderedBytes.getUint8(1)), closeTo(0.25, epsilon)); expect(toFloat(renderedBytes.getUint8(2)), closeTo(0.75, epsilon)); expect(toFloat(renderedBytes.getUint8(3)), closeTo(1.0, epsilon)); shader.dispose(); }); test('FragmentShader shader with array uniforms renders correctly', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'uniform_arrays.frag.iplr', ); final FragmentShader shader = program.fragmentShader(); for (int i = 0; i < 20; i++) { shader.setFloat(i, i.toDouble()); } await _expectShaderRendersGreen(shader); shader.dispose(); }); test('FragmentShader The ink_sparkle shader is accepted', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'ink_sparkle.frag.iplr', ); final FragmentShader shader = program.fragmentShader(); await _imageByteDataFromShader(shader: shader); // Testing that no exceptions are thrown. Tests that the ink_sparkle shader // produces the correct pixels are in the framework. shader.dispose(); }); test('FragmentShader Uniforms are sorted correctly', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'uniforms_sorted.frag.iplr', ); // The shader will not render green if the compiler doesn't keep the // uniforms in the right order. final FragmentShader shader = program.fragmentShader(); for (int i = 0; i < 32; i++) { shader.setFloat(i, i.toDouble()); } await _expectShaderRendersGreen(shader); shader.dispose(); }); test('fromAsset throws an exception on invalid assetKey', () async { bool throws = false; try { await FragmentProgram.fromAsset( '<invalid>', ); } catch (e) { throws = true; } expect(throws, equals(true)); }); test('fromAsset throws an exception on invalid data', () async { bool throws = false; try { await FragmentProgram.fromAsset( 'DashInNooglerHat.jpg', ); } catch (e) { throws = true; } expect(throws, equals(true)); }); test('FragmentShader user defined functions do not redefine builtins', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'no_builtin_redefinition.frag.iplr', ); final FragmentShader shader = program.fragmentShader() ..setFloat(0, 1.0); await _expectShaderRendersGreen(shader); shader.dispose(); }); test('FragmentShader fromAsset accepts a shader with no uniforms', () async { if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } final FragmentProgram program = await FragmentProgram.fromAsset( 'no_uniforms.frag.iplr', ); final FragmentShader shader = program.fragmentShader(); await _expectShaderRendersGreen(shader); shader.dispose(); }); if (impellerEnabled) { print('Skipped for Impeller - https://github.com/flutter/flutter/issues/122823'); return; } // Test all supported GLSL ops. See lib/spirv/lib/src/constants.dart final Map<String, FragmentProgram> iplrSupportedGLSLOpShaders = await _loadShaderAssets( path.join('supported_glsl_op_shaders', 'iplr'), '.iplr', ); expect(iplrSupportedGLSLOpShaders.isNotEmpty, true); _expectFragmentShadersRenderGreen(iplrSupportedGLSLOpShaders); // Test all supported instructions. See lib/spirv/lib/src/constants.dart final Map<String, FragmentProgram> iplrSupportedOpShaders = await _loadShaderAssets( path.join('supported_op_shaders', 'iplr'), '.iplr', ); expect(iplrSupportedOpShaders.isNotEmpty, true); _expectFragmentShadersRenderGreen(iplrSupportedOpShaders); } // Expect that all of the shaders in this folder render green. // Keeping the outer loop of the test synchronous allows for easy printing // of the file name within the test case. void _expectFragmentShadersRenderGreen(Map<String, FragmentProgram> programs) { for (final String key in programs.keys) { test('FragmentProgram $key renders green', () async { final FragmentProgram program = programs[key]!; final FragmentShader shader = program.fragmentShader() ..setFloat(0, 1.0); await _expectShaderRendersGreen(shader); shader.dispose(); }); } } Future<void> _expectShaderRendersColor(Shader shader, Color color) async { final ByteData renderedBytes = (await _imageByteDataFromShader( shader: shader, imageDimension: _shaderImageDimension, ))!; for (final int c in renderedBytes.buffer.asUint32List()) { expect(toHexString(c), toHexString(color.value)); } } // Expects that a shader only outputs the color green. Future<void> _expectShaderRendersGreen(Shader shader) { return _expectShaderRendersColor(shader, _greenColor); } Future<void> _expectShaderRendersBlack(Shader shader) { return _expectShaderRendersColor(shader, _blackColor); } Future<ByteData?> _imageByteDataFromShader({ required Shader shader, int imageDimension = 100, }) async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); final Paint paint = Paint()..shader = shader; canvas.drawPaint(paint); final Picture picture = recorder.endRecording(); final Image image = await picture.toImage( imageDimension, imageDimension, ); return image.toByteData(); } // Loads the path and spirv content of the files at // $FLUTTER_BUILD_DIRECTORY/gen/flutter/lib/spirv/test/$leafFolderName // This is synchronous so that tests can be inside of a loop with // the proper test name. Future<Map<String, FragmentProgram>> _loadShaderAssets( String leafFolderName, String ext, ) async { final Map<String, FragmentProgram> out = SplayTreeMap<String, FragmentProgram>(); final Directory directory = shaderDirectory(leafFolderName); if (!directory.existsSync()) { return out; } await Future.forEach( directory .listSync() .where((FileSystemEntity entry) => path.extension(entry.path) == ext), (FileSystemEntity entry) async { final String key = path.basenameWithoutExtension(entry.path); out[key] = await FragmentProgram.fromAsset( path.basename(entry.path), ); }, ); return out; } // Arbitrary, but needs to be greater than 1 for frag coord tests. const int _shaderImageDimension = 4; const Color _greenColor = Color(0xFF00FF00); const Color _blackColor = Color(0xFF000000); // Precision for checking uniform values. const double epsilon = 0.5 / 255.0; // Maps an int value from 0-255 to a double value of 0.0 to 1.0. double toFloat(int v) => v.toDouble() / 255.0; String toHexString(int color) => '#${color.toRadixString(16)}'; // 10x10 image where the left half is blue and the right half is // green. Future<Image> _createBlueGreenImage() async { const int length = 10; const int bytesPerPixel = 4; final Uint8List pixels = Uint8List(length * length * bytesPerPixel); int i = 0; for (int y = 0; y < length; y++) { for (int x = 0; x < length; x++) { if (x < length/2) { pixels[i+2] = 0xFF; // blue channel } else { pixels[i+1] = 0xFF; // green channel } pixels[i+3] = 0xFF; // alpha channel i += bytesPerPixel; } } final ImageDescriptor descriptor = ImageDescriptor.raw( await ImmutableBuffer.fromUint8List(pixels), width: length, height: length, pixelFormat: PixelFormat.rgba8888, ); final Codec codec = await descriptor.instantiateCodec(); final FrameInfo frame = await codec.getNextFrame(); return frame.image; } // A 10x10 image where the left half is blue and the right half is green. Image _createBlueGreenImageSync() { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect(const Rect.fromLTWH(0, 0, 5, 10), Paint()..color = const Color(0xFF0000FF)); canvas.drawRect(const Rect.fromLTWH(5, 0, 5, 10), Paint()..color = const Color(0xFF00FF00)); final Picture picture = recorder.endRecording(); try { return picture.toImageSync(10, 10); } finally { picture.dispose(); } }
engine/testing/dart/fragment_shader_test.dart/0
{ "file_path": "engine/testing/dart/fragment_shader_test.dart", "repo_id": "engine", "token_count": 6484 }
420
// 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. import 'dart:async'; import 'dart:isolate'; import 'dart:ui'; import 'package:litetest/litetest.dart'; const int kErrorCode = -1; const int kStartCode = 0; const int kCloseCode = 1; const int kDeletedCode = 2; class IsolateSpawnInfo { IsolateSpawnInfo(this.sendPort, this.portName); final SendPort sendPort; final String portName; } void isolateSpawnEntrypoint(IsolateSpawnInfo info) { final SendPort port = info.sendPort; final String portName = info.portName; void sendHelper(int code, [String message = '']) { port.send(<dynamic>[code, message]); } final SendPort? shared = IsolateNameServer.lookupPortByName(portName); if (shared == null) { sendHelper(kErrorCode, 'Could not find port: $portName'); return; } // ack that the SendPort lookup was successful. sendHelper(kStartCode); shared.send(portName); sendHelper(kCloseCode); // We'll fail if the ReceivePort's callback is called more than once. Try to // send another message to ensure we don't crash. shared.send('garbage'); final bool result = IsolateNameServer.removePortNameMapping(portName); if (result) { sendHelper(kDeletedCode); } else { sendHelper(kErrorCode, 'Was unable to remove mapping for $portName'); } } void main() { test('simple isolate name server', () { const String portName = 'foobar1'; try { // Mapping for 'foobar' isn't set. Check these cases to ensure correct // negative response. expect(IsolateNameServer.lookupPortByName(portName), isNull); expect(IsolateNameServer.removePortNameMapping(portName), isFalse); // Register a SendPort. final ReceivePort receivePort = ReceivePort(); final SendPort sendPort = receivePort.sendPort; expect(IsolateNameServer.registerPortWithName(sendPort, portName), isTrue); expect(IsolateNameServer.lookupPortByName(portName), sendPort); // Check we can't register the same name twice. final ReceivePort receivePort2 = ReceivePort(); final SendPort sendPort2 = receivePort2.sendPort; expect( IsolateNameServer.registerPortWithName(sendPort2, portName), isFalse); expect(IsolateNameServer.lookupPortByName(portName), sendPort); // Remove the mapping. expect(IsolateNameServer.removePortNameMapping(portName), isTrue); expect(IsolateNameServer.lookupPortByName(portName), isNull); // Ensure registering a new port with the old name returns the new port. expect( IsolateNameServer.registerPortWithName(sendPort2, portName), isTrue); expect(IsolateNameServer.lookupPortByName(portName), sendPort2); // Close so the test runner doesn't hang. receivePort.close(); receivePort2.close(); } finally { IsolateNameServer.removePortNameMapping(portName); } }); test('isolate name server multi-isolate', () async { const String portName = 'foobar2'; try { // Register our send port with the name server. final ReceivePort receivePort = ReceivePort(); final SendPort sendPort = receivePort.sendPort; expect(IsolateNameServer.registerPortWithName(sendPort, portName), isTrue); // Test driver. final ReceivePort testReceivePort = ReceivePort(); final Completer<void> testPortCompleter = Completer<void>(); testReceivePort.listen(expectAsync1<void, dynamic>((dynamic response) { final List<dynamic> typedResponse = response as List<dynamic>; final int code = typedResponse[0] as int; final String message = typedResponse[1] as String; switch (code) { case kStartCode: break; case kCloseCode: receivePort.close(); case kDeletedCode: expect(IsolateNameServer.lookupPortByName(portName), isNull); // Test is done, close the last ReceivePort. testReceivePort.close(); case kErrorCode: throw message; default: throw 'UNREACHABLE'; } }, count: 3), onDone: testPortCompleter.complete); final Completer<void> portCompleter = Completer<void>(); receivePort.listen(expectAsync1<void, dynamic>((dynamic message) { // If we don't get this message, we timeout and fail. expect(message, portName); }), onDone: portCompleter.complete); // Run the test. await Isolate.spawn( isolateSpawnEntrypoint, IsolateSpawnInfo(testReceivePort.sendPort, portName), ); await testPortCompleter.future; await portCompleter.future; } finally { IsolateNameServer.removePortNameMapping(portName); } }); }
engine/testing/dart/isolate_name_server_test.dart/0
{ "file_path": "engine/testing/dart/isolate_name_server_test.dart", "repo_id": "engine", "token_count": 1772 }
421
// 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. import 'dart:async'; import 'dart:ui'; import 'package:litetest/litetest.dart'; void main() { test('ViewConstraints.tight', () { final ViewConstraints tightConstraints = ViewConstraints.tight(const Size(200, 300)); expect(tightConstraints.minWidth, 200); expect(tightConstraints.maxWidth, 200); expect(tightConstraints.minHeight, 300); expect(tightConstraints.maxHeight, 300); expect(tightConstraints.isTight, true); expect(tightConstraints.isSatisfiedBy(const Size(200, 300)), true); expect(tightConstraints.isSatisfiedBy(const Size(400, 500)), false); expect(tightConstraints / 2, ViewConstraints.tight(const Size(100, 150))); }); test('ViewConstraints unconstrained', () { const ViewConstraints defaultValues = ViewConstraints(); expect(defaultValues.minWidth, 0); expect(defaultValues.maxWidth, double.infinity); expect(defaultValues.minHeight, 0); expect(defaultValues.maxHeight, double.infinity); expect(defaultValues.isTight, false); expect(defaultValues.isSatisfiedBy(const Size(200, 300)), true); expect(defaultValues.isSatisfiedBy(const Size(400, 500)), true); expect(defaultValues / 2, const ViewConstraints()); }); test('ViewConstraints', () { const ViewConstraints constraints = ViewConstraints(minWidth: 100, maxWidth: 200, minHeight: 300, maxHeight: 400); expect(constraints.minWidth, 100); expect(constraints.maxWidth, 200); expect(constraints.minHeight, 300); expect(constraints.maxHeight, 400); expect(constraints.isTight, false); expect(constraints.isSatisfiedBy(const Size(200, 300)), true); expect(constraints.isSatisfiedBy(const Size(400, 500)), false); expect(constraints / 2, const ViewConstraints(minWidth: 50, maxWidth: 100, minHeight: 150, maxHeight: 200)); }); test('scheduleWarmupFrame should call both callbacks and flush microtasks', () async { bool microtaskFlushed = false; bool beginFrameCalled = false; final Completer<void> drawFrameCalled = Completer<void>(); PlatformDispatcher.instance.scheduleWarmUpFrame(beginFrame: () { expect(microtaskFlushed, false); expect(drawFrameCalled.isCompleted, false); expect(beginFrameCalled, false); beginFrameCalled = true; scheduleMicrotask(() { expect(microtaskFlushed, false); expect(drawFrameCalled.isCompleted, false); microtaskFlushed = true; }); expect(microtaskFlushed, false); }, drawFrame: () { expect(beginFrameCalled, true); expect(microtaskFlushed, true); expect(drawFrameCalled.isCompleted, false); drawFrameCalled.complete(); }); await drawFrameCalled.future; expect(beginFrameCalled, true); expect(drawFrameCalled.isCompleted, true); expect(microtaskFlushed, true); }); }
engine/testing/dart/platform_dispatcher_test.dart/0
{ "file_path": "engine/testing/dart/platform_dispatcher_test.dart", "repo_id": "engine", "token_count": 1054 }
422
// 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 FLUTTER_TESTING_DART_FIXTURE_H_ #define FLUTTER_TESTING_DART_FIXTURE_H_ #include <memory> #include "flutter/common/settings.h" #include "flutter/runtime/dart_vm.h" #include "flutter/testing/elf_loader.h" #include "flutter/testing/test_dart_native_resolver.h" #include "flutter/testing/testing.h" #include "flutter/testing/thread_test.h" namespace flutter::testing { class DartFixture { public: // Uses the default filenames from the fixtures generator. DartFixture(); // Allows to customize the kernel, ELF and split ELF filenames. DartFixture(std::string kernel_filename, std::string elf_filename, std::string elf_split_filename); virtual Settings CreateSettingsForFixture(); void AddNativeCallback(const std::string& name, Dart_NativeFunction callback); void AddFfiNativeCallback(const std::string& name, void* callback_ptr); protected: void SetSnapshotsAndAssets(Settings& settings); std::shared_ptr<TestDartNativeResolver> native_resolver_; ELFAOTSymbols split_aot_symbols_; std::string kernel_filename_; std::string elf_filename_; fml::UniqueFD assets_dir_; ELFAOTSymbols aot_symbols_; private: FML_DISALLOW_COPY_AND_ASSIGN(DartFixture); }; } // namespace flutter::testing #endif // FLUTTER_TESTING_DART_FIXTURE_H_
engine/testing/dart_fixture.h/0
{ "file_path": "engine/testing/dart_fixture.h", "repo_id": "engine", "token_count": 516 }
423
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>$(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleVersion</key> <string>1</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> <key>NSExceptionDomains</key> <dict> <key>invalid-site.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> <key>sub.invalid-site.com</key> <dict> <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key> <false/> </dict> </dict> </dict> <key>FLTLeakDartVM</key> <false/> <key>FLTEnableImpeller</key> <false/> <key>FLTTraceSystrace</key> <false/> <key>FLTEnableDartProfiling</key> <false/> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> </dict> </plist>
engine/testing/ios/IosUnitTests/App/Info.plist/0
{ "file_path": "engine/testing/ios/IosUnitTests/App/Info.plist", "repo_id": "engine", "token_count": 983 }
424
# 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. import("//flutter/testing/rules/android.gni") _android_sources = [ "app/build.gradle", "app/src/androidTest/java/dev/flutter/TestRunner.java", "app/src/androidTest/java/dev/flutter/scenarios/ExampleInstrumentedTest.java", "app/src/androidTest/java/dev/flutter/scenariosui/DrawSolidBlueScreenTest.java", "app/src/androidTest/java/dev/flutter/scenariosui/ExternalTextureTests.java", "app/src/androidTest/java/dev/flutter/scenariosui/GetBitmapTests.java", "app/src/androidTest/java/dev/flutter/scenariosui/MemoryLeakTests.java", "app/src/androidTest/java/dev/flutter/scenariosui/PlatformTextureUiTests.java", "app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewUiTests.java", "app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewBadContextUiTest.java", "app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewHybridFallbackUiTest.java", "app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewHybridUiTest.java", "app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewUiTest.java", "app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithTextureViewUiTest.java", "app/src/androidTest/java/dev/flutter/scenariosui/ScreenshotUtil.java", "app/src/androidTest/java/dev/flutter/scenariosui/SpawnEngineTests.java", "app/src/androidTest/java/dev/flutter/scenariosui/SpawnMultiEngineTest.java", "app/src/main/AndroidManifest.xml", "app/src/main/assets/sample.mp4", "app/src/main/java/dev/flutter/scenarios/ExternalTextureFlutterActivity.java", "app/src/main/java/dev/flutter/scenarios/GetBitmapActivity.java", "app/src/main/java/dev/flutter/scenarios/PlatformViewsActivity.java", "app/src/main/java/dev/flutter/scenarios/SpawnMultiEngineActivity.java", "app/src/main/java/dev/flutter/scenarios/SpawnedEngineActivity.java", "app/src/main/java/dev/flutter/scenarios/StrictModeFlutterActivity.java", "app/src/main/java/dev/flutter/scenarios/SurfacePlatformViewFactory.java", "app/src/main/java/dev/flutter/scenarios/TestActivity.java", "app/src/main/java/dev/flutter/scenarios/TestableFlutterActivity.java", "app/src/main/java/dev/flutter/scenarios/TextPlatformViewFactory.java", "app/src/main/java/dev/flutter/scenarios/TexturePlatformViewFactory.java", "app/src/main/res/values/colors.xml", "app/src/main/res/values/styles.xml", "app/src/main/res/xml/data_extraction_rules.xml", "app/src/main/res/xml/extraction_config_11_and_below.xml", "build.gradle", ] gradle_task("android_lint") { app_name = "scenario_app" task = "lint" gradle_project_dir = rebase_path(".") sources = _android_sources outputs = [ "$root_out_dir/scenario_app/reports/lint-results.xml" ] deps = [ "//flutter/testing/scenario_app:scenario_app_snapshot" ] } gradle_task("build_apk") { app_name = "scenario_app" task = "assembleDebug" gradle_project_dir = rebase_path(".") sources = _android_sources outputs = [ "$root_out_dir/scenario_app/app/outputs/apk/debug/app-debug.apk" ] deps = [ ":android_lint", "//flutter/testing/scenario_app:scenario_app_snapshot", ] } gradle_task("build_test_apk") { app_name = "scenario_app" task = ":app:packageDebugAndroidTest" gradle_project_dir = rebase_path(".") sources = _android_sources outputs = [ "$root_out_dir/scenario_app/app/outputs/apk/androidTest/debug/app-debug-androidTest.apk" ] deps = [ ":android_lint", "//flutter/testing/scenario_app:scenario_app_snapshot", ] } copy("firebase_apk") { sources = get_target_outputs(":build_apk") outputs = [ "$root_out_dir/firebase_apks/scenario_app.apk" ] deps = [ ":build_apk" ] } group("android") { deps = [ ":build_apk", ":build_test_apk", ":firebase_apk", ] }
engine/testing/scenario_app/android/BUILD.gn/0
{ "file_path": "engine/testing/scenario_app/android/BUILD.gn", "repo_id": "engine", "token_count": 1524 }
425
// 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. package dev.flutter.scenarios; import android.os.Bundle; import android.view.WindowManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import java.util.concurrent.CountDownLatch; public abstract class TestableFlutterActivity extends FlutterActivity { private final CountDownLatch flutterUiRenderedLatch = new CountDownLatch(1); @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { // Do not call super. We have no plugins to register, and the automatic // registration will fail and print a scary exception in the logs. flutterEngine .getDartExecutor() .setMessageHandler("take_screenshot", (byteBuffer, binaryReply) -> notifyFlutterRendered()); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // On newer versions of Android, this is the default. Because these tests are being used to take // screenshots on Skia Gold, we don't want any of the System UI to show up, even for older API // versions (i.e. 28). // // See also: // https://github.com/flutter/engine/blob/a9081cce1f0dd730577a36ee1ca6d7af5cdc5a9b/shell/platform/android/io/flutter/embedding/android/FlutterView.java#L696 // https://github.com/flutter/flutter/issues/143471 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } protected void notifyFlutterRendered() { flutterUiRenderedLatch.countDown(); } public void waitUntilFlutterRendered() { try { flutterUiRenderedLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TestableFlutterActivity.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TestableFlutterActivity.java", "repo_id": "engine", "token_count": 635 }
426
// 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. import 'dart:io'; bool _supportsAnsi = stdout.supportsAnsiEscapes; String _green = _supportsAnsi ? '\u001b[1;32m' : ''; String _red = _supportsAnsi ? '\u001b[31m' : ''; String _yellow = _supportsAnsi ? '\u001b[33m' : ''; String _gray = _supportsAnsi ? '\u001b[90m' : ''; String _reset = _supportsAnsi? '\u001B[0m' : ''; Future<void> step(String msg, Future<void> Function() fn) async { stdout.writeln('-> $_green$msg$_reset'); try { await fn(); } catch (_) { stderr.writeln('~~ ${_red}Failed$_reset'); rethrow; } finally { stdout.writeln('<- ${_gray}Done$_reset'); } } void _logWithColor(String color, String msg) { stdout.writeln('$color$msg$_reset'); } void log(String msg) { _logWithColor(_gray, msg); } void logImportant(String msg) { stdout.writeln(msg); } void logWarning(String msg) { _logWithColor(_yellow, msg); } final class Panic extends Error {} Never panic(List<String> messages) { for (final String message in messages) { _logWithColor(_red, message); } throw Panic(); }
engine/testing/scenario_app/bin/utils/logs.dart/0
{ "file_path": "engine/testing/scenario_app/bin/utils/logs.dart", "repo_id": "engine", "token_count": 456 }
427
// Copyright 2013 The Chromium 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 FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_TEXTPLATFORMVIEW_H_ #define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_TEXTPLATFORMVIEW_H_ #import <Flutter/Flutter.h> NS_ASSUME_NONNULL_BEGIN @interface TextPlatformView : NSObject <FlutterPlatformView> - (instancetype)initWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger; - (UIView*)view; @end @interface TextPlatformViewFactory : NSObject <FlutterPlatformViewFactory> - (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_TEXTPLATFORMVIEW_H_
engine/testing/scenario_app/ios/Scenarios/Scenarios/TextPlatformView.h/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/TextPlatformView.h", "repo_id": "engine", "token_count": 383 }
428
// 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 FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_GOLDENIMAGE_H_ #define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_GOLDENIMAGE_H_ #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface GoldenImage : NSObject @property(readonly, copy, nonatomic) NSString* goldenName; @property(readonly, strong, nonatomic) UIImage* image; // Initilize with the golden file's prefix. // // Create an image from a golden file named prefix+devicemodel. - (instancetype)initWithGoldenNamePrefix:(NSString*)prefix; // Compare this GoldenImage to `image`. // // Return YES if the `image` of this GoldenImage have the same pixels of provided `image`. - (BOOL)compareGoldenToImage:(UIImage*)image rmesThreshold:(double)rmesThreshold; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_GOLDENIMAGE_H_
engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenImage.h/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenImage.h", "repo_id": "engine", "token_count": 379 }
429
// 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. import 'dart:convert'; import 'dart:ui'; /// Util method to replicate the behavior of a `MethodChannel` in the Flutter /// framework. void sendJsonMethodCall({ required PlatformDispatcher dispatcher, required String channel, required String method, dynamic arguments, PlatformMessageResponseCallback? callback, }) { sendJsonMessage( dispatcher: dispatcher, channel: channel, json: <String, dynamic>{ 'method': method, 'args': arguments, }, ); } /// Send a JSON message over a channel. void sendJsonMessage({ required PlatformDispatcher dispatcher, required String channel, required Map<String, dynamic> json, PlatformMessageResponseCallback? callback, }) { dispatcher.sendPlatformMessage( channel, // This recreates a combination of OptionalMethodChannel, JSONMethodCodec, // and _DefaultBinaryMessenger in the framework. utf8.encode( const JsonCodec().encode(json) ).buffer.asByteData(), callback, ); }
engine/testing/scenario_app/lib/src/channel_util.dart/0
{ "file_path": "engine/testing/scenario_app/lib/src/channel_util.dart", "repo_id": "engine", "token_count": 357 }
430
import '../../bin/utils/adb_logcat_filtering.dart'; /// Simulates the output of `adb logcat`, i.e. for testing. /// /// ## Example /// /// ```dart /// final FakeAdbLogcat logcat = FakeAdbLogcat(); /// final FakeAdbProcess process = logcat.withProcess(); /// process.info('ActivityManager', 'Force stopping dev.flutter.scenarios appid=10226 user=0: start instr'); /// // ... /// final List<String> logLines = logcat.drain(); /// // ... /// ``` final class FakeAdbLogcat { final List<String> _lines = <String>[]; final Map<int, FakeAdbProcess> _processById = <int, FakeAdbProcess>{}; /// The current date and time. DateTime _now = DateTime.now(); /// Returns the date and time for the next log line. /// /// Time is progressed by 1 second each time this method is called. DateTime _progressTime({Duration by = const Duration(seconds: 1)}) { _now = _now.add(by); return _now; } /// `02-22 13:54:39.839` static String _formatTime(DateTime time) { return '${time.month.toString().padLeft(2, '0')}-' '${time.day.toString().padLeft(2, '0')} ' '${time.hour.toString().padLeft(2, '0')}:' '${time.minute.toString().padLeft(2, '0')}:' '${time.second.toString().padLeft(2, '0')}.' '${time.millisecond.toString().padLeft(3, '0')}'; } void _write({ required int processId, required int threadId, required String severity, required String tag, required String message, }) { final DateTime time = _progressTime(); final String line = '${_formatTime(time)} $processId $threadId $severity $tag: $message'; assert(AdbLogLine.tryParse(line) != null, 'Invalid log line: $line'); _lines.add(line); } /// Drains the stored log lines and returns them. List<String> drain() { final List<String> result = List<String>.from(_lines); _lines.clear(); return result; } /// Creates a new process writing to this logcat. /// /// Optionally specify a [processId] to use for the process, otherwise a /// simple default is used (sequential numbers starting from 1000). FakeAdbProcess process({int? processId}) { processId ??= 1000 + _processById.length; return _processById.putIfAbsent( processId, () => _createProcess(processId: processId!), ); } FakeAdbProcess _createProcess({required int processId}) { return FakeAdbProcess._(this, processId: processId); } } /// A stateful fixture that represents a fake process writing to `adb logcat`. /// /// See [FakeAdbLogcat.process] for how to create this fixture. final class FakeAdbProcess { const FakeAdbProcess._( this._logcat, { required this.processId, }); final FakeAdbLogcat _logcat; /// The process ID of this process. final int processId; /// Writes a debug log message. void debug(String tag, String message, {int threadId = 1}) { _logcat._write( processId: processId, threadId: threadId, severity: 'D', tag: tag, message: message, ); } /// Writes an info log message. void info(String tag, String message, {int threadId = 1}) { _logcat._write( processId: processId, threadId: threadId, severity: 'I', tag: tag, message: message, ); } /// Writes a warning log message. void warning(String tag, String message, {int threadId = 1}) { _logcat._write( processId: processId, threadId: threadId, severity: 'W', tag: tag, message: message, ); } /// Writes an error log message. void error(String tag, String message, {int threadId = 1}) { _logcat._write( processId: processId, threadId: threadId, severity: 'E', tag: tag, message: message, ); } /// Writes a fatal log message. void fatal(String tag, String message, {int threadId = 1}) { _logcat._write( processId: processId, threadId: threadId, severity: 'F', tag: tag, message: message, ); } }
engine/testing/scenario_app/test/src/fake_adb_logcat.dart/0
{ "file_path": "engine/testing/scenario_app/test/src/fake_adb_logcat.dart", "repo_id": "engine", "token_count": 1483 }
431
// 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 FLUTTER_TESTING_TEST_METAL_SURFACE_IMPL_H_ #define FLUTTER_TESTING_TEST_METAL_SURFACE_IMPL_H_ #include "flutter/fml/macros.h" #include "flutter/testing/test_metal_context.h" #include "flutter/testing/test_metal_surface.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { class TestMetalSurfaceImpl : public TestMetalSurface { public: TestMetalSurfaceImpl(const TestMetalContext& test_metal_context, const SkISize& surface_size); TestMetalSurfaceImpl(const TestMetalContext& test_metal_context, int64_t texture_id, const SkISize& surface_size); // |TestMetalSurface| ~TestMetalSurfaceImpl() override; private: void Init(const TestMetalContext::TextureInfo& texture_info, const SkISize& surface_size); const TestMetalContext& test_metal_context_; bool is_valid_ = false; sk_sp<SkSurface> surface_; TestMetalContext::TextureInfo texture_info_; // |TestMetalSurface| bool IsValid() const override; // |TestMetalSurface| sk_sp<GrDirectContext> GetGrContext() const override; // |TestMetalSurface| sk_sp<SkSurface> GetSurface() const override; // |TestMetalSurface| sk_sp<SkImage> GetRasterSurfaceSnapshot() override; // |TestMetalSurface| TestMetalContext::TextureInfo GetTextureInfo() override; FML_DISALLOW_COPY_AND_ASSIGN(TestMetalSurfaceImpl); }; } // namespace flutter #endif // FLUTTER_TESTING_TEST_METAL_SURFACE_IMPL_H_
engine/testing/test_metal_surface_impl.h/0
{ "file_path": "engine/testing/test_metal_surface_impl.h", "repo_id": "engine", "token_count": 619 }
432
// Copyright 2019 The Chromium 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 "ax_active_popup.h" #include "base/logging.h" namespace ui { // Represents a global storage for the view accessibility for an // autofill popup. It is a singleton wrapper around the ax unique id of the // autofill popup. This singleton is used for communicating the live status of // the autofill popup between web contents and views. // The assumption here is that only one autofill popup can exist at a time. static std::optional<int32_t> g_active_popup_ax_unique_id; std::optional<int32_t> GetActivePopupAxUniqueId() { return g_active_popup_ax_unique_id; } void SetActivePopupAxUniqueId(std::optional<int32_t> ax_unique_id) { // When an instance of autofill popup hides, the caller of popup hide should // make sure g_active_popup_ax_unique_id is cleared. The assumption is that // there can only be one active autofill popup existing at a time. If on // popup showing, we encounter g_active_popup_ax_unique_id is already set, // this would indicate two autofill popups are showing at the same time or // previous on popup hide call did not clear the variable, so we should fail // DCHECK here. BASE_DCHECK(!GetActivePopupAxUniqueId()); g_active_popup_ax_unique_id = ax_unique_id; } void ClearActivePopupAxUniqueId() { g_active_popup_ax_unique_id = std::nullopt; } } // namespace ui
engine/third_party/accessibility/ax/ax_active_popup.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_active_popup.cc", "repo_id": "engine", "token_count": 458 }
433
// Copyright 2019 The Chromium 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 "ax_mode.h" #include <vector> #include "base/logging.h" #include "base/string_utils.h" namespace ui { std::ostream& operator<<(std::ostream& stream, const AXMode& mode) { return stream << mode.ToString(); } std::string AXMode::ToString() const { std::vector<std::string> tokens; // Written as a loop with a switch so that this crashes if a new // mode flag is added without adding support for logging it. for (uint32_t mode_flag = AXMode::kFirstModeFlag; mode_flag <= AXMode::kLastModeFlag; mode_flag = mode_flag << 1) { const char* flag_name = nullptr; switch (mode_flag) { case AXMode::kNativeAPIs: flag_name = "kNativeAPIs"; break; case AXMode::kWebContents: flag_name = "kWebContents"; break; case AXMode::kInlineTextBoxes: flag_name = "kInlineTextBoxes"; break; case AXMode::kScreenReader: flag_name = "kScreenReader"; break; case AXMode::kHTML: flag_name = "kHTML"; break; case AXMode::kLabelImages: flag_name = "kLabelImages"; break; case AXMode::kPDF: flag_name = "kPDF"; break; } BASE_DCHECK(flag_name); if (has_mode(mode_flag)) tokens.push_back(flag_name); } return base::JoinString(tokens, " | "); } } // namespace ui
engine/third_party/accessibility/ax/ax_mode.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_mode.cc", "repo_id": "engine", "token_count": 625 }
434
// Copyright 2019 The Chromium 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 "ax_range.h" #include <memory> #include <vector> #include "gtest/gtest.h" #include "ax_enums.h" #include "ax_node.h" #include "ax_node_data.h" #include "ax_node_position.h" #include "ax_tree.h" #include "ax_tree_id.h" #include "ax_tree_update.h" #include "test_ax_node_helper.h" #include "test_ax_tree_manager.h" namespace ui { using TestPositionInstance = std::unique_ptr<AXPosition<AXNodePosition, AXNode>>; using TestPositionRange = AXRange<AXPosition<AXNodePosition, AXNode>>; namespace { bool ContainerEQ(std::vector<gfx::Rect> actual, std::vector<gfx::Rect> expected) { for (size_t i = 0; i < actual.size(); i++) { if (actual[i] != expected[i]) return false; } return true; } constexpr AXNode::AXID ROOT_ID = 1; constexpr AXNode::AXID DIV1_ID = 2; constexpr AXNode::AXID BUTTON_ID = 3; constexpr AXNode::AXID DIV2_ID = 4; constexpr AXNode::AXID CHECK_BOX1_ID = 5; constexpr AXNode::AXID CHECK_BOX2_ID = 6; constexpr AXNode::AXID TEXT_FIELD_ID = 7; constexpr AXNode::AXID STATIC_TEXT1_ID = 8; constexpr AXNode::AXID INLINE_BOX1_ID = 9; constexpr AXNode::AXID LINE_BREAK1_ID = 10; constexpr AXNode::AXID STATIC_TEXT2_ID = 11; constexpr AXNode::AXID INLINE_BOX2_ID = 12; constexpr AXNode::AXID LINE_BREAK2_ID = 13; constexpr AXNode::AXID PARAGRAPH_ID = 14; constexpr AXNode::AXID STATIC_TEXT3_ID = 15; constexpr AXNode::AXID INLINE_BOX3_ID = 16; class TestAXRangeScreenRectDelegate : public AXRangeRectDelegate { public: explicit TestAXRangeScreenRectDelegate(TestAXTreeManager* tree_manager) : tree_manager_(tree_manager) {} virtual ~TestAXRangeScreenRectDelegate() = default; TestAXRangeScreenRectDelegate(const TestAXRangeScreenRectDelegate& delegate) = delete; TestAXRangeScreenRectDelegate& operator=( const TestAXRangeScreenRectDelegate& delegate) = delete; gfx::Rect GetInnerTextRangeBoundsRect( AXTreeID tree_id, AXNode::AXID node_id, int start_offset, int end_offset, ui::AXClippingBehavior clipping_behavior, AXOffscreenResult* offscreen_result) override { if (tree_manager_->GetTreeID() != tree_id) return gfx::Rect(); AXNode* node = tree_manager_->GetNodeFromTree(node_id); if (!node) return gfx::Rect(); TestAXNodeHelper* wrapper = TestAXNodeHelper::GetOrCreate(tree_manager_->GetTree(), node); return wrapper->GetInnerTextRangeBoundsRect( start_offset, end_offset, AXCoordinateSystem::kScreenDIPs, clipping_behavior, offscreen_result); } gfx::Rect GetBoundsRect(AXTreeID tree_id, AXNode::AXID node_id, AXOffscreenResult* offscreen_result) override { if (tree_manager_->GetTreeID() != tree_id) return gfx::Rect(); AXNode* node = tree_manager_->GetNodeFromTree(node_id); if (!node) return gfx::Rect(); TestAXNodeHelper* wrapper = TestAXNodeHelper::GetOrCreate(tree_manager_->GetTree(), node); return wrapper->GetBoundsRect(AXCoordinateSystem::kScreenDIPs, AXClippingBehavior::kClipped, offscreen_result); } private: TestAXTreeManager* const tree_manager_; }; class AXRangeTest : public testing::Test, public TestAXTreeManager { public: const std::u16string EMPTY = base::ASCIIToUTF16(""); const std::u16string NEWLINE = base::ASCIIToUTF16("\n"); const std::u16string BUTTON = base::ASCIIToUTF16("Button"); const std::u16string LINE_1 = base::ASCIIToUTF16("Line 1"); const std::u16string LINE_2 = base::ASCIIToUTF16("Line 2"); const std::u16string TEXT_FIELD = LINE_1.substr().append(NEWLINE).append(LINE_2).append(NEWLINE); const std::u16string AFTER_LINE = base::ASCIIToUTF16("After"); const std::u16string ALL_TEXT = BUTTON.substr().append(TEXT_FIELD).append(AFTER_LINE); AXRangeTest() = default; ~AXRangeTest() override = default; protected: void SetUp() override; AXNodeData root_; AXNodeData div1_; AXNodeData div2_; AXNodeData button_; AXNodeData check_box1_; AXNodeData check_box2_; AXNodeData text_field_; AXNodeData line_break1_; AXNodeData line_break2_; AXNodeData static_text1_; AXNodeData static_text2_; AXNodeData static_text3_; AXNodeData inline_box1_; AXNodeData inline_box2_; AXNodeData inline_box3_; AXNodeData paragraph_; private: BASE_DISALLOW_COPY_AND_ASSIGN(AXRangeTest); }; void AXRangeTest::SetUp() { // Most tests use kSuppressCharacter behavior. g_ax_embedded_object_behavior = AXEmbeddedObjectBehavior::kSuppressCharacter; root_.id = ROOT_ID; div1_.id = DIV1_ID; div2_.id = DIV2_ID; button_.id = BUTTON_ID; check_box1_.id = CHECK_BOX1_ID; check_box2_.id = CHECK_BOX2_ID; text_field_.id = TEXT_FIELD_ID; line_break1_.id = LINE_BREAK1_ID; line_break2_.id = LINE_BREAK2_ID; static_text1_.id = STATIC_TEXT1_ID; static_text2_.id = STATIC_TEXT2_ID; static_text3_.id = STATIC_TEXT3_ID; inline_box1_.id = INLINE_BOX1_ID; inline_box2_.id = INLINE_BOX2_ID; inline_box3_.id = INLINE_BOX3_ID; paragraph_.id = PARAGRAPH_ID; root_.role = ax::mojom::Role::kDialog; root_.AddState(ax::mojom::State::kFocusable); root_.SetName(ALL_TEXT); root_.relative_bounds.bounds = gfx::RectF(0, 0, 800, 600); div1_.role = ax::mojom::Role::kGenericContainer; div1_.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject, true); div1_.child_ids.push_back(button_.id); div1_.child_ids.push_back(div2_.id); root_.child_ids.push_back(div1_.id); button_.role = ax::mojom::Role::kButton; button_.SetHasPopup(ax::mojom::HasPopup::kMenu); button_.SetName(BUTTON); button_.SetValue(BUTTON); button_.relative_bounds.bounds = gfx::RectF(20, 20, 100, 30); button_.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId, check_box1_.id); div2_.role = ax::mojom::Role::kGenericContainer; div2_.child_ids.push_back(check_box1_.id); div2_.child_ids.push_back(check_box2_.id); check_box1_.role = ax::mojom::Role::kCheckBox; check_box1_.SetCheckedState(ax::mojom::CheckedState::kTrue); check_box1_.SetName("Checkbox 1"); check_box1_.relative_bounds.bounds = gfx::RectF(120, 20, 30, 30); check_box1_.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId, button_.id); check_box1_.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId, check_box2_.id); check_box2_.role = ax::mojom::Role::kCheckBox; check_box2_.SetCheckedState(ax::mojom::CheckedState::kTrue); check_box2_.SetName("Checkbox 2"); check_box2_.relative_bounds.bounds = gfx::RectF(150, 20, 30, 30); check_box2_.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId, check_box1_.id); text_field_.role = ax::mojom::Role::kGroup; text_field_.AddState(ax::mojom::State::kEditable); text_field_.SetValue(TEXT_FIELD); text_field_.AddIntListAttribute( ax::mojom::IntListAttribute::kCachedLineStarts, std::vector<int32_t>{0, 7}); text_field_.child_ids.push_back(static_text1_.id); text_field_.child_ids.push_back(line_break1_.id); text_field_.child_ids.push_back(static_text2_.id); text_field_.child_ids.push_back(line_break2_.id); root_.child_ids.push_back(text_field_.id); static_text1_.role = ax::mojom::Role::kStaticText; static_text1_.AddState(ax::mojom::State::kEditable); static_text1_.SetName(LINE_1); static_text1_.child_ids.push_back(inline_box1_.id); inline_box1_.role = ax::mojom::Role::kInlineTextBox; inline_box1_.AddState(ax::mojom::State::kEditable); inline_box1_.SetName(LINE_1); inline_box1_.relative_bounds.bounds = gfx::RectF(20, 50, 30, 30); std::vector<int32_t> character_offsets1; // The width of each character is 5px. character_offsets1.push_back(25); // "L" {20, 50, 5x30} character_offsets1.push_back(30); // "i" {25, 50, 5x30} character_offsets1.push_back(35); // "n" {30, 50, 5x30} character_offsets1.push_back(40); // "e" {35, 50, 5x30} character_offsets1.push_back(45); // " " {40, 50, 5x30} character_offsets1.push_back(50); // "1" {45, 50, 5x30} inline_box1_.AddIntListAttribute( ax::mojom::IntListAttribute::kCharacterOffsets, character_offsets1); inline_box1_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0, 5}); inline_box1_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds, std::vector<int32_t>{4, 6}); inline_box1_.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId, line_break1_.id); line_break1_.role = ax::mojom::Role::kLineBreak; line_break1_.AddState(ax::mojom::State::kEditable); line_break1_.SetName(NEWLINE); line_break1_.relative_bounds.bounds = gfx::RectF(50, 50, 0, 30); line_break1_.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId, inline_box1_.id); static_text2_.role = ax::mojom::Role::kStaticText; static_text2_.AddState(ax::mojom::State::kEditable); static_text2_.SetName(LINE_2); static_text2_.child_ids.push_back(inline_box2_.id); inline_box2_.role = ax::mojom::Role::kInlineTextBox; inline_box2_.AddState(ax::mojom::State::kEditable); inline_box2_.SetName(LINE_2); inline_box2_.relative_bounds.bounds = gfx::RectF(20, 80, 42, 30); std::vector<int32_t> character_offsets2; // The width of each character is 7 px. character_offsets2.push_back(27); // "L" {20, 80, 7x30} character_offsets2.push_back(34); // "i" {27, 80, 7x30} character_offsets2.push_back(41); // "n" {34, 80, 7x30} character_offsets2.push_back(48); // "e" {41, 80, 7x30} character_offsets2.push_back(55); // " " {48, 80, 7x30} character_offsets2.push_back(62); // "2" {55, 80, 7x30} inline_box2_.AddIntListAttribute( ax::mojom::IntListAttribute::kCharacterOffsets, character_offsets2); inline_box2_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0, 5}); inline_box2_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds, std::vector<int32_t>{4, 6}); inline_box2_.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId, line_break2_.id); line_break2_.role = ax::mojom::Role::kLineBreak; line_break2_.AddState(ax::mojom::State::kEditable); line_break2_.SetName(NEWLINE); line_break2_.relative_bounds.bounds = gfx::RectF(62, 80, 0, 30); line_break2_.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId, inline_box2_.id); paragraph_.role = ax::mojom::Role::kParagraph; paragraph_.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject, true); paragraph_.child_ids.push_back(static_text3_.id); root_.child_ids.push_back(paragraph_.id); static_text3_.role = ax::mojom::Role::kStaticText; static_text3_.SetName(AFTER_LINE); static_text3_.child_ids.push_back(inline_box3_.id); inline_box3_.role = ax::mojom::Role::kInlineTextBox; inline_box3_.SetName(AFTER_LINE); inline_box3_.relative_bounds.bounds = gfx::RectF(20, 110, 50, 30); std::vector<int32_t> character_offsets3; // The width of each character is 10 px. character_offsets3.push_back(30); // "A" {20, 110, 10x30} character_offsets3.push_back(40); // "f" {30, 110, 10x30} character_offsets3.push_back(50); // "t" {40, 110, 10x30} character_offsets3.push_back(60); // "e" {50, 110, 10x30} character_offsets3.push_back(70); // "r" {60, 110, 10x30} inline_box3_.AddIntListAttribute( ax::mojom::IntListAttribute::kCharacterOffsets, character_offsets3); inline_box3_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0}); inline_box3_.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds, std::vector<int32_t>{5}); AXTreeUpdate initial_state; initial_state.root_id = 1; initial_state.nodes = { root_, div1_, button_, div2_, check_box1_, check_box2_, text_field_, static_text1_, inline_box1_, line_break1_, static_text2_, inline_box2_, line_break2_, paragraph_, static_text3_, inline_box3_}; initial_state.has_tree_data = true; initial_state.tree_data.tree_id = AXTreeID::CreateNewAXTreeID(); initial_state.tree_data.title = "Dialog title"; SetTree(std::make_unique<AXTree>(initial_state)); } } // namespace TEST_F(AXRangeTest, EqualityOperators) { TestPositionInstance null_position = AXNodePosition::CreateNullPosition(); TestPositionInstance test_position1 = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance test_position2 = AXNodePosition::CreateTextPosition( GetTreeID(), line_break1_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance test_position3 = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); // Invalid ranges (with at least one null endpoint). TestPositionRange null_position_and_nullptr(null_position->Clone(), nullptr); TestPositionRange nullptr_and_test_position(nullptr, test_position1->Clone()); TestPositionRange test_position_and_null_position(test_position2->Clone(), null_position->Clone()); TestPositionRange test_positions_1_and_2(test_position1->Clone(), test_position2->Clone()); TestPositionRange test_positions_2_and_1(test_position2->Clone(), test_position1->Clone()); TestPositionRange test_positions_1_and_3(test_position1->Clone(), test_position3->Clone()); TestPositionRange test_positions_2_and_3(test_position2->Clone(), test_position3->Clone()); TestPositionRange test_positions_3_and_2(test_position3->Clone(), test_position2->Clone()); EXPECT_EQ(null_position_and_nullptr, nullptr_and_test_position); EXPECT_EQ(nullptr_and_test_position, test_position_and_null_position); EXPECT_NE(null_position_and_nullptr, test_positions_2_and_1); EXPECT_NE(test_positions_2_and_1, test_position_and_null_position); EXPECT_EQ(test_positions_1_and_2, test_positions_1_and_2); EXPECT_NE(test_positions_2_and_1, test_positions_1_and_2); EXPECT_EQ(test_positions_3_and_2, test_positions_2_and_3); EXPECT_NE(test_positions_1_and_2, test_positions_2_and_3); EXPECT_EQ(test_positions_1_and_2, test_positions_1_and_3); } TEST_F(AXRangeTest, AsForwardRange) { TestPositionRange null_range(AXNodePosition::CreateNullPosition(), AXNodePosition::CreateNullPosition()); null_range = null_range.AsForwardRange(); EXPECT_TRUE(null_range.IsNull()); TestPositionInstance tree_position = AXNodePosition::CreateTreePosition( GetTreeID(), button_.id, 0 /* child_index */); TestPositionInstance text_position1 = AXNodePosition::CreateTextPosition( GetTreeID(), line_break1_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance text_position2 = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange tree_to_text_range(text_position1->Clone(), tree_position->Clone()); tree_to_text_range = tree_to_text_range.AsForwardRange(); EXPECT_EQ(*tree_position, *tree_to_text_range.anchor()); EXPECT_EQ(*text_position1, *tree_to_text_range.focus()); TestPositionRange text_to_text_range(text_position2->Clone(), text_position1->Clone()); text_to_text_range = text_to_text_range.AsForwardRange(); EXPECT_EQ(*text_position1, *text_to_text_range.anchor()); EXPECT_EQ(*text_position2, *text_to_text_range.focus()); } TEST_F(AXRangeTest, IsCollapsed) { TestPositionRange null_range(AXNodePosition::CreateNullPosition(), AXNodePosition::CreateNullPosition()); null_range = null_range.AsForwardRange(); EXPECT_FALSE(null_range.IsCollapsed()); TestPositionInstance tree_position1 = AXNodePosition::CreateTreePosition( GetTreeID(), text_field_.id, 0 /* child_index */); // Since there are no children in inline_box1_, the following is essentially // an "after text" position which should not compare as equivalent to the // above tree position which is a "before text" position inside the text // field. TestPositionInstance tree_position2 = AXNodePosition::CreateTreePosition( GetTreeID(), inline_box1_.id, 0 /* child_index */); TestPositionInstance text_position1 = AXNodePosition::CreateTextPosition( GetTreeID(), static_text1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance text_position2 = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance text_position3 = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange tree_to_null_range(tree_position1->Clone(), AXNodePosition::CreateNullPosition()); EXPECT_TRUE(tree_to_null_range.IsNull()); EXPECT_FALSE(tree_to_null_range.IsCollapsed()); TestPositionRange null_to_text_range(AXNodePosition::CreateNullPosition(), text_position1->Clone()); EXPECT_TRUE(null_to_text_range.IsNull()); EXPECT_FALSE(null_to_text_range.IsCollapsed()); TestPositionRange tree_to_tree_range(tree_position2->Clone(), tree_position1->Clone()); EXPECT_TRUE(tree_to_tree_range.IsCollapsed()); // A tree and a text position that essentially point to the same text offset // are equivalent, even if they are anchored to a different node. TestPositionRange tree_to_text_range(tree_position1->Clone(), text_position1->Clone()); EXPECT_TRUE(tree_to_text_range.IsCollapsed()); // The following positions are not equivalent since tree_position2 is an // "after text" position. tree_to_text_range = TestPositionRange(tree_position2->Clone(), text_position2->Clone()); EXPECT_FALSE(tree_to_text_range.IsCollapsed()); TestPositionRange text_to_text_range(text_position1->Clone(), text_position1->Clone()); EXPECT_TRUE(text_to_text_range.IsCollapsed()); // Two text positions that essentially point to the same text offset are // equivalent, even if they are anchored to a different node. text_to_text_range = TestPositionRange(text_position1->Clone(), text_position2->Clone()); EXPECT_TRUE(text_to_text_range.IsCollapsed()); text_to_text_range = TestPositionRange(text_position1->Clone(), text_position3->Clone()); EXPECT_FALSE(text_to_text_range.IsCollapsed()); } TEST_F(AXRangeTest, BeginAndEndIterators) { TestPositionInstance null_position = AXNodePosition::CreateNullPosition(); TestPositionInstance test_position1 = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance test_position2 = AXNodePosition::CreateTextPosition( GetTreeID(), check_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance test_position3 = AXNodePosition::CreateTextPosition( GetTreeID(), check_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance test_position4 = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange nullptr_and_null_position(nullptr, null_position->Clone()); EXPECT_EQ(TestPositionRange::Iterator(), nullptr_and_null_position.begin()); EXPECT_EQ(TestPositionRange::Iterator(), nullptr_and_null_position.end()); TestPositionRange test_position1_and_nullptr(test_position1->Clone(), nullptr); EXPECT_EQ(TestPositionRange::Iterator(), test_position1_and_nullptr.begin()); EXPECT_EQ(TestPositionRange::Iterator(), test_position1_and_nullptr.end()); TestPositionRange null_position_and_test_position2(null_position->Clone(), test_position2->Clone()); EXPECT_EQ(TestPositionRange::Iterator(), null_position_and_test_position2.begin()); EXPECT_EQ(TestPositionRange::Iterator(), null_position_and_test_position2.end()); TestPositionRange test_position1_and_test_position2(test_position1->Clone(), test_position2->Clone()); EXPECT_NE(TestPositionRange::Iterator(test_position1->Clone(), test_position4->Clone()), test_position1_and_test_position2.begin()); EXPECT_NE(TestPositionRange::Iterator(test_position1->Clone(), test_position3->Clone()), test_position1_and_test_position2.begin()); EXPECT_EQ(TestPositionRange::Iterator(test_position1->Clone(), test_position2->Clone()), test_position1_and_test_position2.begin()); EXPECT_EQ(TestPositionRange::Iterator(nullptr, test_position2->Clone()), test_position1_and_test_position2.end()); TestPositionRange test_position3_and_test_position4(test_position3->Clone(), test_position4->Clone()); EXPECT_NE(TestPositionRange::Iterator(test_position1->Clone(), test_position4->Clone()), test_position3_and_test_position4.begin()); EXPECT_NE(TestPositionRange::Iterator(test_position2->Clone(), test_position4->Clone()), test_position3_and_test_position4.begin()); EXPECT_EQ(TestPositionRange::Iterator(test_position3->Clone(), test_position4->Clone()), test_position3_and_test_position4.begin()); EXPECT_NE(TestPositionRange::Iterator(nullptr, test_position2->Clone()), test_position3_and_test_position4.end()); EXPECT_NE(TestPositionRange::Iterator(nullptr, test_position3->Clone()), test_position3_and_test_position4.end()); EXPECT_EQ(TestPositionRange::Iterator(nullptr, test_position4->Clone()), test_position3_and_test_position4.end()); } TEST_F(AXRangeTest, LeafTextRangeIteration) { TestPositionInstance button_start = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance button_middle = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance button_end = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); // Since a check box is not visible to the text representation, it spans an // empty anchor whose start and end positions are the same. TestPositionInstance check_box1 = AXNodePosition::CreateTextPosition( GetTreeID(), check_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance check_box2 = AXNodePosition::CreateTextPosition( GetTreeID(), check_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_middle = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line_break1_start = AXNodePosition::CreateTextPosition( GetTreeID(), line_break1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line_break1_end = AXNodePosition::CreateTextPosition( GetTreeID(), line_break1_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_middle = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line_break2_start = AXNodePosition::CreateTextPosition( GetTreeID(), line_break2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line_break2_end = AXNodePosition::CreateTextPosition( GetTreeID(), line_break2_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance after_line_start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box3_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance after_line_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box3_.id, 5 /* text_offset */, ax::mojom::TextAffinity::kDownstream); std::vector<TestPositionRange> expected_ranges; auto TestRangeIterator = [&expected_ranges](const TestPositionRange& test_range) { std::vector<TestPositionRange> actual_ranges; for (TestPositionRange leaf_text_range : test_range) { EXPECT_TRUE(leaf_text_range.IsLeafTextRange()); actual_ranges.emplace_back(std::move(leaf_text_range)); } EXPECT_EQ(expected_ranges.size(), actual_ranges.size()); size_t element_count = std::min(expected_ranges.size(), actual_ranges.size()); for (size_t i = 0; i < element_count; ++i) { EXPECT_EQ(expected_ranges[i], actual_ranges[i]); EXPECT_EQ(expected_ranges[i].anchor()->GetAnchor(), actual_ranges[i].anchor()->GetAnchor()); } }; // Iterating over a null range; note that expected_ranges is empty. TestRangeIterator(TestPositionRange(nullptr, nullptr)); TestPositionRange non_null_degenerate_range(check_box1->Clone(), check_box1->Clone()); expected_ranges.clear(); expected_ranges.emplace_back(check_box1->Clone(), check_box1->Clone()); TestRangeIterator(non_null_degenerate_range); TestPositionRange empty_text_forward_range(button_end->Clone(), line1_start->Clone()); TestPositionRange empty_text_backward_range(line1_start->Clone(), button_end->Clone()); expected_ranges.clear(); expected_ranges.emplace_back(button_end->Clone(), button_end->Clone()); expected_ranges.emplace_back(check_box1->Clone(), check_box1->Clone()); expected_ranges.emplace_back(check_box2->Clone(), check_box2->Clone()); expected_ranges.emplace_back(line1_start->Clone(), line1_start->Clone()); TestRangeIterator(empty_text_forward_range); TestRangeIterator(empty_text_backward_range); TestPositionRange entire_anchor_forward_range(button_start->Clone(), button_end->Clone()); TestPositionRange entire_anchor_backward_range(button_end->Clone(), button_start->Clone()); expected_ranges.clear(); expected_ranges.emplace_back(button_start->Clone(), button_end->Clone()); TestRangeIterator(entire_anchor_forward_range); TestRangeIterator(entire_anchor_backward_range); TestPositionRange across_anchors_forward_range(button_middle->Clone(), line1_middle->Clone()); TestPositionRange across_anchors_backward_range(line1_middle->Clone(), button_middle->Clone()); expected_ranges.clear(); expected_ranges.emplace_back(button_middle->Clone(), button_end->Clone()); expected_ranges.emplace_back(check_box1->Clone(), check_box1->Clone()); expected_ranges.emplace_back(check_box2->Clone(), check_box2->Clone()); expected_ranges.emplace_back(line1_start->Clone(), line1_middle->Clone()); TestRangeIterator(across_anchors_forward_range); TestRangeIterator(across_anchors_backward_range); TestPositionRange starting_at_end_position_forward_range( line1_end->Clone(), line2_middle->Clone()); TestPositionRange starting_at_end_position_backward_range( line2_middle->Clone(), line1_end->Clone()); expected_ranges.clear(); expected_ranges.emplace_back(line1_end->Clone(), line1_end->Clone()); expected_ranges.emplace_back(line_break1_start->Clone(), line_break1_end->Clone()); expected_ranges.emplace_back(line2_start->Clone(), line2_middle->Clone()); TestRangeIterator(starting_at_end_position_forward_range); TestRangeIterator(starting_at_end_position_backward_range); TestPositionRange ending_at_start_position_forward_range( line1_middle->Clone(), line2_start->Clone()); TestPositionRange ending_at_start_position_backward_range( line2_start->Clone(), line1_middle->Clone()); expected_ranges.clear(); expected_ranges.emplace_back(line1_middle->Clone(), line1_end->Clone()); expected_ranges.emplace_back(line_break1_start->Clone(), line_break1_end->Clone()); expected_ranges.emplace_back(line2_start->Clone(), line2_start->Clone()); TestRangeIterator(ending_at_start_position_forward_range); TestRangeIterator(ending_at_start_position_backward_range); TestPositionInstance range_start = AXNodePosition::CreateTreePosition( GetTreeID(), root_.id, 0 /* child_index */); TestPositionInstance range_end = AXNodePosition::CreateTextPosition( GetTreeID(), root_.id, ALL_TEXT.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange entire_test_forward_range(range_start->Clone(), range_end->Clone()); TestPositionRange entire_test_backward_range(range_end->Clone(), range_start->Clone()); expected_ranges.clear(); expected_ranges.emplace_back(button_start->Clone(), button_end->Clone()); expected_ranges.emplace_back(check_box1->Clone(), check_box1->Clone()); expected_ranges.emplace_back(check_box2->Clone(), check_box2->Clone()); expected_ranges.emplace_back(line1_start->Clone(), line1_end->Clone()); expected_ranges.emplace_back(line_break1_start->Clone(), line_break1_end->Clone()); expected_ranges.emplace_back(line2_start->Clone(), line2_end->Clone()); expected_ranges.emplace_back(line_break2_start->Clone(), line_break2_end->Clone()); expected_ranges.emplace_back(after_line_start->Clone(), after_line_end->Clone()); TestRangeIterator(entire_test_forward_range); TestRangeIterator(entire_test_backward_range); } TEST_F(AXRangeTest, GetTextWithWholeObjects) { // Create a range starting from the button object and ending at the last // character of the root, i.e. at the last character of the second line in the // text field. TestPositionInstance start = AXNodePosition::CreateTreePosition( GetTreeID(), root_.id, 0 /* child_index */); TestPositionInstance end = AXNodePosition::CreateTextPosition( GetTreeID(), root_.id, ALL_TEXT.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange forward_range(start->Clone(), end->Clone()); EXPECT_EQ(ALL_TEXT, forward_range.GetText()); TestPositionRange backward_range(std::move(end), std::move(start)); EXPECT_EQ(ALL_TEXT, backward_range.GetText()); // Button start = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); end = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, BUTTON.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange button_range(start->Clone(), end->Clone()); EXPECT_EQ(BUTTON, button_range.GetText()); TestPositionRange button_range_backward(std::move(end), std::move(start)); EXPECT_EQ(BUTTON, button_range_backward.GetText()); // text_field_ start = AXNodePosition::CreateTextPosition( GetTreeID(), text_field_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); end = AXNodePosition::CreateTextPosition( GetTreeID(), text_field_.id, TEXT_FIELD.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange text_field_range(start->Clone(), end->Clone()); EXPECT_EQ(TEXT_FIELD, text_field_range.GetText()); TestPositionRange text_field_range_backward(std::move(end), std::move(start)); EXPECT_EQ(TEXT_FIELD, text_field_range_backward.GetText()); // static_text1_ start = AXNodePosition::CreateTextPosition( GetTreeID(), static_text1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); end = AXNodePosition::CreateTextPosition( GetTreeID(), static_text1_.id, LINE_1.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange static_text1_range(start->Clone(), end->Clone()); EXPECT_EQ(LINE_1, static_text1_range.GetText()); TestPositionRange static_text1_range_backward(std::move(end), std::move(start)); EXPECT_EQ(LINE_1, static_text1_range_backward.GetText()); // static_text2_ start = AXNodePosition::CreateTextPosition( GetTreeID(), static_text2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); end = AXNodePosition::CreateTextPosition( GetTreeID(), static_text2_.id, LINE_2.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange static_text2_range(start->Clone(), end->Clone()); EXPECT_EQ(LINE_2, static_text2_range.GetText()); TestPositionRange static_text2_range_backward(std::move(end), std::move(start)); EXPECT_EQ(LINE_2, static_text2_range_backward.GetText()); // static_text1_ to static_text2_ std::u16string text_between_text1_start_and_text2_end = LINE_1.substr().append(NEWLINE).append(LINE_2); start = AXNodePosition::CreateTextPosition( GetTreeID(), static_text1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); end = AXNodePosition::CreateTextPosition( GetTreeID(), static_text2_.id, LINE_2.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange static_text_range(start->Clone(), end->Clone()); EXPECT_EQ(text_between_text1_start_and_text2_end, static_text_range.GetText()); TestPositionRange static_text_range_backward(std::move(end), std::move(start)); EXPECT_EQ(text_between_text1_start_and_text2_end, static_text_range_backward.GetText()); // root_ to static_text2_'s end std::u16string text_up_to_text2_end = BUTTON.substr(0).append(LINE_1).append(NEWLINE).append(LINE_2); start = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, 0 /* child_index */); end = AXNodePosition::CreateTextPosition( GetTreeID(), static_text2_.id, LINE_2.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange root_to_static2_text_range(start->Clone(), end->Clone()); EXPECT_EQ(text_up_to_text2_end, root_to_static2_text_range.GetText()); TestPositionRange root_to_static2_text_range_backward(std::move(end), std::move(start)); EXPECT_EQ(text_up_to_text2_end, root_to_static2_text_range_backward.GetText()); // root_ to static_text2_'s start std::u16string text_up_to_text2_start = BUTTON.substr(0).append(LINE_1).append(NEWLINE); start = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, 0 /* child_index */); end = AXNodePosition::CreateTreePosition(GetTreeID(), static_text2_.id, 0 /* child_index */); TestPositionRange root_to_static2_tree_range(start->Clone(), end->Clone()); EXPECT_EQ(text_up_to_text2_start, root_to_static2_tree_range.GetText()); TestPositionRange root_to_static2_tree_range_backward(std::move(end), std::move(start)); EXPECT_EQ(text_up_to_text2_start, root_to_static2_tree_range_backward.GetText()); } TEST_F(AXRangeTest, GetTextWithTextOffsets) { std::u16string most_text = BUTTON.substr(2).append(TEXT_FIELD.substr(0, 11)); // Create a range starting from the button object and ending two characters // before the end of the root. TestPositionInstance start = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 2 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); TestPositionInstance end = AXNodePosition::CreateTextPosition( GetTreeID(), static_text2_.id, 4 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange forward_range(start->Clone(), end->Clone()); EXPECT_EQ(most_text, forward_range.GetText()); TestPositionRange backward_range(std::move(end), std::move(start)); EXPECT_EQ(most_text, backward_range.GetText()); // root_ to static_text2_'s start with offsets std::u16string text_up_to_text2_tree_start = BUTTON.substr(0).append(TEXT_FIELD.substr(0, 10)); start = AXNodePosition::CreateTreePosition(GetTreeID(), root_.id, 0 /* child_index */); end = AXNodePosition::CreateTextPosition( GetTreeID(), static_text2_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange root_to_static2_tree_range(start->Clone(), end->Clone()); EXPECT_EQ(text_up_to_text2_tree_start, root_to_static2_tree_range.GetText()); TestPositionRange root_to_static2_tree_range_backward(std::move(end), std::move(start)); EXPECT_EQ(text_up_to_text2_tree_start, root_to_static2_tree_range_backward.GetText()); } TEST_F(AXRangeTest, GetTextWithEmptyRanges) { // empty string with non-leaf tree position TestPositionInstance start = AXNodePosition::CreateTreePosition( GetTreeID(), root_.id, 0 /* child_index */); TestPositionRange non_leaf_tree_range(start->Clone(), start->Clone()); EXPECT_EQ(EMPTY, non_leaf_tree_range.GetText()); // empty string with leaf tree position start = AXNodePosition::CreateTreePosition(GetTreeID(), inline_box1_.id, 0 /* child_index */); TestPositionRange leaf_empty_range(start->Clone(), start->Clone()); EXPECT_EQ(EMPTY, leaf_empty_range.GetText()); // empty string with leaf text position and no offset start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange leaf_text_no_offset(start->Clone(), start->Clone()); EXPECT_EQ(EMPTY, leaf_text_no_offset.GetText()); // empty string with leaf text position with offset start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange leaf_text_offset(start->Clone(), start->Clone()); EXPECT_EQ(EMPTY, leaf_text_offset.GetText()); // empty string with non-leaf text with no offset start = AXNodePosition::CreateTextPosition( GetTreeID(), root_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange non_leaf_text_no_offset(start->Clone(), start->Clone()); EXPECT_EQ(EMPTY, non_leaf_text_no_offset.GetText()); // empty string with non-leaf text position with offset start = AXNodePosition::CreateTextPosition( GetTreeID(), root_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange non_leaf_text_offset(start->Clone(), start->Clone()); EXPECT_EQ(EMPTY, non_leaf_text_offset.GetText()); // empty string with same position between two anchors, but different offsets TestPositionInstance after_end = AXNodePosition::CreateTextPosition( GetTreeID(), line_break1_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance before_start = AXNodePosition::CreateTextPosition( GetTreeID(), static_text2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange same_position_different_anchors_forward( after_end->Clone(), before_start->Clone()); EXPECT_EQ(EMPTY, same_position_different_anchors_forward.GetText()); TestPositionRange same_position_different_anchors_backward( before_start->Clone(), after_end->Clone()); EXPECT_EQ(EMPTY, same_position_different_anchors_backward.GetText()); } TEST_F(AXRangeTest, GetTextAddingNewlineBetweenParagraphs) { TestPositionInstance button_start = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance button_end = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance after_line_start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box3_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance after_line_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box3_.id, 5 /* text_offset */, ax::mojom::TextAffinity::kDownstream); auto TestGetTextForRange = [](TestPositionInstance range_start, TestPositionInstance range_end, const std::u16string& expected_text, const size_t expected_appended_newlines_count) { TestPositionRange forward_test_range(range_start->Clone(), range_end->Clone()); TestPositionRange backward_test_range(std::move(range_end), std::move(range_start)); size_t appended_newlines_count = 0; EXPECT_EQ(expected_text, forward_test_range.GetText( AXTextConcatenationBehavior::kAsInnerText, -1, false, &appended_newlines_count)); EXPECT_EQ(expected_appended_newlines_count, appended_newlines_count); EXPECT_EQ(expected_text, backward_test_range.GetText( AXTextConcatenationBehavior::kAsInnerText, -1, false, &appended_newlines_count)); EXPECT_EQ(expected_appended_newlines_count, appended_newlines_count); }; std::u16string button_start_to_line1_end = BUTTON.substr().append(NEWLINE).append(LINE_1); TestGetTextForRange(button_start->Clone(), line1_end->Clone(), button_start_to_line1_end, 1); std::u16string button_start_to_line1_start = BUTTON.substr().append(NEWLINE); TestGetTextForRange(button_start->Clone(), line1_start->Clone(), button_start_to_line1_start, 1); std::u16string button_end_to_line1_end = NEWLINE.substr().append(LINE_1); TestGetTextForRange(button_end->Clone(), line1_end->Clone(), button_end_to_line1_end, 1); std::u16string button_end_to_line1_start = NEWLINE; TestGetTextForRange(button_end->Clone(), line1_start->Clone(), button_end_to_line1_start, 1); std::u16string line2_start_to_after_line_end = LINE_2.substr().append(NEWLINE).append(AFTER_LINE); TestGetTextForRange(line2_start->Clone(), after_line_end->Clone(), line2_start_to_after_line_end, 0); std::u16string line2_start_to_after_line_start = LINE_2.substr().append(NEWLINE); TestGetTextForRange(line2_start->Clone(), after_line_start->Clone(), line2_start_to_after_line_start, 0); std::u16string line2_end_to_after_line_end = NEWLINE.substr().append(AFTER_LINE); TestGetTextForRange(line2_end->Clone(), after_line_end->Clone(), line2_end_to_after_line_end, 0); std::u16string line2_end_to_after_line_start = NEWLINE; TestGetTextForRange(line2_end->Clone(), after_line_start->Clone(), line2_end_to_after_line_start, 0); std::u16string all_text = BUTTON.substr().append(NEWLINE).append(TEXT_FIELD).append(AFTER_LINE); TestPositionInstance start = AXNodePosition::CreateTextPosition( GetTreeID(), root_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance end = AXNodePosition::CreateTextPosition( GetTreeID(), root_.id, ALL_TEXT.length() /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestGetTextForRange(std::move(start), std::move(end), all_text, 1); } TEST_F(AXRangeTest, GetTextWithMaxCount) { TestPositionInstance line1_start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionRange test_range(line1_start->Clone(), line2_end->Clone()); EXPECT_EQ(LINE_1.substr(0, 2), test_range.GetText(AXTextConcatenationBehavior::kAsInnerText, 2)); // Test the case where an appended newline falls right at max_count. EXPECT_EQ(LINE_1.substr().append(NEWLINE), test_range.GetText(AXTextConcatenationBehavior::kAsInnerText, 7)); // Test passing -1 for max_count. EXPECT_EQ(LINE_1.substr().append(NEWLINE).append(LINE_2), test_range.GetText(AXTextConcatenationBehavior::kAsInnerText, -1)); } TEST_F(AXRangeTest, GetTextWithList) { const std::u16string kListMarker1 = base::ASCIIToUTF16("1. "); const std::u16string kListItemContent = base::ASCIIToUTF16("List item 1"); const std::u16string kListMarker2 = base::ASCIIToUTF16("2. "); const std::u16string kAfterList = base::ASCIIToUTF16("After list"); const std::u16string kAllText = kListMarker1.substr() .append(kListItemContent) .append(NEWLINE) .append(kListMarker2) .append(NEWLINE) .append(kAfterList); // This test expects: // "1. List item 1 // 2. // After list" // for the following AXTree: // ++1 kRootWebArea // ++++2 kList // ++++++3 kListItem // ++++++++4 kListMarker // ++++++++++5 kStaticText // ++++++++++++6 kInlineTextBox "1. " // ++++++++7 kStaticText // ++++++++++8 kInlineTextBox "List item 1" // ++++++9 kListItem // ++++++++10 kListMarker // +++++++++++11 kStaticText // ++++++++++++++12 kInlineTextBox "2. " // ++++13 kStaticText // +++++++14 kInlineTextBox "After list" AXNodeData root; AXNodeData list; AXNodeData list_item1; AXNodeData list_item2; AXNodeData list_marker1; AXNodeData list_marker2; AXNodeData inline_box1; AXNodeData inline_box2; AXNodeData inline_box3; AXNodeData inline_box4; AXNodeData static_text1; AXNodeData static_text2; AXNodeData static_text3; AXNodeData static_text4; root.id = 1; list.id = 2; list_item1.id = 3; list_marker1.id = 4; static_text1.id = 5; inline_box1.id = 6; static_text2.id = 7; inline_box2.id = 8; list_item2.id = 9; list_marker2.id = 10; static_text3.id = 11; inline_box3.id = 12; static_text4.id = 13; inline_box4.id = 14; root.role = ax::mojom::Role::kRootWebArea; root.child_ids = {list.id, static_text4.id}; list.role = ax::mojom::Role::kList; list.child_ids = {list_item1.id, list_item2.id}; list_item1.role = ax::mojom::Role::kListItem; list_item1.child_ids = {list_marker1.id, static_text2.id}; list_item1.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject, true); list_marker1.role = ax::mojom::Role::kListMarker; list_marker1.child_ids = {static_text1.id}; static_text1.role = ax::mojom::Role::kStaticText; static_text1.SetName(kListMarker1); static_text1.child_ids = {inline_box1.id}; inline_box1.role = ax::mojom::Role::kInlineTextBox; inline_box1.SetName(kListMarker1); static_text2.role = ax::mojom::Role::kStaticText; static_text2.SetName(kListItemContent); static_text2.child_ids = {inline_box2.id}; inline_box2.role = ax::mojom::Role::kInlineTextBox; inline_box2.SetName(kListItemContent); list_item2.role = ax::mojom::Role::kListItem; list_item2.child_ids = {list_marker2.id}; list_item2.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject, true); list_marker2.role = ax::mojom::Role::kListMarker; list_marker2.child_ids = {static_text3.id}; static_text3.role = ax::mojom::Role::kStaticText; static_text3.SetName(kListMarker2); static_text3.child_ids = {inline_box3.id}; inline_box3.role = ax::mojom::Role::kInlineTextBox; inline_box3.SetName(kListMarker2); static_text4.role = ax::mojom::Role::kStaticText; static_text4.SetName(kAfterList); static_text4.child_ids = {inline_box4.id}; inline_box4.role = ax::mojom::Role::kInlineTextBox; inline_box4.SetName(kAfterList); AXTreeUpdate initial_state; initial_state.root_id = root.id; initial_state.nodes = {root, list, list_item1, list_marker1, static_text1, inline_box1, static_text2, inline_box2, list_item2, list_marker2, static_text3, inline_box3, static_text4, inline_box4}; initial_state.has_tree_data = true; initial_state.tree_data.tree_id = AXTreeID::CreateNewAXTreeID(); initial_state.tree_data.title = "Dialog title"; SetTree(std::make_unique<AXTree>(initial_state)); TestPositionInstance start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(start->IsTextPosition()); TestPositionInstance end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box4.id, 10 /* text_offset */, ax::mojom::TextAffinity::kDownstream); ASSERT_TRUE(end->IsTextPosition()); TestPositionRange forward_range(start->Clone(), end->Clone()); EXPECT_EQ(kAllText, forward_range.GetText(AXTextConcatenationBehavior::kAsInnerText)); TestPositionRange backward_range(std::move(end), std::move(start)); EXPECT_EQ(kAllText, backward_range.GetText(AXTextConcatenationBehavior::kAsInnerText)); } TEST_F(AXRangeTest, GetRects) { TestAXRangeScreenRectDelegate delegate(this); // Setting up ax ranges for testing. TestPositionInstance button = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance check_box1 = AXNodePosition::CreateTextPosition( GetTreeID(), check_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance check_box2 = AXNodePosition::CreateTextPosition( GetTreeID(), check_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_second_char = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_middle = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_second_to_last_char = AXNodePosition::CreateTextPosition(GetTreeID(), inline_box1_.id, 5 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line1_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box1_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_start = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_second_char = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 1 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_middle = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 3 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_second_to_last_char = AXNodePosition::CreateTextPosition(GetTreeID(), inline_box2_.id, 5 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance line2_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box2_.id, 6 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance after_line_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box3_.id, 5 /* text_offset */, ax::mojom::TextAffinity::kDownstream); // Since a button is not visible to the text representation, it spans an // empty anchor whose start and end positions are the same. TestPositionRange button_range(button->Clone(), button->Clone()); std::vector<gfx::Rect> expected_screen_rects = {gfx::Rect(20, 20, 100, 30)}; EXPECT_TRUE( ContainerEQ(button_range.GetRects(&delegate), expected_screen_rects)); // Since a check box is not visible to the text representation, it spans an // empty anchor whose start and end positions are the same. TestPositionRange check_box1_range(check_box1->Clone(), check_box1->Clone()); expected_screen_rects = {gfx::Rect(120, 20, 30, 30)}; EXPECT_TRUE( ContainerEQ(check_box1_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding boxes of the button and both checkboxes. TestPositionRange button_check_box2_range(button->Clone(), check_box2->Clone()); expected_screen_rects = {gfx::Rect(20, 20, 100, 30), gfx::Rect(120, 20, 30, 30), gfx::Rect(150, 20, 30, 30)}; EXPECT_TRUE(ContainerEQ(button_check_box2_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding box of text line 1, its whole range. // 0 1 2 3 4 5 // |L|i|n|e| |1| // |-----------| TestPositionRange line1_whole_range(line1_start->Clone(), line1_end->Clone()); expected_screen_rects = {gfx::Rect(20, 50, 30, 30)}; EXPECT_TRUE(ContainerEQ(line1_whole_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding box of text line 1, its first half range. // 0 1 2 3 4 5 // |L|i|n|e| |1| // |-----| TestPositionRange line1_first_half_range(line1_start->Clone(), line1_middle->Clone()); expected_screen_rects = {gfx::Rect(20, 50, 15, 30)}; EXPECT_TRUE(ContainerEQ(line1_first_half_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding box of text line 1, its second half range. // 0 1 2 3 4 5 // |L|i|n|e| |1| // |-----| TestPositionRange line1_second_half_range(line1_middle->Clone(), line1_end->Clone()); expected_screen_rects = {gfx::Rect(35, 50, 15, 30)}; EXPECT_TRUE(ContainerEQ(line1_second_half_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding box of text line 1, its mid range. // 0 1 2 3 4 5 // |L|i|n|e| |1| // |-------| TestPositionRange line1_mid_range(line1_second_char->Clone(), line1_second_to_last_char->Clone()); expected_screen_rects = {gfx::Rect(25, 50, 20, 30)}; EXPECT_TRUE( ContainerEQ(line1_mid_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding box of text line 2, its whole range. // 0 1 2 3 4 5 // |L|i|n|e| |2| // |-----------| TestPositionRange line2_whole_range(line2_start->Clone(), line2_end->Clone()); expected_screen_rects = {gfx::Rect(20, 80, 42, 30)}; EXPECT_TRUE(ContainerEQ(line2_whole_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding box of text line 2, its first half range. // 0 1 2 3 4 5 // |L|i|n|e| |2| // |-----| TestPositionRange line2_first_half_range(line2_start->Clone(), line2_middle->Clone()); expected_screen_rects = {gfx::Rect(20, 80, 21, 30)}; EXPECT_TRUE(ContainerEQ(line2_first_half_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding box of text line 2, its second half range. // 0 1 2 3 4 5 // |L|i|n|e| |2| // |-----| TestPositionRange line2_second_half_range(line2_middle->Clone(), line2_end->Clone()); expected_screen_rects = {gfx::Rect(41, 80, 21, 30)}; EXPECT_TRUE(ContainerEQ(line2_second_half_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding box of text line 2, its mid range. // 0 1 2 3 4 5 // |L|i|n|e| |2| // |-------| TestPositionRange line2_mid_range(line2_second_char->Clone(), line2_second_to_last_char->Clone()); expected_screen_rects = {gfx::Rect(27, 80, 28, 30)}; EXPECT_TRUE( ContainerEQ(line2_mid_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding boxes of text line 1 and line 2, the entire range. // |L|i|n|e| |1|\n|L|i|n|e| |2|\n| // |--------------------------| TestPositionRange line1_line2_whole_range(line1_start->Clone(), line2_end->Clone()); expected_screen_rects = {gfx::Rect(20, 50, 30, 30), gfx::Rect(20, 80, 42, 30)}; EXPECT_TRUE(ContainerEQ(line1_line2_whole_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding boxes of the range that spans from the middle of text // line 1 to the middle of text line 2. // |L|i|n|e| |1|\n|L|i|n|e| |2|\n| // |--------------| TestPositionRange line1_line2_mid_range(line1_middle->Clone(), line2_middle->Clone()); expected_screen_rects = {gfx::Rect(35, 50, 15, 30), gfx::Rect(20, 80, 21, 30)}; EXPECT_TRUE(ContainerEQ(line1_line2_mid_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding boxes of the range that spans from the checkbox 2 // ("invisible" in the text representation) to the middle of text line 2. // |[Button][Checkbox 1][Checkbox 2]L|i|n|e| |1|\n|L|i|n|e| |2|\n|A|f|t|e|r| // |-------------------------------| TestPositionRange check_box2_line2_mid_range(check_box2->Clone(), line2_middle->Clone()); expected_screen_rects = {gfx::Rect(150, 20, 30, 30), gfx::Rect(20, 50, 30, 30), gfx::Rect(20, 80, 21, 30)}; EXPECT_TRUE(ContainerEQ(check_box2_line2_mid_range.GetRects(&delegate), expected_screen_rects)); // Retrieving bounding boxes of the range spanning the entire document. // |[Button][Checkbox 1][Checkbox 2]L|i|n|e| |1|\n|L|i|n|e| |2|\n|A|f|t|e|r| // |-----------------------------------------------------------------------| TestPositionRange entire_test_range(button->Clone(), after_line_end->Clone()); expected_screen_rects = { gfx::Rect(20, 20, 100, 30), gfx::Rect(120, 20, 30, 30), gfx::Rect(150, 20, 30, 30), gfx::Rect(20, 50, 30, 30), gfx::Rect(20, 80, 42, 30), gfx::Rect(20, 110, 50, 30)}; EXPECT_TRUE(ContainerEQ(entire_test_range.GetRects(&delegate), expected_screen_rects)); } TEST_F(AXRangeTest, GetRectsOffscreen) { // Set up root node bounds/viewport size to {0, 50, 800x60}, so that only // some text will be onscreen the rest will be offscreen. AXNodeData old_root_node_data = GetRootAsAXNode()->data(); AXNodeData new_root_node_data = old_root_node_data; new_root_node_data.relative_bounds.bounds = gfx::RectF(0, 50, 800, 60); GetRootAsAXNode()->SetData(new_root_node_data); TestAXRangeScreenRectDelegate delegate(this); TestPositionInstance button = AXNodePosition::CreateTextPosition( GetTreeID(), button_.id, 0 /* text_offset */, ax::mojom::TextAffinity::kDownstream); TestPositionInstance after_line_end = AXNodePosition::CreateTextPosition( GetTreeID(), inline_box3_.id, 5 /* text_offset */, ax::mojom::TextAffinity::kDownstream); // [Button] [Checkbox 1] [Checkbox 2] // {20, 20, 100x30}, {120, 20, 30x30} {150, 20, 30x30} // --- // [Line 1] | // {20, 50, 30x30} | view port, onscreen // | {0, 50, 800x60} // [Line 2] | // {20, 80, 42x30} | // --- // [After] // {20, 110, 50x30} // // Retrieving bounding boxes of the range spanning the entire document. // |[Button][Checkbox 1][Checkbox 2]L|i|n|e| |1|\n|L|i|n|e| |2|\n|A|f|t|e|r| // |-----------------------------------------------------------------------| TestPositionRange entire_test_range(button->Clone(), after_line_end->Clone()); std::vector<gfx::Rect> expected_screen_rects = {gfx::Rect(20, 50, 30, 30), gfx::Rect(20, 80, 42, 30)}; EXPECT_TRUE(ContainerEQ(entire_test_range.GetRects(&delegate), expected_screen_rects)); // Reset the root node bounds/viewport size back to {0, 0, 800x600}, and // verify all elements should be onscreen. GetRootAsAXNode()->SetData(old_root_node_data); expected_screen_rects = { gfx::Rect(20, 20, 100, 30), gfx::Rect(120, 20, 30, 30), gfx::Rect(150, 20, 30, 30), gfx::Rect(20, 50, 30, 30), gfx::Rect(20, 80, 42, 30), gfx::Rect(20, 110, 50, 30)}; EXPECT_TRUE(ContainerEQ(entire_test_range.GetRects(&delegate), expected_screen_rects)); } } // namespace ui
engine/third_party/accessibility/ax/ax_range_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_range_unittest.cc", "repo_id": "engine", "token_count": 27504 }
435
// Copyright 2014 The Chromium 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 UI_ACCESSIBILITY_AX_TREE_ID_REGISTRY_H_ #define UI_ACCESSIBILITY_AX_TREE_ID_REGISTRY_H_ #include <map> #include <string> #include <utility> #include "ax_action_handler.h" #include "ax_export.h" #include "ax_tree_id.h" #include "base/macros.h" namespace base { template <typename T> struct DefaultSingletonTraits; } // namespace base namespace ui { class AXActionHandlerBase; // This class generates and saves a runtime id for an accessibility tree. // It provides a few distinct forms of generating an id: // - from a frame id (which consists of a process and routing id) // - from a backing |AXActionHandlerBase| object // // The first form allows underlying instances to change but refer to the same // frame. // The second form allows this registry to track the object for later retrieval. class AX_EXPORT AXTreeIDRegistry { public: using FrameID = std::pair<int, int>; // Get the single instance of this class. static AXTreeIDRegistry& GetInstance(); // Gets the frame id based on an ax tree id. FrameID GetFrameID(const AXTreeID& ax_tree_id); // Gets an ax tree id from a frame id. AXTreeID GetAXTreeID(FrameID frame_id); // Retrieve an |AXActionHandlerBase| based on an ax tree id. AXActionHandlerBase* GetActionHandler(AXTreeID ax_tree_id); // Removes an ax tree id, and its associated delegate and frame id (if it // exists). void RemoveAXTreeID(AXTreeID ax_tree_id); // Associate a frame id with an ax tree id. void SetFrameIDForAXTreeID(const FrameID& frame_id, const AXTreeID& ax_tree_id); private: friend struct base::DefaultSingletonTraits<AXTreeIDRegistry>; friend AXActionHandler; friend AXActionHandlerBase; // Get or create a ax tree id keyed on |handler|. AXTreeID GetOrCreateAXTreeID(AXActionHandlerBase* handler); // Set a mapping between an AXTreeID and AXActionHandlerBase explicitly. void SetAXTreeID(const AXTreeID& ax_tree_id, AXActionHandlerBase* action_handler); AXTreeIDRegistry(); virtual ~AXTreeIDRegistry(); // Maps an accessibility tree to its frame via ids. std::map<AXTreeID, FrameID> ax_tree_to_frame_id_map_; // Maps frames to an accessibility tree via ids. std::map<FrameID, AXTreeID> frame_to_ax_tree_id_map_; // Maps an id to its handler. std::map<AXTreeID, AXActionHandlerBase*> id_to_action_handler_; BASE_DISALLOW_COPY_AND_ASSIGN(AXTreeIDRegistry); }; } // namespace ui #endif // UI_ACCESSIBILITY_AX_TREE_ID_REGISTRY_H_
engine/third_party/accessibility/ax/ax_tree_id_registry.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_tree_id_registry.h", "repo_id": "engine", "token_count": 922 }
436
// Copyright 2019 The Chromium 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 "ax_platform_node_base.h" #include "gtest/gtest.h" #include "base/string_utils.h" #include "test_ax_node_wrapper.h" namespace ui { namespace { void MakeStaticText(AXNodeData* node, int id, const std::string& text) { node->id = id; node->role = ax::mojom::Role::kStaticText; node->SetName(text); } void MakeGroup(AXNodeData* node, int id, std::vector<int> child_ids) { node->id = id; node->role = ax::mojom::Role::kGroup; node->child_ids = child_ids; } void SetIsInvisible(AXTree* tree, int id, bool invisible) { AXTreeUpdate update; update.nodes.resize(1); update.nodes[0] = tree->GetFromId(id)->data(); if (invisible) update.nodes[0].AddState(ax::mojom::State::kInvisible); else update.nodes[0].RemoveState(ax::mojom::State::kInvisible); tree->Unserialize(update); } void SetRole(AXTree* tree, int id, ax::mojom::Role role) { AXTreeUpdate update; update.nodes.resize(1); update.nodes[0] = tree->GetFromId(id)->data(); update.nodes[0].role = role; tree->Unserialize(update); } } // namespace TEST(AXPlatformNodeBaseTest, GetHypertext) { AXTreeUpdate update; // RootWebArea #1 // ++++StaticText "text1" #2 // ++++StaticText "text2" #3 // ++++StaticText "text3" #4 update.root_id = 1; update.nodes.resize(4); update.nodes[0].id = 1; update.nodes[0].role = ax::mojom::Role::kWebArea; update.nodes[0].child_ids = {2, 3, 4}; MakeStaticText(&update.nodes[1], 2, "text1"); MakeStaticText(&update.nodes[2], 3, "text2"); MakeStaticText(&update.nodes[3], 4, "text3"); AXTree tree(update); // Set an AXMode on the AXPlatformNode as some platforms (auralinux) use it to // determine if it should enable accessibility. AXPlatformNodeBase::NotifyAddAXModeFlags(kAXModeComplete); AXPlatformNodeBase* root = static_cast<AXPlatformNodeBase*>( TestAXNodeWrapper::GetOrCreate(&tree, tree.root())->ax_platform_node()); EXPECT_EQ(root->GetHypertext(), base::UTF8ToUTF16("text1text2text3")); AXPlatformNodeBase* text1 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(0))); EXPECT_EQ(text1->GetHypertext(), base::UTF8ToUTF16("text1")); AXPlatformNodeBase* text2 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(1))); EXPECT_EQ(text2->GetHypertext(), base::UTF8ToUTF16("text2")); AXPlatformNodeBase* text3 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(2))); EXPECT_EQ(text3->GetHypertext(), base::UTF8ToUTF16("text3")); } TEST(AXPlatformNodeBaseTest, GetHypertextIgnoredContainerSiblings) { AXTreeUpdate update; // RootWebArea #1 // ++genericContainer IGNORED #2 // ++++StaticText "text1" #3 // ++genericContainer IGNORED #4 // ++++StaticText "text2" #5 // ++genericContainer IGNORED #6 // ++++StaticText "text3" #7 update.root_id = 1; update.nodes.resize(7); update.nodes[0].id = 1; update.nodes[0].role = ax::mojom::Role::kWebArea; update.nodes[0].child_ids = {2, 4, 6}; update.nodes[1].id = 2; update.nodes[1].child_ids = {3}; update.nodes[1].role = ax::mojom::Role::kGenericContainer; update.nodes[1].AddState(ax::mojom::State::kIgnored); MakeStaticText(&update.nodes[2], 3, "text1"); update.nodes[3].id = 4; update.nodes[3].child_ids = {5}; update.nodes[3].role = ax::mojom::Role::kGenericContainer; update.nodes[3].AddState(ax::mojom::State::kIgnored); MakeStaticText(&update.nodes[4], 5, "text2"); update.nodes[5].id = 6; update.nodes[5].child_ids = {7}; update.nodes[5].role = ax::mojom::Role::kGenericContainer; update.nodes[5].AddState(ax::mojom::State::kIgnored); MakeStaticText(&update.nodes[6], 7, "text3"); AXTree tree(update); // Set an AXMode on the AXPlatformNode as some platforms (auralinux) use it to // determine if it should enable accessibility. AXPlatformNodeBase::NotifyAddAXModeFlags(kAXModeComplete); AXPlatformNodeBase* root = static_cast<AXPlatformNodeBase*>( TestAXNodeWrapper::GetOrCreate(&tree, tree.root())->ax_platform_node()); EXPECT_EQ(root->GetHypertext(), base::UTF8ToUTF16("text1text2text3")); AXPlatformNodeBase* text1_ignored_container = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(0))); EXPECT_EQ(text1_ignored_container->GetHypertext(), base::UTF8ToUTF16("text1")); AXPlatformNodeBase* text2_ignored_container = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(1))); EXPECT_EQ(text2_ignored_container->GetHypertext(), base::UTF8ToUTF16("text2")); AXPlatformNodeBase* text3_ignored_container = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(2))); EXPECT_EQ(text3_ignored_container->GetHypertext(), base::UTF8ToUTF16("text3")); } TEST(AXPlatformNodeBaseTest, InnerTextIgnoresInvisibleAndIgnored) { AXTreeUpdate update; update.root_id = 1; update.nodes.resize(6); MakeStaticText(&update.nodes[1], 2, "a"); MakeStaticText(&update.nodes[2], 3, "b"); MakeStaticText(&update.nodes[4], 5, "d"); MakeStaticText(&update.nodes[5], 6, "e"); MakeGroup(&update.nodes[3], 4, {5, 6}); MakeGroup(&update.nodes[0], 1, {2, 3, 4}); AXTree tree(update); auto* root = static_cast<AXPlatformNodeBase*>( TestAXNodeWrapper::GetOrCreate(&tree, tree.root())->ax_platform_node()); // Set an AXMode on the AXPlatformNode as some platforms (auralinux) use it to // determine if it should enable accessibility. AXPlatformNodeBase::NotifyAddAXModeFlags(kAXModeComplete); EXPECT_EQ(root->GetInnerText(), base::UTF8ToUTF16("abde")); // Setting invisible or ignored on a static text node causes it to be included // or excluded from the root node's inner text: { SetIsInvisible(&tree, 2, true); EXPECT_EQ(root->GetInnerText(), base::UTF8ToUTF16("bde")); SetIsInvisible(&tree, 2, false); EXPECT_EQ(root->GetInnerText(), base::UTF8ToUTF16("abde")); SetRole(&tree, 2, ax::mojom::Role::kIgnored); EXPECT_EQ(root->GetInnerText(), base::UTF8ToUTF16("bde")); SetRole(&tree, 2, ax::mojom::Role::kStaticText); EXPECT_EQ(root->GetInnerText(), base::UTF8ToUTF16("abde")); } // Setting invisible or ignored on a group node has no effect on the inner // text: { SetIsInvisible(&tree, 4, true); EXPECT_EQ(root->GetInnerText(), base::UTF8ToUTF16("abde")); SetRole(&tree, 4, ax::mojom::Role::kIgnored); EXPECT_EQ(root->GetInnerText(), base::UTF8ToUTF16("abde")); } } TEST(AXPlatformNodeBaseTest, TestSelectedChildren) { AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); AXNodeData root_data; root_data.id = 1; root_data.role = ax::mojom::Role::kListBox; root_data.AddState(ax::mojom::State::kFocusable); root_data.child_ids = {2, 3}; AXNodeData item_1_data; item_1_data.id = 2; item_1_data.role = ax::mojom::Role::kListBoxOption; item_1_data.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); AXNodeData item_2_data; item_2_data.id = 3; item_2_data.role = ax::mojom::Role::kListBoxOption; AXTreeUpdate update; update.root_id = 1; update.nodes = {root_data, item_1_data, item_2_data}; AXTree tree(update); auto* root = static_cast<AXPlatformNodeBase*>( TestAXNodeWrapper::GetOrCreate(&tree, tree.root())->ax_platform_node()); int num = root->GetSelectionCount(); EXPECT_EQ(num, 1); gfx::NativeViewAccessible first_child = root->ChildAtIndex(0); AXPlatformNodeBase* first_selected_node = root->GetSelectedItem(0); EXPECT_EQ(first_child, first_selected_node->GetNativeViewAccessible()); EXPECT_EQ(nullptr, root->GetSelectedItem(1)); } TEST(AXPlatformNodeBaseTest, TestSelectedChildrenWithGroup) { AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); AXNodeData root_data; root_data.id = 1; root_data.role = ax::mojom::Role::kListBox; root_data.AddState(ax::mojom::State::kFocusable); root_data.AddState(ax::mojom::State::kMultiselectable); root_data.child_ids = {2, 3}; AXNodeData group_1_data; group_1_data.id = 2; group_1_data.role = ax::mojom::Role::kGroup; group_1_data.child_ids = {4, 5}; AXNodeData group_2_data; group_2_data.id = 3; group_2_data.role = ax::mojom::Role::kGroup; group_2_data.child_ids = {6, 7}; AXNodeData item_1_data; item_1_data.id = 4; item_1_data.role = ax::mojom::Role::kListBoxOption; item_1_data.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); AXNodeData item_2_data; item_2_data.id = 5; item_2_data.role = ax::mojom::Role::kListBoxOption; AXNodeData item_3_data; item_3_data.id = 6; item_3_data.role = ax::mojom::Role::kListBoxOption; AXNodeData item_4_data; item_4_data.id = 7; item_4_data.role = ax::mojom::Role::kListBoxOption; item_4_data.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); AXTreeUpdate update; update.root_id = 1; update.nodes = {root_data, group_1_data, group_2_data, item_1_data, item_2_data, item_3_data, item_4_data}; AXTree tree(update); auto* root = static_cast<AXPlatformNodeBase*>( TestAXNodeWrapper::GetOrCreate(&tree, tree.root())->ax_platform_node()); int num = root->GetSelectionCount(); EXPECT_EQ(num, 2); gfx::NativeViewAccessible first_group_child = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(0))) ->ChildAtIndex(0); AXPlatformNodeBase* first_selected_node = root->GetSelectedItem(0); EXPECT_EQ(first_group_child, first_selected_node->GetNativeViewAccessible()); gfx::NativeViewAccessible second_group_child = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(1))) ->ChildAtIndex(1); AXPlatformNodeBase* second_selected_node = root->GetSelectedItem(1); EXPECT_EQ(second_group_child, second_selected_node->GetNativeViewAccessible()); } TEST(AXPlatformNodeBaseTest, TestSelectedChildrenMixed) { AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); // Build the below tree which is mixed with listBoxOption and group. // id=1 listBox FOCUSABLE MULTISELECTABLE (0, 0)-(0, 0) child_ids=2,3,4,9 // ++id=2 listBoxOption (0, 0)-(0, 0) selected=true // ++id=3 group (0, 0)-(0, 0) child_ids=5,6 // ++++id=5 listBoxOption (0, 0)-(0, 0) selected=true // ++++id=6 listBoxOption (0, 0)-(0, 0) // ++id=4 group (0, 0)-(0, 0) child_ids=7,8 // ++++id=7 listBoxOption (0, 0)-(0, 0) // ++++id=8 listBoxOption (0, 0)-(0, 0) selected=true // ++id=9 listBoxOption (0, 0)-(0, 0) selected=true AXNodeData root_data; root_data.id = 1; root_data.role = ax::mojom::Role::kListBox; root_data.AddState(ax::mojom::State::kFocusable); root_data.AddState(ax::mojom::State::kMultiselectable); root_data.child_ids = {2, 3, 4, 9}; AXNodeData item_1_data; item_1_data.id = 2; item_1_data.role = ax::mojom::Role::kListBoxOption; item_1_data.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); AXNodeData group_1_data; group_1_data.id = 3; group_1_data.role = ax::mojom::Role::kGroup; group_1_data.child_ids = {5, 6}; AXNodeData item_2_data; item_2_data.id = 5; item_2_data.role = ax::mojom::Role::kListBoxOption; item_2_data.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); AXNodeData item_3_data; item_3_data.id = 6; item_3_data.role = ax::mojom::Role::kListBoxOption; AXNodeData group_2_data; group_2_data.id = 4; group_2_data.role = ax::mojom::Role::kGroup; group_2_data.child_ids = {7, 8}; AXNodeData item_4_data; item_4_data.id = 7; item_4_data.role = ax::mojom::Role::kListBoxOption; AXNodeData item_5_data; item_5_data.id = 8; item_5_data.role = ax::mojom::Role::kListBoxOption; item_5_data.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); AXNodeData item_6_data; item_6_data.id = 9; item_6_data.role = ax::mojom::Role::kListBoxOption; item_6_data.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); AXTreeUpdate update; update.root_id = 1; update.nodes = {root_data, item_1_data, group_1_data, item_2_data, item_3_data, group_2_data, item_4_data, item_5_data, item_6_data}; AXTree tree(update); auto* root = static_cast<AXPlatformNodeBase*>( TestAXNodeWrapper::GetOrCreate(&tree, tree.root())->ax_platform_node()); int num = root->GetSelectionCount(); EXPECT_EQ(num, 4); gfx::NativeViewAccessible first_child = root->ChildAtIndex(0); AXPlatformNodeBase* first_selected_node = root->GetSelectedItem(0); EXPECT_EQ(first_child, first_selected_node->GetNativeViewAccessible()); gfx::NativeViewAccessible first_group_child = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(1))) ->ChildAtIndex(0); AXPlatformNodeBase* second_selected_node = root->GetSelectedItem(1); EXPECT_EQ(first_group_child, second_selected_node->GetNativeViewAccessible()); gfx::NativeViewAccessible second_group_child = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(root->ChildAtIndex(2))) ->ChildAtIndex(1); AXPlatformNodeBase* third_selected_node = root->GetSelectedItem(2); EXPECT_EQ(second_group_child, third_selected_node->GetNativeViewAccessible()); gfx::NativeViewAccessible fourth_child = root->ChildAtIndex(3); AXPlatformNodeBase* fourth_selected_node = root->GetSelectedItem(3); EXPECT_EQ(fourth_child, fourth_selected_node->GetNativeViewAccessible()); } TEST(AXPlatformNodeBaseTest, CompareTo) { // Compare the nodes' logical orders for the following tree. Node name is // denoted according to its id (i.e. "n#" is id#). Nodes that have smaller ids // are always logically less than nodes with bigger ids. // // n1 // | // __ n2 ___ // / \ \ // n3 _ n8 n9 // / \ \ \ // n4 n5 n6 n10 // / // n7 AXPlatformNode::NotifyAddAXModeFlags(kAXModeComplete); AXNodeData node1; node1.id = 1; node1.role = ax::mojom::Role::kWebArea; node1.child_ids = {2}; AXNodeData node2; node2.id = 2; node2.role = ax::mojom::Role::kStaticText; node2.child_ids = {3, 8, 9}; AXNodeData node3; node3.id = 3; node3.role = ax::mojom::Role::kStaticText; node3.child_ids = {4, 5, 6}; AXNodeData node4; node4.id = 4; node4.role = ax::mojom::Role::kStaticText; AXNodeData node5; node5.id = 5; node5.role = ax::mojom::Role::kStaticText; AXNodeData node6; node6.id = 6; node6.role = ax::mojom::Role::kStaticText; node6.child_ids = {7}; AXNodeData node7; node7.id = 7; node7.role = ax::mojom::Role::kStaticText; AXNodeData node8; node8.id = 8; node8.role = ax::mojom::Role::kStaticText; AXNodeData node9; node9.id = 9; node9.role = ax::mojom::Role::kStaticText; node9.child_ids = {10}; AXNodeData node10; node10.id = 10; node10.role = ax::mojom::Role::kStaticText; AXTreeUpdate update; update.root_id = 1; update.nodes = {node1, node2, node3, node4, node5, node6, node7, node8, node9, node10}; AXTree tree(update); // Retrieve the nodes in a level-order traversal way. auto* n1 = static_cast<AXPlatformNodeBase*>( TestAXNodeWrapper::GetOrCreate(&tree, tree.root())->ax_platform_node()); auto* n2 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(n1->ChildAtIndex(0))); auto* n3 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(n2->ChildAtIndex(0))); auto* n8 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(n2->ChildAtIndex(1))); auto* n9 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(n2->ChildAtIndex(2))); auto* n4 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(n3->ChildAtIndex(0))); auto* n5 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(n3->ChildAtIndex(1))); auto* n6 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(n3->ChildAtIndex(2))); auto* n10 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(n9->ChildAtIndex(0))); auto* n7 = static_cast<AXPlatformNodeBase*>( AXPlatformNode::FromNativeViewAccessible(n6->ChildAtIndex(0))); // Test for two nodes that do not share the same root. They should not be // comparable. AXPlatformNodeBase detached_node; EXPECT_EQ(std::nullopt, n1->CompareTo(detached_node)); // Create a test vector of all the tree nodes arranged in a pre-order // traversal way. The node that has a smaller index in the vector should also // be logically less (comes before) the nodes with bigger index. std::vector<AXPlatformNodeBase*> preorder_tree_nodes = {n1, n2, n3, n4, n5, n6, n7, n8, n9, n10}; // Test through all permutations of lhs/rhs comparisons of nodes from // |preorder_tree_nodes|. for (auto* lhs : preorder_tree_nodes) { for (auto* rhs : preorder_tree_nodes) { int expected_result = 0; if (lhs->GetData().id < rhs->GetData().id) expected_result = -1; else if (lhs->GetData().id > rhs->GetData().id) expected_result = 1; EXPECT_NE(std::nullopt, lhs->CompareTo(*rhs)); int actual_result = 0; if (lhs->CompareTo(*rhs) < 0) actual_result = -1; else if (lhs->CompareTo(*rhs) > 0) actual_result = 1; SCOPED_TRACE(testing::Message() << "lhs.id=" << base::NumberToString(lhs->GetData().id) << ", rhs.id=" << base::NumberToString(rhs->GetData().id) << ", lhs->CompareTo(*rhs)={actual:" << base::NumberToString(actual_result) << ", expected:" << base::NumberToString(expected_result) << "}"); EXPECT_EQ(expected_result, actual_result); } } } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_platform_node_base_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_base_unittest.cc", "repo_id": "engine", "token_count": 7355 }
437
// Copyright 2017 The Chromium 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 "ax_platform_node_unittest.h" #include "ax/ax_constants.h" #include "test_ax_node_wrapper.h" namespace ui { AXPlatformNodeTest::AXPlatformNodeTest() = default; AXPlatformNodeTest::~AXPlatformNodeTest() = default; void AXPlatformNodeTest::Init(const AXTreeUpdate& initial_state) { SetTree(std::make_unique<AXTree>(initial_state)); } void AXPlatformNodeTest::Init( const ui::AXNodeData& node1, const ui::AXNodeData& node2 /* = ui::AXNodeData() */, const ui::AXNodeData& node3 /* = ui::AXNodeData() */, const ui::AXNodeData& node4 /* = ui::AXNodeData() */, const ui::AXNodeData& node5 /* = ui::AXNodeData() */, const ui::AXNodeData& node6 /* = ui::AXNodeData() */, const ui::AXNodeData& node7 /* = ui::AXNodeData() */, const ui::AXNodeData& node8 /* = ui::AXNodeData() */, const ui::AXNodeData& node9 /* = ui::AXNodeData() */, const ui::AXNodeData& node10 /* = ui::AXNodeData() */, const ui::AXNodeData& node11 /* = ui::AXNodeData() */, const ui::AXNodeData& node12 /* = ui::AXNodeData() */) { static ui::AXNodeData empty_data; int32_t no_id = empty_data.id; AXTreeUpdate update; update.root_id = node1.id; update.nodes.push_back(node1); if (node2.id != no_id) update.nodes.push_back(node2); if (node3.id != no_id) update.nodes.push_back(node3); if (node4.id != no_id) update.nodes.push_back(node4); if (node5.id != no_id) update.nodes.push_back(node5); if (node6.id != no_id) update.nodes.push_back(node6); if (node7.id != no_id) update.nodes.push_back(node7); if (node8.id != no_id) update.nodes.push_back(node8); if (node9.id != no_id) update.nodes.push_back(node9); if (node10.id != no_id) update.nodes.push_back(node10); if (node11.id != no_id) update.nodes.push_back(node11); if (node12.id != no_id) update.nodes.push_back(node12); Init(update); } AXTreeUpdate AXPlatformNodeTest::BuildTextField() { AXNodeData text_field_node; text_field_node.id = 1; text_field_node.role = ax::mojom::Role::kTextField; text_field_node.AddState(ax::mojom::State::kEditable); text_field_node.SetValue("How now brown cow."); AXTreeUpdate update; update.root_id = text_field_node.id; update.nodes.push_back(text_field_node); return update; } AXTreeUpdate AXPlatformNodeTest::BuildTextFieldWithSelectionRange( int32_t start, int32_t stop) { AXNodeData text_field_node; text_field_node.id = 1; text_field_node.role = ax::mojom::Role::kTextField; text_field_node.AddState(ax::mojom::State::kEditable); text_field_node.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); text_field_node.AddIntAttribute(ax::mojom::IntAttribute::kTextSelStart, start); text_field_node.AddIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, stop); text_field_node.SetValue("How now brown cow."); AXTreeUpdate update; update.root_id = text_field_node.id; update.nodes.push_back(text_field_node); return update; } AXTreeUpdate AXPlatformNodeTest::BuildContentEditable() { AXNodeData content_editable_node; content_editable_node.id = 1; content_editable_node.role = ax::mojom::Role::kGroup; content_editable_node.AddState(ax::mojom::State::kRichlyEditable); content_editable_node.AddBoolAttribute( ax::mojom::BoolAttribute::kEditableRoot, true); content_editable_node.SetValue("How now brown cow."); AXTreeUpdate update; update.root_id = content_editable_node.id; update.nodes.push_back(content_editable_node); return update; } AXTreeUpdate AXPlatformNodeTest::BuildContentEditableWithSelectionRange( int32_t start, int32_t end) { AXNodeData content_editable_node; content_editable_node.id = 1; content_editable_node.role = ax::mojom::Role::kGroup; content_editable_node.AddState(ax::mojom::State::kRichlyEditable); content_editable_node.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); content_editable_node.AddBoolAttribute( ax::mojom::BoolAttribute::kEditableRoot, true); content_editable_node.SetValue("How now brown cow."); AXTreeUpdate update; update.root_id = content_editable_node.id; update.nodes.push_back(content_editable_node); update.has_tree_data = true; update.tree_data.sel_anchor_object_id = content_editable_node.id; update.tree_data.sel_focus_object_id = content_editable_node.id; update.tree_data.sel_anchor_offset = start; update.tree_data.sel_focus_offset = end; return update; } AXTreeUpdate AXPlatformNodeTest::AXPlatformNodeTest::Build3X3Table() { /* Build a table that looks like: ---------------------- (A) Column Header | | (A) | (B) | (B) Column Header ---------------------- (C) Row Header | (C) | 1 | 2 | (D) Row Header ---------------------- | (D) | 3 | 4 | ---------------------- */ AXNodeData table; table.id = 1; table.role = ax::mojom::Role::kTable; table.AddIntAttribute(ax::mojom::IntAttribute::kTableRowCount, 3); table.AddIntAttribute(ax::mojom::IntAttribute::kTableColumnCount, 3); table.child_ids.push_back(50); // Header table.child_ids.push_back(2); // Row 1 table.child_ids.push_back(10); // Row 2 // Table column header AXNodeData table_row_header; table_row_header.id = 50; table_row_header.role = ax::mojom::Role::kRow; table_row_header.child_ids.push_back(51); table_row_header.child_ids.push_back(52); table_row_header.child_ids.push_back(53); AXNodeData table_column_header_1; table_column_header_1.id = 51; table_column_header_1.role = ax::mojom::Role::kColumnHeader; table_column_header_1.AddIntAttribute( ax::mojom::IntAttribute::kTableCellRowIndex, 0); table_column_header_1.AddIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex, 0); AXNodeData table_column_header_2; table_column_header_2.id = 52; table_column_header_2.role = ax::mojom::Role::kColumnHeader; table_column_header_2.SetName("column header 1"); table_column_header_2.AddIntAttribute( ax::mojom::IntAttribute::kTableCellRowIndex, 0); table_column_header_2.AddIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex, 1); AXNodeData table_column_header_3; table_column_header_3.id = 53; table_column_header_3.role = ax::mojom::Role::kColumnHeader; // Either ax::mojom::StringAttribute::kName -or- // ax::mojom::StringAttribute::kDescription is acceptable for a description table_column_header_3.AddStringAttribute( ax::mojom::StringAttribute::kDescription, "column header 2"); table_column_header_3.AddIntAttribute( ax::mojom::IntAttribute::kTableCellRowIndex, 0); table_column_header_3.AddIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex, 2); // Row 1 AXNodeData table_row_1; table_row_1.id = 2; table_row_1.role = ax::mojom::Role::kRow; AXNodeData table_row_header_1; table_row_header_1.id = 3; table_row_header_1.role = ax::mojom::Role::kRowHeader; table_row_header_1.SetName("row header 1"); table_row_header_1.AddIntAttribute( ax::mojom::IntAttribute::kTableCellRowIndex, 1); table_row_header_1.AddIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex, 0); table_row_1.child_ids.push_back(table_row_header_1.id); AXNodeData table_cell_1; table_cell_1.id = 4; table_cell_1.role = ax::mojom::Role::kCell; table_cell_1.SetName("1"); table_cell_1.AddIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex, 1); table_cell_1.AddIntAttribute(ax::mojom::IntAttribute::kTableCellColumnIndex, 1); table_row_1.child_ids.push_back(table_cell_1.id); AXNodeData table_cell_2; table_cell_2.id = 5; table_cell_2.role = ax::mojom::Role::kCell; table_cell_2.SetName("2"); table_cell_2.AddIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex, 1); table_cell_2.AddIntAttribute(ax::mojom::IntAttribute::kTableCellColumnIndex, 2); table_row_1.child_ids.push_back(table_cell_2.id); // Row 2 AXNodeData table_row_2; table_row_2.id = 10; table_row_2.role = ax::mojom::Role::kRow; AXNodeData table_row_header_2; table_row_header_2.id = 11; table_row_header_2.role = ax::mojom::Role::kRowHeader; // Either ax::mojom::StringAttribute::kName -or- // ax::mojom::StringAttribute::kDescription is acceptable for a description table_row_header_2.AddStringAttribute( ax::mojom::StringAttribute::kDescription, "row header 2"); table_row_header_2.AddIntAttribute( ax::mojom::IntAttribute::kTableCellRowIndex, 2); table_row_header_2.AddIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex, 0); table_row_2.child_ids.push_back(table_row_header_2.id); AXNodeData table_cell_3; table_cell_3.id = 12; table_cell_3.role = ax::mojom::Role::kCell; table_cell_3.SetName("3"); table_cell_3.AddIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex, 2); table_cell_3.AddIntAttribute(ax::mojom::IntAttribute::kTableCellColumnIndex, 1); table_row_2.child_ids.push_back(table_cell_3.id); AXNodeData table_cell_4; table_cell_4.id = 13; table_cell_4.role = ax::mojom::Role::kCell; table_cell_4.SetName("4"); table_cell_4.AddIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex, 2); table_cell_4.AddIntAttribute(ax::mojom::IntAttribute::kTableCellColumnIndex, 2); table_row_2.child_ids.push_back(table_cell_4.id); AXTreeUpdate update; update.root_id = table.id; // Some of the table testing code will index into |nodes| // and change the state of the given node. If you reorder // these, you're going to need to update the tests. update.nodes.push_back(table); // 0 update.nodes.push_back(table_row_header); // 1 update.nodes.push_back(table_column_header_1); // 2 update.nodes.push_back(table_column_header_2); // 3 update.nodes.push_back(table_column_header_3); // 4 update.nodes.push_back(table_row_1); // 5 update.nodes.push_back(table_row_header_1); // 6 update.nodes.push_back(table_cell_1); // 7 update.nodes.push_back(table_cell_2); // 8 update.nodes.push_back(table_row_2); // 9 update.nodes.push_back(table_row_header_2); // 10 update.nodes.push_back(table_cell_3); // 11 update.nodes.push_back(table_cell_4); // 12 return update; } AXTreeUpdate AXPlatformNodeTest::BuildAriaColumnAndRowCountGrids() { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kNone; // Empty Grid AXNodeData empty_grid; empty_grid.id = 2; empty_grid.role = ax::mojom::Role::kGrid; root.child_ids.push_back(empty_grid.id); // Grid with a cell that defines aria-rowindex (4) and aria-colindex (5) AXNodeData rowcolindex_grid; rowcolindex_grid.id = 3; rowcolindex_grid.role = ax::mojom::Role::kGrid; root.child_ids.push_back(rowcolindex_grid.id); AXNodeData rowcolindex_row; rowcolindex_row.id = 4; rowcolindex_row.role = ax::mojom::Role::kRow; rowcolindex_grid.child_ids.push_back(rowcolindex_row.id); AXNodeData rowcolindex_cell; rowcolindex_cell.id = 5; rowcolindex_cell.role = ax::mojom::Role::kCell; rowcolindex_cell.AddIntAttribute( ax::mojom::IntAttribute::kAriaCellColumnIndex, 5); rowcolindex_cell.AddIntAttribute(ax::mojom::IntAttribute::kAriaCellRowIndex, 4); rowcolindex_row.child_ids.push_back(rowcolindex_cell.id); // Grid that specifies aria-rowcount (2) and aria-colcount (3) AXNodeData rowcolcount_grid; rowcolcount_grid.id = 6; rowcolcount_grid.role = ax::mojom::Role::kGrid; rowcolcount_grid.AddIntAttribute(ax::mojom::IntAttribute::kAriaRowCount, 2); rowcolcount_grid.AddIntAttribute(ax::mojom::IntAttribute::kAriaColumnCount, 3); root.child_ids.push_back(rowcolcount_grid.id); // Grid that specifies aria-rowcount and aria-colcount are (-1) // ax::mojom::kUnknownAriaColumnOrRowCount AXNodeData unknown_grid; unknown_grid.id = 7; unknown_grid.role = ax::mojom::Role::kGrid; unknown_grid.AddIntAttribute(ax::mojom::IntAttribute::kAriaRowCount, ax::mojom::kUnknownAriaColumnOrRowCount); unknown_grid.AddIntAttribute(ax::mojom::IntAttribute::kAriaColumnCount, ax::mojom::kUnknownAriaColumnOrRowCount); root.child_ids.push_back(unknown_grid.id); AXTreeUpdate update; update.root_id = root.id; update.nodes.push_back(root); update.nodes.push_back(empty_grid); update.nodes.push_back(rowcolindex_grid); update.nodes.push_back(rowcolindex_row); update.nodes.push_back(rowcolindex_cell); update.nodes.push_back(rowcolcount_grid); update.nodes.push_back(unknown_grid); return update; } AXTreeUpdate AXPlatformNodeTest::BuildListBox( bool option_1_is_selected, bool option_2_is_selected, bool option_3_is_selected, const std::vector<ax::mojom::State>& additional_state) { AXNodeData listbox; listbox.id = 1; listbox.role = ax::mojom::Role::kListBox; listbox.SetName("ListBox"); for (auto state : additional_state) listbox.AddState(state); AXNodeData option_1; option_1.id = 2; option_1.role = ax::mojom::Role::kListBoxOption; option_1.SetName("Option1"); if (option_1_is_selected) option_1.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); listbox.child_ids.push_back(option_1.id); AXNodeData option_2; option_2.id = 3; option_2.role = ax::mojom::Role::kListBoxOption; option_2.SetName("Option2"); if (option_2_is_selected) option_2.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); listbox.child_ids.push_back(option_2.id); AXNodeData option_3; option_3.id = 4; option_3.role = ax::mojom::Role::kListBoxOption; option_3.SetName("Option3"); if (option_3_is_selected) option_3.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); listbox.child_ids.push_back(option_3.id); AXTreeUpdate update; update.root_id = listbox.id; update.nodes.push_back(listbox); update.nodes.push_back(option_1); update.nodes.push_back(option_2); update.nodes.push_back(option_3); return update; } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_platform_node_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_unittest.cc", "repo_id": "engine", "token_count": 5886 }
438
// Copyright 2020 The Chromium 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 "uia_registrar_win.h" #include <wrl/implements.h> namespace ui { UiaRegistrarWin::UiaRegistrarWin() { // Create the registrar object and get the IUIAutomationRegistrar // interface pointer. Microsoft::WRL::ComPtr<IUIAutomationRegistrar> registrar; if (FAILED(CoCreateInstance(CLSID_CUIAutomationRegistrar, nullptr, CLSCTX_INPROC_SERVER, IID_IUIAutomationRegistrar, &registrar))) return; // Register the custom UIA property that represents the unique id of an UIA // element which also matches its corresponding IA2 element's unique id. UIAutomationPropertyInfo unique_id_property_info = { kUiaPropertyUniqueIdGuid, L"UniqueId", UIAutomationType_String}; registrar->RegisterProperty(&unique_id_property_info, &uia_unique_id_property_id_); // Register the custom UIA event that represents the test end event for the // UIA test suite. UIAutomationEventInfo test_complete_event_info = { kUiaEventTestCompleteSentinelGuid, L"kUiaTestCompleteSentinel"}; registrar->RegisterEvent(&test_complete_event_info, &uia_test_complete_event_id_); } UiaRegistrarWin::~UiaRegistrarWin() = default; PROPERTYID UiaRegistrarWin::GetUiaUniqueIdPropertyId() const { return uia_unique_id_property_id_; } EVENTID UiaRegistrarWin::GetUiaTestCompleteEventId() const { return uia_test_complete_event_id_; } const UiaRegistrarWin& UiaRegistrarWin::GetInstance() { static base::NoDestructor<UiaRegistrarWin> instance; return *instance; } } // namespace ui
engine/third_party/accessibility/ax/platform/uia_registrar_win.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/uia_registrar_win.cc", "repo_id": "engine", "token_count": 687 }
439
// 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 "gtest/gtest.h" #include "logging.h" namespace base { namespace testing { int UnreachableScopeWithoutReturnDoesNotMakeCompilerMad() { KillProcess(); // return 0; <--- Missing but compiler is fine. } int UnreachableScopeWithMacroWithoutReturnDoesNotMakeCompilerMad() { BASE_UNREACHABLE(); // return 0; <--- Missing but compiler is fine. } TEST(LoggingTest, UnreachableKillProcess) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; ASSERT_DEATH(KillProcess(), ""); } TEST(LoggingTest, UnreachableKillProcessWithMacro) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; ASSERT_DEATH({ BASE_UNREACHABLE(); }, ""); } } // namespace testing } // namespace base
engine/third_party/accessibility/base/logging_unittests.cc/0
{ "file_path": "engine/third_party/accessibility/base/logging_unittests.cc", "repo_id": "engine", "token_count": 282 }
440
// Copyright 2017 The Chromium 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 BASE_NUMERICS_SAFE_MATH_CLANG_GCC_IMPL_H_ #define BASE_NUMERICS_SAFE_MATH_CLANG_GCC_IMPL_H_ #include <cassert> #include <limits> #include <type_traits> #include "base/numerics/safe_conversions.h" #if !defined(__native_client__) && (defined(__ARMEL__) || defined(__arch64__)) #include "base/numerics/safe_math_arm_impl.h" #define BASE_HAS_ASSEMBLER_SAFE_MATH (1) #else #define BASE_HAS_ASSEMBLER_SAFE_MATH (0) #endif namespace base { namespace internal { // These are the non-functioning boilerplate implementations of the optimized // safe math routines. #if !BASE_HAS_ASSEMBLER_SAFE_MATH template <typename T, typename U> struct CheckedMulFastAsmOp { static const bool is_supported = false; template <typename V> static constexpr bool Do(T, U, V*) { // Force a compile failure if instantiated. return CheckOnFailure::template HandleFailure<bool>(); } }; template <typename T, typename U> struct ClampedAddFastAsmOp { static const bool is_supported = false; template <typename V> static constexpr V Do(T, U) { // Force a compile failure if instantiated. return CheckOnFailure::template HandleFailure<V>(); } }; template <typename T, typename U> struct ClampedSubFastAsmOp { static const bool is_supported = false; template <typename V> static constexpr V Do(T, U) { // Force a compile failure if instantiated. return CheckOnFailure::template HandleFailure<V>(); } }; template <typename T, typename U> struct ClampedMulFastAsmOp { static const bool is_supported = false; template <typename V> static constexpr V Do(T, U) { // Force a compile failure if instantiated. return CheckOnFailure::template HandleFailure<V>(); } }; #endif // BASE_HAS_ASSEMBLER_SAFE_MATH #undef BASE_HAS_ASSEMBLER_SAFE_MATH template <typename T, typename U> struct CheckedAddFastOp { static const bool is_supported = true; template <typename V> __attribute__((always_inline)) static constexpr bool Do(T x, U y, V* result) { return !__builtin_add_overflow(x, y, result); } }; template <typename T, typename U> struct CheckedSubFastOp { static const bool is_supported = true; template <typename V> __attribute__((always_inline)) static constexpr bool Do(T x, U y, V* result) { return !__builtin_sub_overflow(x, y, result); } }; template <typename T, typename U> struct CheckedMulFastOp { #if defined(__clang__) // TODO(jschuh): Get the Clang runtime library issues sorted out so we can // support full-width, mixed-sign multiply builtins. // https://crbug.com/613003 // We can support intptr_t, uintptr_t, or a smaller common type. static const bool is_supported = (IsTypeInRangeForNumericType<intptr_t, T>::value && IsTypeInRangeForNumericType<intptr_t, U>::value) || (IsTypeInRangeForNumericType<uintptr_t, T>::value && IsTypeInRangeForNumericType<uintptr_t, U>::value); #else static const bool is_supported = true; #endif template <typename V> __attribute__((always_inline)) static constexpr bool Do(T x, U y, V* result) { return CheckedMulFastAsmOp<T, U>::is_supported ? CheckedMulFastAsmOp<T, U>::Do(x, y, result) : !__builtin_mul_overflow(x, y, result); } }; template <typename T, typename U> struct ClampedAddFastOp { static const bool is_supported = ClampedAddFastAsmOp<T, U>::is_supported; template <typename V> __attribute__((always_inline)) static V Do(T x, U y) { return ClampedAddFastAsmOp<T, U>::template Do<V>(x, y); } }; template <typename T, typename U> struct ClampedSubFastOp { static const bool is_supported = ClampedSubFastAsmOp<T, U>::is_supported; template <typename V> __attribute__((always_inline)) static V Do(T x, U y) { return ClampedSubFastAsmOp<T, U>::template Do<V>(x, y); } }; template <typename T, typename U> struct ClampedMulFastOp { static const bool is_supported = ClampedMulFastAsmOp<T, U>::is_supported; template <typename V> __attribute__((always_inline)) static V Do(T x, U y) { return ClampedMulFastAsmOp<T, U>::template Do<V>(x, y); } }; template <typename T> struct ClampedNegFastOp { static const bool is_supported = std::is_signed<T>::value; __attribute__((always_inline)) static T Do(T value) { // Use this when there is no assembler path available. if (!ClampedSubFastAsmOp<T, T>::is_supported) { T result; return !__builtin_sub_overflow(T(0), value, &result) ? result : std::numeric_limits<T>::max(); } // Fallback to the normal subtraction path. return ClampedSubFastOp<T, T>::template Do<T>(T(0), value); } }; } // namespace internal } // namespace base #endif // BASE_NUMERICS_SAFE_MATH_CLANG_GCC_IMPL_H_
engine/third_party/accessibility/base/numerics/safe_math_clang_gcc_impl.h/0
{ "file_path": "engine/third_party/accessibility/base/numerics/safe_math_clang_gcc_impl.h", "repo_id": "engine", "token_count": 1848 }
441
// Copyright (c) 2011 The Chromium 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 "base/win/display.h" #include "gtest/gtest.h" namespace base { namespace win { TEST(Display, ScaleFactorToFloat) { EXPECT_EQ(ScaleFactorToFloat(SCALE_100_PERCENT), 1.00f); EXPECT_EQ(ScaleFactorToFloat(SCALE_120_PERCENT), 1.20f); EXPECT_EQ(ScaleFactorToFloat(SCALE_125_PERCENT), 1.25f); EXPECT_EQ(ScaleFactorToFloat(SCALE_140_PERCENT), 1.40f); EXPECT_EQ(ScaleFactorToFloat(SCALE_150_PERCENT), 1.50f); EXPECT_EQ(ScaleFactorToFloat(SCALE_160_PERCENT), 1.60f); EXPECT_EQ(ScaleFactorToFloat(SCALE_175_PERCENT), 1.75f); EXPECT_EQ(ScaleFactorToFloat(SCALE_180_PERCENT), 1.80f); EXPECT_EQ(ScaleFactorToFloat(SCALE_200_PERCENT), 2.00f); EXPECT_EQ(ScaleFactorToFloat(SCALE_225_PERCENT), 2.25f); EXPECT_EQ(ScaleFactorToFloat(SCALE_250_PERCENT), 2.50f); EXPECT_EQ(ScaleFactorToFloat(SCALE_350_PERCENT), 3.50f); EXPECT_EQ(ScaleFactorToFloat(SCALE_400_PERCENT), 4.00f); EXPECT_EQ(ScaleFactorToFloat(SCALE_450_PERCENT), 4.50f); EXPECT_EQ(ScaleFactorToFloat(SCALE_500_PERCENT), 5.00f); EXPECT_EQ(ScaleFactorToFloat(DEVICE_SCALE_FACTOR_INVALID), 1.0f); } } // namespace win } // namespace base
engine/third_party/accessibility/base/win/display_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/base/win/display_unittest.cc", "repo_id": "engine", "token_count": 531 }
442
// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file contains defines and typedefs that allow popular Windows types to // be used without the overhead of including windows.h. #ifndef BASE_WIN_WINDOWS_TYPES_H_ #define BASE_WIN_WINDOWS_TYPES_H_ // Needed for function prototypes. #include <concurrencysal.h> #include <sal.h> #include <specstrings.h> #ifdef __cplusplus extern "C" { #endif // typedef and define the most commonly used Windows integer types. typedef unsigned long DWORD; typedef long LONG; typedef __int64 LONGLONG; typedef unsigned __int64 ULONGLONG; #define VOID void typedef char CHAR; typedef short SHORT; typedef long LONG; typedef int INT; typedef unsigned int UINT; typedef unsigned int* PUINT; typedef void* LPVOID; typedef void* PVOID; typedef void* HANDLE; typedef int BOOL; typedef unsigned char BYTE; typedef BYTE BOOLEAN; typedef DWORD ULONG; typedef unsigned short WORD; typedef WORD UWORD; typedef WORD ATOM; #if defined(_WIN64) typedef __int64 INT_PTR, *PINT_PTR; typedef unsigned __int64 UINT_PTR, *PUINT_PTR; typedef __int64 LONG_PTR, *PLONG_PTR; typedef unsigned __int64 ULONG_PTR, *PULONG_PTR; #else typedef __w64 int INT_PTR, *PINT_PTR; typedef __w64 unsigned int UINT_PTR, *PUINT_PTR; typedef __w64 long LONG_PTR, *PLONG_PTR; typedef __w64 unsigned long ULONG_PTR, *PULONG_PTR; #endif typedef UINT_PTR WPARAM; typedef LONG_PTR LPARAM; typedef LONG_PTR LRESULT; #define LRESULT LONG_PTR typedef _Return_type_success_(return >= 0) long HRESULT; typedef ULONG_PTR SIZE_T, *PSIZE_T; typedef LONG_PTR SSIZE_T, *PSSIZE_T; typedef DWORD ACCESS_MASK; typedef ACCESS_MASK REGSAM; typedef LONG NTSTATUS; // As defined in guiddef.h. #ifndef _REFGUID_DEFINED #define _REFGUID_DEFINED #define REFGUID const GUID& #endif // Forward declare Windows compatible handles. #define CHROME_DECLARE_HANDLE(name) \ struct name##__; \ typedef struct name##__* name CHROME_DECLARE_HANDLE(HDESK); CHROME_DECLARE_HANDLE(HGLRC); CHROME_DECLARE_HANDLE(HICON); CHROME_DECLARE_HANDLE(HINSTANCE); CHROME_DECLARE_HANDLE(HKEY); CHROME_DECLARE_HANDLE(HKL); CHROME_DECLARE_HANDLE(HMENU); CHROME_DECLARE_HANDLE(HWINSTA); CHROME_DECLARE_HANDLE(HWND); #undef CHROME_DECLARE_HANDLE typedef LPVOID HINTERNET; typedef HINSTANCE HMODULE; typedef PVOID LSA_HANDLE; typedef PVOID HDEVINFO; // Forward declare some Windows struct/typedef sets. typedef struct _OVERLAPPED OVERLAPPED; typedef struct tagMSG MSG, *PMSG, *NPMSG, *LPMSG; typedef struct _RTL_SRWLOCK RTL_SRWLOCK; typedef RTL_SRWLOCK SRWLOCK, *PSRWLOCK; typedef struct _GUID GUID; typedef GUID CLSID; typedef struct tagLOGFONTW LOGFONTW, *PLOGFONTW, *NPLOGFONTW, *LPLOGFONTW; typedef LOGFONTW LOGFONT; typedef struct _FILETIME FILETIME; typedef struct tagMENUITEMINFOW MENUITEMINFOW, MENUITEMINFO; typedef struct tagNMHDR NMHDR; typedef struct _SP_DEVINFO_DATA SP_DEVINFO_DATA; typedef PVOID PSID; // Declare Chrome versions of some Windows structures. These are needed for // when we need a concrete type but don't want to pull in Windows.h. We can't // declare the Windows types so we declare our types and cast to the Windows // types in a few places. struct CHROME_SRWLOCK { PVOID Ptr; }; struct CHROME_CONDITION_VARIABLE { PVOID Ptr; }; // Define some commonly used Windows constants. Note that the layout of these // macros - including internal spacing - must be 100% consistent with windows.h. // clang-format off #ifndef INVALID_HANDLE_VALUE // Work around there being two slightly different definitions in the SDK. #define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1) #endif #define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF) #define HTNOWHERE 0 #define MAX_PATH 260 #define CS_GLOBALCLASS 0x4000 #define ERROR_SUCCESS 0L #define ERROR_FILE_NOT_FOUND 2L #define ERROR_ACCESS_DENIED 5L #define ERROR_INVALID_HANDLE 6L #define ERROR_SHARING_VIOLATION 32L #define ERROR_LOCK_VIOLATION 33L #define REG_BINARY ( 3ul ) #define STATUS_PENDING ((DWORD )0x00000103L) #define STILL_ACTIVE STATUS_PENDING #define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0) #define FAILED(hr) (((HRESULT)(hr)) < 0) #define HKEY_CLASSES_ROOT (( HKEY ) (ULONG_PTR)((LONG)0x80000000) ) #define HKEY_LOCAL_MACHINE (( HKEY ) (ULONG_PTR)((LONG)0x80000002) ) #define HKEY_CURRENT_USER (( HKEY ) (ULONG_PTR)((LONG)0x80000001) ) #define KEY_QUERY_VALUE (0x0001) #define KEY_SET_VALUE (0x0002) #define KEY_CREATE_SUB_KEY (0x0004) #define KEY_ENUMERATE_SUB_KEYS (0x0008) #define KEY_NOTIFY (0x0010) #define KEY_CREATE_LINK (0x0020) #define KEY_WOW64_32KEY (0x0200) #define KEY_WOW64_64KEY (0x0100) #define KEY_WOW64_RES (0x0300) #define READ_CONTROL (0x00020000L) #define SYNCHRONIZE (0x00100000L) #define STANDARD_RIGHTS_READ (READ_CONTROL) #define STANDARD_RIGHTS_WRITE (READ_CONTROL) #define STANDARD_RIGHTS_ALL (0x001F0000L) #define KEY_READ ((STANDARD_RIGHTS_READ |\ KEY_QUERY_VALUE |\ KEY_ENUMERATE_SUB_KEYS |\ KEY_NOTIFY) \ & \ (~SYNCHRONIZE)) #define KEY_WRITE ((STANDARD_RIGHTS_WRITE |\ KEY_SET_VALUE |\ KEY_CREATE_SUB_KEY) \ & \ (~SYNCHRONIZE)) #define KEY_ALL_ACCESS ((STANDARD_RIGHTS_ALL |\ KEY_QUERY_VALUE |\ KEY_SET_VALUE |\ KEY_CREATE_SUB_KEY |\ KEY_ENUMERATE_SUB_KEYS |\ KEY_NOTIFY |\ KEY_CREATE_LINK) \ & \ (~SYNCHRONIZE)) // clang-format on // Define some macros needed when prototyping Windows functions. #define DECLSPEC_IMPORT __declspec(dllimport) #define WINBASEAPI DECLSPEC_IMPORT #define WINUSERAPI DECLSPEC_IMPORT #define WINAPI __stdcall #define CALLBACK __stdcall // Needed for LockImpl. WINBASEAPI _Releases_exclusive_lock_(*SRWLock) VOID WINAPI ReleaseSRWLockExclusive(_Inout_ PSRWLOCK SRWLock); WINBASEAPI BOOLEAN WINAPI TryAcquireSRWLockExclusive(_Inout_ PSRWLOCK SRWLock); // Needed to support protobuf's GetMessage macro magic. WINUSERAPI BOOL WINAPI GetMessageW(_Out_ LPMSG lpMsg, _In_opt_ HWND hWnd, _In_ UINT wMsgFilterMin, _In_ UINT wMsgFilterMax); // Needed for thread_local_storage.h WINBASEAPI LPVOID WINAPI TlsGetValue(_In_ DWORD dwTlsIndex); // Needed for scoped_handle.h WINBASEAPI _Check_return_ _Post_equals_last_error_ DWORD WINAPI GetLastError(VOID); WINBASEAPI VOID WINAPI SetLastError(_In_ DWORD dwErrCode); #ifdef __cplusplus } #endif // These macros are all defined by windows.h and are also used as the names of // functions in the Chromium code base. Add to this list as needed whenever // there is a Windows macro which causes a function call to be renamed. This // ensures that the same renaming will happen everywhere. Includes of this file // can be added wherever needed to ensure this consistent renaming. #define CopyFile CopyFileW #define CreateDirectory CreateDirectoryW #define CreateEvent CreateEventW #define CreateFile CreateFileW #define CreateService CreateServiceW #define DeleteFile DeleteFileW #define DispatchMessage DispatchMessageW #define DrawText DrawTextW #define FindFirstFile FindFirstFileW #define FindNextFile FindNextFileW #define GetComputerName GetComputerNameW #define GetCurrentDirectory GetCurrentDirectoryW #define GetCurrentTime() GetTickCount() #define GetFileAttributes GetFileAttributesW #define GetMessage GetMessageW #define GetUserName GetUserNameW #define LoadIcon LoadIconW #define LoadImage LoadImageW #define PostMessage PostMessageW #define RemoveDirectory RemoveDirectoryW #define ReplaceFile ReplaceFileW #define ReportEvent ReportEventW #define SendMessage SendMessageW #define SendMessageCallback SendMessageCallbackW #define SetCurrentDirectory SetCurrentDirectoryW #define StartService StartServiceW #define UpdateResource UpdateResourceW #endif // BASE_WIN_WINDOWS_TYPES_H_
engine/third_party/accessibility/base/win/windows_types.h/0
{ "file_path": "engine/third_party/accessibility/base/win/windows_types.h", "repo_id": "engine", "token_count": 3823 }
443
// Copyright (c) 2012 The Chromium 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 "rect_conversions.h" #include <algorithm> #include <cmath> #include "base/logging.h" #include "base/numerics/safe_conversions.h" namespace gfx { namespace { int FloorIgnoringError(float f, float error) { int rounded = base::ClampRound(f); return std::abs(rounded - f) < error ? rounded : base::ClampFloor(f); } int CeilIgnoringError(float f, float error) { int rounded = base::ClampRound(f); return std::abs(rounded - f) < error ? rounded : base::ClampCeil(f); } } // anonymous namespace Rect ToEnclosingRect(const RectF& r) { int left = base::ClampFloor(r.x()); int right = r.width() ? base::ClampCeil(r.right()) : left; int top = base::ClampFloor(r.y()); int bottom = r.height() ? base::ClampCeil(r.bottom()) : top; Rect result; result.SetByBounds(left, top, right, bottom); return result; } Rect ToEnclosingRectIgnoringError(const RectF& r, float error) { int left = FloorIgnoringError(r.x(), error); int right = r.width() ? CeilIgnoringError(r.right(), error) : left; int top = FloorIgnoringError(r.y(), error); int bottom = r.height() ? CeilIgnoringError(r.bottom(), error) : top; Rect result; result.SetByBounds(left, top, right, bottom); return result; } Rect ToEnclosedRect(const RectF& rect) { Rect result; result.SetByBounds(base::ClampCeil(rect.x()), base::ClampCeil(rect.y()), base::ClampFloor(rect.right()), base::ClampFloor(rect.bottom())); return result; } Rect ToEnclosedRectIgnoringError(const RectF& r, float error) { int left = CeilIgnoringError(r.x(), error); int right = r.width() ? FloorIgnoringError(r.right(), error) : left; int top = CeilIgnoringError(r.y(), error); int bottom = r.height() ? FloorIgnoringError(r.bottom(), error) : top; Rect result; result.SetByBounds(left, top, right, bottom); return result; } Rect ToNearestRect(const RectF& rect) { float float_min_x = rect.x(); float float_min_y = rect.y(); float float_max_x = rect.right(); float float_max_y = rect.bottom(); int min_x = base::ClampRound(float_min_x); int min_y = base::ClampRound(float_min_y); int max_x = base::ClampRound(float_max_x); int max_y = base::ClampRound(float_max_y); // If these DCHECKs fail, you're using the wrong method, consider using // ToEnclosingRect or ToEnclosedRect instead. BASE_DCHECK(std::abs(min_x - float_min_x) < 0.01f); BASE_DCHECK(std::abs(min_y - float_min_y) < 0.01f); BASE_DCHECK(std::abs(max_x - float_max_x) < 0.01f); BASE_DCHECK(std::abs(max_y - float_max_y) < 0.01f); Rect result; result.SetByBounds(min_x, min_y, max_x, max_y); return result; } bool IsNearestRectWithinDistance(const gfx::RectF& rect, float distance) { float float_min_x = rect.x(); float float_min_y = rect.y(); float float_max_x = rect.right(); float float_max_y = rect.bottom(); int min_x = base::ClampRound(float_min_x); int min_y = base::ClampRound(float_min_y); int max_x = base::ClampRound(float_max_x); int max_y = base::ClampRound(float_max_y); return (std::abs(min_x - float_min_x) < distance) && (std::abs(min_y - float_min_y) < distance) && (std::abs(max_x - float_max_x) < distance) && (std::abs(max_y - float_max_y) < distance); } gfx::Rect ToRoundedRect(const gfx::RectF& rect) { int left = base::ClampRound(rect.x()); int top = base::ClampRound(rect.y()); int right = base::ClampRound(rect.right()); int bottom = base::ClampRound(rect.bottom()); gfx::Rect result; result.SetByBounds(left, top, right, bottom); return result; } Rect ToFlooredRectDeprecated(const RectF& rect) { return Rect(base::ClampFloor(rect.x()), base::ClampFloor(rect.y()), base::ClampFloor(rect.width()), base::ClampFloor(rect.height())); } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/rect_conversions.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/rect_conversions.cc", "repo_id": "engine", "token_count": 1538 }
444
// Copyright (c) 2012 The Chromium 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 "vector2d_f.h" #include <cmath> #include "base/string_utils.h" namespace gfx { std::string Vector2dF::ToString() const { return base::StringPrintf("[%f %f]", x_, y_); } bool Vector2dF::IsZero() const { return x_ == 0 && y_ == 0; } void Vector2dF::Add(const Vector2dF& other) { x_ += other.x_; y_ += other.y_; } void Vector2dF::Subtract(const Vector2dF& other) { x_ -= other.x_; y_ -= other.y_; } double Vector2dF::LengthSquared() const { return static_cast<double>(x_) * x_ + static_cast<double>(y_) * y_; } float Vector2dF::Length() const { return static_cast<float>(std::sqrt(LengthSquared())); } void Vector2dF::Scale(float x_scale, float y_scale) { x_ *= x_scale; y_ *= y_scale; } double CrossProduct(const Vector2dF& lhs, const Vector2dF& rhs) { return static_cast<double>(lhs.x()) * rhs.y() - static_cast<double>(lhs.y()) * rhs.x(); } double DotProduct(const Vector2dF& lhs, const Vector2dF& rhs) { return static_cast<double>(lhs.x()) * rhs.x() + static_cast<double>(lhs.y()) * rhs.y(); } Vector2dF ScaleVector2d(const Vector2dF& v, float x_scale, float y_scale) { Vector2dF scaled_v(v); scaled_v.Scale(x_scale, y_scale); return scaled_v; } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/vector2d_f.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/vector2d_f.cc", "repo_id": "engine", "token_count": 580 }
445
# 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. public_include_dirs = [ "//flutter/third_party/icu/source/common", "//flutter/third_party/icu/source/i18n", ] config("icu_bidi_public") { include_dirs = public_include_dirs defines = [ "U_USING_ICU_NAMESPACE=0", "U_DISABLE_RENAMING=0", "U_HAVE_LIB_SUFFIX=1", "U_LIB_SUFFIX_C_NAME=_skia", "U_DISABLE_VERSION_SUFFIX=1", "SK_USING_THIRD_PARTY_ICU", ] cflags = [] foreach(dir, include_dirs) { cflags += [ "-isystem", rebase_path(dir), ] } } static_library("icu_bidi") { defines = [ "U_COMMON_IMPLEMENTATION", "U_STATIC_IMPLEMENTATION", "U_I18N_IMPLEMENTATION", ] sources = [ "//flutter/third_party/icu/source/common/cmemory.cpp", "//flutter/third_party/icu/source/common/cstring.cpp", "//flutter/third_party/icu/source/common/ubidi.cpp", "//flutter/third_party/icu/source/common/ubidi_props.cpp", "//flutter/third_party/icu/source/common/ubidiln.cpp", "//flutter/third_party/icu/source/common/ubidiwrt.cpp", "//flutter/third_party/icu/source/common/uchar.cpp", "//flutter/third_party/icu/source/common/udataswp.cpp", "//flutter/third_party/icu/source/common/uinvchar.cpp", "//flutter/third_party/icu/source/common/ustring.cpp", "//flutter/third_party/icu/source/common/ustrtrns.cpp", "//flutter/third_party/icu/source/common/utf_impl.cpp", "//flutter/third_party/icu/source/common/utrie2.cpp", "//flutter/third_party/icu/source/common/utypes.cpp", ] public_configs = [ ":icu_bidi_public" ] cflags = [ "-w" ] }
engine/third_party/canvaskit/icu_bidi/BUILD.gn/0
{ "file_path": "engine/third_party/canvaskit/icu_bidi/BUILD.gn", "repo_id": "engine", "token_count": 769 }
446
# Tonic A collection of C++ utilities for working with the DartVM API.
engine/third_party/tonic/README.md/0
{ "file_path": "engine/third_party/tonic/README.md", "repo_id": "engine", "token_count": 20 }
447
// 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 LIB_TONIC_DART_LIST_H_ #define LIB_TONIC_DART_LIST_H_ #include <cstddef> #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/converter/dart_converter.h" namespace tonic { class DartList { public: DartList(DartList&& other); void Set(size_t index, Dart_Handle value); Dart_Handle Get(size_t index); template <class T> void Set(size_t index, T value) { Set(index, DartConverter<T>::ToDart(value)); } template <class T> T Get(size_t index) { return DartConverter<T>::FromDart(Get(index)); } Dart_Handle dart_handle() const { return dart_handle_; } size_t size() const { return size_; } bool is_valid() const { return is_valid_; } explicit operator bool() const { return is_valid_; } private: explicit DartList(Dart_Handle list); friend struct DartConverter<DartList>; DartList(); Dart_Handle dart_handle_; size_t size_; bool is_valid_; DartList(const DartList& other) = delete; }; template <> struct DartConverter<DartList> { static DartList FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception); }; } // namespace tonic #endif // LIB_TONIC_DART_LIST_H_
engine/third_party/tonic/dart_list.h/0
{ "file_path": "engine/third_party/tonic/dart_list.h", "repo_id": "engine", "token_count": 543 }
448
// 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 "tonic/file_loader/file_loader.h" #include <dirent.h> #include <fcntl.h> #include <sys/types.h> #include <cerrno> #include <iostream> #include <memory> #include <utility> #include "tonic/common/macros.h" #include "tonic/converter/dart_converter.h" #include "tonic/filesystem/filesystem/file.h" #include "tonic/filesystem/filesystem/path.h" #include "tonic/parsers/packages_map.h" namespace tonic { const std::string FileLoader::kPathSeparator = "/"; const char FileLoader::kFileURLPrefix[] = "file://"; const size_t FileLoader::kFileURLPrefixLength = sizeof(FileLoader::kFileURLPrefix) - 1; std::string FileLoader::SanitizePath(const std::string& url) { return SanitizeURIEscapedCharacters(url); } bool FileLoader::ReadFileToString(const std::string& path, std::string* result) { if (dirfd_ == -1) return filesystem::ReadFileToString(path, result); const char* cpath = path.c_str(); const int offset = (cpath[0] == '/') ? 1 : 0; filesystem::Descriptor fd(openat(dirfd_, &cpath[offset], O_RDONLY)); return filesystem::ReadFileDescriptorToString(fd.get(), result); } std::pair<uint8_t*, intptr_t> FileLoader::ReadFileToBytes( const std::string& path) { if (dirfd_ == -1) return filesystem::ReadFileToBytes(path); const char* cpath = path.c_str(); const int offset = (cpath[0] == '/') ? 1 : 0; filesystem::Descriptor fd(openat(dirfd_, &cpath[offset], O_RDONLY)); return filesystem::ReadFileDescriptorToBytes(fd.get()); } } // namespace tonic
engine/third_party/tonic/file_loader/file_loader_fuchsia.cc/0
{ "file_path": "engine/third_party/tonic/file_loader/file_loader_fuchsia.cc", "repo_id": "engine", "token_count": 641 }
449
// 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 "filesystem/file.h" #include <fcntl.h> #include "filesystem/path.h" #include "filesystem/scoped_temp_dir.h" #include "gtest/gtest.h" namespace filesystem { namespace { TEST(File, GetFileSize) { ScopedTempDir dir; std::string path; ASSERT_TRUE(dir.NewTempFile(&path)); uint64_t size; EXPECT_TRUE(GetFileSize(path, &size)); EXPECT_EQ(0u, size); std::string content = "Hello World"; ASSERT_TRUE(WriteFile(path, content.data(), content.size())); EXPECT_TRUE(GetFileSize(path, &size)); EXPECT_EQ(content.size(), size); } TEST(File, WriteFileInTwoPhases) { ScopedTempDir dir; std::string path = dir.path() + "/destination"; std::string content = "Hello World"; ASSERT_TRUE(WriteFileInTwoPhases(path, content, dir.path())); std::string read_content; ASSERT_TRUE(ReadFileToString(path, &read_content)); EXPECT_EQ(read_content, content); } #if defined(OS_LINUX) || defined(OS_FUCHSIA) TEST(File, IsFileAt) { ScopedTempDir dir; std::string path; ASSERT_TRUE(dir.NewTempFile(&path)); fxl::UniqueFD dirfd(open(dir.path().c_str(), O_RDONLY)); ASSERT_TRUE(dirfd.get() != -1); EXPECT_TRUE(IsFileAt(dirfd.get(), GetBaseName(path))); } #endif } // namespace } // namespace filesystem
engine/third_party/tonic/filesystem/tests/file_unittest.cc/0
{ "file_path": "engine/third_party/tonic/filesystem/tests/file_unittest.cc", "repo_id": "engine", "token_count": 528 }
450
// 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 "flutter/testing/dart_isolate_runner.h" #include "flutter/testing/fixture_test.h" namespace flutter { namespace testing { namespace { void NopFinalizer(void* isolate_callback_data, void* peer) {} } // namespace class DartWeakPersistentHandle : public FixtureTest { public: DartWeakPersistentHandle() : settings_(CreateSettingsForFixture()), vm_(DartVMRef::Create(settings_)) {} ~DartWeakPersistentHandle() = default; [[nodiscard]] bool RunWithEntrypoint(const std::string& entrypoint) { if (running_isolate_) { return false; } auto thread = CreateNewThread(); TaskRunners single_threaded_task_runner(GetCurrentTestName(), thread, thread, thread, thread); auto isolate = RunDartCodeInIsolate(vm_, settings_, single_threaded_task_runner, entrypoint, {}, GetDefaultKernelFilePath()); if (!isolate || isolate->get()->GetPhase() != DartIsolate::Phase::Running) { return false; } running_isolate_ = std::move(isolate); return true; } [[nodiscard]] bool RunInIsolateScope(std::function<bool(void)> closure) { return running_isolate_->RunInIsolateScope(closure); } private: Settings settings_; DartVMRef vm_; std::unique_ptr<AutoIsolateShutdown> running_isolate_; FML_DISALLOW_COPY_AND_ASSIGN(DartWeakPersistentHandle); }; TEST_F(DartWeakPersistentHandle, ClearImmediately) { auto weak_persistent_value = tonic::DartWeakPersistentValue(); fml::AutoResetWaitableEvent event; AddNativeCallback( "GiveObjectToNative", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { auto handle = Dart_GetNativeArgument(args, 0); auto dart_state = tonic::DartState::Current(); ASSERT_TRUE(dart_state); ASSERT_TRUE(tonic::DartState::Current()); weak_persistent_value.Set(dart_state, handle, nullptr, 0, NopFinalizer); weak_persistent_value.Clear(); event.Signal(); })); ASSERT_TRUE(RunWithEntrypoint("callGiveObjectToNative")); event.Wait(); } TEST_F(DartWeakPersistentHandle, ClearLaterCc) { auto weak_persistent_value = tonic::DartWeakPersistentValue(); fml::AutoResetWaitableEvent event; AddNativeCallback( "GiveObjectToNative", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { auto handle = Dart_GetNativeArgument(args, 0); auto dart_state = tonic::DartState::Current(); ASSERT_TRUE(dart_state); ASSERT_TRUE(tonic::DartState::Current()); weak_persistent_value.Set(dart_state, handle, nullptr, 0, NopFinalizer); // Do not clear handle immediately. event.Signal(); })); ASSERT_TRUE(RunWithEntrypoint("callGiveObjectToNative")); event.Wait(); ASSERT_TRUE(RunInIsolateScope([&weak_persistent_value]() -> bool { // Clear on initiative of native. weak_persistent_value.Clear(); return true; })); } TEST_F(DartWeakPersistentHandle, ClearLaterDart) { auto weak_persistent_value = tonic::DartWeakPersistentValue(); fml::AutoResetWaitableEvent event; AddNativeCallback( "GiveObjectToNative", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { auto handle = Dart_GetNativeArgument(args, 0); auto dart_state = tonic::DartState::Current(); ASSERT_TRUE(dart_state); ASSERT_TRUE(tonic::DartState::Current()); weak_persistent_value.Set(dart_state, handle, nullptr, 0, NopFinalizer); // Do not clear handle immediately. })); AddNativeCallback("SignalDone", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { // Clear on initiative of Dart. weak_persistent_value.Clear(); event.Signal(); })); ASSERT_TRUE(RunWithEntrypoint("testClearLater")); event.Wait(); } // Handle outside the test body scope so it survives until isolate shutdown. tonic::DartWeakPersistentValue global_weak_persistent_value = tonic::DartWeakPersistentValue(); TEST_F(DartWeakPersistentHandle, ClearOnShutdown) { fml::AutoResetWaitableEvent event; AddNativeCallback("GiveObjectToNative", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { auto handle = Dart_GetNativeArgument(args, 0); auto dart_state = tonic::DartState::Current(); ASSERT_TRUE(dart_state); ASSERT_TRUE(tonic::DartState::Current()); // The test is repeated, ensure the global var is // cleared before use. global_weak_persistent_value.Clear(); global_weak_persistent_value.Set( dart_state, handle, nullptr, 0, NopFinalizer); // Do not clear handle, so it is cleared on shutdown. event.Signal(); })); ASSERT_TRUE(RunWithEntrypoint("callGiveObjectToNative")); event.Wait(); } } // namespace testing } // namespace flutter
engine/third_party/tonic/tests/dart_weak_persistent_handle_unittest.cc/0
{ "file_path": "engine/third_party/tonic/tests/dart_weak_persistent_handle_unittest.cc", "repo_id": "engine", "token_count": 2187 }
451
/* * Copyright 2017 Google, Inc. * * 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 <sstream> #include "flutter/fml/command_line.h" #include "flutter/fml/logging.h" #include "flutter/third_party/txt/tests/txt_test_utils.h" #include "third_party/benchmark/include/benchmark/benchmark.h" #include "third_party/icu/source/common/unicode/unistr.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/modules/skparagraph/include/Paragraph.h" #include "third_party/skia/modules/skparagraph/include/ParagraphBuilder.h" #include "third_party/skia/modules/skparagraph/include/TypefaceFontProvider.h" #include "third_party/skia/modules/skparagraph/utils/TestFontCollection.h" namespace sktxt = skia::textlayout; class SkParagraphFixture : public benchmark::Fixture { public: void SetUp(const ::benchmark::State& state) { font_collection_ = sk_make_sp<sktxt::TestFontCollection>(txt::GetFontDir()); bitmap_ = std::make_unique<SkBitmap>(); bitmap_->allocN32Pixels(1000, 1000); canvas_ = std::make_unique<SkCanvas>(*bitmap_); canvas_->clear(SK_ColorWHITE); } protected: sk_sp<sktxt::TestFontCollection> font_collection_; std::unique_ptr<SkCanvas> canvas_; std::unique_ptr<SkBitmap> bitmap_; }; BENCHMARK_F(SkParagraphFixture, ShortLayout)(benchmark::State& state) { const char* text = "Hello World"; sktxt::ParagraphStyle paragraph_style; sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); auto builder = sktxt::ParagraphBuilder::make(paragraph_style, font_collection_); builder->pushStyle(text_style); builder->addText(text); builder->pop(); auto paragraph = builder->Build(); while (state.KeepRunning()) { paragraph->markDirty(); paragraph->layout(300); } } BENCHMARK_F(SkParagraphFixture, LongLayout)(benchmark::State& state) { const char* text = "This is a very long sentence to test if the text will properly wrap " "around and go to the next line. Sometimes, short sentence. Longer " "sentences are okay too because they are necessary. Very short. " "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea " "commodo consequat. Duis aute irure dolor in reprehenderit in voluptate " "velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia deserunt " "mollit anim id est laborum. " "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea " "commodo consequat. Duis aute irure dolor in reprehenderit in voluptate " "velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia deserunt " "mollit anim id est laborum."; sktxt::ParagraphStyle paragraph_style; sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); auto builder = sktxt::ParagraphBuilder::make(paragraph_style, font_collection_); builder->pushStyle(text_style); builder->addText(text); builder->pop(); auto paragraph = builder->Build(); while (state.KeepRunning()) { paragraph->markDirty(); paragraph->layout(300); } } BENCHMARK_F(SkParagraphFixture, JustifyLayout)(benchmark::State& state) { const char* text = "This is a very long sentence to test if the text will properly wrap " "around and go to the next line. Sometimes, short sentence. Longer " "sentences are okay too because they are necessary. Very short. " "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea " "commodo consequat. Duis aute irure dolor in reprehenderit in voluptate " "velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia deserunt " "mollit anim id est laborum. " "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea " "commodo consequat. Duis aute irure dolor in reprehenderit in voluptate " "velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia deserunt " "mollit anim id est laborum."; sktxt::ParagraphStyle paragraph_style; paragraph_style.setTextAlign(sktxt::TextAlign::kJustify); sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); auto builder = sktxt::ParagraphBuilder::make(paragraph_style, font_collection_); builder->pushStyle(text_style); builder->addText(text); builder->pop(); auto paragraph = builder->Build(); while (state.KeepRunning()) { paragraph->markDirty(); paragraph->layout(300); } } BENCHMARK_F(SkParagraphFixture, ManyStylesLayout)(benchmark::State& state) { const char* text = "-"; sktxt::ParagraphStyle paragraph_style; sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); auto builder = sktxt::ParagraphBuilder::make(paragraph_style, font_collection_); for (int i = 0; i < 1000; ++i) { builder->pushStyle(text_style); builder->addText(text); } auto paragraph = builder->Build(); while (state.KeepRunning()) { paragraph->markDirty(); paragraph->layout(300); } } BENCHMARK_DEFINE_F(SkParagraphFixture, TextBigO)(benchmark::State& state) { std::vector<uint16_t> text; for (uint16_t i = 0; i < state.range(0); ++i) { text.push_back(i % 5 == 0 ? ' ' : i); } std::u16string u16_text(text.data(), text.data() + text.size()); sktxt::ParagraphStyle paragraph_style; sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); auto builder = sktxt::ParagraphBuilder::make(paragraph_style, font_collection_); builder->pushStyle(text_style); builder->addText(u16_text); builder->pop(); auto paragraph = builder->Build(); while (state.KeepRunning()) { paragraph->markDirty(); paragraph->layout(300); } state.SetComplexityN(state.range(0)); } BENCHMARK_REGISTER_F(SkParagraphFixture, TextBigO) ->RangeMultiplier(4) ->Range(1 << 6, 1 << 14) ->Complexity(benchmark::oN); BENCHMARK_DEFINE_F(SkParagraphFixture, StylesBigO)(benchmark::State& state) { const char* text = "vry shrt "; sktxt::ParagraphStyle paragraph_style; sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); auto builder = sktxt::ParagraphBuilder::make( paragraph_style, sk_make_sp<sktxt::TestFontCollection>(txt::GetFontDir())); for (int i = 0; i < 1000; ++i) { builder->pushStyle(text_style); builder->addText(text); } auto paragraph = builder->Build(); while (state.KeepRunning()) { paragraph->markDirty(); paragraph->layout(300); } state.SetComplexityN(state.range(0)); } BENCHMARK_REGISTER_F(SkParagraphFixture, StylesBigO) ->RangeMultiplier(4) ->Range(1 << 3, 1 << 12) ->Complexity(benchmark::oN); BENCHMARK_F(SkParagraphFixture, PaintSimple)(benchmark::State& state) { const char* text = "This is a simple sentence to test drawing."; sktxt::ParagraphStyle paragraph_style; sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); auto builder = sktxt::ParagraphBuilder::make(paragraph_style, font_collection_); builder->pushStyle(text_style); builder->addText(text); builder->pop(); auto paragraph = builder->Build(); paragraph->layout(300); int offset = 0; while (state.KeepRunning()) { paragraph->paint(canvas_.get(), offset % 700, 10); offset++; } } BENCHMARK_F(SkParagraphFixture, PaintLarge)(benchmark::State& state) { const char* text = "Hello world! This is a simple sentence to test drawing. Hello world! " "This is a simple sentence to test drawing. Hello world! This is a " "simple sentence to test drawing.Hello world! This is a simple sentence " "to test drawing. Hello world! " "This is a simple sentence to test drawing. Hello world! This is a " "simple sentence to test drawing.Hello world! This is a simple sentence " "to test drawing. Hello world! " "This is a simple sentence to test drawing. Hello world! This is a " "simple sentence to test drawing.Hello world! This is a simple sentence " "to test drawing. Hello world! " "This is a simple sentence to test drawing. Hello world! This is a " "simple sentence to test drawing.Hello world! This is a simple sentence " "to test drawing. Hello world! " "This is a simple sentence to test drawing. Hello world! This is a " "simple sentence to test drawing.Hello world! This is a simple sentence " "to test drawing. Hello world! " "This is a simple sentence to test drawing. Hello world! This is a " "simple sentence to test drawing."; sktxt::ParagraphStyle paragraph_style; sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); auto builder = sktxt::ParagraphBuilder::make(paragraph_style, font_collection_); builder->pushStyle(text_style); builder->addText(text); builder->pop(); auto paragraph = builder->Build(); paragraph->layout(300); int offset = 0; while (state.KeepRunning()) { paragraph->paint(canvas_.get(), offset % 700, 10); offset++; } } BENCHMARK_F(SkParagraphFixture, PaintDecoration)(benchmark::State& state) { const char* text = "Hello world! This is a simple sentence to test drawing. Hello world! " "This is a simple sentence to test drawing."; sktxt::ParagraphStyle paragraph_style; sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); text_style.setDecoration(static_cast<sktxt::TextDecoration>( sktxt::TextDecoration::kLineThrough | sktxt::TextDecoration::kOverline | sktxt::TextDecoration::kUnderline)); auto builder = sktxt::ParagraphBuilder::make(paragraph_style, font_collection_); text_style.setDecorationStyle(sktxt::TextDecorationStyle::kSolid); builder->pushStyle(text_style); builder->addText(text); text_style.setDecorationStyle(sktxt::TextDecorationStyle::kDotted); builder->pushStyle(text_style); builder->addText(text); text_style.setDecorationStyle(sktxt::TextDecorationStyle::kWavy); builder->pushStyle(text_style); builder->addText(text); auto paragraph = builder->Build(); paragraph->layout(300); int offset = 0; while (state.KeepRunning()) { paragraph->paint(canvas_.get(), offset % 700, 10); offset++; } } BENCHMARK_F(SkParagraphFixture, SimpleBuilder)(benchmark::State& state) { const char* text = "Hello World"; sktxt::ParagraphStyle paragraph_style; sktxt::TextStyle text_style; text_style.setFontFamilies({SkString("Roboto")}); text_style.setColor(SK_ColorBLACK); while (state.KeepRunning()) { auto builder = sktxt::ParagraphBuilder::make(paragraph_style, font_collection_); builder->pushStyle(text_style); builder->addText(text); builder->pop(); auto paragraph = builder->Build(); } }
engine/third_party/txt/benchmarks/skparagraph_benchmarks.cc/0
{ "file_path": "engine/third_party/txt/benchmarks/skparagraph_benchmarks.cc", "repo_id": "engine", "token_count": 4485 }
452
/* * Copyright 2017 Google Inc. * * 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 LIB_TXT_SRC_LINE_METRICS_H_ #define LIB_TXT_SRC_LINE_METRICS_H_ #include <map> #include <vector> #include "run_metrics.h" namespace txt { class LineMetrics { public: // The following fields are used in the layout process itself. // The indexes in the text buffer the line begins and ends. size_t start_index = 0; size_t end_index = 0; size_t end_excluding_whitespace = 0; size_t end_including_newline = 0; bool hard_break = false; // The following fields are tracked after or during layout to provide to // the user as well as for computing bounding boxes. // The final computed ascent and descent for the line. This can be impacted by // the strut, height, scaling, as well as outlying runs that are very tall. // // The top edge is `baseline - ascent` and the bottom edge is `baseline + // descent`. Ascent and descent are provided as positive numbers. Raw numbers // for specific runs of text can be obtained in run_metrics_map. These values // are the cumulative metrics for the entire line. double ascent = 0.0; double descent = 0.0; double unscaled_ascent = 0.0; // Total height of the paragraph including the current line. // // The height of the current line is `round(ascent + descent)`. double height = 0.0; // Width of the line. double width = 0.0; // The left edge of the line. The right edge can be obtained with `left + // width` double left = 0.0; // The y position of the baseline for this line from the top of the paragraph. double baseline = 0.0; // Zero indexed line number. size_t line_number = 0; // Mapping between text index ranges and the FontMetrics associated with // them. The first run will be keyed under start_index. The metrics here // are before layout and are the base values we calculate from. std::map<size_t, RunMetrics> run_metrics; LineMetrics(); LineMetrics(size_t start, size_t end, size_t end_excluding_whitespace, size_t end_including_newline, bool hard_break) : start_index(start), end_index(end), end_excluding_whitespace(end_excluding_whitespace), end_including_newline(end_including_newline), hard_break(hard_break) {} }; } // namespace txt #endif // LIB_TXT_SRC_LINE_METRICS_H_
engine/third_party/txt/src/txt/line_metrics.h/0
{ "file_path": "engine/third_party/txt/src/txt/line_metrics.h", "repo_id": "engine", "token_count": 938 }
453
/* * Copyright 2017 Google Inc. * * 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 LIB_TXT_SRC_RUN_METRICS_H_ #define LIB_TXT_SRC_RUN_METRICS_H_ #include "text_style.h" #include "third_party/skia/include/core/SkFontMetrics.h" namespace txt { // Contains the font metrics and TextStyle of a unique run. class RunMetrics { public: explicit RunMetrics(const TextStyle* style) : text_style(style) {} RunMetrics(const TextStyle* style, const SkFontMetrics& metrics) : text_style(style), font_metrics(metrics) {} const TextStyle* text_style; // SkFontMetrics contains the following metrics: // // * Top distance to reserve above baseline // * Ascent distance to reserve below baseline // * Descent extent below baseline // * Bottom extent below baseline // * Leading distance to add between lines // * AvgCharWidth average character width // * MaxCharWidth maximum character width // * XMin minimum x // * XMax maximum x // * XHeight height of lower-case 'x' // * CapHeight height of an upper-case letter // * UnderlineThickness underline thickness // * UnderlinePosition underline position relative to baseline // * StrikeoutThickness strikeout thickness // * StrikeoutPosition strikeout position relative to baseline SkFontMetrics font_metrics; }; } // namespace txt #endif // LIB_TXT_SRC_RUN_METRICS_H_
engine/third_party/txt/src/txt/run_metrics.h/0
{ "file_path": "engine/third_party/txt/src/txt/run_metrics.h", "repo_id": "engine", "token_count": 692 }
454
name: web_locale_keymap publish_to: none environment: sdk: '>=3.2.0-0 <4.0.0' dev_dependencies: test: ^1.21.7
engine/third_party/web_locale_keymap/pubspec.yaml/0
{ "file_path": "engine/third_party/web_locale_keymap/pubspec.yaml", "repo_id": "engine", "token_count": 61 }
455
#!/usr/bin/env python # Copyright 2022 Google LLC # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys EMSDK_ROOT = os.path.abspath(os.path.join(__file__, '..', '..', 'prebuilts', 'emsdk')) EMSDK_PATH = os.path.join(EMSDK_ROOT, 'emsdk.py') # See lib/web_ui/README.md for instructions on updating the EMSDK version. EMSDK_VERSION = '3.1.44' def main(): try: subprocess.check_call([sys.executable, EMSDK_PATH, 'install', EMSDK_VERSION], stdout=subprocess.DEVNULL) except subprocess.CalledProcessError: print('Failed to install emsdk') return 1 try: subprocess.check_call([sys.executable, EMSDK_PATH, 'activate', EMSDK_VERSION], stdout=subprocess.DEVNULL) except subprocess.CalledProcessError: print('Failed to activate emsdk') return 1 if __name__ == '__main__': sys.exit(main())
engine/tools/activate_emsdk.py/0
{ "file_path": "engine/tools/activate_emsdk.py", "repo_id": "engine", "token_count": 387 }
456
// 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. import 'dart:io'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:apicheck/apicheck.dart'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as path; void main(List<String> arguments) { if (arguments.isEmpty) { print('usage: dart bin/apicheck.dart path/to/engine/src/flutter'); exit(1); } final String flutterRoot = arguments[0]; checkApiConsistency(flutterRoot); checkNativeApi(flutterRoot); } /// Verify that duplicate Flutter API is consistent between implementations. /// /// Flutter contains API that is required to match between implementations. /// Notably, some enums such as those used by Flutter accessibility, appear in: /// * dart:ui (native) /// * dart:ui (web) /// * embedder.h /// * Internal enumerations used by iOS/Android /// /// WARNING: The embedder API makes strong API/ABI stability guarantees. Care /// must be taken when adding new enums, or values to existing enums. These /// CANNOT be removed without breaking backward compatibility, which we have /// never done. See the note at the top of `shell/platform/embedder/embedder.h` /// for further details. void checkApiConsistency(String flutterRoot) { test('AccessibilityFeatures enums match', () { // Dart values: _kFooBarIndex = 1 << N final List<String> uiFields = getDartClassFields( sourcePath: path.join(flutterRoot, 'lib', 'ui', 'window.dart'), className: 'AccessibilityFeatures', ); // C values: kFlutterAccessibilityFeatureFooBar = 1 << N, final List<String> embedderEnumValues = getCppEnumValues( sourcePath: path.join(flutterRoot, 'shell', 'platform', 'embedder', 'embedder.h'), enumName: 'FlutterAccessibilityFeature', ); // C++ values: kFooBar = 1 << N, final List<String> internalEnumValues = getCppEnumClassValues( sourcePath: path.join(flutterRoot, 'lib','ui', 'window', 'platform_configuration.h'), enumName: 'AccessibilityFeatureFlag', ); // Java values: FOO_BAR(1 << N). final List<String> javaEnumValues = getJavaEnumValues( sourcePath: path.join(flutterRoot, 'shell', 'platform', 'android', 'io', 'flutter', 'view', 'AccessibilityBridge.java'), enumName: 'AccessibilityFeature', ).map(allCapsToCamelCase).toList(); expect(embedderEnumValues, uiFields); expect(internalEnumValues, uiFields); expect(javaEnumValues, uiFields); }); test('SemanticsAction enums match', () { // Dart values: _kFooBarIndex = 1 << N. final List<String> uiFields = getDartClassFields( sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics.dart'), className: 'SemanticsAction', ); final List<String> webuiFields = getDartClassFields( sourcePath: path.join(flutterRoot, 'lib', 'web_ui', 'lib', 'semantics.dart'), className: 'SemanticsAction', ); // C values: kFlutterSemanticsActionFooBar = 1 << N. final List<String> embedderEnumValues = getCppEnumValues( sourcePath: path.join(flutterRoot, 'shell', 'platform', 'embedder', 'embedder.h'), enumName: 'FlutterSemanticsAction', ); // C++ values: kFooBar = 1 << N. final List<String> internalEnumValues = getCppEnumClassValues( sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics', 'semantics_node.h'), enumName: 'SemanticsAction', ); // Java values: FOO_BAR(1 << N). final List<String> javaEnumValues = getJavaEnumValues( sourcePath: path.join(flutterRoot, 'shell', 'platform', 'android', 'io', 'flutter', 'view', 'AccessibilityBridge.java'), enumName: 'Action', ).map(allCapsToCamelCase).toList(); expect(webuiFields, uiFields); expect(embedderEnumValues, uiFields); expect(internalEnumValues, uiFields); expect(javaEnumValues, uiFields); }); test('AppLifecycleState enums match', () { // Dart values: _kFooBarIndex = 1 << N. final List<String> uiFields = getDartClassFields( sourcePath: path.join(flutterRoot, 'lib', 'ui', 'platform_dispatcher.dart'), className: 'AppLifecycleState', ); final List<String> webuiFields = getDartClassFields( sourcePath: path.join(flutterRoot, 'lib', 'web_ui', 'lib', 'platform_dispatcher.dart'), className: 'AppLifecycleState', ); // C++ values: kFooBar = 1 << N. final List<String> internalEnumValues = getCppEnumClassValues( sourcePath: path.join(flutterRoot, 'shell', 'platform', 'common', 'app_lifecycle_state.h'), enumName: 'AppLifecycleState', ); // Java values: FOO_BAR(1 << N). final List<String> javaEnumValues = getJavaEnumValues( sourcePath: path.join(flutterRoot, 'shell', 'platform', 'android', 'io', 'flutter', 'embedding', 'engine', 'systemchannels', 'LifecycleChannel.java'), enumName: 'AppLifecycleState', ).map(allCapsToCamelCase).toList(); expect(webuiFields, uiFields); expect(internalEnumValues, uiFields); expect(javaEnumValues, uiFields); }); test('SemanticsFlag enums match', () { // Dart values: _kFooBarIndex = 1 << N. final List<String> uiFields = getDartClassFields( sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics.dart'), className: 'SemanticsFlag', ); final List<String> webuiFields = getDartClassFields( sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics.dart'), className: 'SemanticsFlag', ); // C values: kFlutterSemanticsFlagFooBar = 1 << N. final List<String> embedderEnumValues = getCppEnumValues( sourcePath: path.join(flutterRoot, 'shell', 'platform', 'embedder', 'embedder.h'), enumName: 'FlutterSemanticsFlag', ); // C++ values: kFooBar = 1 << N. final List<String> internalEnumValues = getCppEnumClassValues( sourcePath: path.join(flutterRoot, 'lib', 'ui', 'semantics', 'semantics_node.h'), enumName: 'SemanticsFlags', ); // Java values: FOO_BAR(1 << N). final List<String> javaEnumValues = getJavaEnumValues( sourcePath: path.join(flutterRoot, 'shell', 'platform', 'android', 'io', 'flutter', 'view', 'AccessibilityBridge.java'), enumName: 'Flag', ).map(allCapsToCamelCase).toList(); expect(webuiFields, uiFields); expect(embedderEnumValues, uiFields); expect(internalEnumValues, uiFields); expect(javaEnumValues, uiFields); }); } /// Returns the CamelCase equivalent of an ALL_CAPS identifier. String allCapsToCamelCase(String identifier) { final StringBuffer buffer = StringBuffer(); for (final String word in identifier.split('_')) { if (word.isNotEmpty) { buffer.write(word[0]); } if (word.length > 1) { buffer.write(word.substring(1).toLowerCase()); } } return buffer.toString(); } /// Verify that the native functions in the dart:ui package do not use nullable /// parameters that map to simple types such as numbers and strings. /// /// The Tonic argument converters used by the native function implementations /// expect that values of these types will not be null. class NativeFunctionVisitor extends RecursiveAstVisitor<void> { final Set<String> simpleTypes = <String>{'int', 'double', 'bool', 'String'}; List<String> errors = <String>[]; @override void visitNativeFunctionBody(NativeFunctionBody node) { final MethodDeclaration? method = node.thisOrAncestorOfType<MethodDeclaration>(); if (method != null) { if (method.parameters != null) { check(method.toString(), method.parameters!); } return; } final FunctionDeclaration? func = node.thisOrAncestorOfType<FunctionDeclaration>(); if (func != null) { final FunctionExpression funcExpr = func.functionExpression; if (funcExpr.parameters != null) { check(func.toString(), funcExpr.parameters!); } return; } throw Exception('unreachable'); } void check(String description, FormalParameterList parameters) { for (final FormalParameter parameter in parameters.parameters) { TypeAnnotation? type; if (parameter is SimpleFormalParameter) { type = parameter.type; } else if (parameter is DefaultFormalParameter) { type = (parameter.parameter as SimpleFormalParameter).type; } if (type! is NamedType) { final String name = (type as NamedType).name2.lexeme; if (type.question != null && simpleTypes.contains(name)) { errors.add(description); return; } } } } } void checkNativeApi(String flutterRoot) { test('Native API does not pass nullable parameters of simple types', () { final NativeFunctionVisitor visitor = NativeFunctionVisitor(); visitUIUnits(flutterRoot, visitor); expect(visitor.errors, isEmpty); }); }
engine/tools/api_check/test/apicheck_test.dart/0
{ "file_path": "engine/tools/api_check/test/apicheck_test.dart", "repo_id": "engine", "token_count": 3298 }
457
// 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. import 'dart:convert' show LineSplitter, jsonDecode; import 'dart:io' as io show File, stderr, stdout; import 'package:engine_repo_tools/engine_repo_tools.dart'; import 'package:git_repo_tools/git_repo_tools.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; import 'package:process/process.dart'; import 'package:process_runner/process_runner.dart'; import 'src/command.dart'; import 'src/lint_target.dart'; import 'src/options.dart'; const String _linterOutputHeader = ''' β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Engine Clang Tidy Linter β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ The following errors have been reported by the Engine Clang Tidy Linter. For more information on addressing these issues please see: https://github.com/flutter/flutter/wiki/Engine-Clang-Tidy-Linter '''; class _ComputeJobsResult { _ComputeJobsResult(this.jobs, this.sawMalformed); final List<WorkerJob> jobs; final bool sawMalformed; } enum _SetStatus { Intersection, Difference, } class _SetStatusCommand { _SetStatusCommand(this.setStatus, this.command); final _SetStatus setStatus; final Command command; } /// A class that runs clang-tidy on all or only the changed files in a git /// repo. class ClangTidy { /// Builds an instance of [ClangTidy] using a repo's [buildCommandPath]. /// /// ## Required /// /// - [buildCommandsPath] is the path to the build_commands.json file. /// /// ## Optional /// /// - [checksArg] are specific checks for clang-tidy to do. /// /// If omitted, checks will be determined by the `.clang-tidy` file in the /// repo. /// /// - [lintTarget] is what files to lint. /// /// ## Optional (Test Overrides) /// /// _Most usages of this class will not need to override the following, which /// are primarily used for testing (i.e. to avoid real interaction with I/O)._ /// /// - [outSink] when provided is the destination for normal log messages. /// /// If omitted, [io.stdout] will be used. /// /// - [errSink] when provided is the destination for error messages. /// /// If omitted, [io.stderr] will be used. /// /// - [processManager] when provided is delegated to for running processes. /// /// If omitted, [LocalProcessManager] will be used. ClangTidy({ required io.File buildCommandsPath, String checksArg = '', LintTarget lintTarget = const LintChanged(), bool fix = false, StringSink? outSink, StringSink? errSink, ProcessManager processManager = const LocalProcessManager(), }) : options = Options( buildCommandsPath: buildCommandsPath, checksArg: checksArg, lintTarget: lintTarget, fix: fix, errSink: errSink, ), _outSink = outSink ?? io.stdout, _errSink = errSink ?? io.stderr, _processManager = processManager, _engine = null; /// Builds an instance of [ClangTidy] from a command line. ClangTidy.fromCommandLine( List<String> args, { Engine? engine, StringSink? outSink, StringSink? errSink, ProcessManager processManager = const LocalProcessManager(), }) : options = Options.fromCommandLine(args, errSink: errSink, engine: engine), _outSink = outSink ?? io.stdout, _errSink = errSink ?? io.stderr, _processManager = processManager, _engine = engine; /// The [Options] that specify how this [ClangTidy] operates. final Options options; final StringSink _outSink; final StringSink _errSink; final ProcessManager _processManager; final Engine? _engine; late final DateTime _startTime; /// Runs clang-tidy on the repo as specified by the [Options]. Future<int> run() async { _startTime = DateTime.now(); if (options.help) { options.printUsage(engine: _engine); return 0; } if (options.errorMessage != null) { options.printUsage(message: options.errorMessage, engine: _engine); return 1; } _outSink.writeln(_linterOutputHeader); final List<io.File> filesOfInterest = await computeFilesOfInterest(); if (options.verbose) { _outSink.writeln('Checking lint in repo at ${options.repoPath.path}.'); if (options.checksArg.isNotEmpty) { _outSink.writeln('Checking for specific checks: ${options.checks}.'); } final int changedFilesCount = filesOfInterest.length; switch (options.lintTarget) { case LintAll(): _outSink.writeln('Checking all $changedFilesCount files in the repo.'); case LintChanged(): _outSink.writeln( 'Checking $changedFilesCount files that have changed since the ' 'last commit.', ); case LintHead(): _outSink.writeln( 'Checking $changedFilesCount files that have changed compared to ' 'HEAD.', ); case LintRegex(:final String regex): _outSink.writeln( 'Checking $changedFilesCount files that match the regex "$regex".', ); } } final List<Object?> buildCommandsData = jsonDecode( options.buildCommandsPath.readAsStringSync(), ) as List<Object?>; final List<List<Object?>> shardBuildCommandsData = options .shardCommandsPaths .map((io.File file) => jsonDecode(file.readAsStringSync()) as List<Object?>) .toList(); final List<Command> changedFileBuildCommands = await getLintCommandsForFiles( buildCommandsData, filesOfInterest, shardBuildCommandsData, options.shardId, ); if (changedFileBuildCommands.isEmpty) { _outSink.writeln( 'No changed files that have build commands associated with them were ' 'found.', ); return 0; } if (options.verbose) { _outSink.writeln( 'Found ${changedFileBuildCommands.length} files that have build ' 'commands associated with them and can be lint checked.', ); } final _ComputeJobsResult computeJobsResult = await _computeJobs( changedFileBuildCommands, options, ); final int computeResult = computeJobsResult.sawMalformed ? 1 : 0; final List<WorkerJob> jobs = computeJobsResult.jobs; final int runResult = await _runJobs(jobs); _outSink.writeln('\n'); if (computeResult + runResult == 0) { _outSink.writeln('No lint problems found.'); } else { _errSink.writeln('Lint problems found.'); } return computeResult + runResult > 0 ? 1 : 0; } /// The files with local modifications or all/a subset of all files. /// /// See [LintTarget] for more information. @visibleForTesting Future<List<io.File>> computeFilesOfInterest() async { switch (options.lintTarget) { case LintAll(): return options.repoPath .listSync(recursive: true) .whereType<io.File>() .toList(); case LintRegex(:final String regex): final RegExp pattern = RegExp(regex); return options.repoPath .listSync(recursive: true) .whereType<io.File>() .where((io.File file) => pattern.hasMatch(file.path)) .toList(); case LintChanged(): final GitRepo repo = GitRepo.fromRoot( options.repoPath, processManager: _processManager, verbose: options.verbose, ); return repo.changedFiles; case LintHead(): final GitRepo repo = GitRepo.fromRoot( options.repoPath, processManager: _processManager, verbose: options.verbose, ); return repo.changedFilesAtHead; } } /// Returns f(n) = value(n * [shardCount] + [id]). Iterable<T> _takeShard<T>(Iterable<T> values, int id, int shardCount) sync* { int count = 0; for (final T val in values) { if (count % shardCount == id) { yield val; } count++; } } /// This returns a `_SetStatusCommand` for each [Command] in [items]. /// `Intersection` if the Command shows up in [items] and its filePath in all /// [filePathSets], otherwise `Difference`. Iterable<_SetStatusCommand> _calcIntersection( Iterable<Command> items, Iterable<Set<String>> filePathSets) sync* { bool allSetsContain(Command command) { for (final Set<String> filePathSet in filePathSets) { if (!filePathSet.contains(command.filePath)) { return false; } } return true; } for (final Command command in items) { if (allSetsContain(command)) { yield _SetStatusCommand(_SetStatus.Intersection, command); } else { yield _SetStatusCommand(_SetStatus.Difference, command); } } } /// Given a build commands json file's contents in [buildCommandsData], and /// the [files] with local changes, compute the lint commands to run. If /// build commands are supplied in [sharedBuildCommandsData] the intersection /// of those build commands will be calculated and distributed across /// instances via the [shardId]. @visibleForTesting Future<List<Command>> getLintCommandsForFiles( List<Object?> buildCommandsData, List<io.File> files, List<List<Object?>> sharedBuildCommandsData, int? shardId, ) { final List<Command> totalCommands = <Command>[]; if (sharedBuildCommandsData.isNotEmpty) { final List<Command> buildCommands = <Command>[ for (final Object? data in buildCommandsData) Command.fromMap((data as Map<String, Object?>?)!) ]; final List<Set<String>> shardFilePaths = <Set<String>>[ for (final List<Object?> list in sharedBuildCommandsData) <String>{ for (final Object? data in list) Command.fromMap((data as Map<String, Object?>?)!).filePath } ]; final Iterable<_SetStatusCommand> intersectionResults = _calcIntersection(buildCommands, shardFilePaths); for (final _SetStatusCommand result in intersectionResults) { if (result.setStatus == _SetStatus.Difference) { totalCommands.add(result.command); } } final List<Command> intersection = <Command>[ for (final _SetStatusCommand result in intersectionResults) if (result.setStatus == _SetStatus.Intersection) result.command ]; // Make sure to sort results so the sharding scheme is guaranteed to work // since we are not sure if there is a defined order in the json file. intersection .sort((Command x, Command y) => x.filePath.compareTo(y.filePath)); totalCommands.addAll( _takeShard(intersection, shardId!, 1 + sharedBuildCommandsData.length)); } else { totalCommands.addAll(<Command>[ for (final Object? data in buildCommandsData) Command.fromMap((data as Map<String, Object?>?)!) ]); } return () async { final List<Command> result = <Command>[]; for (final Command command in totalCommands) { final LintAction lintAction = await command.lintAction; // Short-circuit the expensive containsAny call for the many third_party files. if (lintAction != LintAction.skipThirdParty && command.containsAny(files)) { result.add(command); } } return result; }(); } Future<_ComputeJobsResult> _computeJobs( List<Command> commands, Options options, ) async { bool sawMalformed = false; final List<WorkerJob> jobs = <WorkerJob>[]; for (final Command command in commands) { final String relativePath = path.relative( command.filePath, from: options.repoPath.parent.path, ); final LintAction action = await command.lintAction; switch (action) { case LintAction.skipNoLint: _outSink.writeln('πŸ”· ignoring $relativePath (FLUTTER_NOLINT)'); case LintAction.failMalformedNoLint: _errSink.writeln('❌ malformed opt-out $relativePath'); _errSink.writeln( ' Required format: // FLUTTER_NOLINT: $issueUrlPrefix/ISSUE_ID', ); sawMalformed = true; case LintAction.lint: _outSink.writeln('πŸ”Ά linting $relativePath'); jobs.add(command.createLintJob(options)); case LintAction.skipThirdParty: _outSink.writeln('πŸ”· ignoring $relativePath (third_party)'); case LintAction.skipMissing: _outSink.writeln('πŸ”· ignoring $relativePath (missing)'); } } return _ComputeJobsResult(jobs, sawMalformed); } static Iterable<String> _trimGenerator(String output) sync* { const LineSplitter splitter = LineSplitter(); final List<String> lines = splitter.convert(output); bool isPrintingError = false; for (final String line in lines) { if (line.contains(': error:') || line.contains(': warning:')) { isPrintingError = true; yield line; } else if (line == ':') { isPrintingError = false; } else if (isPrintingError) { yield line; } } } /// Visible for testing. /// Function for trimming raw clang-tidy output. @visibleForTesting static String trimOutput(String output) => _trimGenerator(output).join('\n'); Future<int> _runJobs(List<WorkerJob> jobs) async { int result = 0; final Set<String> pendingJobs = <String>{for (final WorkerJob job in jobs) job.name}; void reporter(int totalJobs, int completed, int inProgress, int pending, int failed) { return _logWithTimestamp(ProcessPool.defaultReportToString( totalJobs, completed, inProgress, pending, failed)); } final ProcessPool pool = ProcessPool( printReport: reporter, processRunner: ProcessRunner(processManager: _processManager), ); await for (final WorkerJob job in pool.startWorkers(jobs)) { pendingJobs.remove(job.name); if (pendingJobs.isNotEmpty && pendingJobs.length <= 3) { final List<String> sortedJobs = pendingJobs.toList()..sort(); _logWithTimestamp('Still running: $sortedJobs'); } if (job.result.exitCode == 0) { if (options.enableCheckProfile) { // stderr is lazily evaluated, so force it to be evaluated here. final String stderr = job.result.stderr; _errSink.writeln('Results of --enable-check-profile for ${job.name}:'); _errSink.writeln(stderr); } continue; } _errSink.writeln('❌ Failures for ${job.name}:'); if (!job.printOutput) { final Exception? exception = job.exception; if (exception != null) { _errSink.writeln(trimOutput(exception.toString())); } else { _errSink.writeln(trimOutput(job.result.stdout)); } } result = 1; } return result; } void _logWithTimestamp(String message) { final Duration elapsedTime = DateTime.now().difference(_startTime); final String seconds = (elapsedTime.inSeconds % 60).toString().padLeft(2, '0'); _outSink.writeln('[${elapsedTime.inMinutes}:$seconds] $message'); } }
engine/tools/clang_tidy/lib/clang_tidy.dart/0
{ "file_path": "engine/tools/clang_tidy/lib/clang_tidy.dart", "repo_id": "engine", "token_count": 5930 }
458
# Const Finder This program uses package:kernel from the Dart SDK in //third_party. A snapshot is created via the build rules in BUILD.gn. This is then vended to the Flutter tool, which uses it to find `const` creations of `IconData` classes. The information from this can then be passed to the `font-subset` tool to create a smaller icon font file specific to the application. Once [flutter/flutter#47162](https://github.com/flutter/flutter/issues/47162) is resolved, this package should be moved to the flutter tool.
engine/tools/const_finder/README.md/0
{ "file_path": "engine/tools/const_finder/README.md", "repo_id": "engine", "token_count": 143 }
459
name: dir_contents_diff environment: sdk: '>=3.2.0-0 <4.0.0' dev_dependencies: litetest: any path: any dependency_overrides: async_helper: path: ../../../third_party/dart/pkg/async_helper expect: path: ../../../third_party/dart/pkg/expect litetest: path: ../../testing/litetest meta: path: ../../../third_party/dart/pkg/meta path: path: ../../../third_party/dart/third_party/pkg/path smith: path: ../../../third_party/dart/pkg/smith
engine/tools/dir_contents_diff/pubspec.yaml/0
{ "file_path": "engine/tools/dir_contents_diff/pubspec.yaml", "repo_id": "engine", "token_count": 213 }
460
// 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. import 'package:args/command_runner.dart'; import 'package:engine_build_configs/engine_build_configs.dart'; import '../environment.dart'; import 'build_command.dart'; import 'fetch_command.dart'; import 'flags.dart'; import 'format_command.dart'; import 'lint_command.dart'; import 'query_command.dart'; import 'run_command.dart'; const int _usageLineLength = 80; /// The root command runner. final class ToolCommandRunner extends CommandRunner<int> { /// Constructs the runner and populates commands, subcommands, and global /// options and flags. ToolCommandRunner({ required this.environment, required this.configs, }) : super(toolName, toolDescription, usageLineLength: _usageLineLength) { final List<Command<int>> commands = <Command<int>>[ FetchCommand(environment: environment), FormatCommand(environment: environment), QueryCommand(environment: environment, configs: configs), BuildCommand(environment: environment, configs: configs), RunCommand(environment: environment, configs: configs), LintCommand(environment: environment), ]; commands.forEach(addCommand); argParser.addFlag( verboseFlag, abbr: 'v', help: 'Prints verbose output', negatable: false, ); } /// The name of the tool as reported in the tool's usage and help /// messages. static const String toolName = 'et'; /// The description of the tool reported in the tool's usage and help /// messages. static const String toolDescription = 'A command line tool for working on ' 'the Flutter Engine.'; /// The host system environment. final Environment environment; /// Build configurations loaded from the engine from under ci/builders. final Map<String, BuilderConfig> configs; @override Future<int> run(Iterable<String> args) async { try { return await runCommand(parse(args)) ?? 0; } on FormatException catch (e) { environment.logger.error(e); return 1; } on UsageException catch (e) { environment.logger.error(e); return 1; } } }
engine/tools/engine_tool/lib/src/commands/command_runner.dart/0
{ "file_path": "engine/tools/engine_tool/lib/src/commands/command_runner.dart", "repo_id": "engine", "token_count": 719 }
461
// 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. import 'dart:convert' as convert; import 'dart:ffi' as ffi show Abi; import 'dart:io' as io; import 'package:engine_build_configs/engine_build_configs.dart'; import 'package:engine_repo_tools/engine_repo_tools.dart'; import 'package:engine_tool/src/build_utils.dart'; import 'package:engine_tool/src/commands/command_runner.dart'; import 'package:engine_tool/src/environment.dart'; import 'package:engine_tool/src/logger.dart'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as path; import 'package:platform/platform.dart'; import 'package:process_fakes/process_fakes.dart'; import 'package:process_runner/process_runner.dart'; import 'fixtures.dart' as fixtures; void main() { final BuilderConfig linuxTestConfig = BuilderConfig.fromJson( path: 'ci/builders/linux_test_config.json', map: convert.jsonDecode(fixtures.testConfig('Linux')) as Map<String, Object?>, ); final BuilderConfig macTestConfig = BuilderConfig.fromJson( path: 'ci/builders/mac_test_config.json', map: convert.jsonDecode(fixtures.testConfig('Mac-12')) as Map<String, Object?>, ); final BuilderConfig winTestConfig = BuilderConfig.fromJson( path: 'ci/builders/win_test_config.json', map: convert.jsonDecode(fixtures.testConfig('Windows-11')) as Map<String, Object?>, ); final Map<String, BuilderConfig> configs = <String, BuilderConfig>{ 'linux_test_config': linuxTestConfig, 'linux_test_config2': linuxTestConfig, 'mac_test_config': macTestConfig, 'win_test_config': winTestConfig, }; (Environment, List<List<String>>) linuxEnv( Logger logger, { bool withRbe = false, }) { final io.Directory rootDir = io.Directory.systemTemp.createTempSync('et'); final TestEngine engine = TestEngine.createTemp(rootDir: rootDir); if (withRbe) { io.Directory(path.join( engine.srcDir.path, 'flutter', 'build', 'rbe', )).createSync(recursive: true); } final List<List<String>> runHistory = <List<String>>[]; return ( Environment( abi: ffi.Abi.linuxX64, engine: engine, platform: FakePlatform( operatingSystem: Platform.linux, resolvedExecutable: io.Platform.resolvedExecutable), processRunner: ProcessRunner( processManager: FakeProcessManager( canRun: (Object? exe, {String? workingDirectory}) => true, onStart: (List<String> command) { runHistory.add(command); return FakeProcess(); }, onRun: (List<String> command) { runHistory.add(command); return io.ProcessResult(81, 0, '', ''); }, ), ), logger: logger, ), runHistory ); } void cleanupEnv(Environment env) { try { env.engine.srcDir.parent.deleteSync(recursive: true); } catch (_) { // Ignore failure to clean up. } } test('can find host runnable build', () async { final Logger logger = Logger.test(); final (Environment env, _) = linuxEnv(logger); try { final List<Build> result = runnableBuilds(env, configs); expect(result.length, equals(8)); expect(result[0].name, equals('build_name')); } finally { cleanupEnv(env); } }); test('build command invokes gn', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv(logger); try { final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>[ 'build', '--config', 'build_name', ]); expect(result, equals(0)); expect(runHistory.length, greaterThanOrEqualTo(1)); expect(runHistory[0].length, greaterThanOrEqualTo(1)); expect(runHistory[0][0], contains('gn')); } finally { cleanupEnv(env); } }); test('build command invokes ninja', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv(logger); try { final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>[ 'build', '--config', 'build_name', ]); expect(result, equals(0)); expect(runHistory.length, greaterThanOrEqualTo(2)); expect(runHistory[1].length, greaterThanOrEqualTo(1)); expect(runHistory[1][0], contains('ninja')); } finally { cleanupEnv(env); } }); test('build command invokes generator', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv(logger); try { final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>[ 'build', '--config', 'build_name', ]); expect(result, equals(0)); expect(runHistory.length, greaterThanOrEqualTo(3)); expect( runHistory[2], containsStringsInOrder(<String>['python3', 'gen/script.py']), ); } finally { cleanupEnv(env); } }); test('build command does not invoke tests', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv(logger); try { final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>[ 'build', '--config', 'build_name', ]); expect(result, equals(0)); expect(runHistory.length, lessThanOrEqualTo(3)); } finally { cleanupEnv(env); } }); test('build command runs rbe on an rbe build', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv( logger, withRbe: true, ); try { final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>[ 'build', '--config', 'android_debug_rbe_arm64', ]); expect(result, equals(0)); expect(runHistory[0][0], contains(path.join('tools', 'gn'))); expect(runHistory[0][4], equals('--rbe')); expect(runHistory[1][0], contains(path.join('reclient', 'bootstrap'))); } finally { cleanupEnv(env); } }); test('build command does not run rbe when disabled', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv( logger, withRbe: true, ); try { final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>[ 'build', '--config', 'android_debug_rbe_arm64', '--no-rbe', ]); expect(result, equals(0)); expect(runHistory[0][0], contains(path.join('tools', 'gn'))); expect(runHistory[0], doesNotContainAny(<String>['--rbe'])); expect(runHistory[1][0], contains(path.join('ninja', 'ninja'))); } finally { cleanupEnv(env); } }); test('build command does not run rbe when rbe configs do not exist', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv(logger); try { final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>[ 'build', '--config', 'android_debug_rbe_arm64', ]); expect(result, equals(0)); expect(runHistory[0][0], contains(path.join('tools', 'gn'))); expect(runHistory[0], doesNotContainAny(<String>['--rbe'])); expect(runHistory[1][0], contains(path.join('ninja', 'ninja'))); } finally { cleanupEnv(env); } }); }
engine/tools/engine_tool/test/build_command_test.dart/0
{ "file_path": "engine/tools/engine_tool/test/build_command_test.dart", "repo_id": "engine", "token_count": 3459 }
462
#!/usr/bin/env python3 # 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. import argparse import os import sys import pathlib def main(): parser = argparse.ArgumentParser( "Verifies that all .dart files are included in sources, and sources don't include nonexsitent files" ) parser.add_argument( "--source_dir", help="Path to the directory containing the package sources", required=True ) parser.add_argument("--stamp", help="File to touch when source checking succeeds", required=True) parser.add_argument("sources", help="source files", nargs=argparse.REMAINDER) args = parser.parse_args() actual_sources = set() # Get all dart sources from source directory. src_dir_path = pathlib.Path(args.source_dir) for (dirpath, dirnames, filenames) in os.walk(src_dir_path, topdown=True): relpath_to_src_root = pathlib.Path(dirpath).relative_to(src_dir_path) actual_sources.update( os.path.normpath(relpath_to_src_root.joinpath(filename)) for filename in filenames if pathlib.Path(filename).suffix == ".dart" ) expected_sources = set(args.sources) # It is possible for sources to include dart files outside of source_dir. actual_sources.update([ s for s in (expected_sources - actual_sources) if src_dir_path.joinpath(s).resolve().exists() ],) if actual_sources == expected_sources: with open(args.stamp, "w") as stamp: stamp.write("Success!") return 0 def sources_to_abs_path(sources): return sorted(str(src_dir_path.joinpath(s)) for s in sources) missing_sources = actual_sources - expected_sources if missing_sources: print( '\nSource files found that were missing from the "sources" parameter:\n{}\n'.format( "\n".join(sources_to_abs_path(missing_sources)) ), ) nonexistent_sources = expected_sources - actual_sources if nonexistent_sources: print( '\nSource files listed in "sources" parameter but not found:\n{}\n'.format( "\n".join(sources_to_abs_path(nonexistent_sources)) ), ) return 1 if __name__ == "__main__": sys.exit(main())
engine/tools/fuchsia/dart/verify_sources.py/0
{ "file_path": "engine/tools/fuchsia/dart/verify_sources.py", "repo_id": "engine", "token_count": 810 }
463
package: flutter/fuchsia description: Flutter Fuchsia Artifacts install_mode: copy data: # Don't modify this! This is where the build script put all bucket artifacts. - dir: flutter/
engine/tools/fuchsia/fuchsia.cipd.yaml/0
{ "file_path": "engine/tools/fuchsia/fuchsia.cipd.yaml", "repo_id": "engine", "token_count": 55 }
464
#!/usr/bin/env python3 # # 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. """Uploads debug symbols to the symbols server.""" import argparse import os import subprocess import sys import tempfile ## Path to the engine root checkout. This is used to calculate absolute ## paths if relative ones are passed to the script. BUILD_ROOT_DIR = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..')) FUCHSIA_ARTIFACTS_DEBUG_NAMESPACE = 'debug' FUCHSIA_ARTIFACTS_BUCKET_NAME = 'fuchsia-artifacts-release' def remote_filename(exec_path): # An example of exec_path is: # out/fuchsia_debug_x64/flutter-fuchsia-x64/d4/917f5976.debug # In the above example "d4917f5976" is the elf BuildID for the # executable. First 2 characters are used as the directory name # and the rest of the string is the name of the unstripped executable. parts = exec_path.split('/') # We want d4917f5976.debug as the result. return ''.join(parts[-2:]) def exists_remotely(remote_path): gsutil = os.path.join(os.environ['DEPOT_TOOLS'], 'gsutil.py') command = ['python3', gsutil, '--', 'stat', remote_path] process = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = process.communicate() return_code = process.wait() if return_code == 0: print('%s exists - skipping copy' % remote_path) return return_code == 0 def process_symbols(should_upload, symbol_dir): full_path = os.path.join(BUILD_ROOT_DIR, symbol_dir) files = [] for (dirpath, dirnames, filenames) in os.walk(full_path): files.extend([os.path.join(dirpath, f) for f in filenames]) print('List of files to upload') print('\n'.join(files)) # Remove dbg_files files = [f for f in files if 'dbg_success' not in f] for file in files: remote_path = 'gs://%s/%s/%s' % ( FUCHSIA_ARTIFACTS_BUCKET_NAME, FUCHSIA_ARTIFACTS_DEBUG_NAMESPACE, remote_filename(file) ) if should_upload and not exists_remotely(remote_path): gsutil = os.path.join(os.environ['DEPOT_TOOLS'], 'gsutil.py') command = ['python3', gsutil, '--', 'cp', file, remote_path] subprocess.check_call(command) else: print(remote_path) def main(): parser = argparse.ArgumentParser() parser.add_argument( '--symbol-dir', required=True, help='Directory that contain the debug symbols.' ) parser.add_argument('--engine-version', required=True, help='Specifies the flutter engine SHA.') parser.add_argument( '--upload', default=False, action='store_true', help='If set, uploads symbols to the server.' ) args = parser.parse_args() should_upload = args.upload engine_version = args.engine_version if not engine_version: engine_version = 'HEAD' should_upload = False process_symbols(should_upload, args.symbol_dir) return 0 if __name__ == '__main__': sys.exit(main())
engine/tools/fuchsia/upload_to_symbol_server.py/0
{ "file_path": "engine/tools/fuchsia/upload_to_symbol_server.py", "repo_id": "engine", "token_count": 1086 }
465
# Git Hooks The behavior of `git` commands can be customized through the use of "hooks". These hooks are described in detail in git's [documentation](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks). `git` looks for an executables by name in the directory specified by the `core.hooksPath` `git config` setting. The script `setup.py` here points `core.hooksPath` at this directory. It runs during a `gclient sync` or a `gclient runhooks`. The hooks here are implemented in Dart by the program with entrypoint `bin/main.dart` in this directory. The commands of the program are the implementation of the different hooks, for example `bin/main.dart pre-push ...`. Since the Dart program itself isn't an executable, these commands are invoked by small Python wrapper scripts. These wrapper scripts have the names that `git` will look for. ## pre-push This hooks runs when pushing commits to a remote branch, for example to create or update a pull request: `git push origin my-local-branch`. The `pre-push` hook runs `ci/clang_tidy.sh`, `ci/pylint.sh` and `ci/format.sh`. `ci/analyze.sh` and `ci/licenses.sh` are more expensive and are not run. ### Adding new pre-push checks Since the pre-push checks run on every `git push`, they should run quickly. New checks can be added by modifying the `run()` method of the `PrePushCommand` class in `lib/src/pre_push_command.dart`. ## Creating a new hook 1. Check the `git` documentation, and copy `pre-push` into a script with the right name. 1. Make sure the script has the executable bit set (`chmod +x <script>`). 1. Add a new `Command` implementation under `lib/src`. Give the new `Command` the same name as the new hook. 1. Add the new `Command` to the `CommandRunner` in `lib/githooks.dart`. 1. Make sure the script from step (1) is passing the new command to the Dart program.
engine/tools/githooks/README.md/0
{ "file_path": "engine/tools/githooks/README.md", "repo_id": "engine", "token_count": 543 }
466
#!/usr/bin/env vpython3 # 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. from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import ctypes import multiprocessing import os import platform import re import subprocess import sys SRC_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def get_out_dir(args): if args.target_os is not None: target_dir = [args.target_os] elif args.web: target_dir = ['wasm'] else: target_dir = ['host'] target_dir.append(args.runtime_mode) if args.simulator: target_dir.append('sim') if args.unoptimized: target_dir.append('unopt') if args.target_os != 'ios' and args.interpreter: target_dir.append('interpreter') if args.android_cpu != 'arm': target_dir.append(args.android_cpu) if args.ios_cpu != 'arm64': target_dir.append(args.ios_cpu) if args.mac_cpu != 'x64': target_dir.append(args.mac_cpu) if args.simulator_cpu != 'x64': target_dir.append(args.simulator_cpu) if args.linux_cpu is not None: target_dir.append(args.linux_cpu) if args.windows_cpu != 'x64': target_dir.append(args.windows_cpu) if args.target_os == 'fuchsia' and args.fuchsia_cpu is not None: target_dir.append(args.fuchsia_cpu) # This exists for backwards compatibility of tests that are being run # on LUCI. This can be removed in coordination with a LUCI change: # https://github.com/flutter/flutter/issues/76547 if args.macos_enable_metal: target_dir.append('metal') if args.darwin_extension_safe: target_dir.append('extension_safe') if args.target_dir != '': target_dir = [args.target_dir] return os.path.join(args.out_dir, 'out', '_'.join(target_dir)) def to_command_line(gn_args): """Converts the arguments dictionary to a list of command-line arguments. Args: gn_args: GN arguments dictionary generated by to_gn_args(). """ def merge(key, value): if isinstance(value, bool): return '%s=%s' % (key, 'true' if value else 'false') if isinstance(value, int): return '%s=%d' % (key, value) return '%s="%s"' % (key, value) return [merge(x, y) for x, y in gn_args.items()] def is_host_build(args): # If target_os == None, then this is a host build. if args.target_os is None: return True # For linux arm64 builds, we cross compile from x64 hosts, so the # target_os='linux' and linux-cpu='arm64' if args.target_os == 'linux' and args.linux_cpu == 'arm64': return True # The Mac and host targets are redundant. Again, necessary to disambiguate # during cross-compilation. if args.target_os == 'mac': return True return False # Determines whether a prebuilt Dart SDK can be used instead of building one. def can_use_prebuilt_dart(args): prebuilt = None # When doing a 'host' build (args.target_os is None), or a build when the # target OS and host OS are different, the prebuilt Dart SDK is the Dart SDK # for the host system's OS and archetecture. if args.target_os is None or args.target_os in ['android', 'ios', 'fuchsia']: if sys.platform.startswith(('cygwin', 'win')): prebuilt = 'windows-x64' elif sys.platform == 'darwin': prebuilt = 'macos-x64' else: prebuilt = 'linux-x64' elif args.target_os == 'linux' and args.linux_cpu in ['x64', 'arm64']: prebuilt = 'linux-%s' % args.linux_cpu elif args.target_os == 'mac' and args.mac_cpu in ['x64', 'arm64']: prebuilt = 'macos-%s' % args.mac_cpu elif args.target_os == 'win' and args.windows_cpu in ['x64', 'arm64']: prebuilt = 'windows-%s' % args.windows_cpu prebuilts_dir = None if prebuilt is not None: prebuilts_dir = os.path.join(SRC_ROOT, 'flutter', 'prebuilts', prebuilt) return prebuilts_dir is not None and os.path.isdir(prebuilts_dir) # Returns the host machine operating system. def get_host_os(): if sys.platform.startswith(('cygwin', 'win')): return 'win' if sys.platform == 'darwin': return 'mac' return 'linux' # Runs true if the currently executing python interpreter is running under # Rosetta. I.e., python3 is an x64 executable and we're on an arm64 Mac. def is_rosetta(): if platform.system() == 'Darwin': proc = subprocess.Popen(['sysctl', '-in', 'sysctl.proc_translated'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, _ = proc.communicate() return output.decode('utf-8').strip() == '1' return False # Returns the host machine CPU architecture. def get_host_cpu(): # If gn itself is running under Rosetta on an arm64 Mac, platform.machine() # will return x86_64; instead return the underlying host architecture. if is_rosetta(): return 'arm64' machine = platform.machine() if machine in ['aarch64', 'arm64', 'ARM64']: return 'arm64' if machine in ['x86_64', 'AMD64', 'x64']: return 'x64' if machine in ['i686', 'i386', 'x86']: return 'x86' raise Exception('Unknown CPU architecture: %s' % machine) # Returns the target CPU architecture. # # For macOS host builds where --mac-cpu is specified, returns that value. # For windows host builds where --windows-cpu is specified, returns that value. # For all other host builds, assumes 'x64'. def get_target_cpu(args): if args.target_os == 'android': return args.android_cpu if args.target_os == 'ios': if args.simulator: return args.simulator_cpu return args.ios_cpu if args.target_os == 'mac': return args.mac_cpu if args.target_os == 'linux': return args.linux_cpu if args.target_os == 'fuchsia': return args.fuchsia_cpu if args.target_os == 'wasm': return 'wasm' if args.target_os == 'win': return args.windows_cpu # Host build. Default to x64 unless overridden. if get_host_os() == 'mac' and args.mac_cpu: return args.mac_cpu if get_host_os() == 'win' and args.windows_cpu: return args.windows_cpu return 'x64' def buildtools_dir(): host_os = get_host_os() host_cpu = get_host_cpu() if host_os == 'win': host_os = 'windows' return '%s-%s' % (host_os, host_cpu) def setup_rbe(args): rbe_gn_args = {} # RBE is default-off. If it is not asked for, then silently keep all default # flag values. if not args.rbe: return rbe_gn_args rbe_gn_args['use_rbe'] = True # When running in CI, the recipes use their own rbe install, and take # care of starting and stopping the compiler proxy. running_on_luci = os.environ.get('LUCI_CONTEXT') is not None if args.rbe_server_address: rbe_gn_args['rbe_server_address'] = args.rbe_server_address if args.rbe_exec_strategy: rbe_gn_args['rbe_exec_strategy'] = args.rbe_exec_strategy if args.rbe_dial_timeout: rbe_gn_args['rbe_dial_timeout'] = args.rbe_dial_timeout if args.rbe_platform: rbe_gn_args['rbe_platform'] = args.rbe_platform rbe_gn_args['rbe_dir'] = os.path.join(SRC_ROOT, 'buildtools', buildtools_dir(), 'reclient') rbe_gn_args['rbe_cfg'] = os.path.join( SRC_ROOT, 'flutter', 'build', 'rbe', 'rewrapper-' + buildtools_dir() + '.cfg' ) if sys.platform == 'darwin': if (not running_on_luci or args.xcode_symlinks or os.getenv('FLUTTER_GOMA_CREATE_XCODE_SYMLINKS', '0') == '1'): rbe_gn_args['create_xcode_symlinks'] = True return rbe_gn_args def setup_goma(args): goma_gn_args = {} # If RBE is requested, don't try to use goma. if args.rbe: goma_gn_args['use_goma'] = False goma_gn_args['goma_dir'] = None return goma_gn_args # args.goma has three states, True (--goma), False (--no-goma), and # None (default). In True mode, we force GOMA to be used (and fail # if we cannot enable it) unless the selected target definitely does # not support it (in which case we print a warning). In False mode, # we disable GOMA regardless. In None mode, we enable it if we can # autodetect a configuration, and otherwise disable it. # When running in CI, the recipes use their own goma install, and take # care of starting and stopping the compiler proxy. running_on_luci = os.environ.get('LUCI_CONTEXT') is not None # The GOMA client has no arm64 binary, so run the x64 binary through # Rosetta. buildtools_platform = buildtools_dir() if buildtools_platform == 'mac-arm64': buildtools_platform = 'mac-x64' # Prefer the goma fetched by gclient if it exists. cipd_goma_dir = os.path.join(SRC_ROOT, 'buildtools', buildtools_platform, 'goma') # Next, if GOMA_DIR is set, use that install. goma_dir = os.environ.get('GOMA_DIR') # Finally, look for goma in the install location recommended in our # documentation. goma_home_dir = os.path.join(os.getenv('HOME', ''), 'goma') # GOMA has a different default (home) path on gWindows. if not os.path.exists(goma_home_dir) and sys.platform.startswith(('cygwin', 'win')): goma_home_dir = os.path.join('c:\\', 'src', 'goma', 'goma-win64') if args.target_os == 'wasm' or args.web: goma_gn_args['use_goma'] = False goma_gn_args['goma_dir'] = None if args.goma: print('Disabling GOMA for wasm builds, it is not supported yet.') elif args.goma is not False and not running_on_luci and os.path.exists(cipd_goma_dir): goma_gn_args['use_goma'] = True goma_gn_args['goma_dir'] = cipd_goma_dir elif args.goma is not False and goma_dir and os.path.exists(goma_dir): goma_gn_args['use_goma'] = True goma_gn_args['goma_dir'] = goma_dir elif args.goma is not False and os.path.exists(goma_home_dir): goma_gn_args['use_goma'] = True goma_gn_args['goma_dir'] = goma_home_dir elif args.goma: raise Exception( 'GOMA was specified but was not found. Set the GOMA_DIR environment ' 'variable, install goma at $HOME/goma following the instructions at ' 'https://github.com/flutter/flutter/wiki/Compiling-the-engine, or ' 'run this script with the --no-goma flag to do a non-goma-enabled ' 'build.', ) else: goma_gn_args['use_goma'] = False goma_gn_args['goma_dir'] = None if goma_gn_args['use_goma'] and sys.platform == 'darwin': if (not running_on_luci or args.xcode_symlinks or os.getenv('FLUTTER_GOMA_CREATE_XCODE_SYMLINKS', '0') == '1'): goma_gn_args['create_xcode_symlinks'] = True return goma_gn_args # Find the locations of the macOS and iOS SDKs under flutter/prebuilts. def setup_apple_sdks(): sdks_gn_args = {} # These are needed on a macOS host regardless of target. # This value should agree with the 'mac_sdk_min' value in the DEPS file. sdks_gn_args['mac_sdk_min'] = '10.14' # The MACOSX_DEPLOYMENT_TARGET variable used when compiling. # Must be of the form x.x.x for Info.plist files. sdks_gn_args['mac_deployment_target'] = '10.14.0' running_on_luci = os.environ.get('LUCI_CONTEXT') is not None if running_on_luci: return sdks_gn_args prefixes = [ ('MacOSX', 'mac_sdk_path'), ('iPhoneOS', 'ios_device_sdk_path'), ('iPhoneSimulator', 'ios_simulator_sdk_path'), ] sdks_path = os.path.join(SRC_ROOT, 'flutter', 'prebuilts', 'SDKs') sdk_entries = os.listdir(sdks_path) for (prefix, arg) in prefixes: for entry in sdk_entries: if entry.startswith(prefix): sdks_gn_args[arg] = os.path.join(sdks_path, entry) return sdks_gn_args def get_repository_version(repository): 'Returns the Git HEAD for the supplied repository path as a string.' if not os.path.exists(repository): raise IOError('path does not exist') git = 'git' if sys.platform.startswith(('cygwin', 'win')): git = 'git.bat' version = subprocess.check_output([ git, '-C', repository, 'rev-parse', 'HEAD', ]) return str(version.strip(), 'utf-8') def setup_git_versions(): revision_args = {} engine_path = os.path.join(SRC_ROOT, 'flutter') revision_args['engine_version'] = get_repository_version(engine_path) skia_path = os.path.join(SRC_ROOT, 'flutter', 'third_party', 'skia') revision_args['skia_version'] = get_repository_version(skia_path) dart_path = os.path.join(SRC_ROOT, 'third_party', 'dart') revision_args['dart_version'] = get_repository_version(dart_path) return revision_args # pylint: disable=line-too-long # See https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex # and https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-memorystatusex # pylint: enable=line-too-long class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ('dwLength', ctypes.c_ulong), ('dwMemoryLoad', ctypes.c_ulong), ('ullTotalPhys', ctypes.c_ulonglong), ('ullAvailPhys', ctypes.c_ulonglong), ('ullTotalPageFile', ctypes.c_ulonglong), ('ullAvailPageFile', ctypes.c_ulonglong), ('ullTotalVirtual', ctypes.c_ulonglong), ('ullAvailVirtual', ctypes.c_ulonglong), ('sullAvailExtendedVirtual', ctypes.c_ulonglong), ] def get_total_memory(): if sys.platform in ('win32', 'cygwin'): stat = MEMORYSTATUSEX(dwLength=ctypes.sizeof(MEMORYSTATUSEX)) success = ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) return stat.ullTotalPhys if success else 0 if sys.platform.startswith('linux'): if os.path.exists('/proc/meminfo'): with open('/proc/meminfo') as meminfo: memtotal_re = re.compile(r'^MemTotal:\s*(\d*)\s*kB') for line in meminfo: match = memtotal_re.match(line) if match: return float(match.group(1)) * 2**10 if sys.platform == 'darwin': try: return int(subprocess.check_output(['sysctl', '-n', 'hw.memsize'])) except: # pylint: disable=bare-except return 0 return 0 def parse_size(string): units = {'B': 1, 'KB': 2**10, 'MB': 2**20, 'GB': 2**30, 'TB': 2**40} i = next(i for (i, c) in enumerate(string) if not c.isdigit()) number = string[:i].strip() unit = string[i:].strip() return int(float(number) * units[unit]) def get_concurrent_jobs(reserve_memory, memory_per_job): # reserve_memory = 2**30 total_memory = get_total_memory() # Ensure the total memory used in the calculation below is at least 0 mem_total_bytes = max(0, total_memory - parse_size(reserve_memory)) # Ensure the number of cpus used in the calculation below is at least 1 try: cpu_cap = multiprocessing.cpu_count() except: # pylint: disable=bare-except cpu_cap = 1 # Calculate the number of jobs that will fit in memory. Ensure the # value is at least 1. num_concurrent_jobs = int(max(1, mem_total_bytes / parse_size(memory_per_job))) # Cap the number of jobs by the number of cpus available. concurrent_jobs = min(num_concurrent_jobs, cpu_cap) return concurrent_jobs def to_gn_args(args): if args.simulator: if args.target_os != 'ios': raise Exception('--simulator is only supported for iOS') runtime_mode = args.runtime_mode gn_args = {} gn_args['is_debug'] = args.unoptimized gn_args.update(setup_git_versions()) gn_args.update(setup_goma(args)) gn_args.update(setup_rbe(args)) # If building for WASM, set the GN args using 'to_gn_wasm_args' as most # of the Flutter SDK specific arguments are unused. if args.target_os == 'wasm' or args.web: to_gn_wasm_args(args, gn_args) return gn_args gn_args['full_dart_sdk'] = args.full_dart_sdk if args.enable_unittests: # Ensure that Android and iOS are *not* used with --enable-unittests. # https://github.com/flutter/flutter/issues/132611 if args.target_os == 'android' or args.target_os == 'ios': raise Exception( 'Cannot use --enable-unittests with --target-os=android or ios. If ' + 'you are trying to create an output directory to use for clangd ' + '(i.e. for VSCode integration), use a host build instead.\n\n' + 'See https://github.com/flutter/flutter/wiki/' + 'Setting-up-the-Engine-development-environment' + '#vscode-with-cc-intellisense-cc' ) gn_args['enable_unittests'] = True if args.no_enable_unittests: gn_args['enable_unittests'] = False # Skia GN args. gn_args['skia_use_dng_sdk'] = False # RAW image handling. gn_args['skia_enable_pdf'] = False # PDF handling. gn_args['skia_use_x11'] = False # Never add the X11 dependency (only takes effect on Linux). gn_args['skia_use_wuffs'] = True gn_args['skia_use_expat'] = True gn_args['skia_use_fontconfig'] = args.enable_fontconfig gn_args['skia_use_icu'] = True gn_args['is_official_build'] = True # Disable Skia test utilities. gn_args['android_full_debug'] = args.target_os == 'android' and args.unoptimized if args.clang is None: gn_args['is_clang'] = True else: gn_args['is_clang'] = args.clang if args.target_os == 'android' or args.target_os == 'ios': gn_args['skia_gl_standard'] = 'gles' else: # We explicitly don't want to pick GL because we run GLES tests using SwiftShader. gn_args['skia_gl_standard'] = '' if not sys.platform.startswith(('cygwin', 'win')): gn_args['use_clang_static_analyzer'] = args.clang_static_analyzer gn_args['enable_coverage'] = args.coverage if args.operator_new_alignment is not None: gn_args['operator_new_alignment'] = args.operator_new_alignment enable_lto = args.lto if args.unoptimized: # There is no point in enabling LTO in unoptimized builds. enable_lto = False if not sys.platform.startswith('win'): # The GN arg is not available in the windows toolchain. gn_args['enable_lto'] = enable_lto # Set OS, CPU arch for host or target build. if is_host_build(args): gn_args['host_os'] = get_host_os() gn_args['host_cpu'] = get_host_cpu() gn_args['target_os'] = gn_args['host_os'] gn_args['target_cpu'] = get_target_cpu(args) gn_args['dart_target_arch'] = gn_args['target_cpu'] else: gn_args['target_os'] = args.target_os gn_args['target_cpu'] = get_target_cpu(args) gn_args['dart_target_arch'] = gn_args['target_cpu'] if not args.build_engine_artifacts: gn_args['flutter_build_engine_artifacts'] = False # We cannot cross-compile for 32 bit arm on a Windows host. We work around # this by leaving 'target_cpu' and 'dart_target_arch' set to 'arm' so that # Dart tools such as gen_snapshot that are built for the host will correctly # target arm, but we hardcode the 'current_cpu' to always be the host arch # so that the GN build doesn't go looking for a Windows arm toolchain, which # does not exist. Further, we set the 'host_cpu' so that it shares the # bitwidth of the 32-bit arm target. if sys.platform.startswith( ('cygwin', 'win')) and args.target_os == 'android' and gn_args['target_cpu'] == 'arm': gn_args['host_cpu'] = 'x86' gn_args['current_cpu'] = 'x86' # When building binaries to run on a macOS host (like gen_snapshot), always # use the clang_x64 toolchain, which will run under Rosetta. This is done for # two reasons: # 1. goma currently only supports the clang_x64 toolchain. # 2. gen_snapshot cannot crossbuild from arm64 to x64. Its host architecture # must be x64 to target x64. # TODO(cbracken): https://github.com/flutter/flutter/issues/103386 if get_host_os() == 'mac' and not args.force_mac_arm64: gn_args['host_cpu'] = 'x64' if gn_args['target_os'] == 'ios': gn_args['use_ios_simulator'] = args.simulator gn_args.update(setup_apple_sdks()) elif get_host_os() == 'mac': gn_args['use_ios_simulator'] = False gn_args.update(setup_apple_sdks()) if args.dart_debug: gn_args['dart_debug'] = True if args.full_dart_debug: gn_args['dart_debug'] = True gn_args['dart_debug_optimization_level'] = '0' if args.dart_optimization_level: gn_args['dart_default_optimization_level'] = args.dart_optimization_level elif gn_args['target_os'] in ['android', 'ios']: gn_args['dart_default_optimization_level'] = '2' gn_args['flutter_use_fontconfig'] = args.enable_fontconfig gn_args['dart_component_kind'] = 'static_library' # Always link Dart in statically. gn_args['embedder_for_target'] = args.embedder_for_target gn_args['dart_lib_export_symbols'] = False gn_args['flutter_runtime_mode'] = runtime_mode gn_args['dart_version_git_info'] = not args.no_dart_version_git_info gn_args['dart_lib_export_symbols'] = False if runtime_mode == 'debug': gn_args['dart_runtime_mode'] = 'develop' elif runtime_mode == 'jit_release': gn_args['dart_runtime_mode'] = 'release' else: gn_args['dart_runtime_mode'] = runtime_mode gn_args['concurrent_dart_jobs'] = get_concurrent_jobs('1GB', '1GB') # Hardcoding this avoids invoking a relatively expensive python script from # GN, but removes the ability to use git-worktrees in the Dart checkout from # within the Engine repo, but it's unlikely anyone is using that. gn_args['default_git_folder'] = os.path.join(SRC_ROOT, 'third_party', 'dart', '.git') # By default, the Dart GN build will invoke a relatively expensive python # script to calculate an SDK "hash" that ensures compatibility between the # Dart VM and the Dart front-end. This default hash calculation allows some # wiggle room in which a VM and kernel file will be compatible forwards and # backwards across a small range of git commits. Since Flutter doesn't need # the wiggle room, to avoid running the python script, we instead set the SDK # hash to the exact git commit. sdk_hash = gn_args['dart_version'] gn_args['dart_sdk_verification_hash'] = sdk_hash if len(sdk_hash) <= 10 else sdk_hash[:10] # Desktop embeddings can have more dependencies than the engine library, # which can be problematic in some build environments (e.g., building on # Linux will bring in pkg-config dependencies at generation time). These # flags allow preventing those targets from being part of the build tree. gn_args['enable_desktop_embeddings'] = not args.disable_desktop_embeddings # Determine whether backtace support should be compiled in. if args.backtrace: gn_args['enable_backtrace'] = ( args.target_os in ['linux', 'mac', 'win'] or args.target_os == 'ios' and runtime_mode == 'debug' ) else: gn_args['enable_backtrace'] = False # Overrides whether Boring SSL is compiled with system as. Only meaningful # on Android. gn_args['bssl_use_clang_integrated_as'] = True if args.allow_deprecated_api_calls: gn_args['allow_deprecated_api_calls'] = args.allow_deprecated_api_calls # DBC is not supported anymore. if args.interpreter: raise Exception('--interpreter is no longer needed on any supported platform.') if args.target_os is None: if sys.platform.startswith(('cygwin', 'win')): gn_args['dart_use_fallback_root_certificates'] = True if args.target_sysroot: gn_args['target_sysroot'] = args.target_sysroot gn_args['custom_sysroot'] = args.target_sysroot if args.target_toolchain: gn_args['custom_toolchain'] = args.target_toolchain if args.target_triple: gn_args['custom_target_triple'] = args.target_triple # Enable Metal on iOS builds. if args.target_os == 'ios': gn_args['shell_enable_gl'] = False gn_args['skia_use_gl'] = False gn_args['shell_enable_metal'] = True gn_args['skia_use_metal'] = True else: gn_args['skia_use_gl'] = args.target_os != 'fuchsia' if sys.platform == 'darwin' and args.target_os not in ['android', 'fuchsia']: # OpenGL is deprecated on macOS > 10.11. # This is not necessarily needed but enabling this until we have a way to # build a macOS metal only shell and a gl only shell. gn_args['allow_deprecated_api_calls'] = True gn_args['skia_use_metal'] = True gn_args['shell_enable_metal'] = True # Enable Vulkan on all platforms except for iOS. This is just # to save on mobile binary size, as there's no reason the Vulkan embedder # features can't work on these platforms. if gn_args['target_os'] not in ['ios', 'mac']: gn_args['skia_use_vulkan'] = True gn_args['skia_use_vma'] = False gn_args['shell_enable_vulkan'] = True # Disable VMA's use of std::shared_mutex in environments where the # standard library doesn't support it. if args.target_os == 'ios' or sys.platform.startswith(('cygwin', 'win')): gn_args['disable_vma_stl_shared_mutex'] = True # We should not need a special case for x86, but this seems to introduce text relocations # even with -fPIC everywhere. # gn_args['enable_profiling'] = args.runtime_mode != 'release' and args.android_cpu != 'x86' # Make symbols visible in order to enable symbolization of unit test crash backtraces on Linux gn_args['disable_hidden_visibility'] = args.target_os == 'linux' and args.unoptimized if args.arm_float_abi: gn_args['arm_float_abi'] = args.arm_float_abi # If we have a prebuilt for the Dart SDK for the target architecture, then # use it instead of building a new one. if args.prebuilt_dart_sdk: if can_use_prebuilt_dart(args): print( 'Using prebuilt Dart SDK binary. If you are editing Dart sources ' 'and wish to compile the Dart SDK, set `--no-prebuilt-dart-sdk`.' ) gn_args['flutter_prebuilt_dart_sdk'] = True gn_args['dart_sdk_output'] = 'built-dart-sdk' elif is_host_build(args): print( 'Tried to download prebuilt Dart SDK but an appropriate version ' 'could not be found!' ) print( 'Either retry by running ' 'flutter/tools/download_dart_sdk.py manually or compile from ' 'source by setting `--no-prebuilt-dart-sdk` flag to tools/gn' ) elif is_host_build(args): # If we are building the dart sdk in-tree, exclude the wasm-opt target, as # it doesn't build properly with our gn configuration. gn_args['dart_include_wasm_opt'] = False # dart_platform_sdk is only defined for host builds, linux arm host builds # specify target_os=linux. # dart_platform_sdk=True means exclude web-related files, e.g. dart2js, # dartdevc, web SDK kernel and source files. gn_args['dart_platform_sdk'] = not args.full_dart_sdk if args.build_glfw_shell is not None: gn_args['build_glfw_shell'] = args.build_glfw_shell if args.build_embedder_examples is not None: gn_args['build_embedder_examples'] = args.build_embedder_examples gn_args['stripped_symbols'] = args.stripped if args.msan: gn_args['is_msan'] = True if args.asan: gn_args['is_asan'] = True if args.tsan: gn_args['is_tsan'] = True if args.lsan: gn_args['is_lsan'] = True if args.ubsan: gn_args['is_ubsan'] = True if args.fstack_protector: gn_args['use_fstack_protector'] = True enable_vulkan_validation = args.enable_vulkan_validation_layers # Enable Vulkan validation layer automatically on debug builds for arm64. if args.unoptimized and args.target_os == 'android' and args.android_cpu == 'arm64': enable_vulkan_validation = True if enable_vulkan_validation: gn_args['enable_vulkan_validation_layers'] = True gn_args['impeller_enable_vulkan_validation_layers'] = True # Enable pointer compression on 64-bit mobile targets. iOS is excluded due to # its inability to allocate address space without allocating memory. if args.target_os in ['android'] and gn_args['target_cpu'] in ['x64', 'arm64']: gn_args['dart_use_compressed_pointers'] = True if args.target_os == 'fuchsia': gn_args['gn_configs_path'] = '//flutter/build/config/fuchsia/gn_configs.gni' gn_args['fuchsia_gn_sdk'] = '//flutter/tools/fuchsia/gn-sdk' # Flags for Dart features: if args.use_mallinfo2: gn_args['dart_use_mallinfo2'] = args.use_mallinfo2 # Impeller flags. if args.enable_impeller_3d: gn_args['impeller_enable_3d'] = True if args.enable_impeller_trace_canvas: gn_args['impeller_trace_canvas'] = True if args.prebuilt_impellerc is not None: gn_args['impeller_use_prebuilt_impellerc'] = args.prebuilt_impellerc malioc_path = args.malioc_path if not malioc_path: malioc_path = os.environ.get('MALIOC_PATH') if malioc_path: gn_args['impeller_malioc_path'] = malioc_path gn_args['impeller_concurrent_malioc_jobs'] = get_concurrent_jobs('1GB', '100MB') if args.use_glfw_swiftshader: if get_host_os() == 'mac': gn_args['glfw_vulkan_library'] = r'\"libvulkan.dylib\"' elif get_host_os() == 'linux': gn_args['glfw_vulkan_library'] = r'\"libvulkan.so.1\"' # ANGLE is exclusively used for: # - Windows at runtime # - Non-fuchsia host unit tests (is_host_build evaluates to false). # Setting these variables creates warnings otherwise. # If we add ANGLE usage on other platforms, include them here. # There is a special case for Android on Windows because there we _only_ build # gen_snapshot, but the build defines otherwise make it look like the build is # for a host Windows build and make GN think we will be building ANGLE. # Angle is not used on Mac hosts as there are no tests for the OpenGL backend. if is_host_build(args) or (args.target_os == 'android' and get_host_os() == 'win'): # Don't include git commit information. gn_args['angle_enable_commit_id'] = False # Do not build unnecessary parts of the ANGLE tree. gn_args['angle_build_all'] = False gn_args['angle_has_astc_encoder'] = False # Force ANGLE context checks on Windows to prevent crashes. # TODO(loic-sharma): Remove this once ANGLE crashes have been fixed. # https://github.com/flutter/flutter/issues/114107 if get_host_os() == 'win': gn_args['angle_force_context_check_every_call'] = True if get_host_os() == 'mac': gn_args['angle_enable_metal'] = True gn_args['angle_enable_gl'] = False gn_args['angle_enable_vulkan'] = False # ANGLE and SwiftShader share build flags to enable X11 and Wayland, # but we only need these enabled for SwiftShader. gn_args['angle_use_x11'] = False gn_args['angle_use_wayland'] = False # Requires RTTI. We may want to build this in debug modes, punting on that # for now. gn_args['angle_enable_vulkan_validation_layers'] = False gn_args['angle_vulkan_headers_dir'] = '//flutter/third_party/vulkan-deps/vulkan-headers/src' gn_args['angle_vulkan_loader_dir'] = '//flutter/third_party/vulkan-deps/vulkan-loader/src' gn_args['angle_vulkan_tools_dir'] = '//flutter/third_party/vulkan-deps/vulkan-tools/src' if args.darwin_extension_safe: gn_args['darwin_extension_safe'] = True return gn_args # When building for WASM, almost all GN args used in the Flutter SDK # build are unused. This method is used instead. def to_gn_wasm_args(args, gn_args): gn_args['is_official_build'] = True gn_args['is_component_build'] = False gn_args['use_clang_static_analyzer'] = False gn_args['is_clang'] = True gn_args['target_os'] = 'wasm' gn_args['target_cpu'] = 'wasm' gn_args['wasm_use_dwarf'] = args.wasm_use_dwarf gn_args['skia_use_angle'] = False gn_args['skia_use_dng_sdk'] = False gn_args['skia_use_expat'] = False gn_args['skia_use_vulkan'] = False gn_args['skia_use_webgpu'] = False gn_args['skia_use_libheif'] = False gn_args['skia_use_libjpeg_turbo_encode'] = False gn_args['skia_use_no_jpeg_encode'] = True # TODO(yjbanov): https://github.com/flutter/flutter/issues/122759 # Remove this and implement it through Canvas2d. gn_args['skia_use_libpng_encode'] = True gn_args['skia_use_libwebp_encode'] = False gn_args['skia_use_no_webp_encode'] = True gn_args['skia_use_lua'] = False gn_args['skia_use_wuffs'] = True gn_args['skia_use_zlib'] = True gn_args['skia_gl_standard'] = 'webgl' gn_args['skia_enable_ganesh'] = True gn_args['skia_enable_skottie'] = False gn_args['skia_enable_sksl_tracing'] = False gn_args['icu_use_data_file'] = False gn_args['skia_use_freetype'] = True gn_args['skia_use_harfbuzz'] = True gn_args['skia_use_fontconfig'] = False gn_args['skia_use_libheif'] = False gn_args['skia_enable_fontmgr_custom_directory'] = False gn_args['skia_enable_fontmgr_custom_embedded'] = True gn_args['skia_enable_fontmgr_custom_empty'] = True gn_args['skia_enable_skshaper'] = True gn_args['skia_enable_skparagraph'] = True gn_args['skia_canvaskit_force_tracing'] = False gn_args['skia_canvaskit_enable_skp_serialization'] = True gn_args['skia_canvaskit_enable_effects_deserialization'] = False gn_args['skia_canvaskit_include_viewer'] = False gn_args['skia_canvaskit_enable_pathops'] = True gn_args['skia_canvaskit_enable_rt_shader'] = True gn_args['skia_canvaskit_enable_matrix_helper'] = False gn_args['skia_canvaskit_enable_canvas_bindings'] = False gn_args['skia_canvaskit_enable_font'] = True gn_args['skia_canvaskit_enable_embedded_font'] = False gn_args['skia_canvaskit_enable_alias_font'] = True gn_args['skia_canvaskit_legacy_draw_vertices_blend_mode'] = False gn_args['skia_canvaskit_enable_debugger'] = False gn_args['skia_canvaskit_enable_paragraph'] = True gn_args['skia_canvaskit_enable_webgl'] = True gn_args['skia_canvaskit_enable_webgpu'] = False gn_args['skia_canvaskit_profile_build'] = args.runtime_mode == 'profile' gn_args['flutter_prebuilt_dart_sdk'] = True def run_impeller_cmake(args): impeller_cmake_dir = os.path.join('third_party', 'impeller-cmake-example') if not os.path.isdir(os.path.join(SRC_ROOT, impeller_cmake_dir)): print('The Impeller cmake example directory "{}" does not exist'.format(impeller_cmake_dir)) return 1 goma_gn_args = setup_goma(args) goma_dir = goma_gn_args['goma_dir'] cmake_cmd = [ 'python3', os.path.join(SRC_ROOT, 'flutter', 'ci', 'impeller_cmake_build_test.py'), '--path', impeller_cmake_dir, '--cmake', ] if goma_dir is not None: cmake_cmd = cmake_cmd + ['--goma-dir', goma_dir] if args.xcode_symlinks: cmake_cmd = cmake_cmd + ['--xcode-symlinks'] try: cmake_call_result = subprocess.call(cmake_cmd, cwd=SRC_ROOT) except subprocess.CalledProcessError as exc: print('Failed to generate cmake files: ', exc.returncode, exc.output) return 1 return cmake_call_result def parse_args(args): args = args[1:] parser = argparse.ArgumentParser(description='A script to run `gn gen`.') parser.add_argument('--unoptimized', default=False, action='store_true') parser.add_argument( '--enable-unittests', action='store_true', default=False, help='Force enable building unit test binaries.' ) parser.add_argument( '--no-enable-unittests', default=False, action='store_true', help='Force disable building unit test binaries.' ) parser.add_argument( '--runtime-mode', type=str, choices=['debug', 'profile', 'release', 'jit_release'], default='debug' ) parser.add_argument('--interpreter', default=False, action='store_true') parser.add_argument( '--dart-debug', default=False, action='store_true', help='Enables assertions in the Dart VM. Does not affect optimization ' 'levels. If you need to disable optimizations in Dart, use ' '--full-dart-debug' ) parser.add_argument( '--no-dart-version-git-info', default=False, action='store_true', help='Set by default; if unset, turns off the dart SDK git hash check' ) parser.add_argument( '--full-dart-debug', default=False, action='store_true', help='Implies --dart-debug and also disables optimizations in the Dart ' 'VM making it easier to step through VM code in the debugger.' ) parser.add_argument( '--dart-optimization-level', type=str, help='The default optimization level for the Dart VM runtime.', ) parser.add_argument( '--target-os', type=str, choices=['android', 'ios', 'mac', 'linux', 'fuchsia', 'wasm', 'win'] ) parser.add_argument('--android', dest='target_os', action='store_const', const='android') parser.add_argument( '--android-cpu', type=str, choices=['arm', 'x64', 'x86', 'arm64'], default='arm' ) parser.add_argument('--ios', dest='target_os', action='store_const', const='ios') parser.add_argument('--ios-cpu', type=str, choices=['arm', 'arm64'], default='arm64') parser.add_argument('--mac', dest='target_os', action='store_const', const='mac') parser.add_argument('--mac-cpu', type=str, choices=['x64', 'arm64'], default='x64') parser.add_argument( '--force-mac-arm64', action='store_true', default=False, help='Force use of the clang_arm64 toolchain on an arm64 mac host when ' 'building host binaries.' ) parser.add_argument('--simulator', action='store_true', default=False) parser.add_argument('--linux', dest='target_os', action='store_const', const='linux') parser.add_argument('--fuchsia', dest='target_os', action='store_const', const='fuchsia') parser.add_argument('--wasm', dest='target_os', action='store_const', const='wasm') parser.add_argument( '--wasm-use-dwarf', action='store_true', default=False, help='Embed dwarf debugging info in the output module instead of using ' 'sourcemap files.' ) parser.add_argument('--web', action='store_true', default=False) parser.add_argument('--windows', dest='target_os', action='store_const', const='win') parser.add_argument('--linux-cpu', type=str, choices=['x64', 'x86', 'arm64', 'arm']) parser.add_argument('--fuchsia-cpu', type=str, choices=['x64', 'arm64'], default='x64') parser.add_argument('--windows-cpu', type=str, choices=['x64', 'arm64', 'x86'], default='x64') parser.add_argument('--simulator-cpu', type=str, choices=['x64', 'arm64'], default='x64') parser.add_argument('--arm-float-abi', type=str, choices=['hard', 'soft', 'softfp']) # Whether to compile in backtrace support. # Available for Windows and POSIX platforms whose libc includes execinfo.h. # MUSL doesn't include execinfo.h should be build with --no-backtrace. parser.add_argument( '--backtrace', default=True, action='store_true', help='Whether OS support exists for collecting backtraces.' ) parser.add_argument('--no-backtrace', dest='backtrace', action='store_false') parser.add_argument( '--build-engine-artifacts', default=True, action='store_true', help='Build the host-side development artifacts.' ) parser.add_argument( '--no-build-engine-artifacts', dest='build_engine_artifacts', action='store_false', help='Do not build the host-side development artifacts.' ) parser.add_argument('--rbe', default=None, action='store_true') parser.add_argument('--no-rbe', dest='rbe', action='store_false') parser.add_argument( '--rbe-server-address', default=None, type=str, help='The reproxy serveraddress' ) parser.add_argument( '--rbe-exec-strategy', default=None, type=str, help='The RBE execution strategy.', choices=['local', 'remote', 'remote_local_fallback', 'racing'] ) parser.add_argument( '--rbe-dial-timeout', default=None, type=str, help='The timeout for connecting to the local reproxy server.', ) parser.add_argument( '--rbe-platform', default=None, type=str, help='The RBE "platform" string. This is used to identify remote platform ' 'settings like the docker image to use to run the command.' ) parser.add_argument( '--rbe-dir', default=None, type=str, help='The location of the reclient binaries.' ) parser.add_argument('--goma', default=None, action='store_true') parser.add_argument('--no-goma', dest='goma', action='store_false') parser.add_argument( '--xcode-symlinks', action='store_true', help='Set to true for builds targeting macOS or iOS when using goma. If ' 'set, symlinks to the Xcode provided sysroot and SDKs will be ' 'created in a generated folder, which will avoid potential backend ' 'errors in Fuchsia RBE. Instead of specifying the flag on each ' 'invocation the FLUTTER_GOMA_CREATE_XCODE_SYMLINKS environment ' 'variable may be set to 1 to achieve the same effect.' ) parser.add_argument( '--no-xcode-symlinks', dest='xcode_symlinks', default=False, action='store_false' ) parser.add_argument( '--depot-tools', default='~/depot_tools', type=str, help='Depot tools provides an alternative location for gomacc in ' + '/path/to/depot_tools/.cipd_bin' ) parser.add_argument('--lto', default=True, action='store_true') parser.add_argument('--no-lto', dest='lto', action='store_false') parser.add_argument('--clang', action='store_const', const=True) parser.add_argument('--no-clang', dest='clang', action='store_const', const=False) parser.add_argument('--clang-static-analyzer', default=False, action='store_true') parser.add_argument( '--no-clang-static-analyzer', dest='clang_static_analyzer', action='store_false' ) parser.add_argument('--target-sysroot', type=str) parser.add_argument('--target-toolchain', type=str) parser.add_argument('--target-triple', type=str) parser.add_argument( '--operator-new-alignment', dest='operator_new_alignment', type=str, default=None ) parser.add_argument('--macos-enable-metal', action='store_true', default=False) parser.add_argument('--enable-vulkan', action='store_true', default=False) parser.add_argument('--enable-fontconfig', action='store_true', default=False) parser.add_argument('--enable-vulkan-validation-layers', action='store_true', default=False) parser.add_argument( '--embedder-for-target', dest='embedder_for_target', action='store_true', default=False ) parser.add_argument('--coverage', default=False, action='store_true') parser.add_argument( '--out-dir', default='', type=str, help='Root out directory. Target specific gn files will be generated in ${out-dir}/' ) parser.add_argument( '--target-dir', default='', type=str, help='Use the specified name for target out directory. By default this tool determines one.' ) parser.add_argument( '--full-dart-sdk', default=False, action='store_true', help='include trained dart2js and dartdevc snapshots. Enable only on steps that create an SDK' ) parser.add_argument('--no-full-dart-sdk', dest='full_dart_sdk', action='store_false') parser.add_argument( '--build-canvaskit', default=False, action='store_true', help='build canvaskit from source (DEPRECATED: use ninja targets to select what to build)' ) parser.add_argument( '--ide', default='', type=str, help='The IDE files to generate using GN. Use `gn gen help` and look for the --ide flag to' + ' see supported IDEs. If this flag is not specified, a platform specific default is selected.' ) parser.add_argument( '--allow-deprecated-api-calls', action='store_true', default=False, help='Turns off warnings about the usage of deprecated APIs.' ) parser.add_argument( '--disable-desktop-embeddings', default=False, action='store_true', help='Do not include desktop embeddings in the build.' ) parser.add_argument( '--build-glfw-shell', action='store_const', const=True, help='Build the GLFW shell on supported platforms where it is not built by default.' ) parser.add_argument( '--no-build-glfw-shell', dest='build_glfw_shell', action='store_const', const=False, help='Do not build the GLFW shell on platforms where it is built by default.' ) parser.add_argument( '--build-embedder-examples', action='store_const', const=True, help='Build the example embedders using the Embedder API.' ) parser.add_argument( '--no-build-embedder-examples', dest='build_embedder_examples', action='store_const', const=False, help='Do not build the example embedders using the Embedder API.' ) parser.add_argument( '--stripped', default=True, action='store_true', help='Strip debug symbols from the output. This defaults to true and has no effect on iOS.' ) parser.add_argument('--no-stripped', dest='stripped', action='store_false') parser.add_argument( '--prebuilt-dart-sdk', default=True, action='store_true', help='Whether to use a prebuilt Dart SDK instead of building one. This defaults to ' + 'true and is enabled on CI.' ) parser.add_argument('--no-prebuilt-dart-sdk', dest='prebuilt_dart_sdk', action='store_false') # Flags for Dart features. parser.add_argument( '--use-mallinfo2', dest='use_mallinfo2', default=False, action='store_true', help='Use mallinfo2 to collect malloc stats.' ) # Impeller flags. parser.add_argument( '--prebuilt-impellerc', default=None, type=str, help='Absolute path to a prebuilt impellerc. ' + 'Do not use this outside of CI or with impellerc from a different engine version.' ) parser.add_argument( '--enable-impeller-3d', default=False, action='store_true', help='Enables experimental 3d support.' ) parser.add_argument( '--enable-impeller-trace-canvas', default=False, action='store_true', help='Enables tracing calls to Canvas.' ) parser.add_argument('--malioc-path', type=str, help='The path to the malioc tool.') parser.add_argument( '--impeller-cmake-example', default=False, action='store_true', help='Do not run GN. Instead configure the Impeller cmake example build.', ) # Sanitizers. parser.add_argument('--asan', default=False, action='store_true') parser.add_argument('--lsan', default=False, action='store_true') parser.add_argument('--msan', default=False, action='store_true') parser.add_argument('--tsan', default=False, action='store_true') parser.add_argument('--ubsan', default=False, action='store_true') parser.add_argument( '--fstack-protector', default=False, action='store_true', help='Whether the -fstack-protector flag should be passed unconditionally.' ) parser.add_argument( '--trace-gn', default=True, action='store_true', help='Write a GN trace log (gn_trace.json) in the Chromium tracing ' 'format in the build directory.' ) parser.add_argument( '--darwin-extension-safe', default=False, action='store_true', help='Whether the produced Flutter.framework is app extension safe. Only for iOS.' ) # Verbose output. parser.add_argument('--verbose', default=False, action='store_true') parser.add_argument( '--gn-args', action='append', help='Additional gn args to be passed to gn. If you ' 'need to use this, it should probably be another switch ' 'in //flutter/tools/gn.', ) parser.add_argument( '--use-glfw-swiftshader', default=False, action='store_true', help='Forces glfw to use swiftshader.', ) return parser.parse_args(args) def validate_args(args): valid = True if args.simulator: if args.mac_cpu != 'x64': print( 'Specified a non-default mac-cpu for a simulator build. Did you mean ' 'to use `--simulator-cpu`?' ) valid = False if args.ios_cpu != 'arm64': print( 'Specified a non-default ios-cpu for a simulator build. Did you mean ' 'to use `--simulator-cpu`?' ) valid = False if not valid: sys.exit(-1) def main(argv): args = parse_args(argv) validate_args(args) if args.impeller_cmake_example: return run_impeller_cmake(args) exe = '.exe' if sys.platform.startswith(('cygwin', 'win')) else '' command = [ '%s/flutter/third_party/gn/gn%s' % (SRC_ROOT, exe), 'gen', '--check', '--export-compile-commands', ] if not args.web: if args.ide != '': command.append('--ide=%s' % args.ide) elif sys.platform == 'darwin': # On the Mac, generate an Xcode project by default. command.append('--ide=xcode') command.append('--xcode-project=flutter_engine') command.append('--xcode-build-system=new') elif sys.platform.startswith('win'): # On Windows, generate a Visual Studio project. command.append('--ide=vs') command.append('--ninja-executable=ninja') command.append('--export-compile-commands=default') gn_args = to_command_line(to_gn_args(args)) gn_args.extend(args.gn_args or []) out_dir = get_out_dir(args) command.append(out_dir) command.append('--args=%s' % ' '.join(gn_args)) if args.trace_gn: command.append('--tracelog=%s/gn_trace.json' % out_dir) if args.verbose: command.append('-v') print('Generating GN files in: %s' % out_dir) try: gn_call_result = subprocess.call(command, cwd=SRC_ROOT) except subprocess.CalledProcessError as exc: print('Failed to generate gn files: ', exc.returncode, exc.output) sys.exit(1) return gn_call_result if __name__ == '__main__': sys.exit(main(sys.argv))
engine/tools/gn/0
{ "file_path": "engine/tools/gn", "repo_id": "engine", "token_count": 18811 }
467
GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the library's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. <signature of Ty Coon>, 1 April 1990 Ty Coon, President of Vice That's all there is to it!
engine/tools/licenses/data/lesser-gpl-2.1/0
{ "file_path": "engine/tools/licenses/data/lesser-gpl-2.1", "repo_id": "engine", "token_count": 6224 }
468
// 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. import 'dart:core' as core show RegExp; import 'dart:core' hide RegExp; import 'dart:io'; class RegExp implements core.RegExp { RegExp( String source, { bool multiLine = false, bool caseSensitive = true, bool unicode = false, bool dotAll = false, this.expectNoMatch = false, }) : _pattern = core.RegExp(source, multiLine: multiLine, caseSensitive: caseSensitive, unicode: unicode, dotAll: dotAll), source = _stripFrameNumber(StackTrace.current.toString().split('\n').skip(1).take(1).single) { _allPatterns.add(this); } static String _stripFrameNumber(String frame) { return frame.substring(frame.indexOf(' ')).trim(); } final core.RegExp _pattern; final String source; static final List<RegExp> _allPatterns = <RegExp>[]; final bool expectNoMatch; int _matchCount = 0; int get matchCount => _matchCount; int _testCount = 0; int get testCount => _testCount; final Stopwatch _stopwatch = Stopwatch(); static void printDiagnostics() { final List<RegExp> patterns = _allPatterns.toList(); stderr.writeln('Top ten patterns:'); patterns.sort((RegExp a, RegExp b) => b._stopwatch.elapsed.compareTo(a._stopwatch.elapsed)); for (final RegExp pattern in patterns.take(10)) { stderr.writeln('${pattern._stopwatch.elapsedMicroseconds.toString().padLeft(10)}ΞΌs tests -- /${pattern.pattern}/ (${pattern.testCount} tests, ${pattern.matchCount} matches, ${pattern.source})'); } stderr.writeln(); stderr.writeln('Unmatched patterns:'); patterns.sort((RegExp a, RegExp b) => a.pattern.compareTo(b.pattern)); for (final RegExp pattern in patterns) { if (pattern.matchCount == 0 && !pattern.expectNoMatch && pattern.testCount > 0) { stderr.writeln('/${pattern.pattern}/ (${pattern.testCount} tests, ${pattern.matchCount} matches, ${pattern.source})'); } } stderr.writeln(); stderr.writeln('Unexpectedly matched patterns:'); for (final RegExp pattern in patterns) { if (pattern.matchCount > 0 && pattern.expectNoMatch) { stderr.writeln('/${pattern.pattern}/ (${pattern.testCount} tests, ${pattern.matchCount} matches, ${pattern.source})'); } } stderr.writeln(); stderr.writeln('Unused patterns:'); for (final RegExp pattern in patterns) { if (pattern.testCount == 0) { stderr.writeln('/${pattern.pattern}/ (${pattern.testCount} tests, ${pattern.matchCount} matches, ${pattern.source})'); } } } @override bool get isCaseSensitive => _pattern.isCaseSensitive; @override bool get isDotAll => _pattern.isDotAll; @override bool get isMultiLine => _pattern.isMultiLine; @override bool get isUnicode => _pattern.isUnicode; @override String get pattern => _pattern.pattern; @override Iterable<RegExpMatch> allMatches(String input, [int start = 0]) { _stopwatch.start(); final List<RegExpMatch> result = _pattern.allMatches(input, start).toList(); _stopwatch.stop(); _testCount += 1; if (result.isNotEmpty) { _matchCount += 1; } return result; } @override RegExpMatch? firstMatch(String input) { _stopwatch.start(); final RegExpMatch? result = _pattern.firstMatch(input); _stopwatch.stop(); _testCount += 1; if (result != null) { _matchCount += 1; } return result; } @override bool hasMatch(String input) { _stopwatch.start(); final bool result = _pattern.hasMatch(input); _stopwatch.stop(); _stopwatch.stop(); _testCount += 1; if (result) { _matchCount += 1; } return result; } @override Match? matchAsPrefix(String string, [int start = 0]) { _stopwatch.start(); final Match? result = _pattern.matchAsPrefix(string, start); _stopwatch.stop(); _testCount += 1; if (result != null) { _matchCount += 1; } return result; } @override String? stringMatch(String input) { _stopwatch.start(); final String? result = _pattern.stringMatch(input); _stopwatch.stop(); _testCount += 1; if (result != null) { _matchCount += 1; } return result; } @override String toString() => _pattern.toString(); }
engine/tools/licenses/lib/regexp_debug.dart/0
{ "file_path": "engine/tools/licenses/lib/regexp_debug.dart", "repo_id": "engine", "token_count": 1623 }
469
// 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. import 'package:meta/meta.dart'; import 'package:platform/platform.dart'; // This library parses Engine builder config data out of the "Engine v2" build // config JSON files with the format described at: // https://github.com/flutter/engine/blob/main/ci/builders/README.md /// Base class for all nodes in the build config. sealed class BuildConfigBase { BuildConfigBase(this.errors); /// Accumulated errors. Non-null and non-empty when a node is invalid. final List<String>? errors; /// Whether there were errors when loading the data for this node. late final bool valid = errors == null; /// Returns an empty list when the object is valid, and errors when it is not. /// Subclasses with more data to check for validity should override this /// method and add `super.check(path)` to the returned list. @mustCallSuper List<String> check(String path) { if (valid) { return <String>[]; } return errors!.map((String s) => '$path: $s').toList(); } } /// The builder configuration is a json file containing a list of builds, tests, /// generators and archives. /// /// Each builder config file contains a top-level json map with the following /// fields: /// { /// "builds": [], /// "tests": [], /// "generators": { /// "tasks": [] /// }, /// "archives": [] /// } final class BuilderConfig extends BuildConfigBase { /// Load build configuration data into an instance of this class. /// /// [path] should be the file system path to the file that the JSON data comes /// from. [map] must be the JSON data returned by e.g. `JsonDecoder.convert`. factory BuilderConfig.fromJson({ required String path, required Map<String, Object?> map, }) { final List<String> errors = <String>[]; // Parse the "builds" field. final List<Build>? builds = objListOfJson<Build>( map, 'builds', errors, Build.fromJson, ); // Parse the "tests" field. final List<GlobalTest>? tests = objListOfJson<GlobalTest>( map, 'tests', errors, GlobalTest.fromJson, ); // Parse the "generators" field. final List<TestTask>? generators; if (map['generators'] == null) { generators = <TestTask>[]; } else if (map['generators'] is! Map<String, Object?>) { appendTypeError(map, 'generators', 'map', errors); generators = null; } else { generators = objListOfJson( map['generators']! as Map<String, Object?>, 'tasks', errors, TestTask.fromJson, ); } // Parse the "archives" field. final List<GlobalArchive>? archives = objListOfJson<GlobalArchive>( map, 'archives', errors, GlobalArchive.fromJson, ); if (builds == null || tests == null || generators == null || archives == null) { return BuilderConfig._invalid(path, errors); } return BuilderConfig._(path, builds, tests, generators, archives); } BuilderConfig._( this.path, this.builds, this.tests, this.generators, this.archives, ) : super(null); BuilderConfig._invalid(this.path, super.errors) : builds = <Build>[], tests = <GlobalTest>[], generators = <TestTask>[], archives = <GlobalArchive>[]; /// The path to the JSON file. final String path; /// A list of independent builds that have no dependencies among them. They /// can run in parallel if need be. final List<Build> builds; /// A list of tests. The tests may have dependencies on one or more of the /// builds. final List<GlobalTest> tests; /// A list of generator tasks that produce additional artifacts, which may /// depend on the output of one or more builds. final List<TestTask> generators; /// A description of the upload instructions for the artifacts produced by /// the global generators. final List<GlobalArchive> archives; @override List<String> check(String path) { final List<String> errors = <String>[]; errors.addAll(super.check(path)); for (int i = 0; i < builds.length; i++) { final Build build = builds[i]; errors.addAll(build.check('$path/builds[$i]')); } for (int i = 0; i < tests.length; i++) { final GlobalTest test = tests[i]; errors.addAll(test.check('$path/tests[$i]')); } for (int i = 0; i < generators.length; i++) { final TestTask task = generators[i]; errors.addAll(task.check('$path/generators/tasks[$i]')); } for (int i = 0; i < archives.length; i++) { final GlobalArchive archive = archives[i]; errors.addAll(archive.check('$path/archives[$i]')); } return errors; } /// Returns true if any of the [Build]s it contains can run on /// `platform`, and false otherwise. bool canRunOn(Platform platform) { return builds.any((Build b) => b.canRunOn(platform)); } } /// A "build" is a dictionary with a gn command, a ninja command, zero or more /// generator commands, zero or more local tests, zero or more local generators /// and zero or more output artifacts. /// /// "builds" contains a list of maps with fields like: /// { /// "name": "", /// "gn": [""], /// "ninja": {}, /// "tests": [], /// "generators": { /// "tasks": [] /// }, (optional) /// "archives": [], /// "drone_dimensions": [""], /// "gclient_variables": {} /// } final class Build extends BuildConfigBase { factory Build.fromJson(Map<String, Object?> map) { final List<String> errors = <String>[]; final String? name = stringOfJson(map, 'name', errors); final List<String>? gn = stringListOfJson(map, 'gn', errors); final List<BuildTest>? tests = objListOfJson( map, 'tests', errors, BuildTest.fromJson, ); final List<BuildArchive>? archives = objListOfJson( map, 'archives', errors, BuildArchive.fromJson, ); final List<String>? droneDimensions = stringListOfJson( map, 'drone_dimensions', errors, ); final BuildNinja? ninja; if (map['ninja'] == null) { ninja = BuildNinja.nop(); } else if (map['ninja'] is! Map<String, Object?>) { ninja = null; } else { ninja = BuildNinja.fromJson(map['ninja']! as Map<String, Object?>); } if (ninja == null) { appendTypeError(map, 'ninja', 'map', errors); } final List<BuildTask>? generators; if (map['generators'] == null) { generators = <BuildTask>[]; } else if (map['generators'] is! Map<String, Object?>) { appendTypeError(map, 'generators', 'map', errors); generators = null; } else { generators = objListOfJson( map['generators']! as Map<String, Object?>, 'tasks', errors, BuildTask.fromJson, ); } final Map<String, Object?>? gclientVariables; if (map['gclient_variables'] == null) { gclientVariables = <String, Object?>{}; } else if (map['gclient_variables'] is! Map<String, Object?>) { gclientVariables = null; } else { gclientVariables = map['gclient_variables']! as Map<String, Object?>; } if (gclientVariables == null) { appendTypeError(map, 'gclient_variables', 'map', errors); } if (name == null || gn == null || ninja == null || archives == null || tests == null || generators == null || droneDimensions == null || gclientVariables == null) { return Build._invalid(errors); } return Build._( name, gn, ninja, tests, generators, archives, droneDimensions, gclientVariables, ); } Build._( this.name, this.gn, this.ninja, this.tests, this.generators, this.archives, this.droneDimensions, this.gclientVariables, ) : super(null); Build._invalid(super.errors) : name = '', gn = <String>[], ninja = BuildNinja.nop(), tests = <BuildTest>[], generators = <BuildTask>[], archives = <BuildArchive>[], droneDimensions = <String>[], gclientVariables = <String, Object?>{}; /// The name of the build which may also be used to reference it as a /// depdendency of a global test. final String name; /// The parameters to pass to `flutter/tools/gn` to configure the build. final List<String> gn; /// The data to form the ninja command to perform the build. final BuildNinja ninja; /// The list of tests that can be run after the ninja build is finished. final List<BuildTest> tests; /// A list of other tasks that may generate new artifacts after the ninja /// build is finished. final List<BuildTask> generators; /// Upload instructions for the artifacts produced by the build. final List<BuildArchive> archives; /// A list 'key=value' strings that are used to select the bot where this /// build will be running. final List<String> droneDimensions; /// A dictionary with variables included in the `custom_vars` section of the /// .gclient file before `gclient sync` is run. final Map<String, Object?> gclientVariables; /// Returns true if platform is capable of executing this build and false /// otherwise. bool canRunOn(Platform platform) => _canRunOn(droneDimensions, platform); @override List<String> check(String path) { final List<String> errors = <String>[]; errors.addAll(super.check(path)); errors.addAll(ninja.check('$path/ninja')); for (int i = 0; i < tests.length; i++) { final BuildTest test = tests[i]; errors.addAll(test.check('$path/tests[$i]')); } for (int i = 0; i < generators.length; i++) { final BuildTask task = generators[i]; errors.addAll(task.check('$path/generators/tasks[$i]')); } for (int i = 0; i < archives.length; i++) { final BuildArchive archive = archives[i]; errors.addAll(archive.check('$path/archives[$i]')); } return errors; } } /// "builds" -> "ninja" contains a map with fields like: /// { /// "config": "", /// "targets": [""] /// }, final class BuildNinja extends BuildConfigBase { factory BuildNinja.fromJson(Map<String, Object?> map) { final List<String> errors = <String>[]; final String? config = stringOfJson(map, 'config', errors); final List<String>? targets = stringListOfJson(map, 'targets', errors); if (config == null || targets == null) { return BuildNinja._invalid(errors); } return BuildNinja._(config, targets); } BuildNinja._(this.config, this.targets) : super(null); BuildNinja._invalid(super.errors) : config = '', targets = <String>[]; BuildNinja.nop() : config = '', targets = <String>[], super(null); /// The name of the configuration created by gn. /// /// This is also the subdirectory of the `out/` directory where the build /// output will go. final String config; /// The ninja targets to build. final List<String> targets; } /// "builds" -> "tests" contains a list of maps with fields like: /// { /// "language": "", /// "name": "", /// "parameters": [""], /// "script": "", /// "contexts": [""] /// } final class BuildTest extends BuildConfigBase { factory BuildTest.fromJson(Map<String, Object?> map) { final List<String> errors = <String>[]; final String? name = stringOfJson(map, 'name', errors); final String? language = stringOfJson(map, 'language', errors); final String? script = stringOfJson(map, 'script', errors); final List<String>? parameters = stringListOfJson( map, 'parameters', errors, ); final List<String>? contexts = stringListOfJson( map, 'contexts', errors, ); if (name == null || language == null || script == null || parameters == null || contexts == null) { return BuildTest._invalid(errors); } return BuildTest._(name, language, script, parameters, contexts); } BuildTest._( this.name, this.language, this.script, this.parameters, this.contexts, ) : super(null); BuildTest._invalid(super.errors) : name = '', language = '', script = '', parameters = <String>[], contexts = <String>[]; /// The human readable description of the test. final String name; /// The executable used to run the script. final String language; /// The path to the script to execute relative to the checkout directory. final String script; /// Flags or parameters passed to the script. /// /// Parameters accept magic environment variables (placeholders replaced /// before executing the test). Magic environment variables have the following /// limitations: only ${FLUTTER_LOGS_DIR} is currently supported and it needs /// to be used alone within the parameter string(e.g. ["${FLUTTER_LOGS_DIR}"] /// is OK but ["path=${FLUTTER_LOGS_DIR}"] is not). final List<String> parameters; /// A list of available contexts to add to the text execution step. /// /// Two contexts are supported: "android_virtual_device" and /// "metric_center_token". final List<String> contexts; } /// "builds" -> "generators" is a map containing a single property "tasks", /// which is a list of maps with fields like: /// { /// "name": "", /// "parameters": [""], /// "scripts": [""], /// "language": "" /// } /// /// The semantics of this task are that each script in the list of scripts is /// run in sequence by appending the same parameter list to each one. final class BuildTask extends BuildConfigBase { factory BuildTask.fromJson(Map<String, Object?> map) { final List<String> errors = <String>[]; final String? name = stringOfJson(map, 'name', errors); final String? language = stringOfJson(map, 'language', errors); final List<String>? scripts = stringListOfJson(map, 'scripts', errors); final List<String>? parameters = stringListOfJson( map, 'parameters', errors, ); if (name == null || language == null || scripts == null || parameters == null) { return BuildTask._invalid(errors); } return BuildTask._(name, language, scripts, parameters); } BuildTask._invalid(super.errors) : name = '', language = '', scripts = <String>[], parameters = <String>[]; BuildTask._(this.name, this.language, this.scripts, this.parameters) : super(null); /// The human readable name of the step running the script. final String name; /// The script language executable to run the script. If empty it is assumed /// to be bash. final String language; /// A list of paths of scripts relative to the checkout directory. Each /// script is run in turn by appending the list of parameters to it. final List<String> scripts; /// The flags passed to the script. Paths referenced in the list are relative /// to the checkout directory. final List<String> parameters; } /// "builds" -> "archives" contains a list of maps with fields like: /// { /// "name": "", /// "base_path": "", /// "type": "", /// "include_paths": [""], /// "realm": "" /// } final class BuildArchive extends BuildConfigBase { factory BuildArchive.fromJson(Map<String, Object?> map) { final List<String> errors = <String>[]; final String? name = stringOfJson(map, 'name', errors); final String? type = stringOfJson(map, 'type', errors); final String? basePath = stringOfJson(map, 'base_path', errors); final String? realm = stringOfJson(map, 'realm', errors); final List<String>? includePaths = stringListOfJson( map, 'include_paths', errors, ); if (name == null || type == null || basePath == null || realm == null || includePaths == null) { return BuildArchive._invalid(errors); } return BuildArchive._(name, type, basePath, realm, includePaths); } BuildArchive._invalid(super.error) : name = '', type = '', basePath = '', realm = '', includePaths = <String>[]; BuildArchive._( this.name, this.type, this.basePath, this.realm, this.includePaths, ) : super(null); /// The name which may be referenced later as a dependency of global tests. final String name; /// The type of storage to use. Currently only β€œgcs” and β€œcas” are supported. final String type; /// The portion of the path to remove from the full path before uploading final String basePath; /// Either "production" or "experimental". final String realm; /// A list of strings with the paths to be uploaded to a given destination. final List<String> includePaths; } /// Global "tests" is a list of maps containing fields like: /// { /// "name": "", /// "recipe": "", /// "drone_dimensions": [""], /// "dependencies": [""], /// "tasks": [] (same format as above) /// } final class GlobalTest extends BuildConfigBase { factory GlobalTest.fromJson(Map<String, Object?> map) { final List<String> errors = <String>[]; final String? name = stringOfJson(map, 'name', errors); final String? recipe = stringOfJson(map, 'recipe', errors); final List<String>? droneDimensions = stringListOfJson( map, 'drone_dimensions', errors, ); final List<String>? dependencies = stringListOfJson( map, 'dependencies', errors, ); final List<TestDependency>? testDependencies = objListOfJson( map, 'test_dependencies', errors, TestDependency.fromJson, ); final List<TestTask>? tasks = objListOfJson( map, 'tasks', errors, TestTask.fromJson, ); if (name == null || recipe == null || droneDimensions == null || dependencies == null || testDependencies == null || tasks == null) { return GlobalTest._invalid(errors); } return GlobalTest._( name, recipe, droneDimensions, dependencies, testDependencies, tasks); } GlobalTest._invalid(super.errors) : name = '', recipe = '', droneDimensions = <String>[], dependencies = <String>[], testDependencies = <TestDependency>[], tasks = <TestTask>[]; GlobalTest._( this.name, this.recipe, this.droneDimensions, this.dependencies, this.testDependencies, this.tasks, ) : super(null); /// The name that will be assigned to the sub-build. final String name; /// The recipe name to use if different than tester. final String recipe; /// A list of strings with key values to select the bot where the test will /// run. final List<String> droneDimensions; /// A list of build outputs required by the test. final List<String> dependencies; /// A list of dependencies required for the test to run. final List<TestDependency> testDependencies; /// A list of dictionaries representing scripts and parameters to run them final List<TestTask> tasks; /// Returns true if platform is capable of executing this build and false /// otherwise. bool canRunOn(Platform platform) => _canRunOn(droneDimensions, platform); @override List<String> check(String path) { final List<String> errors = <String>[]; errors.addAll(super.check(path)); for (int i = 0; i < testDependencies.length; i++) { final TestDependency testDependency = testDependencies[i]; errors.addAll(testDependency.check('$path/test_dependencies[$i]')); } for (int i = 0; i < tasks.length; i++) { final TestTask task = tasks[i]; errors.addAll(task.check('$path/tasks[$i]')); } return errors; } } /// A test dependency for a global test has fields like: /// { /// "dependency": "", /// "version": "" /// } final class TestDependency extends BuildConfigBase { factory TestDependency.fromJson(Map<String, Object?> map) { final List<String> errors = <String>[]; final String? dependency = stringOfJson(map, 'dependency', errors); final String? version = stringOfJson(map, 'version', errors); if (dependency == null || version == null) { return TestDependency._invalid(errors); } return TestDependency._(dependency, version); } TestDependency._invalid(super.error) : dependency = '', version = ''; TestDependency._(this.dependency, this.version) : super(null); /// A dependency from the list at: /// https://flutter.googlesource.com/recipes/+/refs/heads/main/recipe_modules/flutter_deps/api.py#75 final String dependency; /// The CIPD version string of the dependency. final String version; } /// Task for a global generator and a global test. /// { /// "name": "", /// "parameters": [""], /// "script": "", /// "language": "" /// } final class TestTask extends BuildConfigBase { factory TestTask.fromJson(Map<String, Object?> map) { final List<String> errors = <String>[]; final String? name = stringOfJson(map, 'name', errors); final String? language = stringOfJson(map, 'language', errors); final String? script = stringOfJson(map, 'script', errors); final int? maxAttempts = intOfJson(map, 'max_attempts', fallback: 1, errors); final List<String>? parameters = stringListOfJson( map, 'parameters', errors, ); if (name == null || language == null || script == null || maxAttempts == null || parameters == null) { return TestTask._invalid(errors); } return TestTask._(name, language, script, maxAttempts, parameters); } TestTask._invalid(super.error) : name = '', language = '', script = '', maxAttempts = 0, parameters = <String>[]; TestTask._( this.name, this.language, this.script, this.maxAttempts, this.parameters, ) : super(null); /// The human readable name of the step running the script. final String name; /// The script language executable to run the script. If empty it is assumed /// to be bash. final String language; /// The script path relative to the checkout repository. final String script; /// The maximum number of failures to tolerate. The default is 1. final int maxAttempts; /// The flags passed to the script. Paths referenced in the list are relative /// to the checkout directory. final List<String> parameters; } /// The objects that populate the list of global archives have fields like: /// { /// "source": "out/debug/artifacts.zip", /// "destination": "ios/artifacts.zip", /// "realm": "production" /// }, final class GlobalArchive extends BuildConfigBase { factory GlobalArchive.fromJson(Map<String, Object?> map) { final List<String> errors = <String>[]; final String? source = stringOfJson(map, 'source', errors); final String? destination = stringOfJson(map, 'destination', errors); final String? realm = stringOfJson(map, 'realm', errors); if (source == null || destination == null || realm == null) { return GlobalArchive._invalid(errors); } return GlobalArchive._(source, destination, realm); } GlobalArchive._invalid(super.error) : source = '', destination = '', realm = ''; GlobalArchive._(this.source, this.destination, this.realm) : super(null); /// The path of the artifact relative to the engine checkout. final String source; /// The destination folder in the storage bucket. final String destination; /// Which storage bucket the destination path is relative to. /// Either "production" or "experimental". final String realm; } bool _canRunOn(List<String> droneDimensions, Platform platform) { String? os; for (final String dimension in droneDimensions) { os ??= switch (dimension.split('=')) { ['os', 'Linux'] => Platform.linux, ['os', final String win] when win.startsWith('Windows') => Platform.windows, ['os', final String mac] when mac.startsWith('Mac') => Platform.macOS, _ => null, }; } return os == platform.operatingSystem; } void appendTypeError( Map<String, Object?> map, String field, String expected, List<String> errors, { Object? element, }) { if (element == null) { final Type actual = map[field]!.runtimeType; errors.add( 'For field "$field", expected type: $expected, actual type: $actual.', ); } else { final Type actual = element.runtimeType; errors.add( 'For element "$element" of "$field", ' 'expected type: $expected, actual type: $actual', ); } } List<T>? objListOfJson<T>( Map<String, Object?> map, String field, List<String> errors, T Function(Map<String, Object?>) fn, ) { if (map[field] == null) { return <T>[]; } if (map[field]! is! List<Object?>) { appendTypeError(map, field, 'list', errors); return null; } for (final Object? obj in map[field]! as List<Object?>) { if (obj is! Map<String, Object?>) { appendTypeError(map, field, 'map', errors); return null; } } return (map[field]! as List<Object?>) .cast<Map<String, Object?>>() .map<T>(fn) .toList(); } List<String>? stringListOfJson( Map<String, Object?> map, String field, List<String> errors, ) { if (map[field] == null) { return <String>[]; } if (map[field]! is! List<Object?>) { appendTypeError(map, field, 'list', errors); return null; } for (final Object? obj in map[field]! as List<Object?>) { if (obj is! String) { appendTypeError(map, field, element: obj, 'string', errors); return null; } } return (map[field]! as List<Object?>).cast<String>(); } String? stringOfJson( Map<String, Object?> map, String field, List<String> errors, ) { if (map[field] == null) { return '<undef>'; } if (map[field]! is! String) { appendTypeError(map, field, 'string', errors); return null; } return map[field]! as String; } int? intOfJson( Map<String, Object?> map, String field, List<String> errors, { int fallback = 0, }) { if (map[field] == null) { return fallback; } if (map[field]! is! int) { appendTypeError(map, field, 'int', errors); return null; } return map[field]! as int; }
engine/tools/pkg/engine_build_configs/lib/src/build_config.dart/0
{ "file_path": "engine/tools/pkg/engine_build_configs/lib/src/build_config.dart", "repo_id": "engine", "token_count": 9553 }
470
// 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 "flutter/vulkan/procs/vulkan_interface.h" namespace vulkan { std::string VulkanResultToString(VkResult result) { switch (result) { case VK_SUCCESS: return "VK_SUCCESS"; case VK_NOT_READY: return "VK_NOT_READY"; case VK_TIMEOUT: return "VK_TIMEOUT"; case VK_EVENT_SET: return "VK_EVENT_SET"; case VK_EVENT_RESET: return "VK_EVENT_RESET"; case VK_INCOMPLETE: return "VK_INCOMPLETE"; case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY"; case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY"; case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED"; case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST"; case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED"; case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT"; case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT"; case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT"; case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER"; case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS"; case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED"; case VK_ERROR_FRAGMENTED_POOL: return "VK_ERROR_FRAGMENTED_POOL"; case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR"; case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR"; case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR"; case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; case VK_ERROR_VALIDATION_FAILED_EXT: return "VK_ERROR_VALIDATION_FAILED_EXT"; case VK_ERROR_INVALID_SHADER_NV: return "VK_ERROR_INVALID_SHADER_NV"; #if VK_HEADER_VERSION < 140 case VK_RESULT_RANGE_SIZE: return "VK_RESULT_RANGE_SIZE"; #endif case VK_RESULT_MAX_ENUM: return "VK_RESULT_MAX_ENUM"; case VK_ERROR_INVALID_EXTERNAL_HANDLE: return "VK_ERROR_INVALID_EXTERNAL_HANDLE"; case VK_ERROR_OUT_OF_POOL_MEMORY: return "VK_ERROR_OUT_OF_POOL_MEMORY"; default: return "Unknown Error"; } return ""; } } // namespace vulkan
engine/vulkan/procs/vulkan_interface.cc/0
{ "file_path": "engine/vulkan/procs/vulkan_interface.cc", "repo_id": "engine", "token_count": 1218 }
471
// 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 FLUTTER_VULKAN_VULKAN_IMAGE_H_ #define FLUTTER_VULKAN_VULKAN_IMAGE_H_ #include "flutter/fml/compiler_specific.h" #include "flutter/fml/macros.h" #include "flutter/vulkan/procs/vulkan_handle.h" namespace vulkan { class VulkanProcTable; class VulkanCommandBuffer; class VulkanImage { public: explicit VulkanImage(VulkanHandle<VkImage> image); ~VulkanImage(); bool IsValid() const; [[nodiscard]] bool InsertImageMemoryBarrier( const VulkanCommandBuffer& command_buffer, VkPipelineStageFlagBits src_pipline_bits, VkPipelineStageFlagBits dest_pipline_bits, VkAccessFlags dest_access_flags, VkImageLayout dest_layout); private: VulkanHandle<VkImage> handle_; VkImageLayout layout_; uint32_t /* mask of VkAccessFlagBits */ access_flags_; bool valid_; FML_DISALLOW_COPY_AND_ASSIGN(VulkanImage); }; } // namespace vulkan #endif // FLUTTER_VULKAN_VULKAN_IMAGE_H_
engine/vulkan/vulkan_image.h/0
{ "file_path": "engine/vulkan/vulkan_image.h", "repo_id": "engine", "token_count": 413 }
472
// 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. // FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/68331 #include "vulkan_window.h" #include <memory> #include <string> #include <utility> #include "flutter/flutter_vma/flutter_skia_vma.h" #include "flutter/vulkan/vulkan_skia_proc_table.h" #include "vulkan_application.h" #include "vulkan_device.h" #include "vulkan_native_surface.h" #include "vulkan_surface.h" #include "vulkan_swapchain.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/ganesh/vk/GrVkDirectContext.h" namespace vulkan { VulkanWindow::VulkanWindow(fml::RefPtr<VulkanProcTable> proc_table, std::unique_ptr<VulkanNativeSurface> native_surface) : VulkanWindow(/*context/*/ nullptr, std::move(proc_table), std::move(native_surface)) {} VulkanWindow::VulkanWindow(const sk_sp<GrDirectContext>& context, fml::RefPtr<VulkanProcTable> proc_table, std::unique_ptr<VulkanNativeSurface> native_surface) : valid_(false), vk_(std::move(proc_table)), skia_gr_context_(context) { if (!vk_ || !vk_->HasAcquiredMandatoryProcAddresses()) { FML_DLOG(INFO) << "Proc table has not acquired mandatory proc addresses."; return; } if (native_surface && !native_surface->IsValid()) { FML_DLOG(INFO) << "Native surface is invalid."; return; } // Create the application instance. std::vector<std::string> extensions = { VK_KHR_SURFACE_EXTENSION_NAME, // parent extension native_surface->GetExtensionName() // child extension }; application_ = std::make_unique<VulkanApplication>(*vk_, "Flutter", std::move(extensions)); if (!application_->IsValid() || !vk_->AreInstanceProcsSetup()) { // Make certain the application instance was created and it set up the // instance proc table entries. FML_DLOG(INFO) << "Instance proc addresses have not been set up."; return; } // Create the device. logical_device_ = application_->AcquireFirstCompatibleLogicalDevice(); if (logical_device_ == nullptr || !logical_device_->IsValid() || !vk_->AreDeviceProcsSetup()) { // Make certain the device was created and it set up the device proc table // entries. FML_DLOG(INFO) << "Device proc addresses have not been set up."; return; } if (!native_surface) { return; } // Create the logical surface from the native platform surface. surface_ = std::make_unique<VulkanSurface>(*vk_, *application_, std::move(native_surface)); if (!surface_->IsValid()) { FML_DLOG(INFO) << "Vulkan surface is invalid."; return; } // Needs to happen before GrDirectContext is created. memory_allocator_ = flutter::FlutterSkiaVulkanMemoryAllocator::Make( application_->GetAPIVersion(), application_->GetInstance(), logical_device_->GetPhysicalDeviceHandle(), logical_device_->GetHandle(), vk_, true); // Create the Skia GrDirectContext. if (!skia_gr_context_ && !CreateSkiaGrContext()) { FML_DLOG(INFO) << "Could not create Skia context."; return; } // Create the swapchain. if (!RecreateSwapchain()) { FML_DLOG(INFO) << "Could not set up the swapchain initially."; return; } valid_ = true; } VulkanWindow::~VulkanWindow() = default; bool VulkanWindow::IsValid() const { return valid_; } GrDirectContext* VulkanWindow::GetSkiaGrContext() { return skia_gr_context_.get(); } bool VulkanWindow::CreateSkiaGrContext() { #ifdef SK_VUKLAN GrVkBackendContext backend_context; if (!CreateSkiaBackendContext(&backend_context)) { return false; } GrContextOptions options; options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo; sk_sp<GrDirectContext> context = GrDirectContexts::MakeVulkan(backend_context, options); if (context == nullptr) { return false; } context->setResourceCacheLimit(kGrCacheMaxByteSize); skia_gr_context_ = context; return true; #else return false; #endif // SK_VULKAN } bool VulkanWindow::CreateSkiaBackendContext(GrVkBackendContext* context) { auto getProc = CreateSkiaGetProc(vk_); if (getProc == nullptr) { return false; } uint32_t skia_features = 0; if (!logical_device_->GetPhysicalDeviceFeaturesSkia(&skia_features)) { return false; } context->fInstance = application_->GetInstance(); context->fPhysicalDevice = logical_device_->GetPhysicalDeviceHandle(); context->fDevice = logical_device_->GetHandle(); context->fQueue = logical_device_->GetQueueHandle(); context->fGraphicsQueueIndex = logical_device_->GetGraphicsQueueIndex(); context->fMinAPIVersion = application_->GetAPIVersion(); context->fExtensions = kKHR_surface_GrVkExtensionFlag | kKHR_swapchain_GrVkExtensionFlag | surface_->GetNativeSurface().GetSkiaExtensionName(); context->fFeatures = skia_features; context->fGetProc = std::move(getProc); context->fOwnsInstanceAndDevice = false; context->fMemoryAllocator = memory_allocator_; return true; } sk_sp<SkSurface> VulkanWindow::AcquireSurface() { if (!IsValid()) { FML_DLOG(INFO) << "Surface is invalid."; return nullptr; } auto surface_size = surface_->GetSize(); // This check is theoretically unnecessary as the swapchain should report that // the surface is out-of-date and perform swapchain recreation at the new // configuration. However, on Android, the swapchain never reports that it is // of date. Hence this extra check. Platforms that don't have this issue, or, // cant report this information (which is optional anyway), report a zero // size. if (surface_size != SkISize::Make(0, 0) && surface_size != swapchain_->GetSize()) { FML_DLOG(INFO) << "Swapchain and surface sizes are out of sync. Recreating " "swapchain."; if (!RecreateSwapchain()) { FML_DLOG(INFO) << "Could not recreate swapchain."; valid_ = false; return nullptr; } } while (true) { sk_sp<SkSurface> surface; auto acquire_result = VulkanSwapchain::AcquireStatus::ErrorSurfaceLost; std::tie(acquire_result, surface) = swapchain_->AcquireSurface(); if (acquire_result == VulkanSwapchain::AcquireStatus::Success) { // Successfully acquired a surface from the swapchain. Nothing more to do. return surface; } if (acquire_result == VulkanSwapchain::AcquireStatus::ErrorSurfaceLost) { // Surface is lost. This is an unrecoverable error. FML_DLOG(INFO) << "Swapchain reported surface was lost."; return nullptr; } if (acquire_result == VulkanSwapchain::AcquireStatus::ErrorSurfaceOutOfDate) { // Surface out of date. Recreate the swapchain at the new configuration. if (RecreateSwapchain()) { // Swapchain was recreated, try surface acquisition again. continue; } else { // Could not recreate the swapchain at the new configuration. FML_DLOG(INFO) << "Swapchain reported surface was out of date but " "could not recreate the swapchain at the new " "configuration."; valid_ = false; return nullptr; } } break; } FML_DCHECK(false) << "Unhandled VulkanSwapchain::AcquireResult"; return nullptr; } bool VulkanWindow::SwapBuffers() { if (!IsValid()) { FML_DLOG(INFO) << "Window was invalid."; return false; } return swapchain_->Submit(); } bool VulkanWindow::RecreateSwapchain() { // This way, we always lose our reference to the old swapchain. Even if we // cannot create a new one to replace it. auto old_swapchain = std::move(swapchain_); if (!vk_->IsValid()) { return false; } if (logical_device_ == nullptr || !logical_device_->IsValid()) { return false; } if (surface_ == nullptr || !surface_->IsValid()) { return false; } if (skia_gr_context_ == nullptr) { return false; } auto swapchain = std::make_unique<VulkanSwapchain>( *vk_, *logical_device_, *surface_, skia_gr_context_.get(), std::move(old_swapchain), logical_device_->GetGraphicsQueueIndex()); if (!swapchain->IsValid()) { return false; } swapchain_ = std::move(swapchain); return true; } } // namespace vulkan
engine/vulkan/vulkan_window.cc/0
{ "file_path": "engine/vulkan/vulkan_window.cc", "repo_id": "engine", "token_count": 3224 }
473
<!DOCTYPE html> <html> <head> <title>Web Engine Test Runner</title> <link rel="stylesheet" type="text/css" href="host.css" /> </head> <body> <script src="host.dart.js"></script> </body> </html>
engine/web_sdk/web_engine_tester/lib/static/index.html/0
{ "file_path": "engine/web_sdk/web_engine_tester/lib/static/index.html", "repo_id": "engine", "token_count": 82 }
474
<component name="libraryTable"> <library name="Dart"> <CLASSES> <root url="jar://$PROJECT_DIR$/lib/dart-plugin/212.5486/Dart.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component>
flutter-intellij/.idea/libraries/Dart.xml/0
{ "file_path": "flutter-intellij/.idea/libraries/Dart.xml", "repo_id": "flutter-intellij", "token_count": 99 }
475
Contributing to Flutter Plugin for IntelliJ ======================= <!-- TOC --> * [Contributing to Flutter Plugin for IntelliJ](#contributing-to-flutter-plugin-for-intellij) * [Contributing code](#contributing-code) * [Getting started](#getting-started) * [Setting environments](#setting-environments) * [Handle symlinks](#handle-symlinks) * [Provision Tool](#provision-tool) * [Running plugin tests](#running-plugin-tests) * [Using test run configurations in IntelliJ](#using-test-run-configurations-in-intellij) * [Using the plugin tool on the command line](#using-the-plugin-tool-on-the-command-line) * [Adding platform sources](#adding-platform-sources) * [Working with Android Studio](#working-with-android-studio) * [Working with Embedded DevTools (JxBrowser)](#working-with-embedded-devtools-jxbrowser) * [Signing commits](#signing-commits) <!-- TOC --> ## Contributing code ![GitHub contributors](https://img.shields.io/github/contributors/flutter/flutter-intellij.svg) We gladly accept contributions via GitHub pull requests! If you are new to codiing IntelliJ plugins, here are a couple links to get started: - [INTRODUCTION TO CREATING INTELLIJ IDEA PLUGINS](https://developerlife.com/2020/11/21/idea-plugin-example-intro/) - [ADVANCED GUIDE TO CREATING INTELLIJ IDEA PLUGINS](https://developerlife.com/2021/03/13/ij-idea-plugin-advanced/) You must complete the [Contributor License Agreement](https://cla.developers.google.com/clas) before any of your contributions with code get merged into the repo. If you've never submitted code before, you must add your (or your organization's) name and contact info to the [AUTHORS](AUTHORS) file. ## Getting started 1. Install Flutter SDK from [Flutter SDK download](https://flutter.dev/docs/get-started/install) or [GitHub](https://github.com/flutter/flutter) and set it up according to its instructions. 2. Verify installation from the command line: - Connect an android device with USB debugging. - `cd path/to/flutter/examples/hello_world` - `flutter pub get` - `flutter doctor` - `flutter run` 3. Fork `https://github.com/flutter/flutter-intellij` into your own GitHub account. If you already have a fork, and are now installing a development environment on a new machine, make sure you've updated your fork with the master branch so that you don't use stale configuration options from long ago. 4. `git clone -c core.symlinks=true https://github.com/<your_name_here>/flutter-intellij` 5. `cd flutter-intellij` 6. `git remote add upstream https://github.com/flutter/flutter-intellij` The name `upsteram` can be whatever you want. ## Setting environments The current Java Developmenet Kit version is: **20**. 1. Set your `JAVA_HOME` directory in your environment. - For example, on macOS, the following works: Check what version of java you have: ```shell /usr/libexec/java_home -V ``` Set your `JAVA_HOME` env variable to match that version. ```shell export JAVA_HOME=`/usr/libexec/java_home -v 20` ``` 2. Set your `FLUTTER_SDK` directory to point to `/path/to/flutter`. 3. Also set your `DART_SDK` directory to `/path/to/flutter/bin/cache/dart-sdk`. 4. Ensure both `DART_SDK`, `FLUTTER_SDK` and `JAVA_HOME` are added to the `PATH` in the shell initialization script that runs at login. (not just for the one used for every interactive shell). ```shell export PATH=$DART_SDK/bin:$FLUTTER_SDK/bin:$JAVA_HOME/bin:$PATH ``` 5. Make sure you're using the latest stable release of IntelliJ, or sownload and install the latest version of IntelliJ (2023.1 or later). - [IntelliJ Downloads](https://www.jetbrains.com/idea/download/) - Either the community edition (free) or Ultimate will work. - Determine the directory of your downloaded IntelliJ IDEA installation. e.g. * `IntelliJ IDEA CE.app` (macOS) * `~/Library/Application Support/JetBrains/Toolbox/apps/IDEA-U/ch-0/231.8109.175/IntelliJ IDEA.app` (macOS) * `~/idea-IC-231.8109.175` (Linux) * `X:\path\to\your\IDEA-U\ch-0\231.8109.175` (Windows after installed) 6. Start the IntelliJ IDEA with the `flutter-intellij` project. If you see a popup with "Gradle build scripts found", **confirm loading the Gradle project, and wait until syncing is done.** If you didn't see the popup at the first start, **delete & re-clone the repo** and try again. - Ignore suggestion for `protobuf-java` plugin, unless you want it. 7. Prepare other dependencies from the command line: - `cd path/to/flutter-intellij` - `dart pub get` - `(cd tool/plugin; dart pub get)` - `bin/plugin test` 8. In the "Project Structure" dialog (`File | Project Structure`): - Select "Platform Settings > SDKs", click the "+" sign at the top "Add New SDK (Alt+Insert)", then select "Add JDK...". - Point it to the directory of the jbr which is under the IDEA's content (e.g. `IntelliJ IDEA CE.app/Contents/jbr`). - Change the name to `IDEA JBR 17` (or any names that your can easily identify). - Select "Platform Settings > SDKs", click the "+" sign at the top "Add New SDK (Alt+Insert)", then select "Add IntelliJ Platform Plugin SDK...". - Point it to the directory of the content which is under the IDEA's installation. - Remember the generated name (probably `IntelliJ IDEA IU-231.8109.175`) or change to name to format like this. - Change the "Internal Java Platform" to the previous `IDEA JBR 17`. - Select "Platform Settings > Project", change the "SDK" selection to **the previous IntelliJ Platform Plugin SDK** (probably `IntelliJ IDEA IU-231.8109.175 java version 17`). - Select "Platform Settings > Modules". - Select "flutter-intellij > flutter-idea > main" module, switch to the "Paths" window, select the **Inherit project compile output path** option then apply. This step can be repeated after everytime the project is open. - Select every module from the top (flutter-intellij) to the bottom (test) (could be 6 modules in summary), switch to the "Dependencies" window, change the "Module SDK" selection to `Project SDK`. 9. In the "File | Settings | Build, Execution, Deployment | Build Tools | Gradle" setting: - Change "Gradle JVM" selection to "Project SDK". 10. In the "File | Settings | Build, Execution, Deployment | Compiler" setting: - In "Java Compiler", change the "Project bytecode version" to the same version of the JDK. - In "Kotlin Compiler", change the "Target JVM version" to the same version of the JDK. 11. One-time Dart plugin install - first-time a new IDE is installed and run you will need to install the Dart plugin. - Find `Plugins` (in "File | Settings | Plugins") and install the Dart plugin, then restart the IDE if needed. 12. Build the project using `Build` | `Build Project`. 13. Try running the plugin; select the `flutter-intellij [runIde]` run config then click the Debug icon. This should open the "runtime workbench", a new instance of IntelliJ IDEA with the plugin installed. 14. If the Flutter Plugin doesn't load (Dart code or files are unknown) see above "One-time Dart plugin install". 15. Verify installation of the Flutter plugin: - Select `flutter-intellij [runIde]` in the Run Configuration drop-down list. - Click Debug button (to the right of that drop-down). - In the new IntelliJ process that spawns, open the `path/to/flutter/examples/hello_world` project. - Choose `Edit Configurations...` in the Run Configuration drop-down list. - Expand `Edit configuration templates...` and verify that Flutter is present. - Click [+] and verify that Flutter is present. ### Handle symlinks If exceptions like these occurred: ``` A problem occurred configuring project ':flutter-idea'. > Source directory 'X:\path\to\your\flutter-intellij\flutter-idea\resources' is not a directory. ``` Check out if the directory is a symlink by open the link in IDEA, and it'll display as: ```symlink ../resources ``` Delete the file, then re-clone the repo using the below command: ```shell git clone -c core.symlinks=true https://github.com/<your_name_here>/flutter-intellij ``` **NOTE**: Avoid symlinks addition during development as possible as you can, since they can lead to various of file-based issues during the development. ## Provision Tool This is not currently required. However, for debugging unit tests it may be handy; please ignore for now. The Gradle build script currently assumes that some dependencies are present in the `artifacts` directory. This project uses an External Tool in IntelliJ to ensure the dependencies are present. It appears that external tools are not shareable. To make one, open the "Run Configuration" dialog and select "Flutter Plugin". Look at the "Before launch" panel. It probably displays an Unknown External Tool. Double-click that, then click edit icon in the new panel (pencil). Set the name to "Provision". Set the values: - Program: /bin/bash - Arguments: bin/plugin test -s - Working directory: $ProjectFileDir$ - You can select that from a list by clicking the "+" symbol in the field There is a screenshot of this dialog in `resources/intellij/Provision.png`. Save, close, and re-open the "Run Configuration" dialog. Confirm that the External Tool is named "Provision". If you know where the Application Support files are located for your version of IntelliJ, you can drop the definition into its `tools` directory before starting IntelliJ. The definition is in `resources/intellij/External Tools.xml`. ## Running plugin tests ### Using test run configurations in IntelliJ [Note: this may be out-of-date. It has not been verified recently.] The repository contains two pre-defined test run configurations. One is for "unit" tests; that is currently defined as tests that do not rely on the IntelliJ UI APIs. The other is for "integration" tests - tests that do use the IntelliJ UI APIs. The integration tests are larger, long-running tests that exercise app use cases. In order to be able to debug a single test class or test method you need to do the following: * Open the test source file in the editor. Navigate to `flutter-idea/testSrc/unit/...` to open it. * Tests must run using Gradle, so be sure to open the source from the Gradle module. * Find the test you want to run. Right-click the green triangle next to the test name and choose `Debug <test-name>`. The test configuration can be tricky due to IntelliJ platform versioning. The plugin tool (below) can be a more reliable way to run tests. ### Using the plugin tool on the command line To run unit tests on the command line: ``` bin/plugin test ``` See `TestCommand` in `tool/plugin/lib/plugin.dart` for more options. It is also possible to run tests directly with Gradle, which would allow passing more command-line arguments: ``` ./gradlew test ``` If you wanted to run a subset of the tests you could do so this way. See the [Gradle docs](https://docs.gradle.org/current/userguide/java_testing.html) for more info about testing. *However*, you must have run the tests once using the plugin tool, to ensure all the dependencies have been configured. ## Adding platform sources Sometimes browsing the source code of IntelliJ is helpful for understanding platform details that aren't documented. - In order to have the platform sources handy, clone the IntelliJ IDEA Community Edition repo (`git clone https://github.com/JetBrains/intellij-community`) - Sync it to the same version of IntelliJ as given by `baseVersion` in gradle.properties (`git checkout 211.7628`). It will be in "detached HEAD" mode. - Open the Project Structure dialog (`File > Project Structure`). In the `IntelliJ IDEA Community Edition` sdk, head over to the `Sourcepaths` tab and add the path to `intellij-community`. Accept all the root folders found by the IDE after scanning. - Do the same for the intellij-plugins repo to get Dart plugin sources. Sync to the same version as before. ## Working with Android Studio Android Studio cannot use the Gradle-based project definition, so it still needs the `flutter-intellij-community.iml` file. Obviously, unit tests can only be run from the command line. 1. Initialize Android Studio sources. 2. Checkout Flutter plugin sources, tip of tree. 3. Follow the directions for setting up the Dart plugin sources in `intellij-plugins/Dart/README.md` with these changes: - you do not need to clone the intellij-community repo - open studio-main/tools/adt/idea in IntelliJ - possibly skip running `intellij-community/getPlugins.sh` 4. Checkout Dart plugin sources. 5. Using the Project Structure editor, import - intellij-plugins/Dart/Dart-community.iml (if there are lots of errors, see step 7) - flutter-intellij/flutter-intellij-community.iml 6. Using the Project Structure editor, expand the tree to show `intellij > android > adt > ui`. Select the `ui` module then add a module dependency from it to `flutter-intellij-community`. Also add a dependency on the Dart module unless using step 7. 7. (Optional, when Dart sources are not usable.) Make sure the `flutter-intellij-community` module has a dependency on a library named `Dart`. It should be pre-defined, but if it is out-of-date then adjust it to point to `flutter-intellij/third_party/lib/dart-plugin/xxx.yyyy/Dart.jar`. Delete the Dart module from the Project Structure modules list. ## Working with Embedded DevTools (JxBrowser) We use [JxBrowser](https://www.teamdev.com/jxbrowser), a commercial product, to embed DevTools within IntelliJ. A license key is required to use this feature in development, but it is not required for developing unrelated (most) features. Getting a key to develop JxBrowser features: - Internal contributors: Ask another internal contributor to give you access to the key. - External contributors: Our license key cannot be transferred externally, but you can acquire your own trial or regular license from [TeamDev](https://www.teamdev.com/jxbrowser) to use here. To set up the license key: 1. Copy the template at resources/jxbrowser/jxbrowser.properties.template and save it as resources/jxbrowser/jxbrowser.properties. 2. Replace `<KEY>` with the actual key. ## Signing commits We require that all commits to the repository are signed with GPG or SSH, see [GitHub's documentation](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification). If you are on macOS, and choose to sign with GPG, here are some additonal notes: - Download GPG's tarball along with its dependencies from [here](https://www.gnupg.org/download/). GPG is the first item, the dependencies are in the block below (Libgpg-error, Libgcrypt, etc.). - To install these tarballs on macOS, follow these instructions: - Download the desired `.tar.gz` or (`.tar.bz2`) file - Open Terminal - Extract the `.tar.gz` or (`.tar.bz2`) file with the following commands (Follow these steps for the dependencies first, then for GPG): ```bash tar xvjf PACKAGENAME.tar.bz2 # Navigate to the extracted folder using cd command cd PACKAGENAME # Now run the following command to install the tarball ./configure make sudo make install ``` - You may need to install pinentry (`brew install pinentry`) - If the Pinentry continues to not work, check its path (`which pinentry`) and add it to the file `~/.gnupg/gpg-agent.conf`, i.e.: ```bash pinentry-program /path/to/pinentry ``` - You may need to set the tty `export GPG_TTY=$(tty)` if you get this error when trying to commit: ```bash error: gpg failed to sign the data fatal: failed to write commit object ```
flutter-intellij/CONTRIBUTING.md/0
{ "file_path": "flutter-intellij/CONTRIBUTING.md", "repo_id": "flutter-intellij", "token_count": 4819 }
476
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. app.reload.action.text=Flutter Hot Reload app.reload.action.description=Hot reload changes into the running Flutter app app.reload.all.action.text=Flutter Hot Reload (All Devices) app.reload.all.action.description=Hot reload changes into all running Flutter apps on all connected devices app.restart.action.text=Flutter Hot Restart app.restart.action.description=Restart the Flutter app app.restart.all.action.text=Flutter Hot Restart (All Devices) app.restart.all.action.description=Restart all running Flutter apps on all connected devices app.profile.action.text=Run in Flutter profile mode app.profile.config.action.text=Flutter Run ''{0}'' in Profile Mode app.profile.action.description=Run Flutter app in profile mode app.release.action.text=Run in Flutter release mode app.release.config.action.text=Flutter Run ''{0}'' in Release Mode app.release.action.description=Run Flutter app in release mode app.inspector.no_properties=Selected node has no properties app.inspector.all_properties_hidden=All properties of the selected node are hidden app.inspector.error_loading_properties=Error loading properties app.inspector.error_loading_property_details=Error loading property details app.inspector.loading_properties=Loading properties app.inspector.nothing_to_show=Nothing to show dart.plugin.update.action.label=Update Dart dart.sdk.is.not.configured=Dart SDK is not configured error.folder.specified.as.sdk.not.exists=The folder specified as the Flutter SDK home does not exist. error.flutter.sdk.without.dart.sdk=The Flutter SDK installation is incomplete; please see: https://flutter.dev/get-started. error.sdk.not.found.in.specified.location=Flutter SDK is not found in the specified location. flutter.command.exception.message=Exception: {0} flutter.incompatible.dart.plugin.warning=Flutter requires a Dart plugin with a minimum version of {0} (currently installed: {1}). flutter.module.name=Flutter flutter.no.sdk.warning=No Flutter SDK Configured. flutter.old.sdk.warning=The current configured Flutter SDK is not known to be fully supported. Please update your SDK and restart IntelliJ. flutter.project.description=Build high-performance, high-fidelity, apps using the Flutter framework. flutter.sdk.browse.path.label=Select Flutter SDK Path flutter.sdk.is.not.configured=The Flutter SDK is not configured flutter.sdk.path.label=Flutter &SDK path: flutter.title=Flutter flutter.sdk.notAvailable.title=No Flutter SDK Configured flutter.sdk.notAvailable.message=This action requires a Flutter SDK to be configured; configure one now? outdated.dependencies.inspection.name=Outdated package dependencies pub.get.not.run='Pub get' has not been run pubspec.edited=Pubspec has been edited get.dependencies=Get dependencies upgrade.dependencies=Upgrade dependencies ignore.warning=Ignore runner.flutter.configuration.description=Flutter run configuration runner.flutter.configuration.name=Flutter runner.flutter.bazel.configuration.description=Flutter Bazel run configuration runner.flutter.bazel.configuration.name=Flutter (Bazel) runner.flutter.bazel.test.configuration.name=Flutter Test (Bazel) runner.flutter.bazel.watch.test.configuration.name=Watch Flutter Test (Bazel) waiting.for.flutter=Waiting for debug connection... entrypoint.not.set=Dart Entrypoint hasn't been set entrypoint.not.found=Entrypoint file not found at {0} entrypoint.not.dart=Entrypoint is not a Dart file main.not.in.entrypoint=Entrypoint doesn't contain a main function entrypoint.not.in.project=Entrypoint isn't within the current project entrypoint.not.in.app.dir=Entrypoint isn't within a Flutter application directory flutter.run.bazel.noLaunchingScript=No launching script specified flutter.run.bazel.launchingScriptNotFound=Launching script not found: {0} flutter.run.bazel.noTargetSet=No Bazel target set flutter.run.bazel.startWithSlashSlash=Bazel targets should start with '//' flutter.run.bazel.newBazelTestRunnerUnavailable=The new Bazel test runner is not available. Only Bazel targets can be run with the old test runner flutter.run.bazel.noBazelOrDartTargetSet=No Bazel target or Dart entrypoint set flutter.perf.linter.statefulWidget.url=https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html#performance-considerations flutter.perf.linter.listViewLoad.url=https://api.flutter.dev/flutter/widgets/ListView-class.html flutter.perf.linter.animatedBuilder.url=https://api.flutter.dev/flutter/widgets/AnimatedBuilder-class.html#performance-optimizations flutter.perf.linter.opacityAnimations.url=https://api.flutter.dev/flutter/widgets/Opacity-class.html#performance-considerations-for-opacity-animation flutter.analytics.notification.content=The Flutter plugin reports feature usage statistics and crash reports to Google \ in order to help Google contribute improvements to Flutter over time. See Google's privacy policy: \ <a href="url">www.google.com/policies/privacy</a>.<br><br>Send usage statistics? flutter.analytics.privacyUrl=https://www.google.com/policies/privacy/ flutter.initializer.module.converted.title=Flutter module type updated flutter.reload.firstRun.title=Flutter supports hot reload! flutter.reload.firstRun.content=Apply changes to your app in place, instantly. flutter.reload.firstRun.url=https://flutter.dev/docs/development/tools/hot-reload flutter.io.gettingStarted.url=https://flutter.dev/docs/get-started/install flutter.io.gettingStarted.IDE.url=https://flutter.dev/docs/development/tools/ide flutter.io.runAndDebug.url=https://flutter.dev/docs/development/tools/ide/android-studio#running-and-debugging devicelist.loading=Loading... flutter.pop.frame.action.text=Drop Frame (Flutter) flutter.pop.frame.action.description=Pop the current frame off the stack flutter.module.create.settings.type.label=Project &type: flutter.module.create.settings.type.application=Application flutter.module.create.settings.type.plugin=Plugin flutter.module.create.settings.type.package=Package flutter.module.create.settings.type.module=Module flutter.module.create.settings.type.import_module=Import Module flutter.module.create.settings.type.tip=Select a project type. flutter.module.create.settings.sample.tip=Select sample content. flutter.module.create.settings.sample.text=Generate sample content: flutter.module.create.settings.radios.org.label=&Organization: flutter.module.create.settings.org.default_text=com.example flutter.module.create.settings.org.tip=Enter a domain. flutter.module.create.settings.description.label=&Description: flutter.module.create.settings.description.tip=Enter a project description which shows up in the pubsec.yaml. flutter.module.create.settings.description.default_text=A new Flutter project. flutter.module.create.settings.location.select=Select Project Location flutter.module.create.settings.radios.android.label=Android language: flutter.module.create.settings.radios.android.java=&Java flutter.module.create.settings.radios.android.kotlin=&Kotlin flutter.module.create.settings.radios.android.tip=Select an Android language. flutter.module.create.settings.radios.ios.label=iOS language: flutter.module.create.settings.radios.ios.object_c=Objective-&C flutter.module.create.settings.radios.ios.swift=&Swift flutter.module.create.settings.radios.ios.tip=Select an iOS language. flutter.module.create.settings.help.label=Help: flutter.module.create.settings.help.getting_started_link_text=Getting started with your first Flutter app. flutter.module.create.settings.help.packages_and_plugins_text=Developing packages and plugins. flutter.module.create.settings.help.project_name.label=Project name: flutter.module.create.settings.help.project_name.description=Enter the project name with all lower case letters. flutter.module.create.settings.help.module_name.label=Module name: flutter.module.create.settings.help.module_name.description=Enter the module name with all lower case letters. flutter.module.create.settings.help.org.label=Organization: flutter.module.create.settings.help.org.description=Enter the organization domain name in reverse domain notation. flutter.module.create.settings.help.project_type.label=Project type: flutter.module.create.settings.help.project_type.description.app=Select an "Application" when building for end users. flutter.module.create.settings.help.project_type.description.plugin=Select a "Plugin" when exposing an Android or iOS API for developers. flutter.module.create.settings.help.project_type.description.package=Select a "Package" when creating a pure Dart component, like a new Widget. flutter.module.create.settings.help.project_type.description.module=Select a "Module" when creating a Flutter component to add to an Android or iOS app. flutter.module.create.settings.help.type.application=An "application" is a stand-alone app that can be installed and run on a mobile device. flutter.module.create.settings.help.type.package=A "package" is a pure-Dart component, like a new Widget, with no native code. flutter.module.create.settings.help.type.plugin=A "plugin" is used to expose an Android or iOS API for developers. module.wizard.language.name_kotlin=Include Kotlin support for Android code module.wizard.language.name_swift=Include Swift support for iOS code module.wizard.app_title=Flutter Application module.wizard.app_title_short=Flutter App module.wizard.app_description=Creates a Flutter application module.wizard.app_step_title=New Flutter Application module.wizard.app_step_body=Configure the new Flutter application module.wizard.app_name=flutter_app module.wizard.app_text=A new Flutter application. module.wizard.package_title=Flutter Package module.wizard.package_description=Creates a Flutter package module.wizard.package_step_title=New Flutter Package module.wizard.package_step_body=Configure the new Flutter package module.wizard.package_name=flutter_package module.wizard.package_text=A new Flutter package. module.wizard.plugin_title=Flutter Plugin module.wizard.plugin_description=Creates a Flutter plugin module.wizard.plugin_step_title=New Flutter Plugin module.wizard.plugin_step_body=Configure the new Flutter plugin module.wizard.plugin_name=flutter_plugin module.wizard.plugin_text=A new Flutter plugin. module.wizard.module_title=Flutter Module module.wizard.module_description=Creates a Flutter module to use in an Android app module.wizard.module_step_title=New Flutter Module module.wizard.module_step_body=Configure the new Flutter module module.wizard.module_name=flutter_module module.wizard.module_text=A new Flutter module. module.wizard.import_module_title=Import Flutter Module module.wizard.import_module_description=Import a Flutter module into an Android app module.wizard.import_module_step_title=Import Flutter Module module.wizard.import_module_step_body=Flutter module location: module.wizard.import_module_name=flutter_module_location module.wizard.import_module_text=Import a Flutter module. flutter.module.import.settings.help.description=Import a Flutter module into an Android app (without copying). flutter.module.import.settings.location.select=Select Module Location old.android.studio.title=Wrong Version old.android.studio.message=Your path contains Android Studio 2.x,\n\ which does not support Flutter.\n\n\ You can change it using the flutter command-line tool via:\n\ flutter\u00a0config\u00a0--android-studio-dir\u00a0{0}path{0}to{0}Android\u00a0Studio\u00a04.x flutter.androidstudio.open.module.text=Open Android module in Android Studio flutter.androidstudio.open.module.description=Open Android Studio in a new window to edit the top-level Android project flutter.androidstudio.open.file.text=Open for Editing in Android Studio flutter.androidstudio.open.file.description=Open Android Studio in a new window to edit this file flutter.androidstudio.open.hide.notification.text=Hide flutter.androidstudio.open.hide.notification.description=Hide notification until IDE restart settings.try.out.features.still.under.development=Try out features still under development (a restart may be required) settings.enable.android.gradle.sync=Enable code completion, navigation, etc. for Java / Kotlin (requires restart to do Gradle build) settings.report.google.analytics=&Report usage information to Google Analytics settings.enable.hot.ui=Enable Hot UI (an early preview of property editing in the outline view) settings.enable.verbose.logging=Enable &verbose logging settings.format.code.on.save=Format code on save settings.organize.imports.on.save=Organize imports on save settings.flutter.version=Version: settings.open.inspector.on.launch=Open Flutter Inspector view on app launch settings.hot.reload.on.save=Perform hot reload on save settings.enable.bazel.hot.restart=Enable Bazel hot restart (refreshes generated files) settings.allow.tests.in.sources=<html>Allow files ending with <b>_test.dart</b> to be recognized as tests settings.allow.tests.tooltip=The directory must be marked as a sources root, such as <b>lib</b>. settings.font.packages=Font Packages settings.show.all.configs=Show all possible run configurations for apps or tests, even if a created configuration already exists settings.show.all.configs.tooltip=If there is a defined run configuration to watch a specific test and one to just run it, show both. settings.jcef.browser=Use JCEF browser to show embedded DevTools settings.jcef.browser.tooltip=JCEF is a browser included in IntelliJ that is an alternative to using JxBrowser for showing embedded DevTools. settings.enable.androi.gradle.sync.tooltip=Provides advanced editing capabilities for Java and Kotlin code. Uses Gradle to find Android libraries then links them into the Flutter project. settings.experiments=Experiments settings.editor=Editor settings.show.build.guides=Show UI Guides for build methods settings.show.build.guides.tooltip=Visualize the widget tree structure from the outline view directly in build methods. settings.format.code.tooltip=On save, run dartfmt on changed Dart files. settings.organize.imports.tooltip=On save, organize imports for changed Dart files. settings.show.closing.labels=Show closing labels in Dart source code settings.sdk.copy.content=Copy to Clipboard settings.report.analytics.tooltip=Report anonymized usage information to Google Analytics. settings.enable.verbose.logging.tooltip=Enables verbose logging (this can be useful for diagnostic purposes). settings.enable.logs.preserve.during.hot.reload.and.restart=Preserve console logs during Hot Reload and Hot Restart action.new.project.title=New Flutter Project... welcome.new.project.title=Create New Flutter Project welcome.new.project.compact=New Flutter Project npw_platform_android=Android npw_platform_ios=iOS npw_platform_linux=Linux npw_platform_macos=MacOS npw_platform_web=Web npw_platform_windows=Windows npw_platform_selection_help=When created, the new project will run on the selected platforms (others can be added later). npw_none_selected_error=At least one platform must be selected npw_invalid_org_error=Invalid organization name: '{0}' - cannot end in '.'. npw_invalid_desc_error=Invalid package description: '{0}' - cannot contain the sequence ': '. flutter.module.create.settings.platforms.label=Platforms: flutter.sdk.invalid.json.error=Invalid Json from flutter config change.color.command.text=Change Color flutter.icon.preview.title=Icon preview flutter.devtools.installing=Installing DevTools... <br><br>If this takes more than 15 seconds, you can restart with these steps:<br>1. \ Remove this window from the sidebar<br>2. Open it again from View -> Tool Windows -> Flutter Inspector<br><br>Attempts: {0} flutter.coverage.presentable.text=Flutter Coverage coverage.path.not.found=Coverage file not found: {0} progress.title.loading.coverage.data=Loading coverage data... project.root.not.found=Could not find project root coverage.data.not.read=Cannot read coverage data from file: {0} icon.preview.disallow.flutter_icons=Package "flutter_icons" is not supported. icon.preview.disallow.flutter_vector_icons=Package "flutter_vector_icons" cannot show previews because it does not include a font file. icon.preview.disallow.material_design_icons_flutter=Package "material_design_icons_flutter" always displays blank icon previews. icon.preview.disallow.package.title=Unsupported icon package icon.preview.analysis=Checking icons...
flutter-intellij/flutter-idea/src/io/flutter/FlutterBundle.properties/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/FlutterBundle.properties", "repo_id": "flutter-intellij", "token_count": 4809 }
477
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.actions; import com.intellij.execution.process.ColoredProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.VirtualFile; import io.flutter.FlutterMessages; import io.flutter.pub.PubRoot; import io.flutter.pub.PubRoots; import io.flutter.sdk.FlutterSdk; import io.flutter.utils.FlutterModuleUtils; import io.flutter.utils.ProgressHelper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class FlutterBuildActionGroup extends DefaultActionGroup { public static void build(@NotNull Project project, @NotNull PubRoot pubRoot, @NotNull FlutterSdk sdk, @NotNull BuildType buildType, @Nullable String desc) { final ProgressHelper progressHelper = new ProgressHelper(project); progressHelper.start(desc == null ? "building" : desc); ProcessAdapter processAdapter = new ProcessAdapter() { @Override public void processTerminated(@NotNull ProcessEvent event) { progressHelper.done(); final int exitCode = event.getExitCode(); if (exitCode != 0) { FlutterMessages.showError("Error while building " + buildType, "`flutter build` returned: " + exitCode, project); } } }; final Module module = pubRoot.getModule(project); if (module != null) { //noinspection ConstantConditions sdk.flutterBuild(pubRoot, buildType.type).startInModuleConsole(module, pubRoot::refresh, processAdapter); } else { //noinspection ConstantConditions final ColoredProcessHandler processHandler = sdk.flutterBuild(pubRoot, buildType.type).startInConsole(project); if (processHandler == null) { progressHelper.done(); } else { processHandler.addProcessListener(processAdapter); } } } public enum BuildType { AAR("aar"), APK("apk"), APP_BUNDLE("appbundle"), IOS("ios"), WEB("web"); final public String type; BuildType(String type) { this.type = type; } } @Override public void update(@NotNull AnActionEvent event) { final Presentation presentation = event.getPresentation(); final boolean enabled = isInFlutterModule(event); presentation.setEnabled(enabled); presentation.setVisible(enabled); } private static boolean isInFlutterModule(@NotNull AnActionEvent event) { final Project project = event.getProject(); if (project == null) { return false; } return FlutterModuleUtils.hasFlutterModule(project); } @Nullable public static Module findFlutterModule(@NotNull Project project, @NotNull VirtualFile file) { Module module = ModuleUtilCore.findModuleForFile(file, project); if (module == null) { return null; } if (FlutterModuleUtils.declaresFlutter(module)) { return module; } // We may get here if the file is in the Android module of a Flutter module project. final VirtualFile parent = ModuleRootManager.getInstance(module).getContentRoots()[0].getParent(); module = ModuleUtilCore.findModuleForFile(parent, project); if (module == null) { return null; } return FlutterModuleUtils.declaresFlutter(module) ? module : null; } abstract public static class FlutterBuildAction extends AnAction { @NotNull abstract protected BuildType buildType(); @Override public void actionPerformed(@NotNull AnActionEvent event) { final Presentation presentation = event.getPresentation(); final Project project = event.getProject(); if (project == null) { return; } final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project); if (sdk == null) { return; } final PubRoot pubRoot = PubRoot.forEventWithRefresh(event); final BuildType buildType = buildType(); if (pubRoot != null) { build(project, pubRoot, sdk, buildType, presentation.getDescription()); } else { List<PubRoot> roots = PubRoots.forProject(project); for (PubRoot sub : roots) { build(project, sub, sdk, buildType, presentation.getDescription()); } } } } public static class AAR extends FlutterBuildAction { @Override protected @NotNull BuildType buildType() { return BuildType.AAR; } } public static class APK extends FlutterBuildAction { @Override protected @NotNull BuildType buildType() { return BuildType.APK; } } public static class AppBundle extends FlutterBuildAction { @Override protected @NotNull BuildType buildType() { return BuildType.APP_BUNDLE; } } public static class Ios extends FlutterBuildAction { @Override protected @NotNull BuildType buildType() { return BuildType.IOS; } @Override public void update(@NotNull AnActionEvent event) { final Presentation presentation = event.getPresentation(); presentation.setEnabled(SystemInfo.isMac); } } public static class Web extends FlutterBuildAction { @Override protected @NotNull BuildType buildType() { return BuildType.WEB; } } }
flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterBuildActionGroup.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterBuildActionGroup.java", "repo_id": "flutter-intellij", "token_count": 2136 }
478
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.actions; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.ColoredProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.VirtualFile; import io.flutter.FlutterMessages; import io.flutter.FlutterUtils; import io.flutter.pub.PubRoot; import io.flutter.sdk.FlutterSdk; import io.flutter.utils.FlutterModuleUtils; import io.flutter.utils.ProgressHelper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class OpenInXcodeAction extends AnAction { @Nullable static VirtualFile findProjectFile(@NotNull AnActionEvent event) { final VirtualFile file = event.getData(CommonDataKeys.VIRTUAL_FILE); final Project project = event.getProject(); if (file != null && file.exists()) { if (FlutterUtils.isXcodeFileName(file.getName())) { return file; } if (project == null) { return null; } // Return null if this is an android folder. if (FlutterExternalIdeActionGroup.isWithinAndroidDirectory(file, project) || OpenInAndroidStudioAction.isProjectFileName(file.getName())) { return null; } } if (project != null) { return FlutterModuleUtils.findXcodeProjectFile(project, file); } return null; } private static void openFile(@NotNull VirtualFile file) { final Project project = ProjectUtil.guessProjectForFile(file); final FlutterSdk sdk = project != null ? FlutterSdk.getFlutterSdk(project) : null; if (sdk == null) { FlutterSdkAction.showMissingSdkDialog(project); return; } final PubRoot pubRoot = PubRoot.forFile(file); if (pubRoot == null) { FlutterMessages.showError("Error Opening Xcode", "Unable to run `flutter build` (no pub root found)", project); return; } // Trigger an iOS build if necessary. if (!hasBeenBuilt(pubRoot, sdk)) { final ProgressHelper progressHelper = new ProgressHelper(project); progressHelper.start("Building for iOS"); String buildArg = "--config-only"; if (!sdk.getVersion().isXcodeConfigOnlySupported()) { buildArg = "--simulator"; } // TODO(pq): consider a popup explaining why we're doing a build. // Note: we build only for the simulator to bypass device provisioning issues. final ColoredProcessHandler processHandler = sdk.flutterBuild(pubRoot, "ios", buildArg).startInConsole(project); if (processHandler == null) { progressHelper.done(); FlutterMessages.showError("Error Opening Xcode", "unable to run `flutter build`", project); } else { processHandler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(@NotNull ProcessEvent event) { progressHelper.done(); final int exitCode = event.getExitCode(); if (exitCode != 0) { FlutterMessages.showError("Error Opening Xcode", "`flutter build` returned: " + exitCode, project); return; } openWithXcode(project, file.getPath()); } }); } } else { openWithXcode(project, file.getPath()); } } private static boolean hasBeenBuilt(@NotNull PubRoot pubRoot, @NotNull FlutterSdk sdk) { if (sdk.getVersion().isXcodeConfigOnlySupported()) { // Derived from packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart final VirtualFile ios = pubRoot.getRoot().findChild("ios"); if (ios == null || !ios.isDirectory()) return false; final VirtualFile flutter = ios.findChild("Flutter"); if (flutter == null || !flutter.isDirectory()) return false; final VirtualFile gen = flutter.findChild("Generated.xcconfig"); if (gen == null || gen.isDirectory()) return false; return sdk.isOlderThanToolsStamp(gen); } else { final VirtualFile buildDir = pubRoot.getRoot().findChild("build"); return buildDir != null && buildDir.isDirectory() && buildDir.findChild("ios") != null; } } private static void openWithXcode(@Nullable Project project, String path) { try { final GeneralCommandLine cmd = new GeneralCommandLine().withExePath("open").withParameters(path); final ColoredProcessHandler handler = new ColoredProcessHandler(cmd); handler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(@NotNull final ProcessEvent event) { if (event.getExitCode() != 0) { FlutterMessages.showError("Error Opening", path, project); } } }); handler.startNotify(); } catch (ExecutionException ex) { FlutterMessages.showError( "Error Opening", "Exception: " + ex.getMessage(), project); } } @Override public void update(@NotNull AnActionEvent event) { // Enable in global menu; action group controls context menu visibility. if (!SystemInfo.isMac) { event.getPresentation().setVisible(false); } else { final Presentation presentation = event.getPresentation(); final boolean enabled = findProjectFile(event) != null; presentation.setEnabledAndVisible(enabled); } } @Override public void actionPerformed(@NotNull AnActionEvent event) { final VirtualFile projectFile = findProjectFile(event); if (projectFile != null) { openFile(projectFile); } else { @Nullable final Project project = event.getProject(); FlutterMessages.showError("Error Opening Xcode", "Project not found.", project); } } }
flutter-intellij/flutter-idea/src/io/flutter/actions/OpenInXcodeAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/OpenInXcodeAction.java", "repo_id": "flutter-intellij", "token_count": 2299 }
479
package io.flutter.analytics; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.util.IncorrectOperationException; import com.jetbrains.lang.dart.ide.completion.DartCompletionTimerExtension; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.time.Instant; /** * Implementation of the {@link DartCompletionTimerExtension} which allows the Flutter plugin to * measure the total time to present a code completion to the user. */ public class DartCompletionTimerListener extends DartCompletionTimerExtension { @Nullable FlutterAnalysisServerListener dasListener; @Nullable Long startTimeMS; @Override public void dartCompletionStart() { if (dasListener == null) { try { Project project = ProjectManager.getInstance().getDefaultProject(); dasListener = FlutterAnalysisServerListener.getInstance(project); } catch (IncorrectOperationException ex) { return; } } startTimeMS = Instant.now().toEpochMilli(); } @Override public void dartCompletionEnd() { if (dasListener != null && startTimeMS != null) { long durationTimeMS = Instant.now().toEpochMilli() - startTimeMS; dasListener.logE2ECompletionSuccessMS(durationTimeMS); // test: logE2ECompletionSuccessMS() startTimeMS = null; } } /** * The parameters match those of {@link org.dartlang.analysis.server.protocol.RequestError}, they * are not used currently because our hypothesis is that this method will never be called. */ @Override public void dartCompletionError( @NotNull String code, @NotNull String message, @NotNull String stackTrace) { if (dasListener != null && startTimeMS != null) { long durationTimeMS = Instant.now().toEpochMilli() - startTimeMS; dasListener.logE2ECompletionErrorMS(durationTimeMS); // test: logE2ECompletionErrorMS() startTimeMS = null; } } }
flutter-intellij/flutter-idea/src/io/flutter/analytics/DartCompletionTimerListener.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/analytics/DartCompletionTimerListener.java", "repo_id": "flutter-intellij", "token_count": 650 }
480
/* * Copyright 2016 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.console; import com.google.common.annotations.VisibleForTesting; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.HyperlinkInfo; import com.intellij.execution.filters.OpenFileHyperlinkInfo; import com.intellij.execution.process.ColoredProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ui.UIUtil; import io.flutter.FlutterMessages; import io.flutter.FlutterUtils; import io.flutter.sdk.FlutterSdk; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The FlutterConsoleFilter handles link detection in consoles for: * <p> * - linking an action to the term 'flutter doctor' * - linking the text "Launching lib/main.dart" or "open ios/Runner.xcworkspace" * - some embedded paths, like "MyApp.xzzzz (lib/main.dart:6)" */ public class FlutterConsoleFilter implements Filter { private static class OpenExternalFileHyperlink implements HyperlinkInfo { private final String myPath; OpenExternalFileHyperlink(VirtualFile file) { myPath = file.getPath(); } @Override public void navigate(@NotNull Project project) { try { final GeneralCommandLine cmd = new GeneralCommandLine().withExePath("open").withParameters(myPath); final ColoredProcessHandler handler = new ColoredProcessHandler(cmd); handler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(@NotNull final ProcessEvent event) { if (event.getExitCode() != 0) { FlutterMessages.showError("Error Opening ", myPath, project); } } }); handler.startNotify(); } catch (ExecutionException e) { FlutterMessages.showError( "Error Opening External File", "Exception: " + e.getMessage(), project); } } } private final @NotNull Module module; public FlutterConsoleFilter(@NotNull Module module) { this.module = module; } @VisibleForTesting @Nullable public VirtualFile fileAtPath(@NotNull String pathPart) { // "lib/main.dart:6" pathPart = pathPart.split(":")[0]; // We require the pathPart reference to be a file reference, otherwise we'd match things like // "Build: Running build completed, took 191ms". if (pathPart.indexOf('.') == -1) { return null; } final VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots(); for (VirtualFile root : roots) { if (!pathPart.isEmpty()) { final String baseDirPath = root.getPath(); final String path = baseDirPath + "/" + pathPart; VirtualFile file = findFile(path); if (file == null) { // check example dir too // TODO(pq): remove when `example` is a content root: https://github.com/flutter/flutter-intellij/issues/2519 final String exampleDirRelativePath = baseDirPath + "/example/" + pathPart; file = findFile(exampleDirRelativePath); } if (file != null) { return file; } } } return null; } private static VirtualFile findFile(final String path) { final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); return file != null && file.exists() ? file : null; } @Override @Nullable public Result applyFilter(final String line, final int entireLength) { if (line.startsWith("Run \"flutter doctor\" for information about installing additional components.")) { return getFlutterDoctorResult(line, entireLength - line.length()); } if (line.startsWith("Lost connection to device")) { TextAttributes attr = new TextAttributes(UIUtil.getErrorForeground(), null, null, EffectType.BOXED, Font.PLAIN); return new Result(entireLength - line.length(), entireLength, null, attr); } int lineNumber = 0; String pathPart = line.trim(); VirtualFile file = null; int lineStart = -1; int highlightLength = 0; // Check for, e.g., // * "Launching lib/main.dart" // * "open ios/Runner.xcworkspace" if (pathPart.startsWith("Launching ") || pathPart.startsWith("open ")) { final String[] parts = pathPart.split(" "); if (parts.length > 1) { pathPart = parts[1]; file = fileAtPath(pathPart); if (file != null) { lineStart = entireLength - line.length() + line.indexOf(pathPart); highlightLength = pathPart.length(); } } } // Check for embedded paths, e.g., // * " β€’ MyApp.xzzzz (lib/main.dart:6)" // * " β€’ _MyHomePageState._incrementCounter (lib/main.dart:49)" final String[] parts = pathPart.split(" "); for (String part : parts) { // "(lib/main.dart:49)" if (part.startsWith("(") && part.endsWith(")")) { part = part.substring(1, part.length() - 1); final String[] split = part.split(":"); if (split.length == 2) { try { // Reconcile line number indexing. lineNumber = Math.max(0, Integer.parseInt(split[1]) - 1); } catch (NumberFormatException e) { // Ignored. } pathPart = part; lineStart = entireLength - line.length() + line.indexOf(pathPart); highlightLength = pathPart.length(); break; } else if (split.length == 4 && split[0].equals("file")) { // part = file:///Users/user/AndroidStudioProjects/flutter_app/test/widget_test.dart:23:18 try { // Reconcile line number indexing. lineNumber = Math.max(0, Integer.parseInt(split[2]) - 1); } catch (NumberFormatException e) { // Ignored. } pathPart = findRelativePath(split[1]); if (pathPart == null) { return null; } lineStart = entireLength - line.length() + line.indexOf(part); highlightLength = part.length(); break; } } } if (lineStart < 0) { // lib/registerC.dart:104:73: Error: Expected ';' after this. final String filePathAndLineNumberExpr = "(^.*?):(\\d+?):\\d+?:\\s*?Error"; final Pattern pattern = Pattern.compile(filePathAndLineNumberExpr); final Matcher matcher = pattern.matcher(line); final boolean found = matcher.find(); if (found) { final String filePathExpr = "((?:[^/]*/)*)(.*)"; final Pattern pathPattern = Pattern.compile(filePathExpr); final Matcher pathMatcher = pathPattern.matcher(matcher.group(1)); if (pathMatcher.find()) { final String path = pathMatcher.group(1) + pathMatcher.group(2); file = fileAtPath(path); if (file == null) { return null; } lineNumber = Integer.parseInt(matcher.group(2)); lineStart = entireLength - line.length(); highlightLength = path.length(); } else { return null; } } else { return null; } } if (file == null) { file = fileAtPath(pathPart); } if (file != null) { // "open ios/Runner.xcworkspace" final boolean openAsExternalFile = FlutterUtils.isXcodeFileName(pathPart); final HyperlinkInfo hyperlinkInfo = openAsExternalFile ? new OpenExternalFileHyperlink(file) : new OpenFileHyperlinkInfo(module.getProject(), file, lineNumber, 0); return new Result(lineStart, lineStart + highlightLength, hyperlinkInfo); } return null; } private String findRelativePath(String threeSlashFileName) { final VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots(); for (VirtualFile root : roots) { final String path = root.getPath(); int index = threeSlashFileName.indexOf(path); if (index > 0) { index += path.length(); return threeSlashFileName.substring(index + 1); } } return null; } private static Result getFlutterDoctorResult(final String line, final int lineStart) { final int commandStart = line.indexOf('"') + 1; final int startOffset = lineStart + commandStart; final int commandLength = "flutter doctor".length(); return new Result(startOffset, startOffset + commandLength, new FlutterDoctorHyperlinkInfo()); } private static class FlutterDoctorHyperlinkInfo implements HyperlinkInfo { @Override public void navigate(final @NotNull Project project) { // TODO(skybrian) analytics for clicking the link? (We do log the command.) final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project); if (sdk == null) { Messages.showErrorDialog(project, "Flutter SDK not found", "Error"); return; } if (sdk.flutterDoctor().startInConsole(project) == null) { Messages.showErrorDialog(project, "Failed to start 'flutter doctor'", "Error"); } } } }
flutter-intellij/flutter-idea/src/io/flutter/console/FlutterConsoleFilter.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/console/FlutterConsoleFilter.java", "repo_id": "flutter-intellij", "token_count": 3821 }
481
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.editor; import com.intellij.openapi.Disposable; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.EditorEventMulticaster; import com.intellij.openapi.editor.event.EditorMouseEvent; import com.intellij.openapi.editor.event.EditorMouseListener; import com.intellij.openapi.editor.event.EditorMouseMotionListener; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import java.awt.event.MouseEvent; import java.util.Objects; /** * Service that tracks interactions with editors making it easy to add * listeners that are notified when interactions with editors occur. * <p> * This class provides a {@link EditorMouseEventService.Listener} that notifies consumers when * mouse events and selection events occur. */ public class EditorMouseEventService extends EditorEventServiceBase<EditorMouseEventService.Listener> implements Disposable { public interface Listener { void onMouseMoved(MouseEvent event); void onMousePressed(MouseEvent event); void onMouseReleased(MouseEvent event); void onMouseEntered(MouseEvent event); void onMouseExited(MouseEvent event); } private final EditorEventMulticaster eventMulticaster; private final EditorMouseMotionListener mouseMotionListener; public EditorMouseEventService(Project project) { super(project); eventMulticaster = EditorFactory.getInstance().getEventMulticaster(); mouseMotionListener = new EditorMouseMotionListener() { @Override public void mouseMoved(@NotNull EditorMouseEvent e) { invokeAll(listener -> listener.onMouseMoved(e.getMouseEvent()), e.getEditor()); } }; eventMulticaster.addEditorMouseMotionListener(mouseMotionListener); eventMulticaster.addEditorMouseListener(new EditorMouseListener() { @Override public void mousePressed(@NotNull EditorMouseEvent e) { invokeAll(listener -> listener.onMousePressed(e.getMouseEvent()), e.getEditor()); } @Override public void mouseReleased(@NotNull EditorMouseEvent e) { invokeAll(listener -> listener.onMouseReleased(e.getMouseEvent()), e.getEditor()); } @Override public void mouseEntered(@NotNull EditorMouseEvent e) { invokeAll(listener -> listener.onMouseEntered(e.getMouseEvent()), e.getEditor()); } @Override public void mouseExited(@NotNull EditorMouseEvent e) { invokeAll(listener -> listener.onMouseExited(e.getMouseEvent()), e.getEditor()); } }, this); // TODO(jacobr): listen for when editors are disposed? } @NotNull public static EditorMouseEventService getInstance(@NotNull final Project project) { return Objects.requireNonNull(project.getService(EditorMouseEventService.class)); } @Override public void dispose() { super.dispose(); eventMulticaster.removeEditorMouseMotionListener(mouseMotionListener); } }
flutter-intellij/flutter-idea/src/io/flutter/editor/EditorMouseEventService.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/EditorMouseEventService.java", "repo_id": "flutter-intellij", "token_count": 979 }
482
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.editor; import com.intellij.openapi.Disposable; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.VisualPosition; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.markup.CustomHighlighterRenderer; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.JBColor; import io.flutter.inspector.DiagnosticsNode; import io.flutter.inspector.InspectorService; import io.flutter.inspector.Screenshot; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.geom.Rectangle2D; /** * PreviewViewController that renders inline in a code editor. */ public class InlinePreviewViewController extends PreviewViewControllerBase implements CustomHighlighterRenderer { protected float previewWidthScale = 0.7f; public InlinePreviewViewController(InlineWidgetViewModelData data, boolean drawBackground, Disposable disposable) { super(data, drawBackground, disposable); data.context.editorPositionService.addListener(getEditor(), new EditorPositionService.Listener() { @Override public void updateVisibleArea(Rectangle newRectangle) { InlinePreviewViewController.this.updateVisibleArea(newRectangle); } @Override public void onVisibleChanged() { InlinePreviewViewController.this.onVisibleChanged(); } }, this); } InlineWidgetViewModelData getData() { return (InlineWidgetViewModelData)data; } protected EditorEx getEditor() { return getData().editor; } public Point offsetToPoint(int offset) { return getEditor().visualPositionToXY(getEditor().offsetToVisualPosition(offset)); } @Override public void forceRender() { if (!visible) return; getEditor().getComponent().repaint(); // TODO(jacobr): consider forcing a repaint of just a fraction of the // editor window instead. // For example, if the marker corresponded to just the lines in the text // editor that the preview is rendereded on, we could do the following: // final TextRange marker = data.getMarker(); // if (marker == null) return; // // data.editor.repaint(marker.getStartOffset(), marker.getEndOffset()); } InspectorService.Location getLocation() { final WidgetIndentGuideDescriptor descriptor = getDescriptor(); if (descriptor == null || descriptor.widget == null) return null; return InspectorService.Location.outlineToLocation(getEditor(), descriptor.outlineNode); } public WidgetIndentGuideDescriptor getDescriptor() { return getData().descriptor; } @Override public void computeScreenshotBounds() { final Rectangle previousScreenshotBounds = screenshotBounds; screenshotBounds = null; maxHeight = Math.round(PREVIEW_MAX_HEIGHT * 0.16f); final WidgetIndentGuideDescriptor descriptor = getDescriptor(); final int lineHeight = getEditor() != null ? getEditor().getLineHeight() : defaultLineHeight; extraHeight = descriptor != null && screenshot != null ? lineHeight : 0; final Rectangle visibleRect = this.visibleRect; if (visibleRect == null) { return; } if (descriptor == null) { // Special case to float in the bottom right corner. final Screenshot latestScreenshot = getScreenshotNow(); int previewWidth = Math.round(PREVIEW_MAX_WIDTH * previewWidthScale); int previewHeight = Math.round((PREVIEW_MAX_HEIGHT * 0.16f) * previewWidthScale); if (latestScreenshot != null) { previewWidth = (int)(latestScreenshot.image.getWidth() / getDPI()); previewHeight = (int)(latestScreenshot.image.getHeight() / getDPI()); } final int previewStartX = Math.max(0, visibleRect.x + visibleRect.width - previewWidth - PREVIEW_PADDING_X); previewHeight = Math.min(previewHeight, visibleRect.height); maxHeight = visibleRect.height; final int previewStartY = Math.max(visibleRect.y, visibleRect.y + visibleRect.height - previewHeight); screenshotBounds = new Rectangle(previewStartX, previewStartY, previewWidth, previewHeight); return; } final TextRange marker = getData().getMarker(); if (marker == null) return; final int startOffset = marker.getStartOffset(); final Document doc = getData().document; final int textLength = doc.getTextLength(); if (startOffset >= textLength) return; final int endOffset = Math.min(marker.getEndOffset(), textLength); int off; final int startLine = doc.getLineNumber(startOffset); final int widgetOffset = getDescriptor().widget.getGuideOffset(); final int widgetLine = doc.getLineNumber(widgetOffset); final int lineEndOffset = doc.getLineEndOffset(widgetLine); // Request a thumbnail and render it in the space available. VisualPosition visualPosition = getEditor().offsetToVisualPosition(lineEndOffset); // e visualPosition = new VisualPosition(Math.max(visualPosition.line, 0), 81); final Point start = getEditor().visualPositionToXY(visualPosition); final Point endz = offsetToPoint(endOffset); final int endY = endz.y; final int visibleEndX = visibleRect.x + visibleRect.width; final int width = Math.max(0, visibleEndX - 20 - start.x); final int height = Math.max(0, endY - start.y); int previewStartY = start.y; int previewStartX = start.x; final int visibleStart = visibleRect.y; final int visibleEnd = (int)visibleRect.getMaxY(); // Add extra room for the descriptor. final Screenshot latestScreenshot = getScreenshotNow(); int previewWidth = PREVIEW_MAX_WIDTH; int previewHeight = PREVIEW_MAX_HEIGHT / 6; if (latestScreenshot != null) { previewWidth = (int)(latestScreenshot.image.getWidth() / getDPI()); previewHeight = (int)(latestScreenshot.image.getHeight() / getDPI()); } previewStartX = Math.max(previewStartX, visibleEndX - previewWidth - PREVIEW_PADDING_X); previewHeight += extraHeight; previewHeight = Math.min(previewHeight, height); maxHeight = endz.y - start.y; if (popupActive()) { // Keep the bounds sticky maintining the same lastScreenshotBoundsWindow. screenshotBounds = new Rectangle(lastScreenshotBoundsWindow); screenshotBounds.translate(visibleRect.x, visibleRect.y); } else { boolean lockUpdate = false; if (isVisiblityLocked()) { // TODO(jacobr): also need to keep sticky if there is some minor scrolling if (previousScreenshotBounds != null && visibleRect.contains(previousScreenshotBounds)) { screenshotBounds = new Rectangle(previousScreenshotBounds); // Fixup if the screenshot changed if (previewWidth != screenshotBounds.width) { screenshotBounds.x += screenshotBounds.width - previewWidth; screenshotBounds.width = previewWidth; } screenshotBounds.height = previewHeight; // TODO(jacobr): refactor this code so there is less duplication. lastScreenshotBoundsWindow = new Rectangle(screenshotBounds); lastScreenshotBoundsWindow.translate(-visibleRect.x, -visibleRect.y); lockUpdate = true; } } if (!lockUpdate) { lastLockedRectangle = null; if (start.y <= visibleEnd && endY >= visibleStart) { if (visibleStart > previewStartY) { previewStartY = Math.max(previewStartY, visibleStart); previewStartY = Math.min(previewStartY, Math.min(endY - previewHeight, visibleEnd - previewHeight)); } screenshotBounds = new Rectangle(previewStartX, previewStartY, previewWidth, previewHeight); lastScreenshotBoundsWindow = new Rectangle(screenshotBounds); lastScreenshotBoundsWindow.translate(-visibleRect.x, -visibleRect.y); } } } if (popupActive()) { lastLockedRectangle = new Rectangle(visibleRect); } } @Override protected Dimension getPreviewSize() { int previewWidth; int previewHeight; previewWidth = PREVIEW_MAX_WIDTH; previewHeight = PREVIEW_MAX_HEIGHT; if (getDescriptor() == null) { previewWidth = Math.round(previewWidth * previewWidthScale); previewHeight = Math.round(previewHeight * previewWidthScale); } return new Dimension(previewWidth, previewHeight); } private void updateVisibleArea(Rectangle newRectangle) { visibleRect = newRectangle; if (getDescriptor() == null || getData().getMarker() == null) { if (!visible) { visible = true; onVisibleChanged(); } return; } final TextRange marker = getData().getMarker(); if (marker == null) return; final Point start = offsetToPoint(marker.getStartOffset()); final Point end = offsetToPoint(marker.getEndOffset()); final boolean nowVisible = newRectangle == null || newRectangle.y <= end.y && newRectangle.y + newRectangle.height >= start.y || updateVisiblityLocked(newRectangle); if (visible != nowVisible) { visible = nowVisible; onVisibleChanged(); } } @Override public void dispose() { } @Override protected Component getComponent() { return getEditor().getComponent(); } @Override protected VirtualFile getVirtualFile() { return getEditor().getVirtualFile(); } @Override protected Document getDocument() { return getEditor().getDocument(); } @Override protected void showPopup(Point location, DiagnosticsNode node) { location = SwingUtilities.convertPoint( getEditor().getContentComponent(), location, getEditor().getComponent() ); popup = PropertyEditorPanel .showPopup(data.context.inspectorGroupManagerService, getEditor(), node, node.getCreationLocation().getLocation(), data.context.flutterDartAnalysisService, location); } @Override TextRange getActiveRange() { return getData().getMarker(); } @Override void setCustomCursor(@Nullable Cursor cursor) { if (getEditor() == null) { // TODO(jacobr): customize the cursor when there is not an associated editor. return; } getEditor().setCustomCursor(this, cursor); } // Determine zOrder of overlapping previews. // Ideally we should work harder to prevent overlapping. public int getPriority() { int priority = 0; if (popupActive()) { priority += 20; } if (isVisiblityLocked()) { priority += 10; } if (isSelected) { priority += 5; } if (getDescriptor() != null) { priority += 1; } if (screenshot == null && (elements == null || elements.isEmpty())) { priority -= 5; if (getDescriptor() != null) { priority -= 100; } } else { if (hasCurrentHits() || _mouseInScreenshot) { priority += 10; } } if (_mouseInScreenshot) { priority += 20; } return priority; } @Override public void paint(@NotNull Editor editor, @NotNull RangeHighlighter highlighter, @NotNull Graphics g) { if (editor != getEditor()) { // Don't want to render on the wrong editor. This shouldn't happen. return; } if (getEditor().isPurePaintingMode()) { // Don't show previews in pure mode. return; } if (!highlighter.isValid()) { return; } if (getDescriptor() != null && !getDescriptor().widget.isValid()) { return; } final int lineHeight = editor.getLineHeight(); paint(g, lineHeight); } public void paint(@NotNull Graphics g, int lineHeight) { final Graphics2D g2d = (Graphics2D)g.create(); final Screenshot latestScreenshot = getScreenshotNow(); if (latestScreenshot != null) { final int imageWidth = (int)(latestScreenshot.image.getWidth() * getDPI()); final int imageHeight = (int)(latestScreenshot.image.getHeight() * getDPI()); if (extraHeight > 0) { if (drawBackground) { g2d.setColor(JBColor.LIGHT_GRAY); g2d.fillRect(screenshotBounds.x, screenshotBounds.y, Math.min(screenshotBounds.width, imageWidth), Math.min(screenshotBounds.height, extraHeight)); } final WidgetIndentGuideDescriptor descriptor = getDescriptor(); if (descriptor != null) { final int line = descriptor.widget.getLine() + 1; final int column = descriptor.widget.getColumn() + 1; final int numActive = elements != null ? elements.size() : 0; String message = descriptor.outlineNode.getClassName() + " ";//+ " Widget "; if (numActive == 0) { message += "(inactive)"; } else if (numActive > 1) { message += "(" + (activeIndex + 1) + " of " + numActive + ")"; } if (numActive > 0 && screenshot != null && screenshot.transformedRect != null) { final Rectangle2D bounds = screenshot.transformedRect.getRectangle(); final long w = Math.round(bounds.getWidth()); final long h = Math.round(bounds.getHeight()); message += " " + w + "x" + h; } g2d.setColor(JBColor.BLACK); drawMultilineString(g2d, message, screenshotBounds.x + 4, screenshotBounds.y + lineHeight - 6, lineHeight); } } } super.paint(g, lineHeight); } @Override String getNoScreenshotMessage() { final WidgetIndentGuideDescriptor descriptor = getDescriptor(); if (descriptor == null) { return super.getNoScreenshotMessage(); } final int line = descriptor.widget.getLine() + 1; final int column = descriptor.widget.getColumn() + 1; return descriptor.outlineNode.getClassName() + " Widget " + line + ":" + column + "\n" + "not currently active"; } }
flutter-intellij/flutter-idea/src/io/flutter/editor/InlinePreviewViewController.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/InlinePreviewViewController.java", "repo_id": "flutter-intellij", "token_count": 5654 }
483
/* * Copyright 2020 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.editor; import com.intellij.codeHighlighting.*; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import io.flutter.utils.FlutterModuleUtils; import org.jetbrains.annotations.NotNull; /** * Registrar that adds the WidgetIndentsHighlightingPassFactory. * * It is now neccessary to register highlighting passes with a registrar to * ensure that highlighting passes do not unpredictably disappear. */ public class WidgetIndentsHighlightingPassFactoryRegistrar implements TextEditorHighlightingPassFactoryRegistrar, DumbAware { @Override public void registerHighlightingPassFactory(@NotNull TextEditorHighlightingPassRegistrar registrar, @NotNull Project project) { if (FlutterModuleUtils.hasFlutterModule(project)) { WidgetIndentsHighlightingPassFactory.getInstance(project).registerHighlightingPassFactory(registrar); } } }
flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentsHighlightingPassFactoryRegistrar.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentsHighlightingPassFactoryRegistrar.java", "repo_id": "flutter-intellij", "token_count": 306 }
484
/* * Copyright 2018 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.inspector; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.Disposer; import com.intellij.ui.components.JBLabel; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import io.flutter.run.daemon.FlutterApp; import io.flutter.vmService.HeapMonitor; import io.flutter.vmService.HeapMonitor.HeapListener; import io.flutter.vmService.HeapMonitor.HeapSample; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.geom.Path2D; import java.util.LinkedList; public class HeapDisplay extends JPanel { public static JPanel createJPanelView(Disposable parentDisposable, FlutterApp app) { final JPanel panel = new JPanel(new BorderLayout()); final JBLabel heapLabel = new JBLabel("", SwingConstants.RIGHT); heapLabel.setAlignmentY(Component.BOTTOM_ALIGNMENT); heapLabel.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL)); heapLabel.setForeground(UIUtil.getLabelDisabledForeground()); heapLabel.setBorder(JBUI.Borders.empty(4)); final HeapState heapState = new HeapState(60 * 1000); final HeapDisplay graph = new HeapDisplay(state -> { heapLabel.setText(heapState.getHeapSummary()); SwingUtilities.invokeLater(heapLabel::repaint); }); graph.setLayout(new BoxLayout(graph, BoxLayout.X_AXIS)); graph.add(Box.createHorizontalGlue()); graph.add(heapLabel); panel.add(graph, BorderLayout.CENTER); final HeapListener listener = memoryUsages -> SwingUtilities.invokeLater(() -> { heapState.handleMemoryUsage(memoryUsages); graph.updateFrom(heapState); panel.repaint(); }); assert app.getVMServiceManager() != null; app.getVMServiceManager().addHeapListener(listener); Disposer.register(parentDisposable, () -> app.getVMServiceManager().removeHeapListener(listener)); return panel; } private static Color getForegroundColor() { return UIUtil.getLabelDisabledForeground(); } private static final int TEN_MB = 1024 * 1024 * 10; private static final Stroke GRAPH_STROKE = new BasicStroke(2f); private interface SummaryCallback { void updatedSummary(HeapState state); } @Nullable private final SummaryCallback summaryCallback; private @Nullable HeapState heapState; public HeapDisplay(@Nullable SummaryCallback summaryCallback) { this.summaryCallback = summaryCallback; setVisible(true); } private void updateFrom(HeapState state) { this.heapState = state; if (!heapState.getSamples().isEmpty()) { final HeapSample sample = heapState.getSamples().get(0); if (summaryCallback != null) { summaryCallback.updatedSummary(state); } } } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (heapState == null) { return; } final int height = getHeight() - 1; final int width = getWidth(); final long now = System.currentTimeMillis(); final long maxDataSize = Math.round(heapState.getCapacity() / (double)TEN_MB) * TEN_MB + TEN_MB; final Graphics2D graphics2D = (Graphics2D)g; graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.setColor(getForegroundColor()); graphics2D.setStroke(GRAPH_STROKE); Path2D path = null; for (HeapSample sample : heapState.getSamples()) { final double x = width - (((double)(now - sample.getSampleTime())) / ((double)heapState.getMaxSampleSizeMs()) * width); final double y = (double)height * sample.getBytes() / maxDataSize; if (path == null) { path = new Path2D.Double(); path.moveTo(x, height - y + 1); } else { path.lineTo(x, height - y + 1); } } graphics2D.draw(path); } } /** * A fixed-length list of captured samples. */ class HeapSamples { final LinkedList<HeapSample> samples = new LinkedList<>(); final int maxSampleSizeMs; HeapSamples(int maxSampleSizeMs) { this.maxSampleSizeMs = maxSampleSizeMs; } void addSample(HeapMonitor.HeapSample sample) { samples.add(sample); // Leave a little bit extra in the samples we trim off. final long oldestTime = System.currentTimeMillis() - maxSampleSizeMs - 2000; while (!samples.isEmpty() && samples.get(0).getSampleTime() < oldestTime) { samples.removeFirst(); } } }
flutter-intellij/flutter-idea/src/io/flutter/inspector/HeapDisplay.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/HeapDisplay.java", "repo_id": "flutter-intellij", "token_count": 1649 }
485