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. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXTURE_REGISTRAR_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXTURE_REGISTRAR_H_ #include "flutter/shell/platform/linux/fl_texture_registrar_private.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlMockTextureRegistrar, fl_mock_texture_registrar, FL, MOCK_TEXTURE_REGISTRAR, GObject) FlMockTextureRegistrar* fl_mock_texture_registrar_new(); FlTexture* fl_mock_texture_registrar_get_texture( FlMockTextureRegistrar* registrar); gboolean fl_mock_texture_registrar_get_frame_available( FlMockTextureRegistrar* registrar); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXTURE_REGISTRAR_H_
engine/shell/platform/linux/testing/mock_texture_registrar.h/0
{ "file_path": "engine/shell/platform/linux/testing/mock_texture_registrar.h", "repo_id": "engine", "token_count": 415 }
369
// 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_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ #include <flutter_windows.h> #include <chrono> #include <memory> #include <optional> #include <string> #include "binary_messenger.h" #include "dart_project.h" #include "plugin_registrar.h" #include "plugin_registry.h" namespace flutter { // An instance of a Flutter engine. // // In the future, this will be the API surface used for all interactions with // the engine, rather than having them duplicated on FlutterViewController. // For now it is only used in the rare case where you need a headless Flutter // engine. class FlutterEngine : public PluginRegistry { public: // Creates a new engine for running the given project. explicit FlutterEngine(const DartProject& project); virtual ~FlutterEngine(); // Prevent copying. FlutterEngine(FlutterEngine const&) = delete; FlutterEngine& operator=(FlutterEngine const&) = delete; // Starts running the engine at the entrypoint function specified in the // DartProject used to configure the engine, or main() by default. bool Run(); // Starts running the engine, with an optional entry point. // // If provided, entry_point must be the name of a top-level function from the // same Dart library that contains the app's main() function, and must be // decorated with `@pragma(vm:entry-point)` to ensure the method is not // tree-shaken by the Dart compiler. If not provided, defaults to main(). bool Run(const char* entry_point); // Terminates the running engine. void ShutDown(); // Processes any pending events in the Flutter engine, and returns the // nanosecond delay until the next scheduled event (or max, if none). // // This should be called on every run of the application-level runloop, and // a wait for native events in the runloop should never be longer than the // last return value from this function. std::chrono::nanoseconds ProcessMessages(); // Tells the engine that the system font list has changed. Should be called // by clients when OS-level font changes happen (e.g., WM_FONTCHANGE in a // Win32 application). void ReloadSystemFonts(); // Tells the engine that the platform brightness value has changed. Should be // called by clients when OS-level theme changes happen (e.g., // WM_DWMCOLORIZATIONCOLORCHANGED in a Win32 application). void ReloadPlatformBrightness(); // flutter::PluginRegistry: FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin( const std::string& plugin_name) override; // Returns the messenger to use for creating channels to communicate with the // Flutter engine. // // This pointer will remain valid for the lifetime of this instance. BinaryMessenger* messenger() { return messenger_.get(); } // Schedule a callback to be called after the next frame is drawn. // // This must be called from the platform thread. The callback is executed only // once on the platform thread. void SetNextFrameCallback(std::function<void()> callback); // Called to pass an external window message to the engine for lifecycle // state updates. Non-Flutter windows must call this method in their WndProc // in order to be included in the logic for application lifecycle state // updates. Returns a result if the message should be consumed. std::optional<LRESULT> ProcessExternalWindowMessage(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); private: // For access to RelinquishEngine. friend class FlutterViewController; // Gives up ownership of |engine_|, but keeps a weak reference to it. // // This is intended to be used by FlutterViewController, since the underlying // C API for view controllers takes over engine ownership. FlutterDesktopEngineRef RelinquishEngine(); // Handle for interacting with the C API's engine reference. FlutterDesktopEngineRef engine_ = nullptr; // Messenger for communicating with the engine. std::unique_ptr<BinaryMessenger> messenger_; // Whether or not this wrapper owns |engine_|. bool owns_engine_ = true; // Whether the engine has been run. This will be true if Run has been called, // or if RelinquishEngine has been called (since the view controller will // run the engine if it hasn't already been run). bool has_been_run_ = false; // The callback to execute once the next frame is drawn. std::function<void()> next_frame_callback_ = nullptr; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_
engine/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h/0
{ "file_path": "engine/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h", "repo_id": "engine", "token_count": 1510 }
370
// 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 <memory> #include <vector> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h" #include "flutter/shell/platform/windows/flutter_windows_view.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_binary_messenger.h" #include "flutter/shell/platform/windows/testing/windows_test.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace flutter { namespace testing { namespace { using ::testing::_; using ::testing::NotNull; using ::testing::Return; static constexpr char kChannelName[] = "flutter/mousecursor"; static constexpr char kActivateSystemCursorMethod[] = "activateSystemCursor"; static constexpr char kCreateCustomCursorMethod[] = "createCustomCursor/windows"; static constexpr char kSetCustomCursorMethod[] = "setCustomCursor/windows"; static constexpr char kDeleteCustomCursorMethod[] = "deleteCustomCursor/windows"; void SimulateCursorMessage(TestBinaryMessenger* messenger, const std::string& method_name, std::unique_ptr<EncodableValue> arguments, MethodResult<EncodableValue>* result_handler) { MethodCall<> call(method_name, std::move(arguments)); auto message = StandardMethodCodec::GetInstance().EncodeMethodCall(call); EXPECT_TRUE(messenger->SimulateEngineMessage( kChannelName, message->data(), message->size(), [&result_handler](const uint8_t* reply, size_t reply_size) { StandardMethodCodec::GetInstance().DecodeAndProcessResponseEnvelope( reply, reply_size, result_handler); })); } } // namespace class CursorHandlerTest : public WindowsTest { public: CursorHandlerTest() = default; virtual ~CursorHandlerTest() = default; protected: FlutterWindowsEngine* engine() { return engine_.get(); } FlutterWindowsView* view() { return view_.get(); } MockWindowBindingHandler* window() { return window_; } void UseHeadlessEngine() { FlutterWindowsEngineBuilder builder{GetContext()}; engine_ = builder.Build(); } void UseEngineWithView() { FlutterWindowsEngineBuilder builder{GetContext()}; auto window = std::make_unique<MockWindowBindingHandler>(); EXPECT_CALL(*window.get(), SetView).Times(1); EXPECT_CALL(*window.get(), GetWindowHandle).WillRepeatedly(Return(nullptr)); window_ = window.get(); engine_ = builder.Build(); view_ = std::make_unique<FlutterWindowsView>(kImplicitViewId, engine_.get(), std::move(window)); EngineModifier modifier{engine_.get()}; modifier.SetImplicitView(view_.get()); } private: std::unique_ptr<FlutterWindowsEngine> engine_; std::unique_ptr<FlutterWindowsView> view_; MockWindowBindingHandler* window_; FML_DISALLOW_COPY_AND_ASSIGN(CursorHandlerTest); }; TEST_F(CursorHandlerTest, ActivateSystemCursor) { UseEngineWithView(); TestBinaryMessenger messenger; CursorHandler cursor_handler(&messenger, engine()); EXPECT_CALL(*window(), UpdateFlutterCursor("click")).Times(1); bool success = false; MethodResultFunctions<> result_handler( [&success](const EncodableValue* result) { success = true; EXPECT_EQ(result, nullptr); }, nullptr, nullptr); SimulateCursorMessage(&messenger, kActivateSystemCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("device"), EncodableValue(0)}, {EncodableValue("kind"), EncodableValue("click")}, }), &result_handler); EXPECT_TRUE(success); } TEST_F(CursorHandlerTest, ActivateSystemCursorRequiresView) { UseHeadlessEngine(); TestBinaryMessenger messenger; CursorHandler cursor_handler(&messenger, engine()); bool error = false; MethodResultFunctions<> result_handler( nullptr, [&error](const std::string& error_code, const std::string& error_message, const EncodableValue* value) { error = true; EXPECT_EQ(error_message, "Cursor is not available in Windows headless mode"); }, nullptr); SimulateCursorMessage(&messenger, kActivateSystemCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("device"), EncodableValue(0)}, {EncodableValue("kind"), EncodableValue("click")}, }), &result_handler); EXPECT_TRUE(error); } TEST_F(CursorHandlerTest, CreateCustomCursor) { UseEngineWithView(); TestBinaryMessenger messenger; CursorHandler cursor_handler(&messenger, engine()); // Create a 4x4 raw BGRA test cursor buffer. std::vector<uint8_t> buffer(4 * 4 * 4, 0); bool success = false; MethodResultFunctions<> result_handler( [&success](const EncodableValue* result) { success = true; EXPECT_EQ(std::get<std::string>(*result), "hello"); }, nullptr, nullptr); SimulateCursorMessage(&messenger, kCreateCustomCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("name"), EncodableValue("hello")}, {EncodableValue("buffer"), EncodableValue(buffer)}, {EncodableValue("width"), EncodableValue(4)}, {EncodableValue("height"), EncodableValue(4)}, {EncodableValue("hotX"), EncodableValue(0.0)}, {EncodableValue("hotY"), EncodableValue(0.0)}, }), &result_handler); EXPECT_TRUE(success); } TEST_F(CursorHandlerTest, SetCustomCursor) { UseEngineWithView(); TestBinaryMessenger messenger; CursorHandler cursor_handler(&messenger, engine()); // Create a 4x4 raw BGRA test cursor buffer. std::vector<uint8_t> buffer(4 * 4 * 4, 0); bool success = false; MethodResultFunctions<> create_result_handler(nullptr, nullptr, nullptr); MethodResultFunctions<> set_result_handler( [&success](const EncodableValue* result) { success = true; EXPECT_EQ(result, nullptr); }, nullptr, nullptr); EXPECT_CALL(*window(), SetFlutterCursor(/*cursor=*/NotNull())).Times(1); SimulateCursorMessage(&messenger, kCreateCustomCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("name"), EncodableValue("hello")}, {EncodableValue("buffer"), EncodableValue(buffer)}, {EncodableValue("width"), EncodableValue(4)}, {EncodableValue("height"), EncodableValue(4)}, {EncodableValue("hotX"), EncodableValue(0.0)}, {EncodableValue("hotY"), EncodableValue(0.0)}, }), &create_result_handler); SimulateCursorMessage(&messenger, kSetCustomCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("name"), EncodableValue("hello")}, }), &set_result_handler); EXPECT_TRUE(success); } TEST_F(CursorHandlerTest, SetCustomCursorRequiresView) { UseHeadlessEngine(); TestBinaryMessenger messenger; CursorHandler cursor_handler(&messenger, engine()); // Create a 4x4 raw BGRA test cursor buffer. std::vector<uint8_t> buffer(4 * 4 * 4, 0); bool error = false; MethodResultFunctions<> create_result_handler(nullptr, nullptr, nullptr); MethodResultFunctions<> set_result_handler( nullptr, [&error](const std::string& error_code, const std::string& error_message, const EncodableValue* value) { error = true; EXPECT_EQ(error_message, "Cursor is not available in Windows headless mode"); }, nullptr); SimulateCursorMessage(&messenger, kCreateCustomCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("name"), EncodableValue("hello")}, {EncodableValue("buffer"), EncodableValue(buffer)}, {EncodableValue("width"), EncodableValue(4)}, {EncodableValue("height"), EncodableValue(4)}, {EncodableValue("hotX"), EncodableValue(0.0)}, {EncodableValue("hotY"), EncodableValue(0.0)}, }), &create_result_handler); SimulateCursorMessage(&messenger, kSetCustomCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("name"), EncodableValue("hello")}, }), &set_result_handler); EXPECT_TRUE(error); } TEST_F(CursorHandlerTest, SetNonexistentCustomCursor) { UseEngineWithView(); TestBinaryMessenger messenger; CursorHandler cursor_handler(&messenger, engine()); bool error = false; MethodResultFunctions<> result_handler( nullptr, [&error](const std::string& error_code, const std::string& error_message, const EncodableValue* value) { error = true; EXPECT_EQ( error_message, "The custom cursor identified by the argument key cannot be found"); }, nullptr); EXPECT_CALL(*window(), SetFlutterCursor).Times(0); SimulateCursorMessage(&messenger, kSetCustomCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("name"), EncodableValue("hello")}, }), &result_handler); EXPECT_TRUE(error); } TEST_F(CursorHandlerTest, DeleteCustomCursor) { UseEngineWithView(); TestBinaryMessenger messenger; CursorHandler cursor_handler(&messenger, engine()); // Create a 4x4 raw BGRA test cursor buffer. std::vector<uint8_t> buffer(4 * 4 * 4, 0); bool success = false; MethodResultFunctions<> create_result_handler(nullptr, nullptr, nullptr); MethodResultFunctions<> delete_result_handler( [&success](const EncodableValue* result) { success = true; EXPECT_EQ(result, nullptr); }, nullptr, nullptr); SimulateCursorMessage(&messenger, kCreateCustomCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("name"), EncodableValue("hello")}, {EncodableValue("buffer"), EncodableValue(buffer)}, {EncodableValue("width"), EncodableValue(4)}, {EncodableValue("height"), EncodableValue(4)}, {EncodableValue("hotX"), EncodableValue(0.0)}, {EncodableValue("hotY"), EncodableValue(0.0)}, }), &create_result_handler); SimulateCursorMessage(&messenger, kDeleteCustomCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("name"), EncodableValue("hello")}, }), &delete_result_handler); EXPECT_TRUE(success); } TEST_F(CursorHandlerTest, DeleteNonexistentCustomCursor) { UseEngineWithView(); TestBinaryMessenger messenger; CursorHandler cursor_handler(&messenger, engine()); bool success = false; MethodResultFunctions<> result_handler( [&success](const EncodableValue* result) { success = true; EXPECT_EQ(result, nullptr); }, nullptr, nullptr); SimulateCursorMessage(&messenger, kDeleteCustomCursorMethod, std::make_unique<EncodableValue>(EncodableMap{ {EncodableValue("name"), EncodableValue("fake")}, }), &result_handler); EXPECT_TRUE(success); } } // namespace testing } // namespace flutter
engine/shell/platform/windows/cursor_handler_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/cursor_handler_unittests.cc", "repo_id": "engine", "token_count": 5665 }
371
// 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_SURFACE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_SURFACE_H_ #include <EGL/egl.h> #include "flutter/fml/macros.h" namespace flutter { namespace egl { // An EGL surface. This can be window surface or an off-screen buffer. // // This enables automatic error logging and mocking. class Surface { public: Surface(EGLDisplay display, EGLContext context, EGLSurface surface); virtual ~Surface(); // Destroy the EGL surface and invalidate this object. // // This also unbinds the current context from the thread. virtual bool Destroy(); // Check whether the EGL surface is valid. virtual bool IsValid() const; // Check whether the EGL display, context, and surface are bound // to the current thread. virtual bool IsCurrent() const; // Bind the EGL surface's context and read and draw surfaces to the // current thread. Returns true on success. virtual bool MakeCurrent() const; // Swap the surface's front the and back buffers. Used to present content. // Returns true on success. virtual bool SwapBuffers() const; // Get the raw EGL surface. virtual const EGLSurface& GetHandle() const; protected: bool is_valid_ = true; EGLDisplay display_ = EGL_NO_DISPLAY; EGLContext context_ = EGL_NO_CONTEXT; EGLSurface surface_ = EGL_NO_SURFACE; FML_DISALLOW_COPY_AND_ASSIGN(Surface); }; } // namespace egl } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_SURFACE_H_
engine/shell/platform/windows/egl/surface.h/0
{ "file_path": "engine/shell/platform/windows/egl/surface.h", "repo_id": "engine", "token_count": 518 }
372
// 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_PROJECT_BUNDLE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_PROJECT_BUNDLE_H_ #include <filesystem> #include <string> #include <vector> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/windows/public/flutter_windows.h" namespace flutter { using UniqueAotDataPtr = std::unique_ptr<_FlutterEngineAOTData, FlutterEngineCollectAOTDataFnPtr>; // The data associated with a Flutter project needed to run it in an engine. class FlutterProjectBundle { public: // Creates a new project bundle from the given properties. // // Treats any relative paths as relative to the directory of this executable. explicit FlutterProjectBundle( const FlutterDesktopEngineProperties& properties); ~FlutterProjectBundle(); // Whether or not the bundle is valid. This does not check that the paths // exist, or contain valid data, just that paths were able to be constructed. bool HasValidPaths(); // Returns the path to the assets directory. const std::filesystem::path& assets_path() { return assets_path_; } // Returns the path to the ICU data file. const std::filesystem::path& icu_path() { return icu_path_; } // Returns any switches that should be passed to the engine. const std::vector<std::string> GetSwitches(); // Sets engine switches. void SetSwitches(const std::vector<std::string>& switches); // Attempts to load AOT data for this bundle. The returned data must be // retained until any engine instance it is passed to has been shut down. // // Logs and returns nullptr on failure. UniqueAotDataPtr LoadAotData(const FlutterEngineProcTable& engine_procs); // Returns the Dart entrypoint. const std::string& dart_entrypoint() const { return dart_entrypoint_; } // Returns the command line arguments to be passed through to the Dart // entrypoint. const std::vector<std::string>& dart_entrypoint_arguments() const { return dart_entrypoint_arguments_; } private: std::filesystem::path assets_path_; std::filesystem::path icu_path_; // Path to the AOT library file, if any. std::filesystem::path aot_library_path_; // The Dart entrypoint to launch. std::string dart_entrypoint_; // Dart entrypoint arguments. std::vector<std::string> dart_entrypoint_arguments_; // Engine switches. std::vector<std::string> engine_switches_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_PROJECT_BUNDLE_H_
engine/shell/platform/windows/flutter_project_bundle.h/0
{ "file_path": "engine/shell/platform/windows/flutter_project_bundle.h", "repo_id": "engine", "token_count": 820 }
373
// 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_WINDOWS_VIEW_CONTROLLER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_VIEW_CONTROLLER_H_ #include <memory> #include "flutter_windows_engine.h" #include "flutter_windows_view.h" namespace flutter { /// Controls a view that displays Flutter content. class FlutterWindowsViewController { public: FlutterWindowsViewController(std::unique_ptr<FlutterWindowsEngine> engine, std::unique_ptr<FlutterWindowsView> view) : engine_(std::move(engine)), view_(std::move(view)) {} FlutterWindowsEngine* engine() { return engine_.get(); } FlutterWindowsView* view() { return view_.get(); } private: std::unique_ptr<FlutterWindowsEngine> engine_; std::unique_ptr<FlutterWindowsView> view_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_VIEW_CONTROLLER_H_
engine/shell/platform/windows/flutter_windows_view_controller.h/0
{ "file_path": "engine/shell/platform/windows/flutter_windows_view_controller.h", "repo_id": "engine", "token_count": 373 }
374
// 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_KEYBOARD_UTILS_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_UTILS_H_ #include <stdint.h> #include <string> namespace flutter { constexpr int kShift = 1 << 0; constexpr int kControl = 1 << 3; constexpr int kScanCodeShiftLeft = 0x2a; constexpr int kScanCodeShiftRight = 0x36; constexpr int kKeyCodeShiftLeft = 0xa0; constexpr int kScanCodeControlLeft = 0x1d; constexpr int kScanCodeControlRight = 0xe01d; constexpr int kKeyCodeControlLeft = 0xa2; // The bit of a mapped character in a WM_KEYDOWN message that indicates the // character is a dead key. // // When a dead key is pressed, the WM_KEYDOWN's lParam is mapped to a special // value: the "normal character" | 0x80000000. For example, when pressing // "dead key caret" (one that makes the following e into ê), its mapped // character is 0x8000005E. "Reverting" it gives 0x5E, which is character '^'. constexpr int kDeadKeyCharMask = 0x80000000; // Revert the "character" for a dead key to its normal value, or the argument // unchanged otherwise. inline uint32_t UndeadChar(uint32_t ch) { return ch & ~kDeadKeyCharMask; } // Encode a Unicode codepoint into a UTF-16 string. // // If the codepoint is invalid, this function throws an assertion error, and // returns an empty string. std::u16string EncodeUtf16(char32_t character); } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_UTILS_H_
engine/shell/platform/windows/keyboard_utils.h/0
{ "file_path": "engine/shell/platform/windows/keyboard_utils.h", "repo_id": "engine", "token_count": 519 }
375
// 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/system_utils.h" #include <Windows.h> #include <sstream> #include "flutter/fml/platform/win/wstring_conversion.h" namespace flutter { std::vector<LanguageInfo> GetPreferredLanguageInfo( const WindowsProcTable& windows_proc_table) { std::vector<std::wstring> languages = GetPreferredLanguages(windows_proc_table); std::vector<LanguageInfo> language_info; language_info.reserve(languages.size()); for (auto language : languages) { language_info.push_back(ParseLanguageName(language)); } return language_info; } std::wstring GetPreferredLanguagesFromMUI( const WindowsProcTable& windows_proc_table) { ULONG buffer_size = 0; ULONG count = 0; DWORD flags = MUI_LANGUAGE_NAME | MUI_UI_FALLBACK; if (!windows_proc_table.GetThreadPreferredUILanguages(flags, &count, nullptr, &buffer_size)) { return std::wstring(); } std::wstring buffer(buffer_size, '\0'); if (!windows_proc_table.GetThreadPreferredUILanguages( flags, &count, buffer.data(), &buffer_size)) { return std::wstring(); } return buffer; } std::vector<std::wstring> GetPreferredLanguages( const WindowsProcTable& windows_proc_table) { std::vector<std::wstring> languages; // Initialize the buffer std::wstring buffer = GetPreferredLanguagesFromMUI(windows_proc_table); // Extract the individual languages from the buffer. size_t start = 0; while (true) { // The buffer is terminated by an empty string (i.e., a double null). if (buffer[start] == L'\0') { break; } // Read the next null-terminated language. std::wstring language(buffer.c_str() + start); if (language.empty()) { break; } languages.push_back(language); // Skip past that language and its terminating null in the buffer. start += language.size() + 1; } return languages; } LanguageInfo ParseLanguageName(std::wstring language_name) { LanguageInfo info; // Split by '-', discarding any suplemental language info (-x-foo). std::vector<std::string> components; std::istringstream stream(fml::WideStringToUtf8(language_name)); std::string component; while (getline(stream, component, '-')) { if (component == "x") { break; } components.push_back(component); } // Determine which components are which. info.language = components[0]; if (components.size() == 3) { info.script = components[1]; info.region = components[2]; } else if (components.size() == 2) { // A script code will always be four characters long. if (components[1].size() == 4) { info.script = components[1]; } else { info.region = components[1]; } } return info; } std::wstring GetUserTimeFormat() { // Rather than do the call-allocate-call-free dance, just use a sufficiently // large buffer to handle any reasonable time format string. const int kBufferSize = 100; wchar_t buffer[kBufferSize]; if (::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_STIMEFORMAT, buffer, kBufferSize) == 0) { return std::wstring(); } return std::wstring(buffer, kBufferSize); } bool Prefer24HourTime(std::wstring time_format) { return time_format.find(L"H") != std::wstring::npos; } } // namespace flutter
engine/shell/platform/windows/system_utils.cc/0
{ "file_path": "engine/shell/platform/windows/system_utils.cc", "repo_id": "engine", "token_count": 1263 }
376
// 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_MOCK_PLATFORM_VIEW_MANAGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_PLATFORM_VIEW_MANAGER_H_ #include "flutter/shell/platform/windows/platform_view_plugin.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "gmock/gmock.h" namespace flutter { class MockPlatformViewManager : public PlatformViewPlugin { public: MockPlatformViewManager(FlutterWindowsEngine* engine) : PlatformViewPlugin(engine->messenger_wrapper(), engine->task_runner()) { } ~MockPlatformViewManager() {} MOCK_METHOD(bool, AddPlatformView, (PlatformViewId id, std::string_view)); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_PLATFORM_VIEW_MANAGER_H_
engine/shell/platform/windows/testing/mock_platform_view_manager.h/0
{ "file_path": "engine/shell/platform/windows/testing/mock_platform_view_manager.h", "repo_id": "engine", "token_count": 319 }
377
// 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_config_builder.h" #include <combaseapi.h> #include <string> #include <string_view> #include <vector> #include "flutter/fml/logging.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/public/flutter_windows.h" #include "flutter/shell/platform/windows/testing/windows_test_context.h" namespace flutter { namespace testing { WindowsConfigBuilder::WindowsConfigBuilder(WindowsTestContext& context) : context_(context) {} WindowsConfigBuilder::~WindowsConfigBuilder() = default; void WindowsConfigBuilder::SetDartEntrypoint(std::string_view entrypoint) { if (entrypoint.empty()) { return; } dart_entrypoint_ = entrypoint; } void WindowsConfigBuilder::AddDartEntrypointArgument(std::string_view arg) { if (arg.empty()) { return; } dart_entrypoint_arguments_.emplace_back(std::move(arg)); } FlutterDesktopEngineProperties WindowsConfigBuilder::GetEngineProperties() const { FlutterDesktopEngineProperties engine_properties = {}; engine_properties.assets_path = context_.GetAssetsPath().c_str(); engine_properties.icu_data_path = context_.GetIcuDataPath().c_str(); // Set Dart entrypoint. engine_properties.dart_entrypoint = dart_entrypoint_.c_str(); // Set Dart entrypoint argc, argv. std::vector<const char*> dart_args; dart_args.reserve(dart_entrypoint_arguments_.size()); for (const auto& arg : dart_entrypoint_arguments_) { dart_args.push_back(arg.c_str()); } if (!dart_args.empty()) { engine_properties.dart_entrypoint_argv = dart_args.data(); engine_properties.dart_entrypoint_argc = dart_args.size(); } else { // Clear this out in case this is not the first engine launch from the // embedder config builder. engine_properties.dart_entrypoint_argv = nullptr; engine_properties.dart_entrypoint_argc = 0; } return engine_properties; } EnginePtr WindowsConfigBuilder::InitializeEngine() const { FlutterDesktopEngineProperties engine_properties = GetEngineProperties(); return EnginePtr{FlutterDesktopEngineCreate(&engine_properties)}; } EnginePtr WindowsConfigBuilder::RunHeadless() const { InitializeCOM(); EnginePtr engine = InitializeEngine(); if (!engine) { return {}; } // Register native functions. FlutterWindowsEngine* windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine.get()); windows_engine->SetRootIsolateCreateCallback( context_.GetRootIsolateCallback()); if (!FlutterDesktopEngineRun(engine.get(), /* entry_point */ nullptr)) { return {}; } return engine; } ViewControllerPtr WindowsConfigBuilder::Run() const { InitializeCOM(); EnginePtr engine = InitializeEngine(); if (!engine) { return {}; } // Register native functions. FlutterWindowsEngine* windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine.get()); windows_engine->SetRootIsolateCreateCallback( context_.GetRootIsolateCallback()); int width = 600; int height = 400; ViewControllerPtr controller{ FlutterDesktopViewControllerCreate(width, height, engine.release())}; if (!controller) { return {}; } return controller; } void WindowsConfigBuilder::InitializeCOM() const { FML_CHECK(SUCCEEDED(::CoInitializeEx(nullptr, COINIT_MULTITHREADED))); } } // namespace testing } // namespace flutter
engine/shell/platform/windows/testing/windows_test_config_builder.cc/0
{ "file_path": "engine/shell/platform/windows/testing/windows_test_config_builder.cc", "repo_id": "engine", "token_count": 1135 }
378
// 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_STATE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_STATE_H_ #include "flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h" #include "flutter/shell/platform/common/incoming_message_dispatcher.h" #include "flutter/shell/platform/embedder/embedder.h" // Structs backing the opaque references used in the C API. // // DO NOT ADD ANY NEW CODE HERE. These are legacy, and are being phased out // in favor of objects that own and manage the relevant functionality. namespace flutter { struct FlutterWindowsEngine; } // namespace flutter // Wrapper to distinguish the plugin registrar ref from the engine ref given out // in the C API. struct FlutterDesktopPluginRegistrar { // The engine that owns this state object. flutter::FlutterWindowsEngine* engine = nullptr; }; #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_STATE_H_
engine/shell/platform/windows/window_state.h/0
{ "file_path": "engine/shell/platform/windows/window_state.h", "repo_id": "engine", "token_count": 324 }
379
// 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 is a minimal dependency heart beat test for the Dart VM Service. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'launcher.dart'; import 'service_client.dart'; class Expect { static void equals(dynamic actual, dynamic expected) { if (actual != expected) { throw 'Expected $actual == $expected'; } } static void contains(String needle, String haystack) { if (!haystack.contains(needle)) { throw 'Expected $haystack to contain $needle'; } } static void isTrue(bool tf) { if (tf != true) { throw 'Expected $tf to be true'; } } static void isFalse(bool tf) { if (tf != false) { throw 'Expected $tf to be false'; } } static void notExecuted() { throw 'Should not have hit'; } static void isNotNull(dynamic a) { if (a == null) { throw 'Expected $a to not be null'; } } } Future<String> readResponse(HttpClientResponse response) { final Completer<String> completer = Completer<String>(); final StringBuffer contents = StringBuffer(); response.transform(utf8.decoder).listen((String data) { contents.write(data); }, onDone: () => completer.complete(contents.toString())); return completer.future; } // Test accessing the service protocol over http. Future<Null> testHttpProtocolRequest(Uri uri) async { uri = uri.replace(path: 'getVM'); final HttpClient client = HttpClient(); final HttpClientRequest request = await client.getUrl(uri); final HttpClientResponse response = await request.close(); Expect.equals(response.statusCode, 200); final Map<String, dynamic> responseAsMap = json.decode(await readResponse(response)) as Map<String, dynamic>; Expect.equals(responseAsMap['jsonrpc'], '2.0'); client.close(); } // Test accessing the service protocol over ws. Future<Null> testWebSocketProtocolRequest(Uri uri) async { uri = uri.replace(scheme: 'ws', path: 'ws'); final WebSocket webSocketClient = await WebSocket.connect(uri.toString()); final ServiceClient serviceClient = ServiceClient(webSocketClient); final Map<String, dynamic> response = await serviceClient.invokeRPC('getVM'); Expect.equals(response['type'], 'VM'); try { await serviceClient.invokeRPC('BART_SIMPSON'); Expect.notExecuted(); } catch (e) { // Method not found. Expect.equals((e as Map<String, dynamic>)['code'], -32601); } } // Test accessing an Observatory UI asset. Future<Null> testHttpAssetRequest(Uri uri) async { uri = uri.replace(path: 'third_party/trace_viewer_full.html'); final HttpClient client = HttpClient(); final HttpClientRequest request = await client.getUrl(uri); final HttpClientResponse response = await request.close(); Expect.equals(response.statusCode, 200); await response.drain(); client.close(); } Future<Null> testStartPaused(Uri uri) async { uri = uri.replace(scheme: 'ws', path: 'ws'); final WebSocket webSocketClient = await WebSocket.connect(uri.toString()); final Completer<dynamic> isolateStartedId = Completer<dynamic>(); final Completer<dynamic> isolatePausedId = Completer<dynamic>(); final Completer<dynamic> isolateResumeId = Completer<dynamic>(); final ServiceClient serviceClient = ServiceClient(webSocketClient, isolateStartedId: isolateStartedId, isolatePausedId: isolatePausedId, isolateResumeId: isolateResumeId); await serviceClient .invokeRPC('streamListen', <String, String>{'streamId': 'Isolate'}); await serviceClient .invokeRPC('streamListen', <String, String>{'streamId': 'Debug'}); final Map<String, dynamic> response = await serviceClient.invokeRPC('getVM'); Expect.equals(response['type'], 'VM'); String isolateId; final List<dynamic> isolates = response['isolates'] as List<dynamic>; if (isolates.isNotEmpty) { isolateId = (isolates[0] as Map<String, String>)['id']!; } else { // Wait until isolate starts. isolateId = await isolateStartedId.future as String; } // Grab the isolate. Map<String, dynamic> isolate = await serviceClient.invokeRPC('getIsolate', <String, String>{ 'isolateId': isolateId, }); Expect.equals(isolate['type'], 'Isolate'); Expect.isNotNull(isolate['pauseEvent']); // If it is not runnable, wait until it becomes runnable. if (isolate['pauseEvent']['kind'] == 'None') { await isolatePausedId.future; isolate = await serviceClient.invokeRPC('getIsolate', <String, String>{ 'isolateId': isolateId, }); } // Verify that it is paused at start. Expect.equals(isolate['pauseEvent']['kind'], 'PauseStart'); // Resume the isolate. await serviceClient.invokeRPC('resume', <String, String>{ 'isolateId': isolateId, }); // Wait until the isolate has resumed. await isolateResumeId.future; final Map<String, dynamic> resumedResponse = await serviceClient .invokeRPC('getIsolate', <String, String>{'isolateId': isolateId}); Expect.equals(resumedResponse['type'], 'Isolate'); Expect.isNotNull(resumedResponse['pauseEvent']); Expect.equals(resumedResponse['pauseEvent']['kind'], 'Resume'); } typedef TestFunction = Future<Null> Function(Uri uri); final List<TestFunction> basicTests = <TestFunction>[ testHttpProtocolRequest, testWebSocketProtocolRequest, testHttpAssetRequest ]; final List<TestFunction> startPausedTests = <TestFunction>[ // TODO(engine): Investigate difference in lifecycle events. // testStartPaused, ]; Future<bool> runTests(ShellLauncher launcher, List<TestFunction> tests) async { final ShellProcess? process = await launcher.launch(); if (process == null) { return false; } final Uri uri = await process.waitForVMService(); try { for (int i = 0; i < tests.length; i++) { print('Executing test ${i + 1}/${tests.length}'); await tests[i](uri); } } catch (e, st) { print('Dart VM Service test failure: $e\n$st'); exitCode = -1; } await process.kill(); return exitCode == 0; } Future<Null> main(List<String> args) async { if (args.length < 2) { print('Usage: dart ${Platform.script} ' '<sky_shell_executable> <main_dart> ...'); return; } final String shellExecutablePath = args[0]; final String mainDartPath = args[1]; final List<String> extraArgs = args.length <= 2 ? <String>[] : args.sublist(2); final ShellLauncher launcher = ShellLauncher(shellExecutablePath, mainDartPath, false, extraArgs); final ShellLauncher startPausedlauncher = ShellLauncher(shellExecutablePath, mainDartPath, true, extraArgs); await runTests(launcher, basicTests); await runTests(startPausedlauncher, startPausedTests); }
engine/shell/testing/observatory/test.dart/0
{ "file_path": "engine/shell/testing/observatory/test.dart", "repo_id": "engine", "token_count": 2308 }
380
#!/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 shutil import subprocess import sys def main(): parser = argparse.ArgumentParser( description='Creates an XCFramework consisting of the specified universal frameworks' ) parser.add_argument( '--frameworks', nargs='+', help='The framework paths used to create the XCFramework.', required=True ) parser.add_argument('--name', help='Name of the XCFramework', type=str, required=True) parser.add_argument('--location', help='Output directory', type=str, required=True) args = parser.parse_args() create_xcframework(args.location, args.name, args.frameworks) def create_xcframework(location, name, frameworks): output_dir = os.path.abspath(location) output_xcframework = os.path.join(output_dir, '%s.xcframework' % name) if not os.path.exists(output_dir): os.makedirs(output_dir) if os.path.exists(output_xcframework): # Remove old xcframework. shutil.rmtree(output_xcframework) # xcrun xcodebuild -create-xcframework -framework foo/baz.framework \ # -framework bar/baz.framework -output output/ command = ['xcrun', 'xcodebuild', '-quiet', '-create-xcframework'] for framework in frameworks: command.extend(['-framework', os.path.abspath(framework)]) command.extend(['-output', output_xcframework]) subprocess.check_call(command, stdout=open(os.devnull, 'w')) if __name__ == '__main__': sys.exit(main())
engine/sky/tools/create_xcframework.py/0
{ "file_path": "engine/sky/tools/create_xcframework.py", "repo_id": "engine", "token_count": 577 }
381
// 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/native_activity.h" #include "flutter/fml/message_loop.h" namespace flutter { NativeActivity::NativeActivity(ANativeActivity* activity) : activity_(activity) { fml::MessageLoop::EnsureInitializedForCurrentThread(); activity->instance = this; activity->callbacks->onStart = [](ANativeActivity* activity) { reinterpret_cast<NativeActivity*>(activity->instance)->OnStart(); }; activity->callbacks->onStop = [](ANativeActivity* activity) { reinterpret_cast<NativeActivity*>(activity->instance)->OnStop(); }; activity->callbacks->onPause = [](ANativeActivity* activity) { reinterpret_cast<NativeActivity*>(activity->instance)->OnPause(); }; activity->callbacks->onResume = [](ANativeActivity* activity) { reinterpret_cast<NativeActivity*>(activity->instance)->OnResume(); }; activity->callbacks->onDestroy = [](ANativeActivity* activity) { delete reinterpret_cast<NativeActivity*>(activity->instance); }; activity->callbacks->onSaveInstanceState = [](ANativeActivity* activity, size_t* out_size) -> void* { auto mapping = reinterpret_cast<NativeActivity*>(activity->instance) ->OnSaveInstanceState(); if (mapping == nullptr || mapping->GetMapping() == nullptr) { *out_size = 0; return nullptr; } // This will be `free`d by the framework. auto copied = malloc(mapping->GetSize()); FML_CHECK(copied != nullptr) << "Allocation failure while saving instance state."; memcpy(copied, mapping->GetMapping(), mapping->GetSize()); *out_size = mapping->GetSize(); return copied; }; activity->callbacks->onWindowFocusChanged = [](ANativeActivity* activity, int has_focus) { reinterpret_cast<NativeActivity*>(activity->instance) ->OnWindowFocusChanged(has_focus); }; activity->callbacks->onNativeWindowCreated = [](ANativeActivity* activity, ANativeWindow* window) { reinterpret_cast<NativeActivity*>(activity->instance) ->OnNativeWindowCreated(window); }; activity->callbacks->onNativeWindowResized = [](ANativeActivity* activity, ANativeWindow* window) { reinterpret_cast<NativeActivity*>(activity->instance) ->OnNativeWindowResized(window); }; activity->callbacks->onNativeWindowRedrawNeeded = [](ANativeActivity* activity, ANativeWindow* window) { reinterpret_cast<NativeActivity*>(activity->instance) ->OnNativeWindowRedrawNeeded(window); }; activity->callbacks->onNativeWindowDestroyed = [](ANativeActivity* activity, ANativeWindow* window) { reinterpret_cast<NativeActivity*>(activity->instance) ->OnNativeWindowDestroyed(window); }; activity->callbacks->onInputQueueCreated = [](ANativeActivity* activity, AInputQueue* queue) { reinterpret_cast<NativeActivity*>(activity->instance) ->OnInputQueueCreated(queue); }; activity->callbacks->onInputQueueDestroyed = [](ANativeActivity* activity, AInputQueue* queue) { reinterpret_cast<NativeActivity*>(activity->instance) ->OnInputQueueDestroyed(queue); }; activity->callbacks->onConfigurationChanged = [](ANativeActivity* activity) { reinterpret_cast<NativeActivity*>(activity->instance) ->OnConfigurationChanged(); }; activity->callbacks->onLowMemory = [](ANativeActivity* activity) { reinterpret_cast<NativeActivity*>(activity->instance)->OnLowMemory(); }; } NativeActivity::~NativeActivity() = default; void NativeActivity::OnStart() {} void NativeActivity::OnStop() {} void NativeActivity::OnPause() {} void NativeActivity::OnResume() {} std::shared_ptr<fml::Mapping> NativeActivity::OnSaveInstanceState() { return nullptr; } void NativeActivity::OnWindowFocusChanged(bool has_focus) {} void NativeActivity::OnNativeWindowCreated(ANativeWindow* window) {} void NativeActivity::OnNativeWindowResized(ANativeWindow* window) {} void NativeActivity::OnNativeWindowRedrawNeeded(ANativeWindow* window) {} void NativeActivity::OnNativeWindowDestroyed(ANativeWindow* window) {} void NativeActivity::OnInputQueueCreated(AInputQueue* queue) {} void NativeActivity::OnInputQueueDestroyed(AInputQueue* queue) {} void NativeActivity::OnConfigurationChanged() {} void NativeActivity::OnLowMemory() {} void NativeActivity::Terminate() { ANativeActivity_finish(activity_); } } // namespace flutter extern "C" __attribute__((visibility("default"))) void ANativeActivity_onCreate( ANativeActivity* activity, void* saved_state, size_t saved_state_size) { std::unique_ptr<fml::Mapping> saved_state_mapping; if (saved_state_size > 0u) { saved_state_mapping = std::make_unique<fml::MallocMapping>( fml::MallocMapping::Copy(saved_state, saved_state_size)); } flutter::NativeActivityMain(activity, std::move(saved_state_mapping)) .release(); // Will be freed when the frame calls the onDestroy. See the // delete in that callback. }
engine/testing/android/native_activity/native_activity.cc/0
{ "file_path": "engine/testing/android/native_activity/native_activity.cc", "repo_id": "engine", "token_count": 2001 }
382
include ':app'
engine/testing/android_background_image/android/settings.gradle/0
{ "file_path": "engine/testing/android_background_image/android/settings.gradle", "repo_id": "engine", "token_count": 6 }
383
// 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:litetest/litetest.dart'; import 'package:metrics_center/metrics_center.dart'; import 'package:path/path.dart' as p; import '../bin/parse_and_send.dart' as pas; void main() { test('runGit() succeeds', () async { // Check that git --version runs successfully final ProcessResult result = await pas.runGit(<String>['--version']); expect(result.exitCode, equals(0)); }); test('getGitLog() succeeds', () async { final List<String> gitLog = await pas.getGitLog(); // Check that gitLog[0] is a hash final RegExp sha1re = RegExp(r'[a-f0-9]{40}'); expect(sha1re.hasMatch(gitLog[0]), true); // Check that gitLog[1] is an int final int secondsSinceEpoch = int.parse(gitLog[1]); // Check that gitLog[1] is a sensible Unix Epoch final int millisecondsSinceEpoch = secondsSinceEpoch * 1000; final DateTime commitDate = DateTime.fromMillisecondsSinceEpoch( millisecondsSinceEpoch, isUtc: true, ); expect(commitDate.year > 2000, true); expect(commitDate.year < 3000, true); }); test('parse() succeeds', () async { // Check that the results of parse() on ../example/txt_benchmarks.json // is as expeted. final String exampleJson = p.join('example', 'txt_benchmarks.json'); final pas.PointsAndDate pad = await pas.parse(exampleJson); final List<FlutterEngineMetricPoint> points = pad.points; expect(points[0].value, equals(101.0)); expect(points[2].value, equals(4460.0)); expect(points[4].value, equals(6548.0)); }); }
engine/testing/benchmark/test/parse_and_send_test.dart/0
{ "file_path": "engine/testing/benchmark/test/parse_and_send_test.dart", "repo_id": "engine", "token_count": 616 }
384
// 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:ui'; import 'package:litetest/litetest.dart'; void main() { test('GestureSettings has a reasonable toString', () { const GestureSettings gestureSettings = GestureSettings(physicalDoubleTapSlop: 2.0, physicalTouchSlop: 1.0); expect(gestureSettings.toString(), 'GestureSettings(physicalTouchSlop: 1.0, physicalDoubleTapSlop: 2.0)'); }); test('GestureSettings has a correct equality', () { // don't refactor these to be const, that defeats the point! final double value = nonconst(2.0); final GestureSettings settingsA = GestureSettings(physicalDoubleTapSlop: value, physicalTouchSlop: 1.0); final GestureSettings settingsB = GestureSettings(physicalDoubleTapSlop: value, physicalTouchSlop: 3.0); final GestureSettings settingsC = GestureSettings(physicalDoubleTapSlop: value, physicalTouchSlop: 1.0); expect(settingsA, equals(settingsC)); expect(settingsC, equals(settingsA)); expect(settingsA, notEquals(settingsB)); expect(settingsC, notEquals(settingsB)); expect(settingsB, notEquals(settingsA)); expect(settingsB, notEquals(settingsC)); }); test('GestureSettings copyWith preserves already set values', () { const GestureSettings initial = GestureSettings(physicalDoubleTapSlop: 1.0, physicalTouchSlop: 1.0); final GestureSettings copyA = initial.copyWith(); expect(copyA.physicalDoubleTapSlop, 1.0); expect(copyA.physicalTouchSlop, 1.0); final GestureSettings copyB = copyA.copyWith(physicalDoubleTapSlop: 2.0, physicalTouchSlop: 2.0); expect(copyB.physicalDoubleTapSlop, 2.0); expect(copyB.physicalTouchSlop, 2.0); }); test('GestureSettings constructor defaults to null', () { const GestureSettings settings = GestureSettings(); expect(settings.physicalDoubleTapSlop, null); expect(settings.physicalTouchSlop, null); }); } // Prevent the linter from complaining about a const value so that // non-identical equality can be tested. T nonconst<T>(T value) => value;
engine/testing/dart/gesture_settings_test.dart/0
{ "file_path": "engine/testing/dart/gesture_settings_test.dart", "repo_id": "engine", "token_count": 689 }
385
// 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:ui'; import 'package:litetest/litetest.dart'; // These tests should be kept in sync with the web tests in // lib/web_ui/test/lerp_test.dart. void main() { test('lerpDouble should return null if and only if both inputs are null', () { expect(lerpDouble(null, null, 1.0), isNull); expect(lerpDouble(5.0, null, 0.25), isNotNull); expect(lerpDouble(null, 5.0, 0.25), isNotNull); expect(lerpDouble(5, null, 0.25), isNotNull); expect(lerpDouble(null, 5, 0.25), isNotNull); }); test('lerpDouble should treat a null input as 0 if the other input is non-null', () { expect(lerpDouble(null, 10.0, 0.25), closeTo(2.5, precisionErrorTolerance)); expect(lerpDouble(10.0, null, 0.25), closeTo(7.5, precisionErrorTolerance)); expect(lerpDouble(null, 10, 0.25), closeTo(2.5, precisionErrorTolerance)); expect(lerpDouble(10, null, 0.25), closeTo(7.5, precisionErrorTolerance)); }); test('lerpDouble should handle interpolation values < 0.0', () { expect(lerpDouble(0.0, 10.0, -5.0), closeTo(-50.0, precisionErrorTolerance)); expect(lerpDouble(10.0, 0.0, -5.0), closeTo(60.0, precisionErrorTolerance)); expect(lerpDouble(0, 10, -5), closeTo(-50, precisionErrorTolerance)); expect(lerpDouble(10, 0, -5), closeTo(60, precisionErrorTolerance)); }); test('lerpDouble should return the start value at 0.0', () { expect(lerpDouble(2.0, 10.0, 0.0), 2.0); expect(lerpDouble(10.0, 2.0, 0.0), 10.0); expect(lerpDouble(2, 10, 0), 2); expect(lerpDouble(10, 2, 0), 10); }); test('lerpDouble should interpolate between two values', () { expect(lerpDouble(0.0, 10.0, 0.25), closeTo(2.5, precisionErrorTolerance)); expect(lerpDouble(10.0, 0.0, 0.25), closeTo(7.5, precisionErrorTolerance)); expect(lerpDouble(0, 10, 0.25), closeTo(2.5, precisionErrorTolerance)); expect(lerpDouble(10, 0, 0.25), closeTo(7.5, precisionErrorTolerance)); // Exact answer: 20.0 - 1.0e-29 expect(lerpDouble(10.0, 1.0e30, 1.0e-29), closeTo(20.0, precisionErrorTolerance)); // Exact answer: 5.0 + 5.0e29 expect(lerpDouble(10.0, 1.0e30, 0.5), closeTo(5.0e29, precisionErrorTolerance)); }); test('lerpDouble should return the end value at 1.0', () { expect(lerpDouble(2.0, 10.0, 1.0), 10.0); expect(lerpDouble(10.0, 2.0, 1.0), 2.0); expect(lerpDouble(0, 10, 5), 50); expect(lerpDouble(10, 0, 5), -40); expect(lerpDouble(1.0e30, 10.0, 1.0), 10.0); expect(lerpDouble(10.0, 1.0e30, 0.0), 10.0); }); test('lerpDouble should handle interpolation values > 1.0', () { expect(lerpDouble(0.0, 10.0, 5.0), closeTo(50.0, precisionErrorTolerance)); expect(lerpDouble(10.0, 0.0, 5.0), closeTo(-40.0, precisionErrorTolerance)); expect(lerpDouble(0, 10, 5), closeTo(50, precisionErrorTolerance)); expect(lerpDouble(10, 0, 5), closeTo(-40, precisionErrorTolerance)); }); test('lerpDouble should return input value in all cases if begin/end are equal', () { expect(lerpDouble(10.0, 10.0, 5.0), 10.0); expect(lerpDouble(10.0, 10.0, double.nan), 10.0); expect(lerpDouble(10.0, 10.0, double.infinity), 10.0); expect(lerpDouble(10.0, 10.0, -double.infinity), 10.0); expect(lerpDouble(10, 10, 5.0), 10.0); expect(lerpDouble(10, 10, double.nan), 10.0); expect(lerpDouble(10, 10, double.infinity), 10.0); expect(lerpDouble(10, 10, -double.infinity), 10.0); expect(lerpDouble(double.nan, double.nan, 5.0), isNaN); expect(lerpDouble(double.nan, double.nan, double.nan), isNaN); expect(lerpDouble(double.nan, double.nan, double.infinity), isNaN); expect(lerpDouble(double.nan, double.nan, -double.infinity), isNaN); expect(lerpDouble(double.infinity, double.infinity, 5.0), double.infinity); expect(lerpDouble(double.infinity, double.infinity, double.nan), double.infinity); expect(lerpDouble(double.infinity, double.infinity, double.infinity), double.infinity); expect(lerpDouble(double.infinity, double.infinity, -double.infinity), double.infinity); expect(lerpDouble(-double.infinity, -double.infinity, 5.0), -double.infinity); expect(lerpDouble(-double.infinity, -double.infinity, double.nan), -double.infinity); expect(lerpDouble(-double.infinity, -double.infinity, double.infinity), -double.infinity); expect(lerpDouble(-double.infinity, -double.infinity, -double.infinity), -double.infinity); }); test('lerpDouble should throw AssertionError if interpolation value is NaN and a != b', () { expectAssertion(() => lerpDouble(0.0, 10.0, double.nan)); }); test('lerpDouble should throw AssertionError if interpolation value is +/- infinity and a != b', () { expectAssertion(() => lerpDouble(0.0, 10.0, double.infinity)); expectAssertion(() => lerpDouble(0.0, 10.0, -double.infinity)); }); test('lerpDouble should throw AssertionError if either start or end are NaN', () { expectAssertion(() => lerpDouble(double.nan, 10.0, 5.0)); expectAssertion(() => lerpDouble(0.0, double.nan, 5.0)); }); test('lerpDouble should throw AssertionError if either start or end are +/- infinity', () { expectAssertion(() => lerpDouble(double.infinity, 10.0, 5.0)); expectAssertion(() => lerpDouble(-double.infinity, 10.0, 5.0)); expectAssertion(() => lerpDouble(0.0, double.infinity, 5.0)); expectAssertion(() => lerpDouble(0.0, -double.infinity, 5.0)); }); }
engine/testing/dart/lerp_test.dart/0
{ "file_path": "engine/testing/dart/lerp_test.dart", "repo_id": "engine", "token_count": 2173 }
386
// Copyright 2024 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'; int counter = 0; void main() { test('PlatformIsolate isRunningOnPlatformThread, false cases', () async { final bool isPlatThread = await Isolate.run(() => isRunningOnPlatformThread); expect(isPlatThread, isFalse); }); test('PlatformIsolate runOnPlatformThread', () async { final bool isPlatThread = await runOnPlatformThread(() => isRunningOnPlatformThread); expect(isPlatThread, isTrue); }); test('PlatformIsolate runOnPlatformThread, async operations', () async { final bool isPlatThread = await runOnPlatformThread(() async { await Future<void>.delayed(const Duration(milliseconds: 100)); await Future<void>.delayed(const Duration(milliseconds: 100)); await Future<void>.delayed(const Duration(milliseconds: 100)); return isRunningOnPlatformThread; }); expect(isPlatThread, isTrue); }); test('PlatformIsolate runOnPlatformThread, retains state', () async { await runOnPlatformThread(() => ++counter); await Future<void>.delayed(const Duration(milliseconds: 100)); await runOnPlatformThread(() => ++counter); await Future<void>.delayed(const Duration(milliseconds: 100)); await runOnPlatformThread(() => ++counter); await Future<void>.delayed(const Duration(milliseconds: 100)); final int counterValue = await runOnPlatformThread(() => counter); expect(counterValue, 3); }); test('PlatformIsolate runOnPlatformThread, concurrent jobs', () async { final Future<int> future1 = runOnPlatformThread(() async { await Future<void>.delayed(const Duration(milliseconds: 100)); return 1; }); final Future<int> future2 = runOnPlatformThread(() async { await Future<void>.delayed(const Duration(milliseconds: 100)); return 2; }); final Future<int> future3 = runOnPlatformThread(() async { await Future<void>.delayed(const Duration(milliseconds: 100)); return 3; }); expect(await future1, 1); expect(await future2, 2); expect(await future3, 3); }); test('PlatformIsolate runOnPlatformThread, send and receive messages', () async { // Send numbers 1 to 10 to the platform isolate. The platform isolate // multiplies them by 100 and sends them back. int sum = 0; final RawReceivePort recvPort = RawReceivePort((Object message) { if (message is SendPort) { for (int i = 1; i <= 10; ++i) { message.send(i); } } else { sum += message as int; } }); final SendPort sendPort = recvPort.sendPort; await runOnPlatformThread(() async { final Completer<void> completer = Completer<void>(); final RawReceivePort recvPort = RawReceivePort((Object message) { sendPort.send((message as int) * 100); if (message == 10) { completer.complete(); } }); sendPort.send(recvPort.sendPort); await completer.future; recvPort.close(); }); expect(sum, 5500); // sum(1 to 10) * 100 recvPort.close(); }); test('PlatformIsolate runOnPlatformThread, throws', () async { bool throws = false; try { await runOnPlatformThread(() => throw 'Oh no!'); } catch (error) { expect(error, 'Oh no!'); throws = true; } expect(throws, true); }); test('PlatformIsolate runOnPlatformThread, async throws', () async { bool throws = false; try { await runOnPlatformThread(() async { await Future<void>.delayed(const Duration(milliseconds: 100)); await Future<void>.delayed(const Duration(milliseconds: 100)); await Future<void>.delayed(const Duration(milliseconds: 100)); throw 'Oh no!'; }); } catch (error) { expect(error, 'Oh no!'); throws = true; } expect(throws, true); }); test('PlatformIsolate runOnPlatformThread, disabled on helper isolates', () async { await Isolate.run(() { expect(() => runOnPlatformThread(() => print('Unreachable')), throws); }); }); test('PlatformIsolate runOnPlatformThread, on platform isolate', () async { final int result = await runOnPlatformThread(() => runOnPlatformThread( () => runOnPlatformThread(() => runOnPlatformThread(() => 123)))); expect(result, 123); }); test('PlatformIsolate runOnPlatformThread, exit disabled', () async { await runOnPlatformThread(() => expect(() => Isolate.exit(), throws)); }); test('PlatformIsolate runOnPlatformThread, unsendable object', () async { bool throws = false; try { await runOnPlatformThread(() => ReceivePort()); } catch (error) { throws = true; } expect(throws, true); }); test('PlatformIsolate runOnPlatformThread, unsendable object async', () async { bool throws = false; try { await runOnPlatformThread(() async { await Future<void>.delayed(const Duration(milliseconds: 100)); return ReceivePort(); }); } catch (error) { throws = true; } expect(throws, true); }); test('PlatformIsolate runOnPlatformThread, throws unsendable', () async { bool throws = false; try { await runOnPlatformThread(() => throw ReceivePort()); } catch (error) { throws = true; } expect(throws, true); }); test('PlatformIsolate runOnPlatformThread, throws unsendable async', () async { bool throws = false; try { await runOnPlatformThread(() async { await Future<void>.delayed(const Duration(milliseconds: 100)); throw ReceivePort(); }); } catch (error) { throws = true; } expect(throws, true); }); }
engine/testing/dart/platform_isolate_test.dart/0
{ "file_path": "engine/testing/dart/platform_isolate_test.dart", "repo_id": "engine", "token_count": 2144 }
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_TESTING_DART_ISOLATE_RUNNER_H_ #define FLUTTER_TESTING_DART_ISOLATE_RUNNER_H_ #include "flutter/common/task_runners.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/paths.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/fml/thread.h" #include "flutter/runtime/dart_isolate.h" #include "flutter/runtime/dart_vm.h" #include "flutter/runtime/dart_vm_lifecycle.h" namespace flutter { namespace testing { class AutoIsolateShutdown { public: AutoIsolateShutdown() = default; AutoIsolateShutdown(std::shared_ptr<DartIsolate> isolate, fml::RefPtr<fml::TaskRunner> runner); ~AutoIsolateShutdown(); bool IsValid() const { return isolate_ != nullptr && runner_; } [[nodiscard]] bool RunInIsolateScope( const std::function<bool(void)>& closure); void Shutdown(); DartIsolate* get() { FML_CHECK(isolate_); return isolate_.get(); } private: std::shared_ptr<DartIsolate> isolate_; fml::RefPtr<fml::TaskRunner> runner_; FML_DISALLOW_COPY_AND_ASSIGN(AutoIsolateShutdown); }; void RunDartCodeInIsolate( DartVMRef& vm_ref, std::unique_ptr<AutoIsolateShutdown>& result, const Settings& settings, const TaskRunners& task_runners, std::string entrypoint, const std::vector<std::string>& args, const std::string& fixtures_path, fml::WeakPtr<IOManager> io_manager = {}, std::shared_ptr<VolatilePathTracker> volatile_path_tracker = nullptr, std::unique_ptr<PlatformConfiguration> platform_configuration = nullptr); std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolate( DartVMRef& vm_ref, const Settings& settings, const TaskRunners& task_runners, std::string entrypoint, const std::vector<std::string>& args, const std::string& fixtures_path, fml::WeakPtr<IOManager> io_manager = {}, std::shared_ptr<VolatilePathTracker> volatile_path_tracker = nullptr, std::unique_ptr<PlatformConfiguration> platform_configuration = nullptr); } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_DART_ISOLATE_RUNNER_H_
engine/testing/dart_isolate_runner.h/0
{ "file_path": "engine/testing/dart_isolate_runner.h", "repo_id": "engine", "token_count": 847 }
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 "flutter/testing/logger_listener.h" namespace flutter::testing { LoggerListener::LoggerListener() = default; LoggerListener::~LoggerListener() = default; void testing::LoggerListener::OnTestStart( const ::testing::TestInfo& test_info) { FML_LOG(IMPORTANT) << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"; FML_LOG(IMPORTANT) << "Starting Test: " << test_info.test_suite_name() << ":" << test_info.name(); } std::string TestStatusAsString(const ::testing::TestResult* result) { if (result == nullptr) { return "UNKNOWN"; } if (result->Passed()) { return "PASSED"; } if (result->Skipped()) { return "SKIPPED"; } if (result->Failed()) { return "FAILED"; } return "UNKNOWN"; } std::string TestLabel(const ::testing::TestInfo& info) { return std::string{info.test_suite_name()} + "." + info.name(); } std::string TestTimeAsString(const ::testing::TestResult* result) { if (result == nullptr) { return "UNKNOWN"; } return std::to_string(result->elapsed_time()) + " ms"; } void testing::LoggerListener::OnTestEnd(const ::testing::TestInfo& info) { FML_LOG(IMPORTANT) << "Test " << TestStatusAsString(info.result()) << " (" << TestTimeAsString(info.result()) << "): " << TestLabel(info); FML_LOG(IMPORTANT) << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"; } void testing::LoggerListener::OnTestDisabled(const ::testing::TestInfo& info) { FML_LOG(IMPORTANT) << "Test Disabled: " << TestLabel(info); } } // namespace flutter::testing
engine/testing/logger_listener.cc/0
{ "file_path": "engine/testing/logger_listener.cc", "repo_id": "engine", "token_count": 639 }
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. package dev.flutter.scenarios; import static io.flutter.Build.API_LEVELS; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.SurfaceTexture; import android.view.Choreographer; import android.view.TextureView; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.Log; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StringCodec; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugin.platform.PlatformViewFactory; import java.nio.ByteBuffer; @TargetApi(API_LEVELS.API_23) public final class TexturePlatformViewFactory extends PlatformViewFactory { TexturePlatformViewFactory() { super( new MessageCodec<Object>() { @Nullable @Override public ByteBuffer encodeMessage(@Nullable Object o) { if (o instanceof String) { return StringCodec.INSTANCE.encodeMessage((String) o); } return null; } @Nullable @Override public Object decodeMessage(@Nullable ByteBuffer byteBuffer) { return StringCodec.INSTANCE.decodeMessage(byteBuffer); } }); } @SuppressWarnings("unchecked") @Override @NonNull public PlatformView create(@NonNull Context context, int id, @Nullable Object args) { return new TexturePlatformView(context); } private static class TexturePlatformView implements PlatformView { static String TAG = "TexturePlatformView"; final TextureView textureView; @SuppressWarnings("unchecked") TexturePlatformView(@NonNull final Context context) { textureView = new TextureView(context); textureView.setSurfaceTextureListener( new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Log.i(TAG, "onSurfaceTextureAvailable"); final Canvas canvas = textureView.lockCanvas(); canvas.drawColor(Color.WHITE); final Paint paint = new Paint(); paint.setColor(Color.GREEN); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, 20, paint); textureView.unlockCanvasAndPost(canvas); Choreographer.getInstance() .postFrameCallbackDelayed( new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { textureView.invalidate(); } }, 500); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { Log.i(TAG, "onSurfaceTextureDestroyed"); return true; } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { Log.i(TAG, "onSurfaceTextureSizeChanged"); } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { Log.i(TAG, "onSurfaceTextureUpdated"); } }); } @Override @NonNull public View getView() { return textureView; } @Override public void dispose() {} } }
engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TexturePlatformViewFactory.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TexturePlatformViewFactory.java", "repo_id": "engine", "token_count": 1561 }
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. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:process/process.dart'; (Future<int> exitCode, Stream<String> output) getProcessStreams( Process process, ) { final Completer<void> stdoutCompleter = Completer<void>(); final Completer<void> stderrCompleter = Completer<void>(); final StreamController<String> outputController = StreamController<String>(); final StreamSubscription<void> stdoutSub = process.stdout .transform(utf8.decoder) .transform<String>(const LineSplitter()) .listen(outputController.add, onDone: stdoutCompleter.complete); // From looking at historic logs, it seems that the stderr output is rare. // Instead of prefacing every line with [stdout] unnecessarily, we'll just // use [stderr] to indicate that it's from the stderr stream. // // For example, a historic log which has 0 occurrences of stderr: // https://gist.github.com/matanlurey/84cf9c903ef6d507dcb63d4c303ca45f final StreamSubscription<void> stderrSub = process.stderr .transform(utf8.decoder) .transform<String>(const LineSplitter()) .map((String line) => '[stderr] $line') .listen(outputController.add, onDone: stderrCompleter.complete); final Future<int> exitCode = process.exitCode.then<int>((int code) async { await (stdoutSub.cancel(), stderrSub.cancel()).wait; outputController.close(); return code; }); return (exitCode, outputController.stream); } /// Pipes the [process] streams and writes them to [out] sink. /// /// If [out] is null, then the current [Process.stdout] is used as the sink. Future<int> pipeProcessStreams( Process process, { StringSink? out, }) async { out ??= stdout; final (Future<int> exitCode, Stream<String> output) = getProcessStreams(process); output.listen(out.writeln); return exitCode; } extension RunAndForward on ProcessManager { /// Runs [cmd], and forwards the stdout and stderr pipes to the current process stdout pipe. Future<int> runAndForward(List<String> cmd) async { return pipeProcessStreams(await start(cmd), out: stdout); } /// Runs [cmd], and captures the stdout and stderr pipes. Future<(int, StringBuffer)> runAndCapture(List<String> cmd) async { final StringBuffer buffer = StringBuffer(); final int exitCode = await pipeProcessStreams(await start(cmd), out: buffer); return (exitCode, buffer); } }
engine/testing/scenario_app/bin/utils/process_manager_extension.dart/0
{ "file_path": "engine/testing/scenario_app/bin/utils/process_manager_extension.dart", "repo_id": "engine", "token_count": 829 }
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. #ifndef FLUTTER_TESTING_SCENARIO_APP_IOS_FLUTTERAPPEXTENSIONTESTHOST_FLUTTERAPPEXTENSIONTESTHOST_SCENEDELEGATE_H_ #define FLUTTER_TESTING_SCENARIO_APP_IOS_FLUTTERAPPEXTENSIONTESTHOST_FLUTTERAPPEXTENSIONTESTHOST_SCENEDELEGATE_H_ #import <UIKit/UIKit.h> @interface SceneDelegate : UIResponder <UIWindowSceneDelegate> @property(strong, nonatomic) UIWindow* window; @end #endif // FLUTTER_TESTING_SCENARIO_APP_IOS_FLUTTERAPPEXTENSIONTESTHOST_FLUTTERAPPEXTENSIONTESTHOST_SCENEDELEGATE_H_
engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/SceneDelegate.h/0
{ "file_path": "engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/SceneDelegate.h", "repo_id": "engine", "token_count": 263 }
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. #ifndef FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_GOLDENPLATFORMVIEWTESTS_H_ #define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_GOLDENPLATFORMVIEWTESTS_H_ #import <XCTest/XCTest.h> #import "GoldenTestManager.h" NS_ASSUME_NONNULL_BEGIN // The base class of all the PlatformView golden tests. // // A new PlatformView golden tests can subclass this and override the `-initiWithInvocation:` // method, which then retun the `-initWithManager:invocation:` // // Then in any test method, call `checkPlatformViewGolden` to perform the golden test. // // This base class doesn't run any test case on its own. @interface GoldenPlatformViewTests : XCTestCase @property(nonatomic, strong) XCUIApplication* application; @property(nonatomic, assign) double rmseThreadhold; // Initialize with a `GoldenTestManager`. - (instancetype)initWithManager:(GoldenTestManager*)manager invocation:(NSInvocation*)invocation; // Take a sceenshot of the test app and check it has the same pixels with goldenImage inside the // `GoldenTestManager`. - (void)checkPlatformViewGolden; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_GOLDENPLATFORMVIEWTESTS_H_
engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenPlatformViewTests.h/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenPlatformViewTests.h", "repo_id": "engine", "token_count": 469 }
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. import 'dart:ui'; import 'channel_util.dart'; import 'scenario.dart'; /// Tries to draw darwin system font: CupertinoSystemDisplay, CupertinoSystemText class DarwinSystemFont extends Scenario { /// Creates the DarwinSystemFont scenario. DarwinSystemFont(super.view); // Semi-arbitrary. final double _screenWidth = 700; @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); final ParagraphBuilder paragraphBuilderDisplay = ParagraphBuilder(ParagraphStyle(fontFamily: 'CupertinoSystemDisplay')) ..pushStyle(TextStyle(fontSize: 50)) ..addText('Cupertino System Display\n') ..pop(); final ParagraphBuilder paragraphBuilderText = ParagraphBuilder(ParagraphStyle(fontFamily: 'CupertinoSystemText')) ..pushStyle(TextStyle(fontSize: 50)) ..addText('Cupertino System Text\n') ..pop(); final Paragraph paragraphPro = paragraphBuilderDisplay.build(); paragraphPro.layout(ParagraphConstraints(width: _screenWidth)); canvas.drawParagraph(paragraphPro, const Offset(50, 80)); final Paragraph paragraphText = paragraphBuilderText.build(); paragraphText.layout(ParagraphConstraints(width: _screenWidth)); canvas.drawParagraph(paragraphText, const Offset(50, 200)); final Picture picture = recorder.endRecording(); builder.addPicture( Offset.zero, picture, willChangeHint: true, ); final Scene scene = builder.build(); view.render(scene); scene.dispose(); sendJsonMessage( dispatcher: view.platformDispatcher, channel: 'display_data', json: <String, dynamic>{ 'data': 'ready', }, ); } }
engine/testing/scenario_app/lib/src/darwin_system_font.dart/0
{ "file_path": "engine/testing/scenario_app/lib/src/darwin_system_font.dart", "repo_id": "engine", "token_count": 681 }
394
# skia_gold_client This package allows to create a Skia gold client in the engine repo. The client uses the `goldctl` tool on LUCI builders to upload screenshots, and verify if a new screenshot matches the baseline screenshot. The web UI is available on https://flutter-engine-gold.skia.org/. ## Using the client 1. In `.ci.yaml`, ensure that the task has a dependency on `goldctl`: ```yaml dependencies: [{ "dependency": "goldctl" }] ``` 2. In the builder `.json` file, ensure the drone has a dependency on `goldctl`: ```yaml "dependencies": [ { "dependency": "goldctl", "version": "git_revision:<sha>" } ], ``` 3. Add dependency in `pubspec.yaml`: ```yaml dependencies: # needed for skia_gold_client to avoid a cache miss. engine_repo_tools: path: <relative-path>/tools/pkg/engine_repo_tools skia_gold_client: path: <relative-path>/testing/skia_gold_client ``` 4. Use the client: ```dart import 'package:skia_gold_client/skia_gold_client.dart'; Future<void> main() { final Directory tmpDirectory = Directory.current.createTempSync('skia_gold_wd'); final SkiaGoldClient client = SkiaGoldClient( tmpDirectory, dimensions: <String, String> {'<attribute-name>': '<attribute-value>'}, ); try { if (SkiaGoldClient.isAvailable()) { await client.auth(); await client.addImg( '<file-name>', File('gold-file.png'), screenshotSize: 1024, ); } } catch (error) { // Failed to authenticate or compare pixels. stderr.write(error.toString()); rethrow; } finally { tmpDirectory.deleteSync(recursive: true); } } ```
engine/testing/skia_gold_client/README.md/0
{ "file_path": "engine/testing/skia_gold_client/README.md", "repo_id": "engine", "token_count": 774 }
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. #include "flutter/testing/stream_capture.h" namespace flutter { namespace testing { StreamCapture::StreamCapture(std::ostream* ostream) : ostream_(ostream), old_buffer_(ostream_->rdbuf()) { ostream_->rdbuf(buffer_.rdbuf()); } StreamCapture::~StreamCapture() { Stop(); } void StreamCapture::Stop() { if (old_buffer_) { ostream_->rdbuf(old_buffer_); old_buffer_ = nullptr; } } std::string StreamCapture::GetOutput() const { return buffer_.str(); } } // namespace testing } // namespace flutter
engine/testing/stream_capture.cc/0
{ "file_path": "engine/testing/stream_capture.cc", "repo_id": "engine", "token_count": 229 }
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. #include "flutter/testing/test_metal_context.h" #include "flutter/testing/test_metal_surface.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { #ifdef SHELL_ENABLE_METAL TEST(TestMetalSurface, EmptySurfaceIsInvalid) { if (!TestMetalSurface::PlatformSupportsMetal()) { GTEST_SKIP(); } TestMetalContext metal_context = TestMetalContext(); auto surface = TestMetalSurface::Create(metal_context); ASSERT_NE(surface, nullptr); ASSERT_FALSE(surface->IsValid()); } TEST(TestMetalSurface, CanCreateValidTestMetalSurface) { if (!TestMetalSurface::PlatformSupportsMetal()) { GTEST_SKIP(); } TestMetalContext metal_context = TestMetalContext(); auto surface = TestMetalSurface::Create(metal_context, SkISize::Make(100, 100)); ASSERT_NE(surface, nullptr); ASSERT_TRUE(surface->IsValid()); ASSERT_NE(surface->GetSurface(), nullptr); ASSERT_NE(surface->GetGrContext(), nullptr); } #endif } // namespace testing } // namespace flutter
engine/testing/test_metal_surface_unittests.cc/0
{ "file_path": "engine/testing/test_metal_surface_unittests.cc", "repo_id": "engine", "token_count": 384 }
397
# 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. """Functions to setup xvfb, which is used by the linux machines. """ import os import signal import subprocess import tempfile import time def xvfb_display_index(_child_build_name): return '9' def xvfb_pid_filename(child_build_name): """Returns the filename to the Xvfb pid file. This name is unique for each builder. This is used by the linux builders.""" return os.path.join( tempfile.gettempdir(), 'xvfb-' + xvfb_display_index(child_build_name) + '.pid' ) def start_virtual_x(child_build_name, build_dir): """Start a virtual X server and set the DISPLAY environment variable so sub processes will use the virtual X server. Also start openbox. This only works on Linux and assumes that xvfb and openbox are installed. Args: child_build_name: The name of the build that we use for the pid file. E.g., webkit-rel-linux. build_dir: The directory where binaries are produced. If this is non-empty, we try running xdisplaycheck from |build_dir| to verify our X connection. """ # We use a pid file to make sure we don't have any xvfb processes running # from a previous test run. stop_virtual_x(child_build_name) xdisplaycheck_path = None if build_dir: xdisplaycheck_path = os.path.join(build_dir, 'xdisplaycheck') display = ':%s' % xvfb_display_index(child_build_name) # Note we don't add the optional screen here (+ '.0') os.environ['DISPLAY'] = display # Parts of Xvfb use a hard-coded "/tmp" for its temporary directory. # This can cause a failure when those parts expect to hardlink against # files that were created in "TEMPDIR" / "TMPDIR". # # See: https://crbug.com/715848 env = os.environ.copy() if env.get('TMPDIR') and env['TMPDIR'] != '/tmp': print('Overriding TMPDIR to "/tmp" for Xvfb, was: %s' % (env['TMPDIR'],)) env['TMPDIR'] = '/tmp' if xdisplaycheck_path and os.path.exists(xdisplaycheck_path): print('Verifying Xvfb is not running ...') checkstarttime = time.time() xdisplayproc = subprocess.Popen([xdisplaycheck_path, '--noserver'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) # Wait for xdisplaycheck to exit. logs = xdisplayproc.communicate()[0] if xdisplayproc.returncode == 0: print('xdisplaycheck says there is a display still running, exiting...') raise Exception('Display already present.') xvfb_lock_filename = '/tmp/.X%s-lock' % xvfb_display_index(child_build_name) if os.path.exists(xvfb_lock_filename): print('Removing stale xvfb lock file %r' % xvfb_lock_filename) try: os.unlink(xvfb_lock_filename) except OSError as err: print('Removing xvfb lock file failed: %s' % err) # Figure out which X server to try. cmd = 'Xvfb' # Start a virtual X server that we run the tests in. This makes it so we can # run the tests even if we didn't start the tests from an X session. proc = subprocess.Popen([ cmd, display, '-screen', '0', '1280x800x24', '-ac', '-dpi', '96', '-maxclients', '512', '-extension', 'MIT-SHM' ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) pid_filename = xvfb_pid_filename(child_build_name) open(pid_filename, 'w').write(str(proc.pid)) # Wait for Xvfb to start up. time.sleep(10) # Verify that Xvfb has started by using xdisplaycheck. if xdisplaycheck_path and os.path.exists(xdisplaycheck_path): print('Verifying Xvfb has started...') checkstarttime = time.time() xdisplayproc = subprocess.Popen([xdisplaycheck_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # Wait for xdisplaycheck to exit. logs = xdisplayproc.communicate()[0] checktime = time.time() - checkstarttime if xdisplayproc.returncode != 0: print('xdisplaycheck failed after %d seconds.' % checktime) print('xdisplaycheck output:') for line in logs.splitlines(): print('> %s' % line) return_code = proc.poll() if return_code is None: print('Xvfb still running, stopping.') proc.terminate() else: print('Xvfb exited, code %d' % return_code) print('Xvfb output:') for line in proc.communicate()[0].splitlines(): print('> %s' % line) raise Exception(logs) print('xdisplaycheck succeeded after %d seconds.' % checktime) print('xdisplaycheck output:') for line in logs.splitlines(): print('> %s' % line) print('...OK') # Some ChromeOS tests need a window manager. subprocess.Popen('openbox', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print('Window manager (openbox) started.') def stop_virtual_x(child_build_name): """Try and stop the virtual X server if one was started with StartVirtualX. When the X server dies, it takes down the window manager with it. If a virtual x server is not running, this method does nothing.""" pid_filename = xvfb_pid_filename(child_build_name) if os.path.exists(pid_filename): xvfb_pid = int(open(pid_filename).read()) print('Stopping Xvfb with pid %d ...' % xvfb_pid) # If the process doesn't exist, we raise an exception that we can ignore. try: os.kill(xvfb_pid, signal.SIGKILL) except OSError: print('... killing failed, presuming unnecessary.') os.remove(pid_filename) print('Xvfb pid file removed')
engine/testing/xvfb.py/0
{ "file_path": "engine/testing/xvfb.py", "repo_id": "engine", "token_count": 2239 }
398
// 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. #ifndef UI_ACCESSIBILITY_AX_BASE_EXPORT_H_ #define UI_ACCESSIBILITY_AX_BASE_EXPORT_H_ // Defines AX_BASE_EXPORT so that functionality implemented by the // ui/accessibility:ax_base module can be exported to consumers. #if defined(COMPONENT_BUILD) #if defined(WIN32) #if defined(AX_BASE_IMPLEMENTATION) #define AX_BASE_EXPORT __declspec(dllexport) #else #define AX_BASE_EXPORT __declspec(dllimport) #endif // defined(AX_BASE_IMPLEMENTATION) #else // defined(WIN32) #if defined(AX_BASE_IMPLEMENTATION) #define AX_BASE_EXPORT __attribute__((visibility("default"))) #else #define AX_BASE_EXPORT #endif #endif #else // defined(COMPONENT_BUILD) #define AX_BASE_EXPORT #endif #endif // UI_ACCESSIBILITY_AX_BASE_EXPORT_H_
engine/third_party/accessibility/ax/ax_base_export.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_base_export.h", "repo_id": "engine", "token_count": 330 }
399
// 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 UI_ACCESSIBILITY_AX_MODE_OBSERVER_H_ #define UI_ACCESSIBILITY_AX_MODE_OBSERVER_H_ #include "ax_export.h" #include "ax_mode.h" namespace ui { class AX_EXPORT AXModeObserver { public: virtual ~AXModeObserver() {} // Notifies when accessibility mode changes. virtual void OnAXModeAdded(ui::AXMode mode) = 0; }; } // namespace ui #endif // UI_ACCESSIBILITY_AX_MODE_OBSERVER_H_
engine/third_party/accessibility/ax/ax_mode_observer.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_mode_observer.h", "repo_id": "engine", "token_count": 201 }
400
// 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. #ifndef UI_ACCESSIBILITY_AX_RELATIVE_BOUNDS_H_ #define UI_ACCESSIBILITY_AX_RELATIVE_BOUNDS_H_ #include <cstdint> #include <memory> #include <ostream> #include "ax_base_export.h" #include "ax_enums.h" #include "gfx/geometry/rect_f.h" #include "gfx/transform.h" namespace ui { // The relative bounding box of an AXNode. // // This is an efficient, compact, serializable representation of a node's // bounding box that requires minimal changes to the tree when layers are // moved or scrolled. Computing the absolute bounding box of a node requires // walking up the tree and applying node offsets and transforms until reaching // the top. // // If the offset container id is valid, the bounds are relative // to the node with that offset container id. // // Otherwise, for a node other than the root, the bounds are relative to // the root of the tree, and for the root of a tree, the bounds are relative // to its immediate containing node. struct AX_BASE_EXPORT AXRelativeBounds final { AXRelativeBounds(); virtual ~AXRelativeBounds(); AXRelativeBounds(const AXRelativeBounds& other); AXRelativeBounds& operator=(AXRelativeBounds other); bool operator!=(const AXRelativeBounds& other) const; bool operator==(const AXRelativeBounds& other) const; std::string ToString() const; // The id of an ancestor node in the same AXTree that this object's // bounding box is relative to, or -1 if there's no offset container. int32_t offset_container_id; // The relative bounding box of this node. gfx::RectF bounds; // An additional transform to apply to position this object and its subtree. // NOTE: this member is a std::unique_ptr because it's rare and gfx::Transform // takes up a fair amount of space. The assignment operator and copy // constructor both make a duplicate of the owned pointer, so it acts more // like a member than a pointer. std::unique_ptr<gfx::Transform> transform; }; AX_BASE_EXPORT std::ostream& operator<<(std::ostream& stream, const AXRelativeBounds& bounds); } // namespace ui #endif // UI_ACCESSIBILITY_AX_RELATIVE_BOUNDS_H_
engine/third_party/accessibility/ax/ax_relative_bounds.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_relative_bounds.h", "repo_id": "engine", "token_count": 711 }
401
// 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_tree_manager_map.h" #include "ax_enums.h" #include "base/container_utils.h" #include "base/logging.h" namespace ui { AXTreeManagerMap::AXTreeManagerMap() {} AXTreeManagerMap::~AXTreeManagerMap() {} AXTreeManagerMap& AXTreeManagerMap::GetInstance() { static base::NoDestructor<AXTreeManagerMap> instance; return *instance; } void AXTreeManagerMap::AddTreeManager(AXTreeID tree_id, AXTreeManager* manager) { if (tree_id != AXTreeIDUnknown()) map_[tree_id] = manager; } void AXTreeManagerMap::RemoveTreeManager(AXTreeID tree_id) { if (tree_id != AXTreeIDUnknown()) map_.erase(tree_id); } AXTreeManager* AXTreeManagerMap::GetManager(AXTreeID tree_id) { if (tree_id == AXTreeIDUnknown() || !base::Contains(map_, tree_id)) return nullptr; return map_.at(tree_id); } AXTreeManager* AXTreeManagerMap::GetManagerForChildTree( const AXNode& parent_node) { if (!parent_node.data().HasStringAttribute( ax::mojom::StringAttribute::kChildTreeId)) { return nullptr; } AXTreeID child_tree_id = AXTreeID::FromString(parent_node.data().GetStringAttribute( ax::mojom::StringAttribute::kChildTreeId)); AXTreeManager* child_tree_manager = AXTreeManagerMap::GetInstance().GetManager(child_tree_id); // Some platforms do not use AXTreeManagers, so child trees don't exist in // the browser process. if (!child_tree_manager) return nullptr; BASE_DCHECK(child_tree_manager->GetParentNodeFromParentTreeAsAXNode()->id() == parent_node.id()); return child_tree_manager; } } // namespace ui
engine/third_party/accessibility/ax/ax_tree_manager_map.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_tree_manager_map.cc", "repo_id": "engine", "token_count": 686 }
402
// 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. #include "ax_platform_node_delegate_base.h" #include <vector> #include "ax/ax_action_data.h" #include "ax/ax_constants.h" #include "ax/ax_node_data.h" #include "ax/ax_role_properties.h" #include "ax/ax_tree_data.h" #include "base/no_destructor.h" #include "ax_platform_node.h" #include "ax_platform_node_base.h" namespace ui { AXPlatformNodeDelegateBase::AXPlatformNodeDelegateBase() = default; AXPlatformNodeDelegateBase::~AXPlatformNodeDelegateBase() = default; const AXNodeData& AXPlatformNodeDelegateBase::GetData() const { static base::NoDestructor<AXNodeData> empty_data; return *empty_data; } const AXTreeData& AXPlatformNodeDelegateBase::GetTreeData() const { static base::NoDestructor<AXTreeData> empty_data; return *empty_data; } std::u16string AXPlatformNodeDelegateBase::GetInnerText() const { // Unlike in web content The "kValue" attribute always takes precedence, // because we assume that users of this base class, such as Views controls, // are carefully crafted by hand, in contrast to HTML pages, where any content // that might be present in the shadow DOM (AKA in the internal accessibility // tree) is actually used by the renderer when assigning the "kValue" // attribute, including any redundant white space. std::u16string value = GetData().GetString16Attribute(ax::mojom::StringAttribute::kValue); if (!value.empty()) return value; // TODO(https://crbug.com/1030703): The check for IsInvisibleOrIgnored() // should not be needed. ChildAtIndex() and GetChildCount() are already // supposed to skip over nodes that are invisible or ignored, but // ViewAXPlatformNodeDelegate does not currently implement this behavior. if (IsLeaf() && !GetData().IsInvisibleOrIgnored()) return GetData().GetString16Attribute(ax::mojom::StringAttribute::kName); std::u16string inner_text; for (int i = 0; i < GetChildCount(); ++i) { // TODO(nektar): Add const to all tree traversal methods and remove // const_cast. const AXPlatformNode* child = AXPlatformNode::FromNativeViewAccessible( const_cast<AXPlatformNodeDelegateBase*>(this)->ChildAtIndex(i)); if (!child || !child->GetDelegate()) continue; inner_text += child->GetDelegate()->GetInnerText(); } return inner_text; } const AXTree::Selection AXPlatformNodeDelegateBase::GetUnignoredSelection() const { return AXTree::Selection{false, -1, -1, ax::mojom::TextAffinity::kDownstream}; } AXNodePosition::AXPositionInstance AXPlatformNodeDelegateBase::CreateTextPositionAt(int offset) const { return AXNodePosition::CreateNullPosition(); } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetNSWindow() { return nullptr; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetNativeViewAccessible() { return nullptr; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetParent() { return nullptr; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetLowestPlatformAncestor() const { AXPlatformNodeDelegateBase* current_delegate = const_cast<AXPlatformNodeDelegateBase*>(this); AXPlatformNodeDelegateBase* lowest_unignored_delegate = current_delegate; // `highest_leaf_delegate` could be nullptr. AXPlatformNodeDelegateBase* highest_leaf_delegate = lowest_unignored_delegate; // For the purposes of this method, a leaf node does not include leaves in the // internal accessibility tree, only in the platform exposed tree. for (AXPlatformNodeDelegateBase* ancestor_delegate = lowest_unignored_delegate; ancestor_delegate; ancestor_delegate = static_cast<AXPlatformNodeDelegateBase*>( ancestor_delegate->GetParentDelegate())) { if (ancestor_delegate->IsLeaf()) highest_leaf_delegate = ancestor_delegate; } if (highest_leaf_delegate) return highest_leaf_delegate->GetNativeViewAccessible(); if (lowest_unignored_delegate) return lowest_unignored_delegate->GetNativeViewAccessible(); return current_delegate->GetNativeViewAccessible(); } int AXPlatformNodeDelegateBase::GetChildCount() const { return 0; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::ChildAtIndex(int index) { return nullptr; } bool AXPlatformNodeDelegateBase::HasModalDialog() const { return false; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetFirstChild() { if (GetChildCount() > 0) return ChildAtIndex(0); return nullptr; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetLastChild() { if (GetChildCount() > 0) return ChildAtIndex(GetChildCount() - 1); return nullptr; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetNextSibling() { AXPlatformNodeDelegate* parent = GetParentDelegate(); if (parent && GetIndexInParent() >= 0) { int next_index = GetIndexInParent() + 1; if (next_index >= 0 && next_index < parent->GetChildCount()) return parent->ChildAtIndex(next_index); } return nullptr; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetPreviousSibling() { AXPlatformNodeDelegate* parent = GetParentDelegate(); if (parent && GetIndexInParent() >= 0) { int next_index = GetIndexInParent() - 1; if (next_index >= 0 && next_index < parent->GetChildCount()) return parent->ChildAtIndex(next_index); } return nullptr; } bool AXPlatformNodeDelegateBase::IsChildOfLeaf() const { // TODO(nektar): Make all tree traversal methods const and remove const_cast. const AXPlatformNodeDelegate* parent = const_cast<AXPlatformNodeDelegateBase*>(this)->GetParentDelegate(); if (!parent) return false; if (parent->IsLeaf()) return true; return parent->IsChildOfLeaf(); } bool AXPlatformNodeDelegateBase::IsLeaf() const { return !GetChildCount(); } bool AXPlatformNodeDelegateBase::IsToplevelBrowserWindow() { return false; } bool AXPlatformNodeDelegateBase::IsChildOfPlainTextField() const { return false; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetClosestPlatformObject() const { return nullptr; } AXPlatformNodeDelegateBase::ChildIteratorBase::ChildIteratorBase( AXPlatformNodeDelegateBase* parent, int index) : index_(index), parent_(parent) { BASE_DCHECK(parent); BASE_DCHECK(0 <= index && index <= parent->GetChildCount()); } AXPlatformNodeDelegateBase::ChildIteratorBase::ChildIteratorBase( const AXPlatformNodeDelegateBase::ChildIteratorBase& it) : index_(it.index_), parent_(it.parent_) { BASE_DCHECK(parent_); } bool AXPlatformNodeDelegateBase::ChildIteratorBase::operator==( const AXPlatformNodeDelegate::ChildIterator& rhs) const { return rhs.GetIndexInParent() == index_; } bool AXPlatformNodeDelegateBase::ChildIteratorBase::operator!=( const AXPlatformNodeDelegate::ChildIterator& rhs) const { return rhs.GetIndexInParent() != index_; } void AXPlatformNodeDelegateBase::ChildIteratorBase::operator++() { index_++; } void AXPlatformNodeDelegateBase::ChildIteratorBase::operator++(int) { index_++; } void AXPlatformNodeDelegateBase::ChildIteratorBase::operator--() { BASE_DCHECK(index_ > 0); index_--; } void AXPlatformNodeDelegateBase::ChildIteratorBase::operator--(int) { BASE_DCHECK(index_ > 0); index_--; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::ChildIteratorBase::GetNativeViewAccessible() const { if (index_ < parent_->GetChildCount()) return parent_->ChildAtIndex(index_); return nullptr; } int AXPlatformNodeDelegateBase::ChildIteratorBase::GetIndexInParent() const { return index_; } AXPlatformNodeDelegate& AXPlatformNodeDelegateBase::ChildIteratorBase::operator*() const { AXPlatformNode* platform_node = AXPlatformNode::FromNativeViewAccessible(GetNativeViewAccessible()); BASE_DCHECK(platform_node && platform_node->GetDelegate()); return *(platform_node->GetDelegate()); } AXPlatformNodeDelegate* AXPlatformNodeDelegateBase::ChildIteratorBase::operator->() const { AXPlatformNode* platform_node = AXPlatformNode::FromNativeViewAccessible(GetNativeViewAccessible()); return platform_node ? platform_node->GetDelegate() : nullptr; } std::unique_ptr<AXPlatformNodeDelegate::ChildIterator> AXPlatformNodeDelegateBase::ChildrenBegin() { return std::make_unique<ChildIteratorBase>(this, 0); } std::unique_ptr<AXPlatformNodeDelegate::ChildIterator> AXPlatformNodeDelegateBase::ChildrenEnd() { return std::make_unique<ChildIteratorBase>(this, GetChildCount()); } std::string AXPlatformNodeDelegateBase::GetName() const { return GetData().GetStringAttribute(ax::mojom::StringAttribute::kName); } std::u16string AXPlatformNodeDelegateBase::GetHypertext() const { return std::u16string(); } bool AXPlatformNodeDelegateBase::SetHypertextSelection(int start_offset, int end_offset) { AXActionData action_data; action_data.action = ax::mojom::Action::kSetSelection; action_data.anchor_node_id = action_data.focus_node_id = GetData().id; action_data.anchor_offset = start_offset; action_data.focus_offset = end_offset; return AccessibilityPerformAction(action_data); } gfx::Rect AXPlatformNodeDelegateBase::GetBoundsRect( const AXCoordinateSystem coordinate_system, const AXClippingBehavior clipping_behavior, AXOffscreenResult* offscreen_result) const { return gfx::Rect(); } gfx::Rect AXPlatformNodeDelegateBase::GetHypertextRangeBoundsRect( const int start_offset, const int end_offset, const AXCoordinateSystem coordinate_system, const AXClippingBehavior clipping_behavior, AXOffscreenResult* offscreen_result) const { return gfx::Rect(); } gfx::Rect AXPlatformNodeDelegateBase::GetInnerTextRangeBoundsRect( const int start_offset, const int end_offset, const AXCoordinateSystem coordinate_system, const AXClippingBehavior clipping_behavior, AXOffscreenResult* offscreen_result = nullptr) const { return gfx::Rect(); } gfx::Rect AXPlatformNodeDelegateBase::GetClippedScreenBoundsRect( AXOffscreenResult* offscreen_result) const { return GetBoundsRect(AXCoordinateSystem::kScreenDIPs, AXClippingBehavior::kClipped, offscreen_result); } gfx::Rect AXPlatformNodeDelegateBase::GetUnclippedScreenBoundsRect( AXOffscreenResult* offscreen_result) const { return GetBoundsRect(AXCoordinateSystem::kScreenDIPs, AXClippingBehavior::kUnclipped, offscreen_result); } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::HitTestSync( int screen_physical_pixel_x, int screen_physical_pixel_y) const { return nullptr; } gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetFocus() { return nullptr; } AXPlatformNode* AXPlatformNodeDelegateBase::GetFromNodeID(int32_t id) { return nullptr; } AXPlatformNode* AXPlatformNodeDelegateBase::GetFromTreeIDAndNodeID( const ui::AXTreeID& ax_tree_id, int32_t id) { return nullptr; } int AXPlatformNodeDelegateBase::GetIndexInParent() { AXPlatformNodeDelegate* parent = GetParentDelegate(); if (!parent) return -1; for (int i = 0; i < parent->GetChildCount(); i++) { AXPlatformNode* child_node = AXPlatformNode::FromNativeViewAccessible(parent->ChildAtIndex(i)); if (child_node && child_node->GetDelegate() == this) return i; } return -1; } gfx::AcceleratedWidget AXPlatformNodeDelegateBase::GetTargetForNativeAccessibilityEvent() { return gfx::kNullAcceleratedWidget; } bool AXPlatformNodeDelegateBase::IsTable() const { return ui::IsTableLike(GetData().role); } std::optional<int> AXPlatformNodeDelegateBase::GetTableRowCount() const { return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableRowCount); } std::optional<int> AXPlatformNodeDelegateBase::GetTableColCount() const { return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableColumnCount); } std::optional<int> AXPlatformNodeDelegateBase::GetTableAriaColCount() const { int aria_column_count; if (!GetData().GetIntAttribute(ax::mojom::IntAttribute::kAriaColumnCount, &aria_column_count)) { return std::nullopt; } return aria_column_count; } std::optional<int> AXPlatformNodeDelegateBase::GetTableAriaRowCount() const { int aria_row_count; if (!GetData().GetIntAttribute(ax::mojom::IntAttribute::kAriaRowCount, &aria_row_count)) { return std::nullopt; } return aria_row_count; } std::optional<int> AXPlatformNodeDelegateBase::GetTableCellCount() const { return std::nullopt; } std::optional<bool> AXPlatformNodeDelegateBase::GetTableHasColumnOrRowHeaderNode() const { return std::nullopt; } std::vector<int32_t> AXPlatformNodeDelegateBase::GetColHeaderNodeIds() const { return {}; } std::vector<int32_t> AXPlatformNodeDelegateBase::GetColHeaderNodeIds( int col_index) const { return {}; } std::vector<int32_t> AXPlatformNodeDelegateBase::GetRowHeaderNodeIds() const { return {}; } std::vector<int32_t> AXPlatformNodeDelegateBase::GetRowHeaderNodeIds( int row_index) const { return {}; } AXPlatformNode* AXPlatformNodeDelegateBase::GetTableCaption() const { return nullptr; } bool AXPlatformNodeDelegateBase::IsTableRow() const { return ui::IsTableRow(GetData().role); } std::optional<int> AXPlatformNodeDelegateBase::GetTableRowRowIndex() const { return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableRowIndex); } bool AXPlatformNodeDelegateBase::IsTableCellOrHeader() const { return ui::IsCellOrTableHeader(GetData().role); } std::optional<int> AXPlatformNodeDelegateBase::GetTableCellColIndex() const { return GetData().GetIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex); } std::optional<int> AXPlatformNodeDelegateBase::GetTableCellRowIndex() const { return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex); } std::optional<int> AXPlatformNodeDelegateBase::GetTableCellColSpan() const { return GetData().GetIntAttribute( ax::mojom::IntAttribute::kTableCellColumnSpan); } std::optional<int> AXPlatformNodeDelegateBase::GetTableCellRowSpan() const { return GetData().GetIntAttribute(ax::mojom::IntAttribute::kTableCellRowSpan); } std::optional<int> AXPlatformNodeDelegateBase::GetTableCellAriaColIndex() const { return GetData().GetIntAttribute( ax::mojom::IntAttribute::kAriaCellColumnIndex); } std::optional<int> AXPlatformNodeDelegateBase::GetTableCellAriaRowIndex() const { return GetData().GetIntAttribute(ax::mojom::IntAttribute::kAriaCellRowIndex); } std::optional<int32_t> AXPlatformNodeDelegateBase::GetCellId( int row_index, int col_index) const { return std::nullopt; } std::optional<int> AXPlatformNodeDelegateBase::GetTableCellIndex() const { return std::nullopt; } std::optional<int32_t> AXPlatformNodeDelegateBase::CellIndexToId( int cell_index) const { return std::nullopt; } bool AXPlatformNodeDelegateBase::IsCellOrHeaderOfARIATable() const { return false; } bool AXPlatformNodeDelegateBase::IsCellOrHeaderOfARIAGrid() const { return false; } bool AXPlatformNodeDelegateBase::IsOrderedSetItem() const { return false; } bool AXPlatformNodeDelegateBase::IsOrderedSet() const { return false; } std::optional<int> AXPlatformNodeDelegateBase::GetPosInSet() const { return std::nullopt; } std::optional<int> AXPlatformNodeDelegateBase::GetSetSize() const { return std::nullopt; } bool AXPlatformNodeDelegateBase::AccessibilityPerformAction( const ui::AXActionData& data) { return false; } std::u16string AXPlatformNodeDelegateBase::GetLocalizedStringForImageAnnotationStatus( ax::mojom::ImageAnnotationStatus status) const { return std::u16string(); } std::u16string AXPlatformNodeDelegateBase::GetLocalizedRoleDescriptionForUnlabeledImage() const { return std::u16string(); } std::u16string AXPlatformNodeDelegateBase::GetLocalizedStringForLandmarkType() const { return std::u16string(); } std::u16string AXPlatformNodeDelegateBase::GetLocalizedStringForRoleDescription() const { return std::u16string(); } std::u16string AXPlatformNodeDelegateBase::GetStyleNameAttributeAsLocalizedString() const { return std::u16string(); } TextAttributeMap AXPlatformNodeDelegateBase::ComputeTextAttributeMap( const TextAttributeList& default_attributes) const { ui::TextAttributeMap attributes_map; attributes_map[0] = default_attributes; return attributes_map; } std::string AXPlatformNodeDelegateBase::GetInheritedFontFamilyName() const { // We don't have access to AXNodeData here, so we cannot return // an inherited font family name. return std::string(); } bool AXPlatformNodeDelegateBase::ShouldIgnoreHoveredStateForTesting() { return true; } bool AXPlatformNodeDelegateBase::IsOffscreen() const { return false; } bool AXPlatformNodeDelegateBase::IsMinimized() const { return false; } bool AXPlatformNodeDelegateBase::IsText() const { return ui::IsText(GetData().role); } bool AXPlatformNodeDelegateBase::IsWebContent() const { return false; } bool AXPlatformNodeDelegateBase::HasVisibleCaretOrSelection() const { return false; } AXPlatformNode* AXPlatformNodeDelegateBase::GetTargetNodeForRelation( ax::mojom::IntAttribute attr) { BASE_DCHECK(IsNodeIdIntAttribute(attr)); int target_id; if (!GetData().GetIntAttribute(attr, &target_id)) return nullptr; return GetFromNodeID(target_id); } std::set<AXPlatformNode*> AXPlatformNodeDelegateBase::GetNodesForNodeIds( const std::set<int32_t>& ids) { std::set<AXPlatformNode*> nodes; for (int32_t node_id : ids) { if (AXPlatformNode* node = GetFromNodeID(node_id)) { nodes.insert(node); } } return nodes; } std::vector<AXPlatformNode*> AXPlatformNodeDelegateBase::GetTargetNodesForRelation( ax::mojom::IntListAttribute attr) { BASE_DCHECK(IsNodeIdIntListAttribute(attr)); std::vector<int32_t> target_ids; if (!GetData().GetIntListAttribute(attr, &target_ids)) return std::vector<AXPlatformNode*>(); // If we use std::set to eliminate duplicates, the resulting set will be // sorted by the id and we will lose the original order which may be of // interest to ATs. The number of ids should be small. std::vector<ui::AXPlatformNode*> nodes; for (int32_t target_id : target_ids) { if (ui::AXPlatformNode* node = GetFromNodeID(target_id)) { if (std::find(nodes.begin(), nodes.end(), node) == nodes.end()) nodes.push_back(node); } } return nodes; } std::set<AXPlatformNode*> AXPlatformNodeDelegateBase::GetReverseRelations( ax::mojom::IntAttribute attr) { // TODO(accessibility) Implement these if views ever use relations more // widely. The use so far has been for the Omnibox to the suggestion popup. // If this is ever implemented, then the "popup for" to "controlled by" // mapping in AXPlatformRelationWin can be removed, as it would be // redundant with setting the controls relationship. return std::set<AXPlatformNode*>(); } std::set<AXPlatformNode*> AXPlatformNodeDelegateBase::GetReverseRelations( ax::mojom::IntListAttribute attr) { return std::set<AXPlatformNode*>(); } std::u16string AXPlatformNodeDelegateBase::GetAuthorUniqueId() const { return std::u16string(); } const AXUniqueId& AXPlatformNodeDelegateBase::GetUniqueId() const { static base::NoDestructor<AXUniqueId> dummy_unique_id; return *dummy_unique_id; } std::optional<int> AXPlatformNodeDelegateBase::FindTextBoundary( ax::mojom::TextBoundary boundary, int offset, ax::mojom::MoveDirection direction, ax::mojom::TextAffinity affinity) const { return std::nullopt; } const std::vector<gfx::NativeViewAccessible> AXPlatformNodeDelegateBase::GetUIADescendants() const { return {}; } std::string AXPlatformNodeDelegateBase::GetLanguage() const { return std::string(); } AXPlatformNodeDelegate* AXPlatformNodeDelegateBase::GetParentDelegate() { AXPlatformNode* parent_node = ui::AXPlatformNode::FromNativeViewAccessible(GetParent()); if (parent_node) return parent_node->GetDelegate(); return nullptr; } std::string AXPlatformNodeDelegateBase::SubtreeToStringHelper(size_t level) { std::string result(level * 2, '+'); result += ToString(); result += '\n'; // We can't use ChildrenBegin() and ChildrenEnd() here, because they both // return an std::unique_ptr<ChildIterator> which is an abstract class. // // TODO(accessibility): Refactor ChildIterator into a separate base // (non-abstract) class. auto iter_start = ChildIteratorBase(this, 0); auto iter_end = ChildIteratorBase(this, GetChildCount()); for (auto iter = iter_start; iter != iter_end; ++iter) { AXPlatformNodeDelegateBase& child = static_cast<AXPlatformNodeDelegateBase&>(*iter); result += child.SubtreeToStringHelper(level + 1); } return result; } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_platform_node_delegate_base.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_delegate_base.cc", "repo_id": "engine", "token_count": 6994 }
403
// Copyright 2015 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_win.h" #include <wrl/client.h> #include <wrl/implements.h> #include <algorithm> #include <map> #include <set> #include <string> #include <unordered_set> #include <utility> #include "ax/ax_action_data.h" #include "ax/ax_active_popup.h" #include "ax/ax_enum_util.h" #include "ax/ax_mode_observer.h" #include "ax/ax_node_data.h" #include "ax/ax_node_position.h" #include "ax/ax_role_properties.h" #include "ax/ax_tree_data.h" #include "base/win/enum_variant.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_safearray.h" #include "base/win/scoped_variant.h" #include "base/win/variant_vector.h" #include "ax_fragment_root_win.h" #include "ax_platform_node_delegate.h" #include "ax_platform_node_delegate_utils_win.h" #include "ax_platform_node_textprovider_win.h" #include "shellscalingapi.h" #include "uia_registrar_win.h" #include "base/logging.h" #include "base/win/atl_module.h" #include "base/win/display.h" #include "flutter/fml/platform/win/wstring_conversion.h" #include "gfx/geometry/rect_conversions.h" // From ax.constants.mojom namespace ax { namespace mojom { const int32_t kUnknownAriaColumnOrRowCount = -1; } } // namespace ax // // Macros to use at the top of any AXPlatformNodeWin function that implements // a non-UIA COM interface. Because COM objects are reference counted and // clients are completely untrusted, it's important to always first check that // our object is still valid, and then check that all pointer arguments are not // NULL. // #define COM_OBJECT_VALIDATE() \ if (!GetDelegate()) \ return E_FAIL; #define COM_OBJECT_VALIDATE_1_ARG(arg) \ if (!GetDelegate()) \ return E_FAIL; \ if (!arg) \ return E_INVALIDARG; \ *arg = {}; #define COM_OBJECT_VALIDATE_2_ARGS(arg1, arg2) \ if (!GetDelegate()) \ return E_FAIL; \ if (!arg1) \ return E_INVALIDARG; \ *arg1 = {}; \ if (!arg2) \ return E_INVALIDARG; \ *arg2 = {}; #define COM_OBJECT_VALIDATE_3_ARGS(arg1, arg2, arg3) \ if (!GetDelegate()) \ return E_FAIL; \ if (!arg1) \ return E_INVALIDARG; \ *arg1 = {}; \ if (!arg2) \ return E_INVALIDARG; \ *arg2 = {}; \ if (!arg3) \ return E_INVALIDARG; \ *arg3 = {}; #define COM_OBJECT_VALIDATE_4_ARGS(arg1, arg2, arg3, arg4) \ if (!GetDelegate()) \ return E_FAIL; \ if (!arg1) \ return E_INVALIDARG; \ *arg1 = {}; \ if (!arg2) \ return E_INVALIDARG; \ *arg2 = {}; \ if (!arg3) \ return E_INVALIDARG; \ *arg3 = {}; \ if (!arg4) \ return E_INVALIDARG; \ *arg4 = {}; #define COM_OBJECT_VALIDATE_5_ARGS(arg1, arg2, arg3, arg4, arg5) \ if (!GetDelegate()) \ return E_FAIL; \ if (!arg1) \ return E_INVALIDARG; \ *arg1 = {}; \ if (!arg2) \ return E_INVALIDARG; \ *arg2 = {}; \ if (!arg3) \ return E_INVALIDARG; \ *arg3 = {}; \ if (!arg4) \ return E_INVALIDARG; \ *arg4 = {}; \ if (!arg5) \ return E_INVALIDARG; \ *arg5 = {}; #define COM_OBJECT_VALIDATE_VAR_ID_AND_GET_TARGET(var_id, target) \ if (!GetDelegate()) \ return E_FAIL; \ target = GetTargetFromChildID(var_id); \ if (!target) \ return E_INVALIDARG; \ if (!target->GetDelegate()) \ return E_INVALIDARG; #define COM_OBJECT_VALIDATE_VAR_ID_1_ARG_AND_GET_TARGET(var_id, arg, target) \ if (!GetDelegate()) \ return E_FAIL; \ if (!arg) \ return E_INVALIDARG; \ *arg = {}; \ target = GetTargetFromChildID(var_id); \ if (!target) \ return E_INVALIDARG; \ if (!target->GetDelegate()) \ return E_INVALIDARG; #define COM_OBJECT_VALIDATE_VAR_ID_2_ARGS_AND_GET_TARGET(var_id, arg1, arg2, \ target) \ if (!GetDelegate()) \ return E_FAIL; \ if (!arg1) \ return E_INVALIDARG; \ *arg1 = {}; \ if (!arg2) \ return E_INVALIDARG; \ *arg2 = {}; \ target = GetTargetFromChildID(var_id); \ if (!target) \ return E_INVALIDARG; \ if (!target->GetDelegate()) \ return E_INVALIDARG; #define COM_OBJECT_VALIDATE_VAR_ID_3_ARGS_AND_GET_TARGET(var_id, arg1, arg2, \ arg3, target) \ if (!GetDelegate()) \ return E_FAIL; \ if (!arg1) \ return E_INVALIDARG; \ *arg1 = {}; \ if (!arg2) \ return E_INVALIDARG; \ *arg2 = {}; \ if (!arg3) \ return E_INVALIDARG; \ *arg3 = {}; \ target = GetTargetFromChildID(var_id); \ if (!target) \ return E_INVALIDARG; \ if (!target->GetDelegate()) \ return E_INVALIDARG; #define COM_OBJECT_VALIDATE_VAR_ID_4_ARGS_AND_GET_TARGET(var_id, arg1, arg2, \ arg3, arg4, target) \ if (!GetDelegate()) \ return E_FAIL; \ if (!arg1) \ return E_INVALIDARG; \ *arg1 = {}; \ if (!arg2) \ return E_INVALIDARG; \ *arg2 = {}; \ if (!arg3) \ return E_INVALIDARG; \ *arg3 = {}; \ if (!arg4) \ return E_INVALIDARG; \ *arg4 = {}; \ target = GetTargetFromChildID(var_id); \ if (!target) \ return E_INVALIDARG; \ if (!target->GetDelegate()) \ return E_INVALIDARG; namespace ui { namespace { typedef std::unordered_set<AXPlatformNodeWin*> AXPlatformNodeWinSet; // Sets the multiplier by which large changes to a RangeValueProvider are // greater than small changes. constexpr int kLargeChangeScaleFactor = 10; // The amount to scroll when UI Automation asks to scroll by a small increment. // Value is in device independent pixels and is the same used by Blink when // cursor keys are used to scroll a webpage. constexpr float kSmallScrollIncrement = 40.0f; // The filename of the DLL to load for UIA. constexpr wchar_t kUIADLLFilename[] = L"uiautomationcore.dll"; void AppendTextToString(std::u16string extra_text, std::u16string* string) { if (extra_text.empty()) return; if (string->empty()) { *string = extra_text; return; } *string += std::u16string(u". ") + extra_text; } // Helper function to GetPatternProviderFactoryMethod that, given a node, // will return a pattern interface through result based on the provided type T. template <typename T> void PatternProvider(AXPlatformNodeWin* node, IUnknown** result) { node->AddRef(); *result = static_cast<T*>(node); } } // namespace void AXPlatformNodeWin::AddAttributeToList(const char* name, const char* value, PlatformAttributeList* attributes) { std::string str_value = value; SanitizeStringAttribute(str_value, &str_value); attributes->push_back(base::UTF8ToUTF16(name) + u":" + base::UTF8ToUTF16(str_value)); } // There is no easy way to decouple |kScreenReader| and |kHTML| accessibility // modes when Windows screen readers are used. For example, certain roles use // the HTML tag name. Input fields require their type attribute to be exposed. const uint32_t kScreenReaderAndHTMLAccessibilityModes = AXMode::kScreenReader | AXMode::kHTML; // // AXPlatformNode::Create // // static AXPlatformNode* AXPlatformNode::Create(AXPlatformNodeDelegate* delegate) { // Make sure ATL is initialized in this module. win::CreateATLModuleIfNeeded(); CComObject<AXPlatformNodeWin>* instance = nullptr; HRESULT hr = CComObject<AXPlatformNodeWin>::CreateInstance(&instance); BASE_DCHECK(SUCCEEDED(hr)); instance->Init(delegate); instance->AddRef(); return instance; } // static AXPlatformNode* AXPlatformNode::FromNativeViewAccessible( gfx::NativeViewAccessible accessible) { if (!accessible) return nullptr; Microsoft::WRL::ComPtr<AXPlatformNodeWin> ax_platform_node; accessible->QueryInterface(IID_PPV_ARGS(&ax_platform_node)); return ax_platform_node.Get(); } // // AXPlatformNodeWin // AXPlatformNodeWin::AXPlatformNodeWin() {} AXPlatformNodeWin::~AXPlatformNodeWin() {} void AXPlatformNodeWin::Init(AXPlatformNodeDelegate* delegate) { AXPlatformNodeBase::Init(delegate); } // Static void AXPlatformNodeWin::SanitizeStringAttributeForUIAAriaProperty( const std::u16string& input, std::u16string* output) { BASE_DCHECK(output); // According to the UIA Spec, these characters need to be escaped with a // backslash in an AriaProperties string: backslash, equals and semicolon. // Note that backslash must be replaced first. base::ReplaceChars(input, u"\\", u"\\\\", output); base::ReplaceChars(*output, u"=", u"\\=", output); base::ReplaceChars(*output, u";", u"\\;", output); } void AXPlatformNodeWin::StringAttributeToUIAAriaProperty( std::vector<std::u16string>& properties, ax::mojom::StringAttribute attribute, const char* uia_aria_property) { std::u16string value; if (GetString16Attribute(attribute, &value)) { SanitizeStringAttributeForUIAAriaProperty(value, &value); properties.push_back(base::ASCIIToUTF16(uia_aria_property) + u"=" + value); } } void AXPlatformNodeWin::BoolAttributeToUIAAriaProperty( std::vector<std::u16string>& properties, ax::mojom::BoolAttribute attribute, const char* uia_aria_property) { bool value; if (GetBoolAttribute(attribute, &value)) { properties.push_back((base::ASCIIToUTF16(uia_aria_property) + u"=") + (value ? u"true" : u"false")); } } void AXPlatformNodeWin::IntAttributeToUIAAriaProperty( std::vector<std::u16string>& properties, ax::mojom::IntAttribute attribute, const char* uia_aria_property) { int value; if (GetIntAttribute(attribute, &value)) { properties.push_back(base::ASCIIToUTF16(uia_aria_property) + u"=" + base::NumberToString16(value)); } } void AXPlatformNodeWin::FloatAttributeToUIAAriaProperty( std::vector<std::u16string>& properties, ax::mojom::FloatAttribute attribute, const char* uia_aria_property) { float value; if (GetFloatAttribute(attribute, &value)) { properties.push_back(base::ASCIIToUTF16(uia_aria_property) + u"=" + base::NumberToString16(value)); } } void AXPlatformNodeWin::StateToUIAAriaProperty( std::vector<std::u16string>& properties, ax::mojom::State state, const char* uia_aria_property) { const AXNodeData& data = GetData(); bool value = data.HasState(state); properties.push_back((base::ASCIIToUTF16(uia_aria_property) + u"=") + (value ? u"true" : u"false")); } void AXPlatformNodeWin::HtmlAttributeToUIAAriaProperty( std::vector<std::u16string>& properties, const char* html_attribute_name, const char* uia_aria_property) { std::u16string html_attribute_value; if (GetData().GetHtmlAttribute(html_attribute_name, &html_attribute_value)) { SanitizeStringAttributeForUIAAriaProperty(html_attribute_value, &html_attribute_value); properties.push_back(base::ASCIIToUTF16(uia_aria_property) + u"=" + html_attribute_value); } } std::vector<AXPlatformNodeWin*> AXPlatformNodeWin::CreatePlatformNodeVectorFromRelationIdVector( std::vector<int32_t>& relation_id_list) { std::vector<AXPlatformNodeWin*> platform_node_list; for (int32_t id : relation_id_list) { AXPlatformNode* platform_node = GetDelegate()->GetFromNodeID(id); if (IsValidUiaRelationTarget(platform_node)) { platform_node_list.push_back( static_cast<AXPlatformNodeWin*>(platform_node)); } } return platform_node_list; } SAFEARRAY* AXPlatformNodeWin::CreateUIAElementsSafeArray( std::vector<AXPlatformNodeWin*>& platform_node_list) { if (platform_node_list.empty()) return nullptr; SAFEARRAY* uia_array = SafeArrayCreateVector(VT_UNKNOWN, 0, platform_node_list.size()); LONG i = 0; for (AXPlatformNodeWin* platform_node : platform_node_list) { // All incoming ids should already be validated to have a valid relation // targets so that this function does not need to re-check before allocating // the SAFEARRAY. BASE_DCHECK(IsValidUiaRelationTarget(platform_node)); SafeArrayPutElement(uia_array, &i, static_cast<IRawElementProviderSimple*>(platform_node)); ++i; } return uia_array; } SAFEARRAY* AXPlatformNodeWin::CreateUIAControllerForArray() { std::vector<int32_t> relation_id_list = GetIntListAttribute(ax::mojom::IntListAttribute::kControlsIds); std::vector<AXPlatformNodeWin*> platform_node_list = CreatePlatformNodeVectorFromRelationIdVector(relation_id_list); if (GetActivePopupAxUniqueId() != std::nullopt) { AXPlatformNodeWin* view_popup_node_win = static_cast<AXPlatformNodeWin*>( GetFromUniqueId(GetActivePopupAxUniqueId().value())); if (IsValidUiaRelationTarget(view_popup_node_win)) platform_node_list.push_back(view_popup_node_win); } return CreateUIAElementsSafeArray(platform_node_list); } SAFEARRAY* AXPlatformNodeWin::CreateUIAElementsArrayForRelation( const ax::mojom::IntListAttribute& attribute) { std::vector<int32_t> relation_id_list = GetIntListAttribute(attribute); std::vector<AXPlatformNodeWin*> platform_node_list = CreatePlatformNodeVectorFromRelationIdVector(relation_id_list); return CreateUIAElementsSafeArray(platform_node_list); } SAFEARRAY* AXPlatformNodeWin::CreateUIAElementsArrayForReverseRelation( const ax::mojom::IntListAttribute& attribute) { std::set<AXPlatformNode*> reverse_relations = GetDelegate()->GetReverseRelations(attribute); std::vector<int32_t> id_list; std::transform( reverse_relations.cbegin(), reverse_relations.cend(), std::back_inserter(id_list), [](AXPlatformNode* platform_node) { return static_cast<AXPlatformNodeWin*>(platform_node)->GetData().id; }); std::vector<AXPlatformNodeWin*> platform_node_list = CreatePlatformNodeVectorFromRelationIdVector(id_list); return CreateUIAElementsSafeArray(platform_node_list); } SAFEARRAY* AXPlatformNodeWin::CreateClickablePointArray() { SAFEARRAY* clickable_point_array = SafeArrayCreateVector(VT_R8, 0, 2); gfx::Point center = GetDelegate() ->GetBoundsRect(AXCoordinateSystem::kScreenDIPs, AXClippingBehavior::kUnclipped) .CenterPoint(); double* double_array; SafeArrayAccessData(clickable_point_array, reinterpret_cast<void**>(&double_array)); double_array[0] = center.x(); double_array[1] = center.y(); SafeArrayUnaccessData(clickable_point_array); return clickable_point_array; } gfx::Vector2d AXPlatformNodeWin::CalculateUIAScrollPoint( const ScrollAmount horizontal_amount, const ScrollAmount vertical_amount) const { if (!GetDelegate() || !IsScrollable()) return {}; const gfx::Rect bounds = GetDelegate()->GetBoundsRect( AXCoordinateSystem::kScreenDIPs, AXClippingBehavior::kClipped); const int large_horizontal_change = bounds.width(); const int large_vertical_change = bounds.height(); const HWND hwnd = GetDelegate()->GetTargetForNativeAccessibilityEvent(); BASE_DCHECK(hwnd); const float scale_factor = base::win::GetScaleFactorForHWND(hwnd); const int small_change = base::ClampRound(kSmallScrollIncrement * scale_factor); const int x_min = GetIntAttribute(ax::mojom::IntAttribute::kScrollXMin); const int x_max = GetIntAttribute(ax::mojom::IntAttribute::kScrollXMax); const int y_min = GetIntAttribute(ax::mojom::IntAttribute::kScrollYMin); const int y_max = GetIntAttribute(ax::mojom::IntAttribute::kScrollYMax); int x = GetIntAttribute(ax::mojom::IntAttribute::kScrollX); int y = GetIntAttribute(ax::mojom::IntAttribute::kScrollY); switch (horizontal_amount) { case ScrollAmount_LargeDecrement: x -= large_horizontal_change; break; case ScrollAmount_LargeIncrement: x += large_horizontal_change; break; case ScrollAmount_NoAmount: break; case ScrollAmount_SmallDecrement: x -= small_change; break; case ScrollAmount_SmallIncrement: x += small_change; break; } x = std::min(x, x_max); x = std::max(x, x_min); switch (vertical_amount) { case ScrollAmount_LargeDecrement: y -= large_vertical_change; break; case ScrollAmount_LargeIncrement: y += large_vertical_change; break; case ScrollAmount_NoAmount: break; case ScrollAmount_SmallDecrement: y -= small_change; break; case ScrollAmount_SmallIncrement: y += small_change; break; } y = std::min(y, y_max); y = std::max(y, y_min); return {x, y}; } // // AXPlatformNodeBase implementation. // void AXPlatformNodeWin::Dispose() { Release(); } void AXPlatformNodeWin::Destroy() { RemoveAlertTarget(); // This will end up calling Dispose() which may result in deleting this object // if there are no more outstanding references. AXPlatformNodeBase::Destroy(); } // // AXPlatformNode implementation. // gfx::NativeViewAccessible AXPlatformNodeWin::GetNativeViewAccessible() { return this; } void AXPlatformNodeWin::NotifyAccessibilityEvent(ax::mojom::Event event_type) { AXPlatformNodeBase::NotifyAccessibilityEvent(event_type); // Menu items fire selection events but Windows screen readers work reliably // with focus events. Remap here. if (event_type == ax::mojom::Event::kSelection) { // A menu item could have something other than a role of // |ROLE_SYSTEM_MENUITEM|. Zoom modification controls for example have a // role of button. auto* parent = static_cast<AXPlatformNodeWin*>(FromNativeViewAccessible(GetParent())); int role = MSAARole(); if (role == ROLE_SYSTEM_MENUITEM) { event_type = ax::mojom::Event::kFocus; } else if (role == ROLE_SYSTEM_LISTITEM) { if (AXPlatformNodeBase* container = GetSelectionContainer()) { const AXNodeData& data = container->GetData(); if (data.role == ax::mojom::Role::kListBox && !data.HasState(ax::mojom::State::kMultiselectable) && GetDelegate()->GetFocus() == GetNativeViewAccessible()) { event_type = ax::mojom::Event::kFocus; } } } else if (parent) { int parent_role = parent->MSAARole(); if (parent_role == ROLE_SYSTEM_MENUPOPUP || parent_role == ROLE_SYSTEM_LIST) { event_type = ax::mojom::Event::kFocus; } } } if (event_type == ax::mojom::Event::kValueChanged) { // For the IAccessibleText interface to work on non-web content nodes, we // need to update the nodes' hypertext // when the value changes. Otherwise, for web and PDF content, this is // handled by "BrowserAccessibilityComWin". if (!GetDelegate()->IsWebContent()) UpdateComputedHypertext(); } if (std::optional<DWORD> native_event = MojoEventToMSAAEvent(event_type)) { HWND hwnd = GetDelegate()->GetTargetForNativeAccessibilityEvent(); if (!hwnd) return; ::NotifyWinEvent((*native_event), hwnd, OBJID_CLIENT, -GetUniqueId()); } if (std::optional<PROPERTYID> uia_property = MojoEventToUIAProperty(event_type)) { // For this event, we're not concerned with the old value. base::win::ScopedVariant old_value; ::VariantInit(old_value.Receive()); base::win::ScopedVariant new_value; ::VariantInit(new_value.Receive()); GetPropertyValueImpl((*uia_property), new_value.Receive()); ::UiaRaiseAutomationPropertyChangedEvent(this, (*uia_property), old_value, new_value); } if (std::optional<EVENTID> uia_event = MojoEventToUIAEvent(event_type)) ::UiaRaiseAutomationEvent(this, (*uia_event)); // Keep track of objects that are a target of an alert event. if (event_type == ax::mojom::Event::kAlert) AddAlertTarget(); } bool AXPlatformNodeWin::HasActiveComposition() const { return active_composition_range_.end() > active_composition_range_.start(); } gfx::Range AXPlatformNodeWin::GetActiveCompositionOffsets() const { return active_composition_range_; } void AXPlatformNodeWin::OnActiveComposition( const gfx::Range& range, const std::u16string& active_composition_text, bool is_composition_committed) { // Cache the composition range that will be used when // GetActiveComposition and GetConversionTarget is called in // AXPlatformNodeTextProviderWin active_composition_range_ = range; // Fire the UiaTextEditTextChangedEvent FireUiaTextEditTextChangedEvent(range, active_composition_text, is_composition_committed); } void AXPlatformNodeWin::FireUiaTextEditTextChangedEvent( const gfx::Range& range, const std::u16string& active_composition_text, bool is_composition_committed) { // This API is only supported from Win8.1 onwards // Check if the function pointer is valid or not using UiaRaiseTextEditTextChangedEventFunction = HRESULT(WINAPI*)( IRawElementProviderSimple*, TextEditChangeType, SAFEARRAY*); UiaRaiseTextEditTextChangedEventFunction text_edit_text_changed_func = reinterpret_cast<UiaRaiseTextEditTextChangedEventFunction>( ::GetProcAddress(GetModuleHandleW(kUIADLLFilename), "UiaRaiseTextEditTextChangedEvent")); if (!text_edit_text_changed_func) { return; } TextEditChangeType text_edit_change_type = is_composition_committed ? TextEditChangeType_CompositionFinalized : TextEditChangeType_Composition; // Composition has been finalized by TSF base::win::ScopedBstr composition_text( (wchar_t*)active_composition_text.data()); base::win::ScopedSafearray changed_data( ::SafeArrayCreateVector(VT_BSTR /* element type */, 0 /* lower bound */, 1 /* number of elements */)); if (!changed_data.Get()) { return; } LONG index = 0; HRESULT hr = SafeArrayPutElement(changed_data.Get(), &index, composition_text.Get()); if (FAILED(hr)) { return; } else { // Fire the UiaRaiseTextEditTextChangedEvent text_edit_text_changed_func(this, text_edit_change_type, changed_data.Release()); } } bool AXPlatformNodeWin::IsValidUiaRelationTarget( AXPlatformNode* ax_platform_node) { if (!ax_platform_node) return false; if (!ax_platform_node->GetDelegate()) return false; // This is needed for get_FragmentRoot. if (!ax_platform_node->GetDelegate()->GetTargetForNativeAccessibilityEvent()) return false; return true; } // // IAccessible implementation. // IFACEMETHODIMP AXPlatformNodeWin::accHitTest(LONG screen_physical_pixel_x, LONG screen_physical_pixel_y, VARIANT* child) { COM_OBJECT_VALIDATE_1_ARG(child); gfx::Point point(screen_physical_pixel_x, screen_physical_pixel_y); if (!GetDelegate() ->GetBoundsRect(AXCoordinateSystem::kScreenPhysicalPixels, AXClippingBehavior::kClipped) .Contains(point)) { // Return S_FALSE and VT_EMPTY when outside the object's boundaries. child->vt = VT_EMPTY; return S_FALSE; } AXPlatformNode* current_result = this; while (true) { gfx::NativeViewAccessible hit_child = current_result->GetDelegate()->HitTestSync(screen_physical_pixel_x, screen_physical_pixel_y); if (!hit_child) { child->vt = VT_EMPTY; return S_FALSE; } AXPlatformNode* hit_child_node = AXPlatformNode::FromNativeViewAccessible(hit_child); if (!hit_child_node) break; // If we get the same node, we're done. if (hit_child_node == current_result) break; // Prevent cycles / loops. // // This is a workaround for a bug where a hit test in web content might // return a node that's not a strict descendant. To catch that case // without disallowing other valid cases of hit testing, add the // following check: // // If the hit child comes from the same HWND, but it's not a descendant, // just ignore the result and stick with the current result. Note that // GetTargetForNativeAccessibilityEvent returns a node's owning HWND. // // Ideally this shouldn't happen - see http://crbug.com/1061323 bool is_descendant = hit_child_node->IsDescendantOf(current_result); bool is_same_hwnd = hit_child_node->GetDelegate()->GetTargetForNativeAccessibilityEvent() == current_result->GetDelegate()->GetTargetForNativeAccessibilityEvent(); if (!is_descendant && is_same_hwnd) break; // Continue to check recursively. That's because HitTestSync may have // returned the best result within a particular accessibility tree, // but we might need to recurse further in a tree of a different type // (for example, from Views to Web). current_result = hit_child_node; } if (current_result == this) { // This object is the best match, so return CHILDID_SELF. It's tempting to // simplify the logic and use VT_DISPATCH everywhere, but the Windows // call AccessibleObjectFromPoint will keep calling accHitTest until some // object returns CHILDID_SELF. child->vt = VT_I4; child->lVal = CHILDID_SELF; return S_OK; } child->vt = VT_DISPATCH; child->pdispVal = static_cast<AXPlatformNodeWin*>(current_result); // Always increment ref when returning a reference to a COM object. child->pdispVal->AddRef(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::accDoDefaultAction(VARIANT var_id) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_AND_GET_TARGET(var_id, target); AXActionData data; data.action = ax::mojom::Action::kDoDefault; if (target->GetDelegate()->AccessibilityPerformAction(data)) return S_OK; return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::accLocation(LONG* physical_pixel_left, LONG* physical_pixel_top, LONG* width, LONG* height, VARIANT var_id) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_4_ARGS_AND_GET_TARGET( var_id, physical_pixel_left, physical_pixel_top, width, height, target); gfx::Rect bounds = target->GetDelegate()->GetBoundsRect( AXCoordinateSystem::kScreenPhysicalPixels, AXClippingBehavior::kUnclipped); *physical_pixel_left = bounds.x(); *physical_pixel_top = bounds.y(); *width = bounds.width(); *height = bounds.height(); if (bounds.IsEmpty()) return S_FALSE; return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::accNavigate(LONG nav_dir, VARIANT start, VARIANT* end) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_1_ARG_AND_GET_TARGET(start, end, target); end->vt = VT_EMPTY; if ((nav_dir == NAVDIR_FIRSTCHILD || nav_dir == NAVDIR_LASTCHILD) && V_VT(&start) == VT_I4 && V_I4(&start) != CHILDID_SELF) { // MSAA states that navigating to first/last child can only be from self. return E_INVALIDARG; } IAccessible* result = nullptr; switch (nav_dir) { case NAVDIR_FIRSTCHILD: if (GetDelegate()->GetChildCount() > 0) result = GetDelegate()->GetFirstChild(); break; case NAVDIR_LASTCHILD: if (GetDelegate()->GetChildCount() > 0) result = GetDelegate()->GetLastChild(); break; case NAVDIR_NEXT: { AXPlatformNodeBase* next = target->GetNextSibling(); if (next) result = next->GetNativeViewAccessible(); break; } case NAVDIR_PREVIOUS: { AXPlatformNodeBase* previous = target->GetPreviousSibling(); if (previous) result = previous->GetNativeViewAccessible(); break; } case NAVDIR_DOWN: { // This direction is not implemented except in tables. if (!GetTableRow() || !GetTableRowSpan() || !GetTableColumn()) return E_NOTIMPL; AXPlatformNodeBase* next = target->GetTableCell( *GetTableRow() + *GetTableRowSpan(), *GetTableColumn()); if (!next) return S_OK; result = next->GetNativeViewAccessible(); break; } case NAVDIR_UP: { // This direction is not implemented except in tables. if (!GetTableRow() || !GetTableColumn()) return E_NOTIMPL; AXPlatformNodeBase* next = target->GetTableCell(*GetTableRow() - 1, *GetTableColumn()); if (!next) return S_OK; result = next->GetNativeViewAccessible(); break; } case NAVDIR_LEFT: { // This direction is not implemented except in tables. if (!GetTableRow() || !GetTableColumn()) return E_NOTIMPL; AXPlatformNodeBase* next = target->GetTableCell(*GetTableRow(), *GetTableColumn() - 1); if (!next) return S_OK; result = next->GetNativeViewAccessible(); break; } case NAVDIR_RIGHT: { // This direction is not implemented except in tables. if (!GetTableRow() || !GetTableColumn() || !GetTableColumnSpan()) return E_NOTIMPL; AXPlatformNodeBase* next = target->GetTableCell( *GetTableRow(), *GetTableColumn() + *GetTableColumnSpan()); if (!next) return S_OK; result = next->GetNativeViewAccessible(); break; } } if (!result) return S_FALSE; end->vt = VT_DISPATCH; end->pdispVal = result; // Always increment ref when returning a reference to a COM object. end->pdispVal->AddRef(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_accChild(VARIANT var_child, IDispatch** disp_child) { *disp_child = nullptr; AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_AND_GET_TARGET(var_child, target); *disp_child = target; (*disp_child)->AddRef(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_accChildCount(LONG* child_count) { COM_OBJECT_VALIDATE_1_ARG(child_count); *child_count = GetDelegate()->GetChildCount(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_accDefaultAction(VARIANT var_id, BSTR* def_action) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_1_ARG_AND_GET_TARGET(var_id, def_action, target); AXPlatformNode::NotifyAddAXModeFlags(kScreenReaderAndHTMLAccessibilityModes); int action; if (!target->GetIntAttribute(ax::mojom::IntAttribute::kDefaultActionVerb, &action)) { *def_action = nullptr; return S_FALSE; } // TODO(gw280): https://github.com/flutter/flutter/issues/78799 // Use localized strings std::u16string action_verb = base::UTF8ToUTF16( ui::ToString(static_cast<ax::mojom::DefaultActionVerb>(action))); if (action_verb.empty()) { *def_action = nullptr; return S_FALSE; } *def_action = ::SysAllocString(fml::Utf16ToWideString(action_verb).c_str()); BASE_DCHECK(def_action); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_accDescription(VARIANT var_id, BSTR* desc) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_1_ARG_AND_GET_TARGET(var_id, desc, target); return target->GetStringAttributeAsBstr( ax::mojom::StringAttribute::kDescription, desc); } IFACEMETHODIMP AXPlatformNodeWin::get_accFocus(VARIANT* focus_child) { COM_OBJECT_VALIDATE_1_ARG(focus_child); gfx::NativeViewAccessible focus_accessible = GetDelegate()->GetFocus(); if (focus_accessible == this) { focus_child->vt = VT_I4; focus_child->lVal = CHILDID_SELF; } else if (focus_accessible) { Microsoft::WRL::ComPtr<IDispatch> focus_idispatch; if (FAILED( focus_accessible->QueryInterface(IID_PPV_ARGS(&focus_idispatch)))) { focus_child->vt = VT_EMPTY; return E_FAIL; } focus_child->vt = VT_DISPATCH; focus_child->pdispVal = focus_idispatch.Detach(); } else { focus_child->vt = VT_EMPTY; } return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_accKeyboardShortcut(VARIANT var_id, BSTR* acc_key) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_1_ARG_AND_GET_TARGET(var_id, acc_key, target); return target->GetStringAttributeAsBstr( ax::mojom::StringAttribute::kKeyShortcuts, acc_key); } IFACEMETHODIMP AXPlatformNodeWin::get_accName(VARIANT var_id, BSTR* name_bstr) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_1_ARG_AND_GET_TARGET(var_id, name_bstr, target); if (!IsNameExposed()) return S_FALSE; bool has_name = target->HasStringAttribute(ax::mojom::StringAttribute::kName); std::u16string name = target->GetNameAsString16(); // Simply appends the tooltip, if any, to the end of the MSAA name. const std::u16string tooltip = target->GetString16Attribute(ax::mojom::StringAttribute::kTooltip); if (!tooltip.empty()) { AppendTextToString(tooltip, &name); } auto status = GetData().GetImageAnnotationStatus(); switch (status) { case ax::mojom::ImageAnnotationStatus::kNone: case ax::mojom::ImageAnnotationStatus::kWillNotAnnotateDueToScheme: case ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation: case ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation: break; case ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation: case ax::mojom::ImageAnnotationStatus::kAnnotationPending: case ax::mojom::ImageAnnotationStatus::kAnnotationEmpty: case ax::mojom::ImageAnnotationStatus::kAnnotationAdult: case ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed: AppendTextToString( GetDelegate()->GetLocalizedStringForImageAnnotationStatus(status), &name); break; case ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded: AppendTextToString( GetString16Attribute(ax::mojom::StringAttribute::kImageAnnotation), &name); break; } if (name.empty() && !has_name) return S_FALSE; *name_bstr = ::SysAllocString(fml::Utf16ToWideString(name).c_str()); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_accParent(IDispatch** disp_parent) { COM_OBJECT_VALIDATE_1_ARG(disp_parent); *disp_parent = GetParent(); if (*disp_parent) { (*disp_parent)->AddRef(); return S_OK; } IRawElementProviderFragmentRoot* root; if (SUCCEEDED(get_FragmentRoot(&root))) { gfx::NativeViewAccessible parent; if (SUCCEEDED(root->QueryInterface(IID_PPV_ARGS(&parent)))) { if (parent && parent != GetNativeViewAccessible()) { *disp_parent = parent; parent->AddRef(); return S_OK; } } } return S_FALSE; } IFACEMETHODIMP AXPlatformNodeWin::get_accRole(VARIANT var_id, VARIANT* role) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_1_ARG_AND_GET_TARGET(var_id, role, target); role->vt = VT_I4; role->lVal = target->MSAARole(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_accState(VARIANT var_id, VARIANT* state) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_1_ARG_AND_GET_TARGET(var_id, state, target); state->vt = VT_I4; state->lVal = target->MSAAState(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_accHelp(VARIANT var_id, BSTR* help) { COM_OBJECT_VALIDATE_1_ARG(help); return S_FALSE; } IFACEMETHODIMP AXPlatformNodeWin::get_accValue(VARIANT var_id, BSTR* value) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_1_ARG_AND_GET_TARGET(var_id, value, target); *value = GetValueAttributeAsBstr(target); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::put_accValue(VARIANT var_id, BSTR new_value) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_AND_GET_TARGET(var_id, target); if (!new_value) return E_INVALIDARG; std::u16string new_value_utf16((char16_t*)new_value); AXActionData data; data.action = ax::mojom::Action::kSetValue; data.value = base::UTF16ToUTF8(new_value_utf16); if (target->GetDelegate()->AccessibilityPerformAction(data)) return S_OK; return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::get_accSelection(VARIANT* selected) { COM_OBJECT_VALIDATE_1_ARG(selected); std::vector<Microsoft::WRL::ComPtr<IDispatch>> selected_nodes; for (int i = 0; i < GetDelegate()->GetChildCount(); ++i) { auto* node = static_cast<AXPlatformNodeWin*>( FromNativeViewAccessible(GetDelegate()->ChildAtIndex(i))); if (node && node->GetData().GetBoolAttribute(ax::mojom::BoolAttribute::kSelected)) { Microsoft::WRL::ComPtr<IDispatch> node_idispatch; if (SUCCEEDED(node->QueryInterface(IID_PPV_ARGS(&node_idispatch)))) selected_nodes.push_back(node_idispatch); } } if (selected_nodes.empty()) { selected->vt = VT_EMPTY; return S_OK; } if (selected_nodes.size() == 1) { selected->vt = VT_DISPATCH; selected->pdispVal = selected_nodes[0].Detach(); return S_OK; } // Multiple items are selected. LONG selected_count = static_cast<LONG>(selected_nodes.size()); Microsoft::WRL::ComPtr<base::win::EnumVariant> enum_variant = Microsoft::WRL::Make<base::win::EnumVariant>(selected_count); for (LONG i = 0; i < selected_count; ++i) { enum_variant->ItemAt(i)->vt = VT_DISPATCH; enum_variant->ItemAt(i)->pdispVal = selected_nodes[i].Detach(); } selected->vt = VT_UNKNOWN; return enum_variant.CopyTo(IID_PPV_ARGS(&V_UNKNOWN(selected))); } IFACEMETHODIMP AXPlatformNodeWin::accSelect(LONG flagsSelect, VARIANT var_id) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_AND_GET_TARGET(var_id, target); if (flagsSelect & SELFLAG_TAKEFOCUS) { AXActionData action_data; action_data.action = ax::mojom::Action::kFocus; target->GetDelegate()->AccessibilityPerformAction(action_data); return S_OK; } return S_FALSE; } IFACEMETHODIMP AXPlatformNodeWin::get_accHelpTopic(BSTR* help_file, VARIANT var_id, LONG* topic_id) { AXPlatformNodeWin* target; COM_OBJECT_VALIDATE_VAR_ID_2_ARGS_AND_GET_TARGET(var_id, help_file, topic_id, target); if (help_file) { *help_file = nullptr; } if (topic_id) { *topic_id = static_cast<LONG>(-1); } return E_NOTIMPL; } IFACEMETHODIMP AXPlatformNodeWin::put_accName(VARIANT var_id, BSTR put_name) { // TODO(dougt): We may want to collect an API histogram here. // Deprecated. return E_NOTIMPL; } // // IExpandCollapseProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::Collapse() { UIA_VALIDATE_CALL(); if (GetData().GetRestriction() == ax::mojom::Restriction::kDisabled) return UIA_E_ELEMENTNOTAVAILABLE; if (GetData().HasState(ax::mojom::State::kCollapsed)) return UIA_E_INVALIDOPERATION; AXActionData action_data; action_data.action = ax::mojom::Action::kDoDefault; if (GetDelegate()->AccessibilityPerformAction(action_data)) return S_OK; return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::Expand() { UIA_VALIDATE_CALL(); if (GetData().GetRestriction() == ax::mojom::Restriction::kDisabled) return UIA_E_ELEMENTNOTAVAILABLE; if (GetData().HasState(ax::mojom::State::kExpanded)) return UIA_E_INVALIDOPERATION; AXActionData action_data; action_data.action = ax::mojom::Action::kDoDefault; if (GetDelegate()->AccessibilityPerformAction(action_data)) return S_OK; return E_FAIL; } ExpandCollapseState AXPlatformNodeWin::ComputeExpandCollapseState() const { const AXNodeData& data = GetData(); // Since a menu button implies there is a popup and it is either expanded or // collapsed, and it should not support ExpandCollapseState_LeafNode. // According to the UIA spec, ExpandCollapseState_LeafNode indicates that the // element neither expands nor collapses. if (data.IsMenuButton()) { if (data.IsButtonPressed()) return ExpandCollapseState_Expanded; return ExpandCollapseState_Collapsed; } if (data.HasState(ax::mojom::State::kExpanded)) { return ExpandCollapseState_Expanded; } else if (data.HasState(ax::mojom::State::kCollapsed)) { return ExpandCollapseState_Collapsed; } else { return ExpandCollapseState_LeafNode; } } IFACEMETHODIMP AXPlatformNodeWin::get_ExpandCollapseState( ExpandCollapseState* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = ComputeExpandCollapseState(); return S_OK; } // // IGridItemProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::get_Column(int* result) { UIA_VALIDATE_CALL_1_ARG(result); std::optional<int> column = GetTableColumn(); if (!column) return E_FAIL; *result = *column; return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_ColumnSpan(int* result) { UIA_VALIDATE_CALL_1_ARG(result); std::optional<int> column_span = GetTableColumnSpan(); if (!column_span) return E_FAIL; *result = *column_span; return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_ContainingGrid( IRawElementProviderSimple** result) { UIA_VALIDATE_CALL_1_ARG(result); AXPlatformNodeBase* table = GetTable(); if (!table) return E_FAIL; auto* node_win = static_cast<AXPlatformNodeWin*>(table); node_win->AddRef(); *result = static_cast<IRawElementProviderSimple*>(node_win); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_Row(int* result) { UIA_VALIDATE_CALL_1_ARG(result); std::optional<int> row = GetTableRow(); if (!row) return E_FAIL; *result = *row; return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_RowSpan(int* result) { UIA_VALIDATE_CALL_1_ARG(result); std::optional<int> row_span = GetTableRowSpan(); if (!row_span) return E_FAIL; *result = *row_span; return S_OK; } // // IGridProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::GetItem(int row, int column, IRawElementProviderSimple** result) { UIA_VALIDATE_CALL_1_ARG(result); AXPlatformNodeBase* cell = GetTableCell(row, column); if (!cell) return E_INVALIDARG; auto* node_win = static_cast<AXPlatformNodeWin*>(cell); node_win->AddRef(); *result = static_cast<IRawElementProviderSimple*>(node_win); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_RowCount(int* result) { UIA_VALIDATE_CALL_1_ARG(result); std::optional<int> row_count = GetTableAriaRowCount(); if (!row_count) row_count = GetTableRowCount(); if (!row_count || *row_count == ax::mojom::kUnknownAriaColumnOrRowCount) return E_UNEXPECTED; *result = *row_count; return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_ColumnCount(int* result) { UIA_VALIDATE_CALL_1_ARG(result); std::optional<int> column_count = GetTableAriaColumnCount(); if (!column_count) column_count = GetTableColumnCount(); if (!column_count || *column_count == ax::mojom::kUnknownAriaColumnOrRowCount) { return E_UNEXPECTED; } *result = *column_count; return S_OK; } // // IInvokeProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::Invoke() { UIA_VALIDATE_CALL(); if (GetData().GetRestriction() == ax::mojom::Restriction::kDisabled) return UIA_E_ELEMENTNOTENABLED; AXActionData action_data; action_data.action = ax::mojom::Action::kDoDefault; GetDelegate()->AccessibilityPerformAction(action_data); return S_OK; } // // IScrollItemProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::ScrollIntoView() { UIA_VALIDATE_CALL(); gfx::Rect r = gfx::ToEnclosingRect(GetData().relative_bounds.bounds); r -= r.OffsetFromOrigin(); AXActionData action_data; action_data.target_node_id = GetData().id; action_data.target_rect = r; action_data.horizontal_scroll_alignment = ax::mojom::ScrollAlignment::kScrollAlignmentCenter; action_data.vertical_scroll_alignment = ax::mojom::ScrollAlignment::kScrollAlignmentCenter; action_data.scroll_behavior = ax::mojom::ScrollBehavior::kDoNotScrollIfVisible; if (GetDelegate()->AccessibilityPerformAction(action_data)) return S_OK; return E_FAIL; } // // IScrollProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::Scroll(ScrollAmount horizontal_amount, ScrollAmount vertical_amount) { UIA_VALIDATE_CALL(); if (!IsScrollable()) return E_FAIL; AXActionData action_data; action_data.target_node_id = GetData().id; action_data.action = ax::mojom::Action::kSetScrollOffset; action_data.target_point = gfx::PointAtOffsetFromOrigin( CalculateUIAScrollPoint(horizontal_amount, vertical_amount)); if (GetDelegate()->AccessibilityPerformAction(action_data)) return S_OK; return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::SetScrollPercent(double horizontal_percent, double vertical_percent) { UIA_VALIDATE_CALL(); if (!IsScrollable()) return E_FAIL; const double x_min = GetIntAttribute(ax::mojom::IntAttribute::kScrollXMin); const double x_max = GetIntAttribute(ax::mojom::IntAttribute::kScrollXMax); const double y_min = GetIntAttribute(ax::mojom::IntAttribute::kScrollYMin); const double y_max = GetIntAttribute(ax::mojom::IntAttribute::kScrollYMax); const int x = base::ClampRound(horizontal_percent / 100.0 * (x_max - x_min) + x_min); const int y = base::ClampRound(vertical_percent / 100.0 * (y_max - y_min) + y_min); const gfx::Point scroll_to(x, y); AXActionData action_data; action_data.target_node_id = GetData().id; action_data.action = ax::mojom::Action::kSetScrollOffset; action_data.target_point = scroll_to; if (GetDelegate()->AccessibilityPerformAction(action_data)) return S_OK; return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::get_HorizontallyScrollable(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = IsHorizontallyScrollable(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_HorizontalScrollPercent(double* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = GetHorizontalScrollPercent(); return S_OK; } // Horizontal size of the viewable region as a percentage of the total content // area. IFACEMETHODIMP AXPlatformNodeWin::get_HorizontalViewSize(double* result) { UIA_VALIDATE_CALL_1_ARG(result); if (!IsHorizontallyScrollable()) { *result = 100.; return S_OK; } gfx::RectF clipped_bounds(GetDelegate()->GetBoundsRect( AXCoordinateSystem::kScreenDIPs, AXClippingBehavior::kClipped)); float x_min = GetIntAttribute(ax::mojom::IntAttribute::kScrollXMin); float x_max = GetIntAttribute(ax::mojom::IntAttribute::kScrollXMax); float total_width = clipped_bounds.width() + x_max - x_min; BASE_DCHECK(clipped_bounds.width() <= total_width); *result = 100.0 * clipped_bounds.width() / total_width; return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_VerticallyScrollable(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = IsVerticallyScrollable(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_VerticalScrollPercent(double* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = GetVerticalScrollPercent(); return S_OK; } // Vertical size of the viewable region as a percentage of the total content // area. IFACEMETHODIMP AXPlatformNodeWin::get_VerticalViewSize(double* result) { UIA_VALIDATE_CALL_1_ARG(result); if (!IsVerticallyScrollable()) { *result = 100.0; return S_OK; } gfx::RectF clipped_bounds(GetDelegate()->GetBoundsRect( AXCoordinateSystem::kScreenDIPs, AXClippingBehavior::kClipped)); float y_min = GetIntAttribute(ax::mojom::IntAttribute::kScrollYMin); float y_max = GetIntAttribute(ax::mojom::IntAttribute::kScrollYMax); float total_height = clipped_bounds.height() + y_max - y_min; BASE_DCHECK(clipped_bounds.height() <= total_height); *result = 100.0 * clipped_bounds.height() / total_height; return S_OK; } // // ISelectionItemProvider implementation. // HRESULT AXPlatformNodeWin::ISelectionItemProviderSetSelected( bool selected) const { UIA_VALIDATE_CALL(); if (GetData().GetRestriction() == ax::mojom::Restriction::kDisabled) return UIA_E_ELEMENTNOTENABLED; // The platform implements selection follows focus for single-selection // container elements. Focus action can change a node's accessibility selected // state, but does not cause the actual control to be selected. // https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_selection_follows_focus // https://www.w3.org/TR/core-aam-1.2/#mapping_events_selection // // We don't want to perform |Action::kDoDefault| for an ax node that has // |kSelected=true| and |kSelectedFromFocus=false|, because perform // |Action::kDoDefault| may cause the control to be unselected. However, if an // ax node is selected due to focus, i.e. |kSelectedFromFocus=true|, we need // to perform |Action::kDoDefault| on the ax node, since focus action only // changes an ax node's accessibility selected state to |kSelected=true| and // no |Action::kDoDefault| was performed on that node yet. So we need to // perform |Action::kDoDefault| on the ax node to cause its associated control // to be selected. if (selected == ISelectionItemProviderIsSelected() && !GetBoolAttribute(ax::mojom::BoolAttribute::kSelectedFromFocus)) return S_OK; AXActionData data; data.action = ax::mojom::Action::kDoDefault; if (GetDelegate()->AccessibilityPerformAction(data)) return S_OK; return UIA_E_INVALIDOPERATION; } bool AXPlatformNodeWin::ISelectionItemProviderIsSelected() const { // https://www.w3.org/TR/core-aam-1.1/#mapping_state-property_table // SelectionItem.IsSelected is set according to the True or False value of // aria-checked for 'radio' and 'menuitemradio' roles. if (GetData().role == ax::mojom::Role::kRadioButton || GetData().role == ax::mojom::Role::kMenuItemRadio) return GetData().GetCheckedState() == ax::mojom::CheckedState::kTrue; // https://www.w3.org/TR/wai-aria-1.1/#aria-selected // SelectionItem.IsSelected is set according to the True or False value of // aria-selected. return GetBoolAttribute(ax::mojom::BoolAttribute::kSelected); } IFACEMETHODIMP AXPlatformNodeWin::AddToSelection() { return ISelectionItemProviderSetSelected(true); } IFACEMETHODIMP AXPlatformNodeWin::RemoveFromSelection() { return ISelectionItemProviderSetSelected(false); } IFACEMETHODIMP AXPlatformNodeWin::Select() { return ISelectionItemProviderSetSelected(true); } IFACEMETHODIMP AXPlatformNodeWin::get_IsSelected(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = ISelectionItemProviderIsSelected(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_SelectionContainer( IRawElementProviderSimple** result) { UIA_VALIDATE_CALL_1_ARG(result); auto* node_win = static_cast<AXPlatformNodeWin*>(GetSelectionContainer()); if (!node_win) return E_FAIL; node_win->AddRef(); *result = static_cast<IRawElementProviderSimple*>(node_win); return S_OK; } // // ISelectionProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::GetSelection(SAFEARRAY** result) { UIA_VALIDATE_CALL_1_ARG(result); std::vector<AXPlatformNodeBase*> selected_children; int max_items = GetMaxSelectableItems(); if (max_items) GetSelectedItems(max_items, &selected_children); LONG selected_children_count = selected_children.size(); *result = SafeArrayCreateVector(VT_UNKNOWN, 0, selected_children_count); if (!*result) return E_OUTOFMEMORY; for (LONG i = 0; i < selected_children_count; ++i) { AXPlatformNodeWin* children = static_cast<AXPlatformNodeWin*>(selected_children[i]); HRESULT hr = SafeArrayPutElement( *result, &i, static_cast<IRawElementProviderSimple*>(children)); if (FAILED(hr)) { SafeArrayDestroy(*result); *result = nullptr; return hr; } } return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_CanSelectMultiple(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = GetData().HasState(ax::mojom::State::kMultiselectable); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_IsSelectionRequired(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = GetData().HasState(ax::mojom::State::kRequired); return S_OK; } // // ITableItemProvider methods. // IFACEMETHODIMP AXPlatformNodeWin::GetColumnHeaderItems(SAFEARRAY** result) { UIA_VALIDATE_CALL_1_ARG(result); std::optional<int> column = GetTableColumn(); if (!column) return E_FAIL; std::vector<int32_t> column_header_ids = GetDelegate()->GetColHeaderNodeIds(*column); std::vector<AXPlatformNodeWin*> platform_node_list = CreatePlatformNodeVectorFromRelationIdVector(column_header_ids); *result = CreateUIAElementsSafeArray(platform_node_list); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::GetRowHeaderItems(SAFEARRAY** result) { UIA_VALIDATE_CALL_1_ARG(result); std::optional<int> row = GetTableRow(); if (!row) return E_FAIL; std::vector<int32_t> row_header_ids = GetDelegate()->GetRowHeaderNodeIds(*row); std::vector<AXPlatformNodeWin*> platform_node_list = CreatePlatformNodeVectorFromRelationIdVector(row_header_ids); *result = CreateUIAElementsSafeArray(platform_node_list); return S_OK; } // // ITableProvider methods. // IFACEMETHODIMP AXPlatformNodeWin::GetColumnHeaders(SAFEARRAY** result) { UIA_VALIDATE_CALL_1_ARG(result); std::vector<int32_t> column_header_ids = GetDelegate()->GetColHeaderNodeIds(); std::vector<AXPlatformNodeWin*> platform_node_list = CreatePlatformNodeVectorFromRelationIdVector(column_header_ids); *result = CreateUIAElementsSafeArray(platform_node_list); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::GetRowHeaders(SAFEARRAY** result) { UIA_VALIDATE_CALL_1_ARG(result); std::vector<int32_t> row_header_ids = GetDelegate()->GetRowHeaderNodeIds(); std::vector<AXPlatformNodeWin*> platform_node_list = CreatePlatformNodeVectorFromRelationIdVector(row_header_ids); *result = CreateUIAElementsSafeArray(platform_node_list); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_RowOrColumnMajor( RowOrColumnMajor* result) { UIA_VALIDATE_CALL_1_ARG(result); // Tables and ARIA grids are always in row major order // see AXPlatformNodeBase::GetTableCell *result = RowOrColumnMajor_RowMajor; return S_OK; } // // IToggleProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::Toggle() { UIA_VALIDATE_CALL(); AXActionData action_data; action_data.action = ax::mojom::Action::kDoDefault; if (GetDelegate()->AccessibilityPerformAction(action_data)) return S_OK; return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::get_ToggleState(ToggleState* result) { UIA_VALIDATE_CALL_1_ARG(result); const auto checked_state = GetData().GetCheckedState(); if (checked_state == ax::mojom::CheckedState::kTrue) { *result = ToggleState_On; } else if (checked_state == ax::mojom::CheckedState::kMixed) { *result = ToggleState_Indeterminate; } else { *result = ToggleState_Off; } return S_OK; } // // IValueProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::SetValue(LPCWSTR value) { UIA_VALIDATE_CALL(); if (!value) return E_INVALIDARG; if (GetData().IsReadOnlyOrDisabled()) return UIA_E_ELEMENTNOTENABLED; AXActionData data; data.action = ax::mojom::Action::kSetValue; data.value = base::UTF16ToUTF8(fml::WideStringToUtf16(value)); if (GetDelegate()->AccessibilityPerformAction(data)) return S_OK; return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::get_IsReadOnly(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = GetData().IsReadOnlyOrDisabled(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_Value(BSTR* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = GetValueAttributeAsBstr(this); return S_OK; } // // IWindowProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::SetVisualState( WindowVisualState window_visual_state) { UIA_VALIDATE_CALL(); return UIA_E_NOTSUPPORTED; } IFACEMETHODIMP AXPlatformNodeWin::Close() { UIA_VALIDATE_CALL(); return UIA_E_NOTSUPPORTED; } IFACEMETHODIMP AXPlatformNodeWin::WaitForInputIdle(int milliseconds, BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); return UIA_E_NOTSUPPORTED; } IFACEMETHODIMP AXPlatformNodeWin::get_CanMaximize(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); return UIA_E_NOTSUPPORTED; } IFACEMETHODIMP AXPlatformNodeWin::get_CanMinimize(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); return UIA_E_NOTSUPPORTED; } IFACEMETHODIMP AXPlatformNodeWin::get_IsModal(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); *result = GetBoolAttribute(ax::mojom::BoolAttribute::kModal); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_WindowVisualState( WindowVisualState* result) { UIA_VALIDATE_CALL_1_ARG(result); return UIA_E_NOTSUPPORTED; } IFACEMETHODIMP AXPlatformNodeWin::get_WindowInteractionState( WindowInteractionState* result) { UIA_VALIDATE_CALL_1_ARG(result); return UIA_E_NOTSUPPORTED; } IFACEMETHODIMP AXPlatformNodeWin::get_IsTopmost(BOOL* result) { UIA_VALIDATE_CALL_1_ARG(result); return UIA_E_NOTSUPPORTED; } // // IRangeValueProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::SetValue(double value) { UIA_VALIDATE_CALL(); AXActionData data; data.action = ax::mojom::Action::kSetValue; data.value = base::NumberToString(value); if (GetDelegate()->AccessibilityPerformAction(data)) return S_OK; return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::get_LargeChange(double* result) { UIA_VALIDATE_CALL_1_ARG(result); float attribute; if (GetFloatAttribute(ax::mojom::FloatAttribute::kStepValueForRange, &attribute)) { *result = attribute * kLargeChangeScaleFactor; return S_OK; } return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::get_Maximum(double* result) { UIA_VALIDATE_CALL_1_ARG(result); float attribute; if (GetFloatAttribute(ax::mojom::FloatAttribute::kMaxValueForRange, &attribute)) { *result = attribute; return S_OK; } return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::get_Minimum(double* result) { UIA_VALIDATE_CALL_1_ARG(result); float attribute; if (GetFloatAttribute(ax::mojom::FloatAttribute::kMinValueForRange, &attribute)) { *result = attribute; return S_OK; } return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::get_SmallChange(double* result) { UIA_VALIDATE_CALL_1_ARG(result); float attribute; if (GetFloatAttribute(ax::mojom::FloatAttribute::kStepValueForRange, &attribute)) { *result = attribute; return S_OK; } return E_FAIL; } IFACEMETHODIMP AXPlatformNodeWin::get_Value(double* result) { UIA_VALIDATE_CALL_1_ARG(result); float attribute; if (GetFloatAttribute(ax::mojom::FloatAttribute::kValueForRange, &attribute)) { *result = attribute; return S_OK; } return E_FAIL; } // // IRawElementProviderFragment implementation. // IFACEMETHODIMP AXPlatformNodeWin::Navigate( NavigateDirection direction, IRawElementProviderFragment** element_provider) { UIA_VALIDATE_CALL_1_ARG(element_provider); *element_provider = nullptr; // // Navigation to a fragment root node: // // In order for the platform-neutral accessibility tree to support IA2 and UIA // simultaneously, we handle navigation to and from fragment roots in UIA // specific code. Consider the following platform-neutral tree: // // N1 // _____/ \_____ // / \ // N2---N3---N4---N5 // / \ / \ // N6---N7 N8---N9 // // N3 and N5 are nodes for which we need a fragment root. This will correspond // to the following tree in UIA: // // U1 // _____/ \_____ // / \ // U2---R3---U4---R5 // | | // U3 U5 // / \ / \ // U6---U7 U8---U9 // // Ux is the platform node for Nx. // R3 and R5 are the fragment root nodes for U3 and U5 respectively. // // Navigation has the following behaviors: // // 1. Parent navigation: If source node Ux is the child of a fragment root, // return Rx. Otherwise, consult the platform-neutral tree. // 2. First/last child navigation: If target node Ux is the child of a // fragment root and the source node isn't Rx, return Rx. Otherwise, return // Ux. // 3. Next/previous sibling navigation: // a. If source node Ux is the child of a fragment root, return nullptr. // b. If target node Ux is the child of a fragment root, return Rx. // Otherwise, return Ux. // // Note that the condition in 3b is a special case of the condition in 2. In // 3b, the source node is never Rx. So in the code, we collapse them to a // common implementation. // // Navigation from an Rx node is set up by delegate APIs on AXFragmentRootWin. // gfx::NativeViewAccessible neighbor = nullptr; switch (direction) { case NavigateDirection_Parent: { // 1. If source node Ux is the child of a fragment root, return Rx. // Otherwise, consult the platform-neutral tree. AXFragmentRootWin* fragment_root = AXFragmentRootWin::GetFragmentRootParentOf(GetNativeViewAccessible()); if (BASE_UNLIKELY(fragment_root)) { neighbor = fragment_root->GetNativeViewAccessible(); } else { neighbor = GetParent(); } } break; case NavigateDirection_FirstChild: if (GetChildCount() > 0) neighbor = GetFirstChild()->GetNativeViewAccessible(); break; case NavigateDirection_LastChild: if (GetChildCount() > 0) neighbor = GetLastChild()->GetNativeViewAccessible(); break; case NavigateDirection_NextSibling: // 3a. If source node Ux is the child of a fragment root, return nullptr. if (AXFragmentRootWin::GetFragmentRootParentOf( GetNativeViewAccessible()) == nullptr) { AXPlatformNodeBase* neighbor_node = GetNextSibling(); if (neighbor_node) neighbor = neighbor_node->GetNativeViewAccessible(); } break; case NavigateDirection_PreviousSibling: // 3a. If source node Ux is the child of a fragment root, return nullptr. if (AXFragmentRootWin::GetFragmentRootParentOf( GetNativeViewAccessible()) == nullptr) { AXPlatformNodeBase* neighbor_node = GetPreviousSibling(); if (neighbor_node) neighbor = neighbor_node->GetNativeViewAccessible(); } break; default: BASE_UNREACHABLE(); break; } if (neighbor) { if (direction != NavigateDirection_Parent) { // 2 / 3b. If target node Ux is the child of a fragment root and the // source node isn't Rx, return Rx. AXFragmentRootWin* fragment_root = AXFragmentRootWin::GetFragmentRootParentOf(neighbor); if (BASE_UNLIKELY(fragment_root && fragment_root != GetDelegate())) neighbor = fragment_root->GetNativeViewAccessible(); } neighbor->QueryInterface(IID_PPV_ARGS(element_provider)); } return S_OK; } void AXPlatformNodeWin::GetRuntimeIdArray( AXPlatformNodeWin::RuntimeIdArray& runtime_id) { runtime_id[0] = UiaAppendRuntimeId; runtime_id[1] = GetUniqueId(); } IFACEMETHODIMP AXPlatformNodeWin::GetRuntimeId(SAFEARRAY** runtime_id) { UIA_VALIDATE_CALL_1_ARG(runtime_id); RuntimeIdArray id_array; GetRuntimeIdArray(id_array); *runtime_id = ::SafeArrayCreateVector(VT_I4, 0, id_array.size()); int* array_data = nullptr; ::SafeArrayAccessData(*runtime_id, reinterpret_cast<void**>(&array_data)); size_t runtime_id_byte_count = id_array.size() * sizeof(int); memcpy_s(array_data, runtime_id_byte_count, id_array.data(), runtime_id_byte_count); ::SafeArrayUnaccessData(*runtime_id); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_BoundingRectangle( UiaRect* screen_physical_pixel_bounds) { UIA_VALIDATE_CALL_1_ARG(screen_physical_pixel_bounds); gfx::Rect bounds = delegate_->GetBoundsRect(AXCoordinateSystem::kScreenPhysicalPixels, AXClippingBehavior::kUnclipped); screen_physical_pixel_bounds->left = bounds.x(); screen_physical_pixel_bounds->top = bounds.y(); screen_physical_pixel_bounds->width = bounds.width(); screen_physical_pixel_bounds->height = bounds.height(); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::GetEmbeddedFragmentRoots( SAFEARRAY** embedded_fragment_roots) { UIA_VALIDATE_CALL_1_ARG(embedded_fragment_roots); *embedded_fragment_roots = nullptr; return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::SetFocus() { UIA_VALIDATE_CALL(); AXActionData action_data; action_data.action = ax::mojom::Action::kFocus; delegate_->AccessibilityPerformAction(action_data); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_FragmentRoot( IRawElementProviderFragmentRoot** fragment_root) { UIA_VALIDATE_CALL_1_ARG(fragment_root); gfx::AcceleratedWidget widget = delegate_->GetTargetForNativeAccessibilityEvent(); if (widget) { AXFragmentRootWin* root = AXFragmentRootWin::GetForAcceleratedWidget(widget); if (root != nullptr) { root->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(fragment_root)); BASE_DCHECK(*fragment_root); return S_OK; } } *fragment_root = nullptr; return UIA_E_ELEMENTNOTAVAILABLE; } // // IRawElementProviderSimple implementation. // IFACEMETHODIMP AXPlatformNodeWin::GetPatternProvider(PATTERNID pattern_id, IUnknown** result) { return GetPatternProviderImpl(pattern_id, result); } HRESULT AXPlatformNodeWin::GetPatternProviderImpl(PATTERNID pattern_id, IUnknown** result) { UIA_VALIDATE_CALL_1_ARG(result); *result = nullptr; PatternProviderFactoryMethod factory_method = GetPatternProviderFactoryMethod(pattern_id); if (factory_method) (*factory_method)(this, result); return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::GetPropertyValue(PROPERTYID property_id, VARIANT* result) { return GetPropertyValueImpl(property_id, result); } HRESULT AXPlatformNodeWin::GetPropertyValueImpl(PROPERTYID property_id, VARIANT* result) { UIA_VALIDATE_CALL_1_ARG(result); result->vt = VT_EMPTY; int int_attribute; const AXNodeData& data = GetData(); // Default UIA Property Ids. switch (property_id) { case UIA_AriaPropertiesPropertyId: result->vt = VT_BSTR; result->bstrVal = ::SysAllocString( fml::Utf16ToWideString(ComputeUIAProperties()).c_str()); break; case UIA_AriaRolePropertyId: result->vt = VT_BSTR; result->bstrVal = ::SysAllocString(fml::Utf16ToWideString(UIAAriaRole()).c_str()); break; case UIA_AutomationIdPropertyId: V_VT(result) = VT_BSTR; V_BSTR(result) = ::SysAllocString( fml::Utf16ToWideString(GetDelegate()->GetAuthorUniqueId()).c_str()); break; case UIA_ClassNamePropertyId: result->vt = VT_BSTR; GetStringAttributeAsBstr(ax::mojom::StringAttribute::kClassName, &result->bstrVal); break; case UIA_ClickablePointPropertyId: result->vt = VT_ARRAY | VT_R8; result->parray = CreateClickablePointArray(); break; case UIA_ControllerForPropertyId: result->vt = VT_ARRAY | VT_UNKNOWN; result->parray = CreateUIAControllerForArray(); break; case UIA_ControlTypePropertyId: result->vt = VT_I4; result->lVal = ComputeUIAControlType(); break; case UIA_CulturePropertyId: { std::optional<LCID> lcid = GetCultureAttributeAsLCID(); if (!lcid) return E_FAIL; result->vt = VT_I4; result->lVal = lcid.value(); break; } case UIA_DescribedByPropertyId: result->vt = VT_ARRAY | VT_UNKNOWN; result->parray = CreateUIAElementsArrayForRelation( ax::mojom::IntListAttribute::kDescribedbyIds); break; case UIA_FlowsFromPropertyId: V_VT(result) = VT_ARRAY | VT_UNKNOWN; V_ARRAY(result) = CreateUIAElementsArrayForReverseRelation( ax::mojom::IntListAttribute::kFlowtoIds); break; case UIA_FlowsToPropertyId: result->vt = VT_ARRAY | VT_UNKNOWN; result->parray = CreateUIAElementsArrayForRelation( ax::mojom::IntListAttribute::kFlowtoIds); break; case UIA_FrameworkIdPropertyId: V_VT(result) = VT_BSTR; V_BSTR(result) = SysAllocString(FRAMEWORK_ID); break; case UIA_HasKeyboardFocusPropertyId: result->vt = VT_BOOL; result->boolVal = (delegate_->GetFocus() == GetNativeViewAccessible()) ? VARIANT_TRUE : VARIANT_FALSE; break; case UIA_FullDescriptionPropertyId: result->vt = VT_BSTR; GetStringAttributeAsBstr(ax::mojom::StringAttribute::kDescription, &result->bstrVal); break; case UIA_HelpTextPropertyId: if (HasStringAttribute(ax::mojom::StringAttribute::kPlaceholder)) { V_VT(result) = VT_BSTR; GetStringAttributeAsBstr(ax::mojom::StringAttribute::kPlaceholder, &V_BSTR(result)); } else if (data.GetNameFrom() == ax::mojom::NameFrom::kPlaceholder || data.GetNameFrom() == ax::mojom::NameFrom::kTitle) { V_VT(result) = VT_BSTR; GetNameAsBstr(&V_BSTR(result)); } else if (HasStringAttribute(ax::mojom::StringAttribute::kTooltip)) { V_VT(result) = VT_BSTR; GetStringAttributeAsBstr(ax::mojom::StringAttribute::kTooltip, &V_BSTR(result)); } break; case UIA_IsContentElementPropertyId: case UIA_IsControlElementPropertyId: result->vt = VT_BOOL; result->boolVal = IsUIAControl() ? VARIANT_TRUE : VARIANT_FALSE; break; case UIA_IsDataValidForFormPropertyId: if (data.GetIntAttribute(ax::mojom::IntAttribute::kInvalidState, &int_attribute)) { result->vt = VT_BOOL; result->boolVal = (static_cast<int>(ax::mojom::InvalidState::kFalse) == int_attribute) ? VARIANT_TRUE : VARIANT_FALSE; } break; case UIA_IsDialogPropertyId: result->vt = VT_BOOL; result->boolVal = IsDialog(data.role) ? VARIANT_TRUE : VARIANT_FALSE; break; case UIA_IsKeyboardFocusablePropertyId: result->vt = VT_BOOL; result->boolVal = ShouldNodeHaveFocusableState(data) ? VARIANT_TRUE : VARIANT_FALSE; break; case UIA_IsOffscreenPropertyId: result->vt = VT_BOOL; result->boolVal = GetDelegate()->IsOffscreen() ? VARIANT_TRUE : VARIANT_FALSE; break; case UIA_IsRequiredForFormPropertyId: result->vt = VT_BOOL; if (data.HasState(ax::mojom::State::kRequired)) { result->boolVal = VARIANT_TRUE; } else { result->boolVal = VARIANT_FALSE; } break; case UIA_ItemStatusPropertyId: { // https://www.w3.org/TR/core-aam-1.1/#mapping_state-property_table // aria-sort='ascending|descending|other' is mapped for the // HeaderItem Control Type. int32_t sort_direction; if (IsTableHeader(data.role) && GetIntAttribute(ax::mojom::IntAttribute::kSortDirection, &sort_direction)) { switch (static_cast<ax::mojom::SortDirection>(sort_direction)) { case ax::mojom::SortDirection::kNone: case ax::mojom::SortDirection::kUnsorted: break; case ax::mojom::SortDirection::kAscending: V_VT(result) = VT_BSTR; V_BSTR(result) = SysAllocString(L"ascending"); break; case ax::mojom::SortDirection::kDescending: V_VT(result) = VT_BSTR; V_BSTR(result) = SysAllocString(L"descending"); break; case ax::mojom::SortDirection::kOther: V_VT(result) = VT_BSTR; V_BSTR(result) = SysAllocString(L"other"); break; } } break; } case UIA_LabeledByPropertyId: if (AXPlatformNodeWin* node = ComputeUIALabeledBy()) { result->vt = VT_UNKNOWN; result->punkVal = node->GetNativeViewAccessible(); result->punkVal->AddRef(); } break; case UIA_LocalizedControlTypePropertyId: { std::u16string localized_control_type = GetRoleDescription(); if (!localized_control_type.empty()) { result->vt = VT_BSTR; result->bstrVal = ::SysAllocString( fml::Utf16ToWideString(localized_control_type).c_str()); } // If a role description has not been provided, leave as VT_EMPTY. // UIA core handles Localized Control type for some built-in types and // also has a mapping for ARIA roles. To get these defaults, we need to // have returned VT_EMPTY. } break; case UIA_NamePropertyId: if (IsNameExposed()) { result->vt = VT_BSTR; GetNameAsBstr(&result->bstrVal); } break; case UIA_OrientationPropertyId: if (SupportsOrientation(data.role)) { if (data.HasState(ax::mojom::State::kHorizontal) && data.HasState(ax::mojom::State::kVertical)) { BASE_UNREACHABLE(); // << "An accessibility object cannot have a // horizontal " //"and a vertical orientation at the same time."; } if (data.HasState(ax::mojom::State::kHorizontal)) { result->vt = VT_I4; result->intVal = OrientationType_Horizontal; } if (data.HasState(ax::mojom::State::kVertical)) { result->vt = VT_I4; result->intVal = OrientationType_Vertical; } } else { result->vt = VT_I4; result->intVal = OrientationType_None; } break; case UIA_IsEnabledPropertyId: V_VT(result) = VT_BOOL; switch (data.GetRestriction()) { case ax::mojom::Restriction::kDisabled: V_BOOL(result) = VARIANT_FALSE; break; case ax::mojom::Restriction::kNone: case ax::mojom::Restriction::kReadOnly: V_BOOL(result) = VARIANT_TRUE; break; } break; case UIA_IsPasswordPropertyId: result->vt = VT_BOOL; result->boolVal = data.HasState(ax::mojom::State::kProtected) ? VARIANT_TRUE : VARIANT_FALSE; break; case UIA_AcceleratorKeyPropertyId: if (data.HasStringAttribute(ax::mojom::StringAttribute::kKeyShortcuts)) { result->vt = VT_BSTR; GetStringAttributeAsBstr(ax::mojom::StringAttribute::kKeyShortcuts, &result->bstrVal); } break; case UIA_AccessKeyPropertyId: if (data.HasStringAttribute(ax::mojom::StringAttribute::kAccessKey)) { result->vt = VT_BSTR; GetStringAttributeAsBstr(ax::mojom::StringAttribute::kAccessKey, &result->bstrVal); } break; case UIA_IsPeripheralPropertyId: result->vt = VT_BOOL; result->boolVal = VARIANT_FALSE; break; case UIA_LevelPropertyId: if (data.GetIntAttribute(ax::mojom::IntAttribute::kHierarchicalLevel, &int_attribute)) { result->vt = VT_I4; result->intVal = int_attribute; } break; case UIA_LiveSettingPropertyId: { result->vt = VT_I4; result->intVal = LiveSetting::Off; std::string string_attribute; if (data.GetStringAttribute(ax::mojom::StringAttribute::kLiveStatus, &string_attribute)) { if (string_attribute == "polite") result->intVal = LiveSetting::Polite; else if (string_attribute == "assertive") result->intVal = LiveSetting::Assertive; } break; } case UIA_OptimizeForVisualContentPropertyId: result->vt = VT_BOOL; result->boolVal = VARIANT_FALSE; break; case UIA_PositionInSetPropertyId: { std::optional<int> pos_in_set = GetPosInSet(); if (pos_in_set) { result->vt = VT_I4; result->intVal = *pos_in_set; } } break; case UIA_ScrollHorizontalScrollPercentPropertyId: { V_VT(result) = VT_R8; V_R8(result) = GetHorizontalScrollPercent(); break; } case UIA_ScrollVerticalScrollPercentPropertyId: { V_VT(result) = VT_R8; V_R8(result) = GetVerticalScrollPercent(); break; } case UIA_SizeOfSetPropertyId: { std::optional<int> set_size = GetSetSize(); if (set_size) { result->vt = VT_I4; result->intVal = *set_size; } break; } case UIA_LandmarkTypePropertyId: { std::optional<LONG> landmark_type = ComputeUIALandmarkType(); if (landmark_type) { result->vt = VT_I4; result->intVal = landmark_type.value(); } break; } case UIA_LocalizedLandmarkTypePropertyId: { std::u16string localized_landmark_type = GetDelegate()->GetLocalizedStringForLandmarkType(); if (!localized_landmark_type.empty()) { result->vt = VT_BSTR; result->bstrVal = ::SysAllocString( fml::Utf16ToWideString(localized_landmark_type).c_str()); } break; } case UIA_ExpandCollapseExpandCollapseStatePropertyId: result->vt = VT_I4; result->intVal = static_cast<int>(ComputeExpandCollapseState()); break; case UIA_ToggleToggleStatePropertyId: { ToggleState state; get_ToggleState(&state); result->vt = VT_I4; result->lVal = state; break; } case UIA_ValueValuePropertyId: result->vt = VT_BSTR; result->bstrVal = GetValueAttributeAsBstr(this); break; // Not currently implemented. case UIA_AnnotationObjectsPropertyId: case UIA_AnnotationTypesPropertyId: case UIA_CenterPointPropertyId: case UIA_FillColorPropertyId: case UIA_FillTypePropertyId: case UIA_HeadingLevelPropertyId: case UIA_ItemTypePropertyId: case UIA_OutlineColorPropertyId: case UIA_OutlineThicknessPropertyId: case UIA_RotationPropertyId: case UIA_SizePropertyId: case UIA_VisualEffectsPropertyId: break; // Provided by UIA Core; we should not implement. case UIA_BoundingRectanglePropertyId: case UIA_NativeWindowHandlePropertyId: case UIA_ProcessIdPropertyId: case UIA_ProviderDescriptionPropertyId: case UIA_RuntimeIdPropertyId: break; } // End of default UIA property ids. // Custom UIA Property Ids. if (property_id == UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId()) { // We want to negate the unique id for it to be consistent across different // Windows accessiblity APIs. The negative unique id convention originated // from ::NotifyWinEvent() takes an hwnd and a child id. A 0 child id means // self, and a positive child id means child #n. In order to fire an event // for an arbitrary descendant of the window, Firefox started the practice // of using a negative unique id. We follow the same negative unique id // convention here and when we fire events via ::NotifyWinEvent(). result->vt = VT_BSTR; result->bstrVal = ::SysAllocString( fml::Utf16ToWideString(base::NumberToString16(-GetUniqueId())).c_str()); } return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_ProviderOptions(ProviderOptions* ret) { UIA_VALIDATE_CALL_1_ARG(ret); *ret = ProviderOptions_ServerSideProvider | ProviderOptions_UseComThreading | ProviderOptions_RefuseNonClientSupport | ProviderOptions_HasNativeIAccessible; return S_OK; } IFACEMETHODIMP AXPlatformNodeWin::get_HostRawElementProvider( IRawElementProviderSimple** provider) { UIA_VALIDATE_CALL_1_ARG(provider); *provider = nullptr; return S_OK; } // // IRawElementProviderSimple2 implementation. // IFACEMETHODIMP AXPlatformNodeWin::ShowContextMenu() { UIA_VALIDATE_CALL(); AXActionData action_data; action_data.action = ax::mojom::Action::kShowContextMenu; delegate_->AccessibilityPerformAction(action_data); return S_OK; } // // IServiceProvider implementation. // IFACEMETHODIMP AXPlatformNodeWin::QueryService(REFGUID guidService, REFIID riid, void** object) { COM_OBJECT_VALIDATE_1_ARG(object); if (guidService == IID_IAccessible) { return QueryInterface(riid, object); } // TODO(suproteem): Include IAccessibleEx in the list, potentially checking // for version. *object = nullptr; return E_FAIL; } // // Methods used by the ATL COM map. // // static STDMETHODIMP AXPlatformNodeWin::InternalQueryInterface( void* this_ptr, const _ATL_INTMAP_ENTRY* entries, REFIID riid, void** object) { if (!object) return E_INVALIDARG; *object = nullptr; AXPlatformNodeWin* accessible = reinterpret_cast<AXPlatformNodeWin*>(this_ptr); BASE_DCHECK(accessible); return CComObjectRootBase::InternalQueryInterface(this_ptr, entries, riid, object); } HRESULT AXPlatformNodeWin::GetTextAttributeValue( TEXTATTRIBUTEID attribute_id, const std::optional<int>& start_offset, const std::optional<int>& end_offset, base::win::VariantVector* result) { BASE_DCHECK(!start_offset || start_offset.value() >= 0); BASE_DCHECK(!end_offset || end_offset.value() >= 0); switch (attribute_id) { case UIA_AnnotationTypesAttributeId: return GetAnnotationTypesAttribute(start_offset, end_offset, result); case UIA_BackgroundColorAttributeId: result->Insert<VT_I4>( GetIntAttributeAsCOLORREF(ax::mojom::IntAttribute::kBackgroundColor)); break; case UIA_BulletStyleAttributeId: result->Insert<VT_I4>(ComputeUIABulletStyle()); break; case UIA_CultureAttributeId: { std::optional<LCID> lcid = GetCultureAttributeAsLCID(); if (!lcid) return E_FAIL; result->Insert<VT_I4>(lcid.value()); break; } case UIA_FontNameAttributeId: result->Insert<VT_BSTR>(GetFontNameAttributeAsBSTR()); break; case UIA_FontSizeAttributeId: { std::optional<float> font_size_in_points = GetFontSizeInPoints(); if (font_size_in_points) { result->Insert<VT_R8>(*font_size_in_points); } break; } case UIA_FontWeightAttributeId: result->Insert<VT_I4>( GetFloatAttribute(ax::mojom::FloatAttribute::kFontWeight)); break; case UIA_ForegroundColorAttributeId: result->Insert<VT_I4>( GetIntAttributeAsCOLORREF(ax::mojom::IntAttribute::kColor)); break; case UIA_IsHiddenAttributeId: result->Insert<VT_BOOL>(IsInvisibleOrIgnored()); break; case UIA_IsItalicAttributeId: result->Insert<VT_BOOL>( GetData().HasTextStyle(ax::mojom::TextStyle::kItalic)); break; case UIA_IsReadOnlyAttributeId: // Placeholder text should return the enclosing element's read-only value. if (IsPlaceholderText()) { AXPlatformNodeWin* parent_platform_node = static_cast<AXPlatformNodeWin*>( FromNativeViewAccessible(GetParent())); return parent_platform_node->GetTextAttributeValue( attribute_id, start_offset, end_offset, result); } result->Insert<VT_BOOL>(GetData().IsReadOnlyOrDisabled()); break; case UIA_IsSubscriptAttributeId: result->Insert<VT_BOOL>(GetData().GetTextPosition() == ax::mojom::TextPosition::kSubscript); break; case UIA_IsSuperscriptAttributeId: result->Insert<VT_BOOL>(GetData().GetTextPosition() == ax::mojom::TextPosition::kSuperscript); break; case UIA_OverlineStyleAttributeId: result->Insert<VT_I4>(GetUIATextDecorationStyle( ax::mojom::IntAttribute::kTextOverlineStyle)); break; case UIA_StrikethroughStyleAttributeId: result->Insert<VT_I4>(GetUIATextDecorationStyle( ax::mojom::IntAttribute::kTextStrikethroughStyle)); break; case UIA_StyleNameAttributeId: result->Insert<VT_BSTR>(GetStyleNameAttributeAsBSTR()); break; case UIA_StyleIdAttributeId: result->Insert<VT_I4>(ComputeUIAStyleId()); break; case UIA_HorizontalTextAlignmentAttributeId: { std::optional<HorizontalTextAlignment> horizontal_text_alignment = AXTextAlignToUIAHorizontalTextAlignment(GetData().GetTextAlign()); if (horizontal_text_alignment) result->Insert<VT_I4>(*horizontal_text_alignment); break; } case UIA_UnderlineStyleAttributeId: result->Insert<VT_I4>(GetUIATextDecorationStyle( ax::mojom::IntAttribute::kTextUnderlineStyle)); break; case UIA_TextFlowDirectionsAttributeId: result->Insert<VT_I4>( TextDirectionToFlowDirections(GetData().GetTextDirection())); break; default: { Microsoft::WRL::ComPtr<IUnknown> not_supported_value; HRESULT hr = ::UiaGetReservedNotSupportedValue(&not_supported_value); if (SUCCEEDED(hr)) result->Insert<VT_UNKNOWN>(not_supported_value.Get()); return hr; } break; } return S_OK; } HRESULT AXPlatformNodeWin::GetAnnotationTypesAttribute( const std::optional<int>& start_offset, const std::optional<int>& end_offset, base::win::VariantVector* result) { base::win::VariantVector variant_vector; MarkerTypeRangeResult grammar_result = MarkerTypeRangeResult::kNone; MarkerTypeRangeResult spelling_result = MarkerTypeRangeResult::kNone; if (IsText() || IsPlainTextField()) { grammar_result = GetMarkerTypeFromRange(start_offset, end_offset, ax::mojom::MarkerType::kGrammar); spelling_result = GetMarkerTypeFromRange(start_offset, end_offset, ax::mojom::MarkerType::kSpelling); } if (grammar_result == MarkerTypeRangeResult::kMixed || spelling_result == MarkerTypeRangeResult::kMixed) { Microsoft::WRL::ComPtr<IUnknown> mixed_attribute_value; HRESULT hr = ::UiaGetReservedMixedAttributeValue(&mixed_attribute_value); if (SUCCEEDED(hr)) result->Insert<VT_UNKNOWN>(mixed_attribute_value.Get()); return hr; } if (spelling_result == MarkerTypeRangeResult::kMatch) result->Insert<VT_I4>(AnnotationType_SpellingError); if (grammar_result == MarkerTypeRangeResult::kMatch) result->Insert<VT_I4>(AnnotationType_GrammarError); return S_OK; } std::optional<LCID> AXPlatformNodeWin::GetCultureAttributeAsLCID() const { const std::u16string language = GetInheritedString16Attribute(ax::mojom::StringAttribute::kLanguage); const LCID lcid = LocaleNameToLCID((wchar_t*)language.c_str(), LOCALE_ALLOW_NEUTRAL_NAMES); if (!lcid) return std::nullopt; return lcid; } COLORREF AXPlatformNodeWin::GetIntAttributeAsCOLORREF( ax::mojom::IntAttribute attribute) const { uint32_t color = GetIntAttribute(attribute); // From skia_utils_win.cc return (_byteswap_ulong(color) >> 8); } BulletStyle AXPlatformNodeWin::ComputeUIABulletStyle() const { // UIA expects the list style of a non-list-item to be none however the // default list style cascaded is disc not none. Therefore we must ensure that // this node is contained within a list-item to distinguish non-list-items and // disc styled list items. const AXPlatformNodeBase* current_node = this; while (current_node && current_node->GetData().role != ax::mojom::Role::kListItem) { current_node = FromNativeViewAccessible(current_node->GetParent()); } const ax::mojom::ListStyle list_style = current_node ? current_node->GetData().GetListStyle() : ax::mojom::ListStyle::kNone; switch (list_style) { case ax::mojom::ListStyle::kNone: return BulletStyle::BulletStyle_None; case ax::mojom::ListStyle::kCircle: return BulletStyle::BulletStyle_HollowRoundBullet; case ax::mojom::ListStyle::kDisc: return BulletStyle::BulletStyle_FilledRoundBullet; case ax::mojom::ListStyle::kImage: return BulletStyle::BulletStyle_Other; case ax::mojom::ListStyle::kNumeric: case ax::mojom::ListStyle::kOther: return BulletStyle::BulletStyle_None; case ax::mojom::ListStyle::kSquare: return BulletStyle::BulletStyle_FilledSquareBullet; } } LONG AXPlatformNodeWin::ComputeUIAStyleId() const { const AXPlatformNodeBase* current_node = this; do { switch (current_node->GetData().role) { case ax::mojom::Role::kHeading: return AXHierarchicalLevelToUIAStyleId(current_node->GetIntAttribute( ax::mojom::IntAttribute::kHierarchicalLevel)); case ax::mojom::Role::kListItem: return AXListStyleToUIAStyleId(current_node->GetData().GetListStyle()); case ax::mojom::Role::kMark: return StyleId_Custom; case ax::mojom::Role::kBlockquote: return StyleId_Quote; default: break; } current_node = FromNativeViewAccessible(current_node->GetParent()); } while (current_node); return StyleId_Normal; } // static std::optional<HorizontalTextAlignment> AXPlatformNodeWin::AXTextAlignToUIAHorizontalTextAlignment( ax::mojom::TextAlign text_align) { switch (text_align) { case ax::mojom::TextAlign::kNone: return std::nullopt; case ax::mojom::TextAlign::kLeft: return HorizontalTextAlignment_Left; case ax::mojom::TextAlign::kRight: return HorizontalTextAlignment_Right; case ax::mojom::TextAlign::kCenter: return HorizontalTextAlignment_Centered; case ax::mojom::TextAlign::kJustify: return HorizontalTextAlignment_Justified; } } // static LONG AXPlatformNodeWin::AXHierarchicalLevelToUIAStyleId( int32_t hierarchical_level) { switch (hierarchical_level) { case 0: return StyleId_Normal; case 1: return StyleId_Heading1; case 2: return StyleId_Heading2; case 3: return StyleId_Heading3; case 4: return StyleId_Heading4; case 5: return StyleId_Heading5; case 6: return StyleId_Heading6; case 7: return StyleId_Heading7; case 8: return StyleId_Heading8; case 9: return StyleId_Heading9; default: return StyleId_Custom; } } // static LONG AXPlatformNodeWin::AXListStyleToUIAStyleId( ax::mojom::ListStyle list_style) { switch (list_style) { case ax::mojom::ListStyle::kNone: return StyleId_Normal; case ax::mojom::ListStyle::kCircle: case ax::mojom::ListStyle::kDisc: case ax::mojom::ListStyle::kImage: case ax::mojom::ListStyle::kSquare: return StyleId_BulletedList; case ax::mojom::ListStyle::kNumeric: case ax::mojom::ListStyle::kOther: return StyleId_NumberedList; } } // static FlowDirections AXPlatformNodeWin::TextDirectionToFlowDirections( ax::mojom::WritingDirection text_direction) { switch (text_direction) { case ax::mojom::WritingDirection::kNone: return FlowDirections::FlowDirections_Default; case ax::mojom::WritingDirection::kLtr: return FlowDirections::FlowDirections_Default; case ax::mojom::WritingDirection::kRtl: return FlowDirections::FlowDirections_RightToLeft; case ax::mojom::WritingDirection::kTtb: return FlowDirections::FlowDirections_Vertical; case ax::mojom::WritingDirection::kBtt: return FlowDirections::FlowDirections_BottomToTop; } } // static void AXPlatformNodeWin::AggregateRangesForMarkerType( AXPlatformNodeBase* node, ax::mojom::MarkerType marker_type, int offset_ranges_amount, std::vector<std::pair<int, int>>* ranges) { BASE_DCHECK(node->IsText()); const std::vector<int32_t>& marker_types = node->GetIntListAttribute(ax::mojom::IntListAttribute::kMarkerTypes); const std::vector<int>& marker_starts = node->GetIntListAttribute(ax::mojom::IntListAttribute::kMarkerStarts); const std::vector<int>& marker_ends = node->GetIntListAttribute(ax::mojom::IntListAttribute::kMarkerEnds); for (size_t i = 0; i < marker_types.size(); ++i) { if (static_cast<ax::mojom::MarkerType>(marker_types[i]) != marker_type) continue; const int marker_start = marker_starts[i] + offset_ranges_amount; const int marker_end = marker_ends[i] + offset_ranges_amount; ranges->emplace_back(std::make_pair(marker_start, marker_end)); } } AXPlatformNodeWin::MarkerTypeRangeResult AXPlatformNodeWin::GetMarkerTypeFromRange( const std::optional<int>& start_offset, const std::optional<int>& end_offset, ax::mojom::MarkerType marker_type) { BASE_DCHECK(IsText() || IsPlainTextField()); std::vector<std::pair<int, int>> relevant_ranges; if (IsText()) { AggregateRangesForMarkerType(this, marker_type, /*offset_ranges_amount=*/0, &relevant_ranges); } else if (IsPlainTextField()) { int offset_ranges_amount = 0; for (AXPlatformNodeBase* static_text = GetFirstTextOnlyDescendant(); static_text; static_text = static_text->GetNextSibling()) { const int child_offset_ranges_amount = offset_ranges_amount; if (start_offset || end_offset) { // Break if the current node is after the desired |end_offset|. if (end_offset && child_offset_ranges_amount > end_offset.value()) break; // Skip over nodes preceding the desired |start_offset|. offset_ranges_amount += static_text->GetHypertext().length(); if (start_offset && offset_ranges_amount < start_offset.value()) continue; } AggregateRangesForMarkerType(static_text, marker_type, child_offset_ranges_amount, &relevant_ranges); } } // Sort the ranges by their start offset. const auto sort_ranges_by_start_offset = [](const std::pair<int, int>& a, const std::pair<int, int>& b) { return a.first < b.first; }; std::sort(relevant_ranges.begin(), relevant_ranges.end(), sort_ranges_by_start_offset); // Validate that the desired range has a contiguous MarkerType. std::optional<std::pair<int, int>> contiguous_range; for (const std::pair<int, int>& range : relevant_ranges) { if (end_offset && range.first > end_offset.value()) break; if (start_offset && range.second < start_offset.value()) continue; if (!contiguous_range) { contiguous_range = range; continue; } // If there is a gap, then the range must be mixed. if ((range.first - contiguous_range->second) > 1) return MarkerTypeRangeResult::kMixed; // Expand the range if possible. contiguous_range->second = std::max(contiguous_range->second, range.second); } // The desired range does not overlap with |marker_type|. if (!contiguous_range) return MarkerTypeRangeResult::kNone; // If there is a partial overlap, then the desired range must be mixed. // 1. The |start_offset| is not specified, treat it as offset 0. if (!start_offset && contiguous_range->first > 0) return MarkerTypeRangeResult::kMixed; // 2. The |end_offset| is not specified, treat it as max text offset. if (!end_offset && contiguous_range->second < GetHypertext().length()) return MarkerTypeRangeResult::kMixed; // 3. The |start_offset| is specified, but is before the first matching range. if (start_offset && start_offset.value() < contiguous_range->first) return MarkerTypeRangeResult::kMixed; // 4. The |end_offset| is specified, but is after the last matching range. if (end_offset && end_offset.value() > contiguous_range->second) return MarkerTypeRangeResult::kMixed; // The desired range is a complete match for |marker_type|. return MarkerTypeRangeResult::kMatch; } // IRawElementProviderSimple support methods. bool AXPlatformNodeWin::IsPatternProviderSupported(PATTERNID pattern_id) { return GetPatternProviderFactoryMethod(pattern_id); } // // Private member functions. // int AXPlatformNodeWin::MSAARole() { // If this is a web area for a presentational iframe, give it a role of // something other than DOCUMENT so that the fact that it's a separate doc // is not exposed to AT. if (IsWebAreaForPresentationalIframe()) return ROLE_SYSTEM_GROUPING; switch (GetData().role) { case ax::mojom::Role::kAlert: return ROLE_SYSTEM_ALERT; case ax::mojom::Role::kAlertDialog: return ROLE_SYSTEM_DIALOG; case ax::mojom::Role::kAnchor: return ROLE_SYSTEM_LINK; case ax::mojom::Role::kComment: case ax::mojom::Role::kSuggestion: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kApplication: return ROLE_SYSTEM_APPLICATION; case ax::mojom::Role::kArticle: return ROLE_SYSTEM_DOCUMENT; case ax::mojom::Role::kAudio: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kBanner: case ax::mojom::Role::kHeader: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kBlockquote: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kButton: return ROLE_SYSTEM_PUSHBUTTON; case ax::mojom::Role::kCanvas: return ROLE_SYSTEM_GRAPHIC; case ax::mojom::Role::kCaption: return ROLE_SYSTEM_TEXT; case ax::mojom::Role::kCaret: return ROLE_SYSTEM_CARET; case ax::mojom::Role::kCell: return ROLE_SYSTEM_CELL; case ax::mojom::Role::kCheckBox: return ROLE_SYSTEM_CHECKBUTTON; case ax::mojom::Role::kClient: return ROLE_SYSTEM_PANE; case ax::mojom::Role::kColorWell: return ROLE_SYSTEM_TEXT; case ax::mojom::Role::kColumn: return ROLE_SYSTEM_COLUMN; case ax::mojom::Role::kColumnHeader: return ROLE_SYSTEM_COLUMNHEADER; case ax::mojom::Role::kComboBoxGrouping: case ax::mojom::Role::kComboBoxMenuButton: return ROLE_SYSTEM_COMBOBOX; case ax::mojom::Role::kComplementary: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kContentDeletion: case ax::mojom::Role::kContentInsertion: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kContentInfo: case ax::mojom::Role::kFooter: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kDate: case ax::mojom::Role::kDateTime: return ROLE_SYSTEM_DROPLIST; case ax::mojom::Role::kDefinition: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kDescriptionListDetail: return ROLE_SYSTEM_TEXT; case ax::mojom::Role::kDescriptionList: return ROLE_SYSTEM_LIST; case ax::mojom::Role::kDescriptionListTerm: return ROLE_SYSTEM_LISTITEM; case ax::mojom::Role::kDesktop: return ROLE_SYSTEM_PANE; case ax::mojom::Role::kDetails: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kDialog: return ROLE_SYSTEM_DIALOG; case ax::mojom::Role::kDisclosureTriangle: return ROLE_SYSTEM_PUSHBUTTON; case ax::mojom::Role::kDirectory: return ROLE_SYSTEM_LIST; case ax::mojom::Role::kDocCover: return ROLE_SYSTEM_GRAPHIC; case ax::mojom::Role::kDocBackLink: case ax::mojom::Role::kDocBiblioRef: case ax::mojom::Role::kDocGlossRef: case ax::mojom::Role::kDocNoteRef: return ROLE_SYSTEM_LINK; case ax::mojom::Role::kDocBiblioEntry: case ax::mojom::Role::kDocEndnote: case ax::mojom::Role::kDocFootnote: return ROLE_SYSTEM_LISTITEM; case ax::mojom::Role::kDocPageBreak: return ROLE_SYSTEM_SEPARATOR; case ax::mojom::Role::kDocAbstract: case ax::mojom::Role::kDocAcknowledgments: case ax::mojom::Role::kDocAfterword: case ax::mojom::Role::kDocAppendix: case ax::mojom::Role::kDocBibliography: case ax::mojom::Role::kDocChapter: case ax::mojom::Role::kDocColophon: case ax::mojom::Role::kDocConclusion: case ax::mojom::Role::kDocCredit: case ax::mojom::Role::kDocCredits: case ax::mojom::Role::kDocDedication: case ax::mojom::Role::kDocEndnotes: case ax::mojom::Role::kDocEpigraph: case ax::mojom::Role::kDocEpilogue: case ax::mojom::Role::kDocErrata: case ax::mojom::Role::kDocExample: case ax::mojom::Role::kDocForeword: case ax::mojom::Role::kDocGlossary: case ax::mojom::Role::kDocIndex: case ax::mojom::Role::kDocIntroduction: case ax::mojom::Role::kDocNotice: case ax::mojom::Role::kDocPageList: case ax::mojom::Role::kDocPart: case ax::mojom::Role::kDocPreface: case ax::mojom::Role::kDocPrologue: case ax::mojom::Role::kDocPullquote: case ax::mojom::Role::kDocQna: case ax::mojom::Role::kDocSubtitle: case ax::mojom::Role::kDocTip: case ax::mojom::Role::kDocToc: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kDocument: case ax::mojom::Role::kRootWebArea: case ax::mojom::Role::kWebArea: return ROLE_SYSTEM_DOCUMENT; case ax::mojom::Role::kEmbeddedObject: // Even though the HTML-AAM has ROLE_SYSTEM_CLIENT for <embed>, we are // forced to use ROLE_SYSTEM_GROUPING when the <embed> has children in the // accessibility tree. // https://www.w3.org/TR/html-aam-1.0/#html-element-role-mappings // // Screen readers Jaws and NVDA do not "see" any of the <embed>'s contents // if they are represented as its children in the accessibility tree. For // example, one of the places that would be negatively impacted is the // reading of PDFs. if (GetDelegate()->GetChildCount()) { return ROLE_SYSTEM_GROUPING; } else { return ROLE_SYSTEM_CLIENT; } case ax::mojom::Role::kFigcaption: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kFigure: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kFeed: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kFooterAsNonLandmark: case ax::mojom::Role::kHeaderAsNonLandmark: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kForm: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kGenericContainer: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kGraphicsDocument: return ROLE_SYSTEM_DOCUMENT; case ax::mojom::Role::kGraphicsObject: return ROLE_SYSTEM_PANE; case ax::mojom::Role::kGraphicsSymbol: return ROLE_SYSTEM_GRAPHIC; case ax::mojom::Role::kGrid: return ROLE_SYSTEM_TABLE; case ax::mojom::Role::kGroup: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kHeading: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kIframe: return ROLE_SYSTEM_DOCUMENT; case ax::mojom::Role::kIframePresentational: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kImage: case ax::mojom::Role::kImageMap: return ROLE_SYSTEM_GRAPHIC; case ax::mojom::Role::kInputTime: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kInlineTextBox: return ROLE_SYSTEM_STATICTEXT; case ax::mojom::Role::kLabelText: case ax::mojom::Role::kLegend: return ROLE_SYSTEM_TEXT; case ax::mojom::Role::kLayoutTable: return ROLE_SYSTEM_TABLE; case ax::mojom::Role::kLayoutTableCell: return ROLE_SYSTEM_CELL; case ax::mojom::Role::kLayoutTableRow: return ROLE_SYSTEM_ROW; case ax::mojom::Role::kLink: return ROLE_SYSTEM_LINK; case ax::mojom::Role::kList: return ROLE_SYSTEM_LIST; case ax::mojom::Role::kListBox: return ROLE_SYSTEM_LIST; case ax::mojom::Role::kListBoxOption: return ROLE_SYSTEM_LISTITEM; case ax::mojom::Role::kListGrid: return ROLE_SYSTEM_LIST; case ax::mojom::Role::kListItem: return ROLE_SYSTEM_LISTITEM; case ax::mojom::Role::kListMarker: if (!GetDelegate()->GetChildCount()) { // There's only a name attribute when using Legacy layout. With Legacy // layout, list markers have no child and are considered as StaticText. // We consider a list marker as a group in LayoutNG since it has // a text child node. return ROLE_SYSTEM_STATICTEXT; } return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kLog: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kMain: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kMark: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kMarquee: return ROLE_SYSTEM_ANIMATION; case ax::mojom::Role::kMath: return ROLE_SYSTEM_EQUATION; case ax::mojom::Role::kMenu: return ROLE_SYSTEM_MENUPOPUP; case ax::mojom::Role::kMenuBar: return ROLE_SYSTEM_MENUBAR; case ax::mojom::Role::kMenuItem: case ax::mojom::Role::kMenuItemCheckBox: case ax::mojom::Role::kMenuItemRadio: return ROLE_SYSTEM_MENUITEM; case ax::mojom::Role::kMenuListPopup: return ROLE_SYSTEM_LIST; case ax::mojom::Role::kMenuListOption: return ROLE_SYSTEM_LISTITEM; case ax::mojom::Role::kMeter: return ROLE_SYSTEM_PROGRESSBAR; case ax::mojom::Role::kNavigation: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kNote: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kParagraph: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kPdfActionableHighlight: return ROLE_SYSTEM_PUSHBUTTON; case ax::mojom::Role::kPluginObject: // See also case ax::mojom::Role::kEmbeddedObject. if (GetDelegate()->GetChildCount()) { return ROLE_SYSTEM_GROUPING; } else { return ROLE_SYSTEM_CLIENT; } case ax::mojom::Role::kPopUpButton: { std::string html_tag = GetData().GetStringAttribute(ax::mojom::StringAttribute::kHtmlTag); if (html_tag == "select") return ROLE_SYSTEM_COMBOBOX; return ROLE_SYSTEM_BUTTONMENU; } case ax::mojom::Role::kPortal: return ROLE_SYSTEM_PUSHBUTTON; case ax::mojom::Role::kPre: return ROLE_SYSTEM_TEXT; case ax::mojom::Role::kProgressIndicator: return ROLE_SYSTEM_PROGRESSBAR; case ax::mojom::Role::kRadioButton: return ROLE_SYSTEM_RADIOBUTTON; case ax::mojom::Role::kRadioGroup: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kRegion: return ROLE_SYSTEM_PANE; case ax::mojom::Role::kRow: { // Role changes depending on whether row is inside a treegrid // https://www.w3.org/TR/core-aam-1.1/#role-map-row return IsInTreeGrid() ? ROLE_SYSTEM_OUTLINEITEM : ROLE_SYSTEM_ROW; } case ax::mojom::Role::kRowGroup: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kRowHeader: return ROLE_SYSTEM_ROWHEADER; case ax::mojom::Role::kRuby: return ROLE_SYSTEM_TEXT; case ax::mojom::Role::kSection: { if (GetNameAsString16().empty()) { // Do not use ARIA mapping for nameless <section>. return ROLE_SYSTEM_GROUPING; } // Use ARIA mapping. return ROLE_SYSTEM_PANE; } case ax::mojom::Role::kScrollBar: return ROLE_SYSTEM_SCROLLBAR; case ax::mojom::Role::kScrollView: return ROLE_SYSTEM_PANE; case ax::mojom::Role::kSearch: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kSlider: return ROLE_SYSTEM_SLIDER; case ax::mojom::Role::kSliderThumb: return ROLE_SYSTEM_SLIDER; case ax::mojom::Role::kSpinButton: return ROLE_SYSTEM_SPINBUTTON; case ax::mojom::Role::kSwitch: return ROLE_SYSTEM_CHECKBUTTON; case ax::mojom::Role::kRubyAnnotation: case ax::mojom::Role::kStaticText: return ROLE_SYSTEM_STATICTEXT; case ax::mojom::Role::kStatus: return ROLE_SYSTEM_STATUSBAR; case ax::mojom::Role::kSplitter: return ROLE_SYSTEM_SEPARATOR; case ax::mojom::Role::kSvgRoot: return ROLE_SYSTEM_GRAPHIC; case ax::mojom::Role::kTab: return ROLE_SYSTEM_PAGETAB; case ax::mojom::Role::kTable: return ROLE_SYSTEM_TABLE; case ax::mojom::Role::kTableHeaderContainer: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kTabList: return ROLE_SYSTEM_PAGETABLIST; case ax::mojom::Role::kTabPanel: return ROLE_SYSTEM_PROPERTYPAGE; case ax::mojom::Role::kTerm: return ROLE_SYSTEM_LISTITEM; case ax::mojom::Role::kTitleBar: return ROLE_SYSTEM_TITLEBAR; case ax::mojom::Role::kToggleButton: return ROLE_SYSTEM_CHECKBUTTON; case ax::mojom::Role::kTextField: case ax::mojom::Role::kSearchBox: return ROLE_SYSTEM_TEXT; case ax::mojom::Role::kTextFieldWithComboBox: return ROLE_SYSTEM_COMBOBOX; case ax::mojom::Role::kAbbr: case ax::mojom::Role::kCode: case ax::mojom::Role::kEmphasis: case ax::mojom::Role::kStrong: case ax::mojom::Role::kTime: return ROLE_SYSTEM_TEXT; case ax::mojom::Role::kTimer: return ROLE_SYSTEM_CLOCK; case ax::mojom::Role::kToolbar: return ROLE_SYSTEM_TOOLBAR; case ax::mojom::Role::kTooltip: return ROLE_SYSTEM_TOOLTIP; case ax::mojom::Role::kTree: return ROLE_SYSTEM_OUTLINE; case ax::mojom::Role::kTreeGrid: return ROLE_SYSTEM_OUTLINE; case ax::mojom::Role::kTreeItem: return ROLE_SYSTEM_OUTLINEITEM; case ax::mojom::Role::kLineBreak: return ROLE_SYSTEM_WHITESPACE; case ax::mojom::Role::kVideo: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kWebView: return ROLE_SYSTEM_CLIENT; case ax::mojom::Role::kPane: case ax::mojom::Role::kWindow: // Do not return ROLE_SYSTEM_WINDOW as that is a special MSAA system // role used to indicate a real native window object. It is // automatically created by oleacc.dll as a parent of the root of our // hierarchy, matching the HWND. return ROLE_SYSTEM_PANE; case ax::mojom::Role::kImeCandidate: case ax::mojom::Role::kIgnored: case ax::mojom::Role::kKeyboard: case ax::mojom::Role::kNone: case ax::mojom::Role::kPresentational: case ax::mojom::Role::kUnknown: return ROLE_SYSTEM_PANE; } BASE_UNREACHABLE(); return ROLE_SYSTEM_GROUPING; } bool AXPlatformNodeWin::IsWebAreaForPresentationalIframe() { if (GetData().role != ax::mojom::Role::kWebArea && GetData().role != ax::mojom::Role::kRootWebArea) { return false; } AXPlatformNodeBase* parent = FromNativeViewAccessible(GetParent()); if (!parent) return false; return parent->GetData().role == ax::mojom::Role::kIframePresentational; } std::u16string AXPlatformNodeWin::UIAAriaRole() { // If this is a web area for a presentational iframe, give it a role of // something other than document so that the fact that it's a separate doc // is not exposed to AT. if (IsWebAreaForPresentationalIframe()) return u"group"; switch (GetData().role) { case ax::mojom::Role::kAlert: return u"alert"; case ax::mojom::Role::kAlertDialog: // Our MSAA implementation suggests the use of // "alert", not "alertdialog" because some // Windows screen readers are not compatible with // |ax::mojom::Role::kAlertDialog| yet. return u"alert"; case ax::mojom::Role::kAnchor: return u"link"; case ax::mojom::Role::kComment: case ax::mojom::Role::kSuggestion: return u"group"; case ax::mojom::Role::kApplication: return u"application"; case ax::mojom::Role::kArticle: return u"article"; case ax::mojom::Role::kAudio: return u"group"; case ax::mojom::Role::kBanner: case ax::mojom::Role::kHeader: return u"banner"; case ax::mojom::Role::kBlockquote: return u"group"; case ax::mojom::Role::kButton: return u"button"; case ax::mojom::Role::kCanvas: return u"img"; case ax::mojom::Role::kCaption: return u"description"; case ax::mojom::Role::kCaret: return u"region"; case ax::mojom::Role::kCell: return u"gridcell"; case ax::mojom::Role::kCode: return u"code"; case ax::mojom::Role::kCheckBox: return u"checkbox"; case ax::mojom::Role::kClient: return u"region"; case ax::mojom::Role::kColorWell: return u"textbox"; case ax::mojom::Role::kColumn: return u"region"; case ax::mojom::Role::kColumnHeader: return u"columnheader"; case ax::mojom::Role::kComboBoxGrouping: case ax::mojom::Role::kComboBoxMenuButton: return u"combobox"; case ax::mojom::Role::kComplementary: return u"complementary"; case ax::mojom::Role::kContentDeletion: case ax::mojom::Role::kContentInsertion: return u"group"; case ax::mojom::Role::kContentInfo: case ax::mojom::Role::kFooter: return u"contentinfo"; case ax::mojom::Role::kDate: case ax::mojom::Role::kDateTime: return u"textbox"; case ax::mojom::Role::kDefinition: return u"definition"; case ax::mojom::Role::kDescriptionListDetail: return u"description"; case ax::mojom::Role::kDescriptionList: return u"list"; case ax::mojom::Role::kDescriptionListTerm: return u"listitem"; case ax::mojom::Role::kDesktop: return u"document"; case ax::mojom::Role::kDetails: return u"group"; case ax::mojom::Role::kDialog: return u"dialog"; case ax::mojom::Role::kDisclosureTriangle: return u"button"; case ax::mojom::Role::kDirectory: return u"directory"; case ax::mojom::Role::kDocCover: return u"img"; case ax::mojom::Role::kDocBackLink: case ax::mojom::Role::kDocBiblioRef: case ax::mojom::Role::kDocGlossRef: case ax::mojom::Role::kDocNoteRef: return u"link"; case ax::mojom::Role::kDocBiblioEntry: case ax::mojom::Role::kDocEndnote: case ax::mojom::Role::kDocFootnote: return u"listitem"; case ax::mojom::Role::kDocPageBreak: return u"separator"; case ax::mojom::Role::kDocAbstract: case ax::mojom::Role::kDocAcknowledgments: case ax::mojom::Role::kDocAfterword: case ax::mojom::Role::kDocAppendix: case ax::mojom::Role::kDocBibliography: case ax::mojom::Role::kDocChapter: case ax::mojom::Role::kDocColophon: case ax::mojom::Role::kDocConclusion: case ax::mojom::Role::kDocCredit: case ax::mojom::Role::kDocCredits: case ax::mojom::Role::kDocDedication: case ax::mojom::Role::kDocEndnotes: case ax::mojom::Role::kDocEpigraph: case ax::mojom::Role::kDocEpilogue: case ax::mojom::Role::kDocErrata: case ax::mojom::Role::kDocExample: case ax::mojom::Role::kDocForeword: case ax::mojom::Role::kDocGlossary: case ax::mojom::Role::kDocIndex: case ax::mojom::Role::kDocIntroduction: case ax::mojom::Role::kDocNotice: case ax::mojom::Role::kDocPageList: case ax::mojom::Role::kDocPart: case ax::mojom::Role::kDocPreface: case ax::mojom::Role::kDocPrologue: case ax::mojom::Role::kDocPullquote: case ax::mojom::Role::kDocQna: case ax::mojom::Role::kDocSubtitle: case ax::mojom::Role::kDocTip: case ax::mojom::Role::kDocToc: return u"group"; case ax::mojom::Role::kDocument: case ax::mojom::Role::kRootWebArea: case ax::mojom::Role::kWebArea: return u"document"; case ax::mojom::Role::kEmbeddedObject: if (GetDelegate()->GetChildCount()) { return u"group"; } else { return u"document"; } case ax::mojom::Role::kEmphasis: return u"emphasis"; case ax::mojom::Role::kFeed: return u"group"; case ax::mojom::Role::kFigcaption: return u"description"; case ax::mojom::Role::kFigure: return u"group"; case ax::mojom::Role::kFooterAsNonLandmark: case ax::mojom::Role::kHeaderAsNonLandmark: return u"group"; case ax::mojom::Role::kForm: return u"form"; case ax::mojom::Role::kGenericContainer: return u"group"; case ax::mojom::Role::kGraphicsDocument: return u"document"; case ax::mojom::Role::kGraphicsObject: return u"region"; case ax::mojom::Role::kGraphicsSymbol: return u"img"; case ax::mojom::Role::kGrid: return u"grid"; case ax::mojom::Role::kGroup: return u"group"; case ax::mojom::Role::kHeading: return u"heading"; case ax::mojom::Role::kIframe: return u"document"; case ax::mojom::Role::kIframePresentational: return u"group"; case ax::mojom::Role::kImage: return u"img"; case ax::mojom::Role::kImageMap: return u"document"; case ax::mojom::Role::kImeCandidate: // Internal role, not used on Windows. return u"group"; case ax::mojom::Role::kInputTime: return u"group"; case ax::mojom::Role::kInlineTextBox: return u"textbox"; case ax::mojom::Role::kKeyboard: return u"group"; case ax::mojom::Role::kLabelText: case ax::mojom::Role::kLegend: return u"description"; case ax::mojom::Role::kLayoutTable: return u"grid"; case ax::mojom::Role::kLayoutTableCell: return u"gridcell"; case ax::mojom::Role::kLayoutTableRow: return u"row"; case ax::mojom::Role::kLink: return u"link"; case ax::mojom::Role::kList: return u"list"; case ax::mojom::Role::kListBox: return u"listbox"; case ax::mojom::Role::kListBoxOption: return u"option"; case ax::mojom::Role::kListGrid: return u"listview"; case ax::mojom::Role::kListItem: return u"listitem"; case ax::mojom::Role::kListMarker: if (!GetDelegate()->GetChildCount()) { // There's only a name attribute when using Legacy layout. With Legacy // layout, list markers have no child and are considered as StaticText. // We consider a list marker as a group in LayoutNG since it has // a text child node. return u"description"; } return u"group"; case ax::mojom::Role::kLog: return u"log"; case ax::mojom::Role::kMain: return u"main"; case ax::mojom::Role::kMark: return u"description"; case ax::mojom::Role::kMarquee: return u"marquee"; case ax::mojom::Role::kMath: return u"group"; case ax::mojom::Role::kMenu: return u"menu"; case ax::mojom::Role::kMenuBar: return u"menubar"; case ax::mojom::Role::kMenuItem: return u"menuitem"; case ax::mojom::Role::kMenuItemCheckBox: return u"menuitemcheckbox"; case ax::mojom::Role::kMenuItemRadio: return u"menuitemradio"; case ax::mojom::Role::kMenuListPopup: return u"list"; case ax::mojom::Role::kMenuListOption: return u"listitem"; case ax::mojom::Role::kMeter: return u"progressbar"; case ax::mojom::Role::kNavigation: return u"navigation"; case ax::mojom::Role::kNote: return u"note"; case ax::mojom::Role::kParagraph: return u"group"; case ax::mojom::Role::kPdfActionableHighlight: return u"button"; case ax::mojom::Role::kPluginObject: if (GetDelegate()->GetChildCount()) { return u"group"; } else { return u"document"; } case ax::mojom::Role::kPopUpButton: { std::string html_tag = GetData().GetStringAttribute(ax::mojom::StringAttribute::kHtmlTag); if (html_tag == "select") return u"combobox"; return u"button"; } case ax::mojom::Role::kPortal: return u"button"; case ax::mojom::Role::kPre: return u"region"; case ax::mojom::Role::kProgressIndicator: return u"progressbar"; case ax::mojom::Role::kRadioButton: return u"radio"; case ax::mojom::Role::kRadioGroup: return u"radiogroup"; case ax::mojom::Role::kRegion: return u"region"; case ax::mojom::Role::kRow: { // Role changes depending on whether row is inside a treegrid // https://www.w3.org/TR/core-aam-1.1/#role-map-row return IsInTreeGrid() ? u"treeitem" : u"row"; } case ax::mojom::Role::kRowGroup: return u"rowgroup"; case ax::mojom::Role::kRowHeader: return u"rowheader"; case ax::mojom::Role::kRuby: return u"region"; case ax::mojom::Role::kSection: { if (GetNameAsString16().empty()) { // Do not use ARIA mapping for nameless <section>. return u"group"; } // Use ARIA mapping. return u"region"; } case ax::mojom::Role::kScrollBar: return u"scrollbar"; case ax::mojom::Role::kScrollView: return u"region"; case ax::mojom::Role::kSearch: return u"search"; case ax::mojom::Role::kSlider: return u"slider"; case ax::mojom::Role::kSliderThumb: return u"slider"; case ax::mojom::Role::kSpinButton: return u"spinbutton"; case ax::mojom::Role::kStrong: return u"strong"; case ax::mojom::Role::kSwitch: return u"switch"; case ax::mojom::Role::kRubyAnnotation: case ax::mojom::Role::kStaticText: return u"description"; case ax::mojom::Role::kStatus: return u"status"; case ax::mojom::Role::kSplitter: return u"separator"; case ax::mojom::Role::kSvgRoot: return u"img"; case ax::mojom::Role::kTab: return u"tab"; case ax::mojom::Role::kTable: return u"grid"; case ax::mojom::Role::kTableHeaderContainer: return u"group"; case ax::mojom::Role::kTabList: return u"tablist"; case ax::mojom::Role::kTabPanel: return u"tabpanel"; case ax::mojom::Role::kTerm: return u"listitem"; case ax::mojom::Role::kTitleBar: return u"document"; case ax::mojom::Role::kToggleButton: return u"button"; case ax::mojom::Role::kTextField: return u"textbox"; case ax::mojom::Role::kSearchBox: return u"searchbox"; case ax::mojom::Role::kTextFieldWithComboBox: return u"combobox"; case ax::mojom::Role::kAbbr: return u"description"; case ax::mojom::Role::kTime: return u"time"; case ax::mojom::Role::kTimer: return u"timer"; case ax::mojom::Role::kToolbar: return u"toolbar"; case ax::mojom::Role::kTooltip: return u"tooltip"; case ax::mojom::Role::kTree: return u"tree"; case ax::mojom::Role::kTreeGrid: return u"treegrid"; case ax::mojom::Role::kTreeItem: return u"treeitem"; case ax::mojom::Role::kLineBreak: return u"separator"; case ax::mojom::Role::kVideo: return u"group"; case ax::mojom::Role::kWebView: return u"document"; case ax::mojom::Role::kPane: case ax::mojom::Role::kWindow: case ax::mojom::Role::kIgnored: case ax::mojom::Role::kNone: case ax::mojom::Role::kPresentational: case ax::mojom::Role::kUnknown: return u"region"; } BASE_UNREACHABLE(); return u"document"; } std::u16string AXPlatformNodeWin::ComputeUIAProperties() { std::vector<std::u16string> properties; const AXNodeData& data = GetData(); BoolAttributeToUIAAriaProperty( properties, ax::mojom::BoolAttribute::kLiveAtomic, "atomic"); BoolAttributeToUIAAriaProperty(properties, ax::mojom::BoolAttribute::kBusy, "busy"); switch (data.GetCheckedState()) { case ax::mojom::CheckedState::kNone: break; case ax::mojom::CheckedState::kFalse: if (data.role == ax::mojom::Role::kToggleButton) { properties.emplace_back(u"pressed=false"); } else if (data.role == ax::mojom::Role::kSwitch) { // ARIA switches are exposed to Windows accessibility as toggle // buttons. For maximum compatibility with ATs, we expose both the // pressed and checked states. properties.emplace_back(u"pressed=false"); properties.emplace_back(u"checked=false"); } else { properties.emplace_back(u"checked=false"); } break; case ax::mojom::CheckedState::kTrue: if (data.role == ax::mojom::Role::kToggleButton) { properties.emplace_back(u"pressed=true"); } else if (data.role == ax::mojom::Role::kSwitch) { // ARIA switches are exposed to Windows accessibility as toggle // buttons. For maximum compatibility with ATs, we expose both the // pressed and checked states. properties.emplace_back(u"pressed=true"); properties.emplace_back(u"checked=true"); } else { properties.emplace_back(u"checked=true"); } break; case ax::mojom::CheckedState::kMixed: if (data.role == ax::mojom::Role::kToggleButton) { properties.emplace_back(u"pressed=mixed"); } else if (data.role == ax::mojom::Role::kSwitch) { // This is disallowed both by the ARIA standard and by Blink. BASE_UNREACHABLE(); } else { properties.emplace_back(u"checked=mixed"); } break; } const auto restriction = static_cast<ax::mojom::Restriction>( GetIntAttribute(ax::mojom::IntAttribute::kRestriction)); if (restriction == ax::mojom::Restriction::kDisabled) { properties.push_back(u"disabled=true"); } else { // The readonly property is complex on Windows. We set "readonly=true" // on *some* document structure roles such as paragraph, heading or list // even if the node data isn't marked as read only, as long as the // node is not editable. if (GetData().IsReadOnlyOrDisabled()) properties.push_back(u"readonly=true"); } // aria-dropeffect is deprecated in WAI-ARIA 1.1. if (data.HasIntAttribute(ax::mojom::IntAttribute::kDropeffect)) { properties.push_back(u"dropeffect=" + base::UTF8ToUTF16(data.DropeffectBitfieldToString())); } StateToUIAAriaProperty(properties, ax::mojom::State::kExpanded, "expanded"); BoolAttributeToUIAAriaProperty(properties, ax::mojom::BoolAttribute::kGrabbed, "grabbed"); switch (static_cast<ax::mojom::HasPopup>( data.GetIntAttribute(ax::mojom::IntAttribute::kHasPopup))) { case ax::mojom::HasPopup::kFalse: break; case ax::mojom::HasPopup::kTrue: properties.push_back(u"haspopup=true"); break; case ax::mojom::HasPopup::kMenu: properties.push_back(u"haspopup=menu"); break; case ax::mojom::HasPopup::kListbox: properties.push_back(u"haspopup=listbox"); break; case ax::mojom::HasPopup::kTree: properties.push_back(u"haspopup=tree"); break; case ax::mojom::HasPopup::kGrid: properties.push_back(u"haspopup=grid"); break; case ax::mojom::HasPopup::kDialog: properties.push_back(u"haspopup=dialog"); break; } if (IsInvisibleOrIgnored()) properties.push_back(u"hidden=true"); if (HasIntAttribute(ax::mojom::IntAttribute::kInvalidState) && GetIntAttribute(ax::mojom::IntAttribute::kInvalidState) != static_cast<int32_t>(ax::mojom::InvalidState::kFalse)) { properties.push_back(u"invalid=true"); } IntAttributeToUIAAriaProperty( properties, ax::mojom::IntAttribute::kHierarchicalLevel, "level"); StringAttributeToUIAAriaProperty( properties, ax::mojom::StringAttribute::kLiveStatus, "live"); StateToUIAAriaProperty(properties, ax::mojom::State::kMultiline, "multiline"); StateToUIAAriaProperty(properties, ax::mojom::State::kMultiselectable, "multiselectable"); IntAttributeToUIAAriaProperty(properties, ax::mojom::IntAttribute::kPosInSet, "posinset"); StringAttributeToUIAAriaProperty( properties, ax::mojom::StringAttribute::kLiveRelevant, "relevant"); StateToUIAAriaProperty(properties, ax::mojom::State::kRequired, "required"); BoolAttributeToUIAAriaProperty( properties, ax::mojom::BoolAttribute::kSelected, "selected"); IntAttributeToUIAAriaProperty(properties, ax::mojom::IntAttribute::kSetSize, "setsize"); int32_t sort_direction; if (IsTableHeader(data.role) && GetIntAttribute(ax::mojom::IntAttribute::kSortDirection, &sort_direction)) { switch (static_cast<ax::mojom::SortDirection>(sort_direction)) { case ax::mojom::SortDirection::kNone: break; case ax::mojom::SortDirection::kUnsorted: properties.push_back(u"sort=none"); break; case ax::mojom::SortDirection::kAscending: properties.push_back(u"sort=ascending"); break; case ax::mojom::SortDirection::kDescending: properties.push_back(u"sort=descending"); break; case ax::mojom::SortDirection::kOther: properties.push_back(u"sort=other"); break; } } if (data.IsRangeValueSupported()) { FloatAttributeToUIAAriaProperty( properties, ax::mojom::FloatAttribute::kMaxValueForRange, "valuemax"); FloatAttributeToUIAAriaProperty( properties, ax::mojom::FloatAttribute::kMinValueForRange, "valuemin"); StringAttributeToUIAAriaProperty( properties, ax::mojom::StringAttribute::kValue, "valuetext"); std::u16string value_now = GetRangeValueText(); SanitizeStringAttributeForUIAAriaProperty(value_now, &value_now); if (!value_now.empty()) properties.push_back(u"valuenow=" + value_now); } std::u16string result = base::JoinString(properties, u";"); return result; } LONG AXPlatformNodeWin::ComputeUIAControlType() { // NOLINT(runtime/int) // If this is a web area for a presentational iframe, give it a role of // something other than document so that the fact that it's a separate doc // is not exposed to AT. if (IsWebAreaForPresentationalIframe()) return UIA_GroupControlTypeId; switch (GetData().role) { case ax::mojom::Role::kAlert: return UIA_TextControlTypeId; case ax::mojom::Role::kAlertDialog: // Our MSAA implementation suggests the use of // |UIA_TextControlTypeId|, not |UIA_PaneControlTypeId| because some // Windows screen readers are not compatible with // |ax::mojom::Role::kAlertDialog| yet. return UIA_TextControlTypeId; case ax::mojom::Role::kAnchor: return UIA_HyperlinkControlTypeId; case ax::mojom::Role::kComment: case ax::mojom::Role::kSuggestion: return ROLE_SYSTEM_GROUPING; case ax::mojom::Role::kApplication: return UIA_PaneControlTypeId; case ax::mojom::Role::kArticle: return UIA_GroupControlTypeId; case ax::mojom::Role::kAudio: return UIA_GroupControlTypeId; case ax::mojom::Role::kBanner: case ax::mojom::Role::kHeader: return UIA_GroupControlTypeId; case ax::mojom::Role::kBlockquote: return UIA_GroupControlTypeId; case ax::mojom::Role::kButton: return UIA_ButtonControlTypeId; case ax::mojom::Role::kCanvas: return UIA_ImageControlTypeId; case ax::mojom::Role::kCaption: return UIA_TextControlTypeId; case ax::mojom::Role::kCaret: return UIA_PaneControlTypeId; case ax::mojom::Role::kCell: return UIA_DataItemControlTypeId; case ax::mojom::Role::kCheckBox: return UIA_CheckBoxControlTypeId; case ax::mojom::Role::kClient: return UIA_PaneControlTypeId; case ax::mojom::Role::kCode: return UIA_TextControlTypeId; case ax::mojom::Role::kColorWell: return UIA_ButtonControlTypeId; case ax::mojom::Role::kColumn: return UIA_PaneControlTypeId; case ax::mojom::Role::kColumnHeader: return UIA_DataItemControlTypeId; case ax::mojom::Role::kComboBoxGrouping: case ax::mojom::Role::kComboBoxMenuButton: return UIA_ComboBoxControlTypeId; case ax::mojom::Role::kComplementary: return UIA_GroupControlTypeId; case ax::mojom::Role::kContentDeletion: case ax::mojom::Role::kContentInsertion: return UIA_GroupControlTypeId; case ax::mojom::Role::kContentInfo: case ax::mojom::Role::kFooter: return UIA_GroupControlTypeId; case ax::mojom::Role::kDate: case ax::mojom::Role::kDateTime: return UIA_EditControlTypeId; case ax::mojom::Role::kDefinition: return UIA_GroupControlTypeId; case ax::mojom::Role::kDescriptionListDetail: return UIA_TextControlTypeId; case ax::mojom::Role::kDescriptionList: return UIA_ListControlTypeId; case ax::mojom::Role::kDescriptionListTerm: return UIA_ListItemControlTypeId; case ax::mojom::Role::kDesktop: return UIA_DocumentControlTypeId; case ax::mojom::Role::kDetails: return UIA_GroupControlTypeId; case ax::mojom::Role::kDialog: return UIA_PaneControlTypeId; case ax::mojom::Role::kDisclosureTriangle: return UIA_ButtonControlTypeId; case ax::mojom::Role::kDirectory: return UIA_ListControlTypeId; case ax::mojom::Role::kDocCover: return UIA_ImageControlTypeId; case ax::mojom::Role::kDocBackLink: case ax::mojom::Role::kDocBiblioRef: case ax::mojom::Role::kDocGlossRef: case ax::mojom::Role::kDocNoteRef: return UIA_HyperlinkControlTypeId; case ax::mojom::Role::kDocBiblioEntry: case ax::mojom::Role::kDocEndnote: case ax::mojom::Role::kDocFootnote: return UIA_ListItemControlTypeId; case ax::mojom::Role::kDocPageBreak: return UIA_SeparatorControlTypeId; case ax::mojom::Role::kDocAbstract: case ax::mojom::Role::kDocAcknowledgments: case ax::mojom::Role::kDocAfterword: case ax::mojom::Role::kDocAppendix: case ax::mojom::Role::kDocBibliography: case ax::mojom::Role::kDocChapter: case ax::mojom::Role::kDocColophon: case ax::mojom::Role::kDocConclusion: case ax::mojom::Role::kDocCredit: case ax::mojom::Role::kDocCredits: case ax::mojom::Role::kDocDedication: case ax::mojom::Role::kDocEndnotes: case ax::mojom::Role::kDocEpigraph: case ax::mojom::Role::kDocEpilogue: case ax::mojom::Role::kDocErrata: case ax::mojom::Role::kDocExample: case ax::mojom::Role::kDocForeword: case ax::mojom::Role::kDocGlossary: case ax::mojom::Role::kDocIndex: case ax::mojom::Role::kDocIntroduction: case ax::mojom::Role::kDocNotice: case ax::mojom::Role::kDocPageList: case ax::mojom::Role::kDocPart: case ax::mojom::Role::kDocPreface: case ax::mojom::Role::kDocPrologue: case ax::mojom::Role::kDocPullquote: case ax::mojom::Role::kDocQna: case ax::mojom::Role::kDocSubtitle: case ax::mojom::Role::kDocTip: case ax::mojom::Role::kDocToc: return UIA_GroupControlTypeId; case ax::mojom::Role::kDocument: case ax::mojom::Role::kRootWebArea: case ax::mojom::Role::kWebArea: return UIA_DocumentControlTypeId; case ax::mojom::Role::kEmbeddedObject: return UIA_PaneControlTypeId; case ax::mojom::Role::kEmphasis: return UIA_TextControlTypeId; case ax::mojom::Role::kFeed: return UIA_GroupControlTypeId; case ax::mojom::Role::kFigcaption: return UIA_TextControlTypeId; case ax::mojom::Role::kFigure: return UIA_GroupControlTypeId; case ax::mojom::Role::kFooterAsNonLandmark: case ax::mojom::Role::kHeaderAsNonLandmark: return UIA_GroupControlTypeId; case ax::mojom::Role::kForm: return UIA_GroupControlTypeId; case ax::mojom::Role::kGenericContainer: return UIA_GroupControlTypeId; case ax::mojom::Role::kGraphicsDocument: return UIA_DocumentControlTypeId; case ax::mojom::Role::kGraphicsObject: return UIA_PaneControlTypeId; case ax::mojom::Role::kGraphicsSymbol: return UIA_ImageControlTypeId; case ax::mojom::Role::kGrid: return UIA_DataGridControlTypeId; case ax::mojom::Role::kGroup: return UIA_GroupControlTypeId; case ax::mojom::Role::kHeading: return UIA_TextControlTypeId; case ax::mojom::Role::kIframe: return UIA_DocumentControlTypeId; case ax::mojom::Role::kIframePresentational: return UIA_GroupControlTypeId; case ax::mojom::Role::kImage: return UIA_ImageControlTypeId; case ax::mojom::Role::kImageMap: return UIA_DocumentControlTypeId; case ax::mojom::Role::kInputTime: return UIA_GroupControlTypeId; case ax::mojom::Role::kInlineTextBox: return UIA_DocumentControlTypeId; case ax::mojom::Role::kLabelText: case ax::mojom::Role::kLegend: return UIA_TextControlTypeId; case ax::mojom::Role::kLayoutTable: return UIA_TableControlTypeId; case ax::mojom::Role::kLayoutTableCell: return UIA_DataItemControlTypeId; case ax::mojom::Role::kLayoutTableRow: return UIA_DataItemControlTypeId; case ax::mojom::Role::kLink: return UIA_HyperlinkControlTypeId; case ax::mojom::Role::kList: return UIA_ListControlTypeId; case ax::mojom::Role::kListBox: return UIA_ListControlTypeId; case ax::mojom::Role::kListBoxOption: return UIA_ListItemControlTypeId; case ax::mojom::Role::kListGrid: return UIA_DataGridControlTypeId; case ax::mojom::Role::kListItem: return UIA_ListItemControlTypeId; case ax::mojom::Role::kListMarker: if (!GetDelegate()->GetChildCount()) { // There's only a name attribute when using Legacy layout. With Legacy // layout, list markers have no child and are considered as StaticText. // We consider a list marker as a group in LayoutNG since it has // a text child node. return UIA_TextControlTypeId; } return UIA_GroupControlTypeId; case ax::mojom::Role::kLog: return UIA_GroupControlTypeId; case ax::mojom::Role::kMain: return UIA_GroupControlTypeId; case ax::mojom::Role::kMark: return UIA_TextControlTypeId; case ax::mojom::Role::kMarquee: return UIA_TextControlTypeId; case ax::mojom::Role::kMath: return UIA_GroupControlTypeId; case ax::mojom::Role::kMenu: return UIA_MenuControlTypeId; case ax::mojom::Role::kMenuBar: return UIA_MenuBarControlTypeId; case ax::mojom::Role::kMenuItem: return UIA_MenuItemControlTypeId; case ax::mojom::Role::kMenuItemCheckBox: return UIA_CheckBoxControlTypeId; case ax::mojom::Role::kMenuItemRadio: return UIA_RadioButtonControlTypeId; case ax::mojom::Role::kMenuListPopup: return UIA_ListControlTypeId; case ax::mojom::Role::kMenuListOption: return UIA_ListItemControlTypeId; case ax::mojom::Role::kMeter: return UIA_ProgressBarControlTypeId; case ax::mojom::Role::kNavigation: return UIA_GroupControlTypeId; case ax::mojom::Role::kNote: return UIA_GroupControlTypeId; case ax::mojom::Role::kParagraph: return UIA_GroupControlTypeId; case ax::mojom::Role::kPdfActionableHighlight: return UIA_CustomControlTypeId; case ax::mojom::Role::kPluginObject: if (GetDelegate()->GetChildCount()) { return UIA_GroupControlTypeId; } else { return UIA_DocumentControlTypeId; } case ax::mojom::Role::kPopUpButton: { std::string html_tag = GetData().GetStringAttribute(ax::mojom::StringAttribute::kHtmlTag); if (html_tag == "select") return UIA_ComboBoxControlTypeId; return UIA_ButtonControlTypeId; } case ax::mojom::Role::kPortal: return UIA_ButtonControlTypeId; case ax::mojom::Role::kPre: return UIA_PaneControlTypeId; case ax::mojom::Role::kProgressIndicator: return UIA_ProgressBarControlTypeId; case ax::mojom::Role::kRadioButton: return UIA_RadioButtonControlTypeId; case ax::mojom::Role::kRadioGroup: return UIA_GroupControlTypeId; case ax::mojom::Role::kRegion: return UIA_GroupControlTypeId; case ax::mojom::Role::kRow: { // Role changes depending on whether row is inside a treegrid // https://www.w3.org/TR/core-aam-1.1/#role-map-row return IsInTreeGrid() ? UIA_TreeItemControlTypeId : UIA_DataItemControlTypeId; } case ax::mojom::Role::kRowGroup: return UIA_GroupControlTypeId; case ax::mojom::Role::kRowHeader: return UIA_DataItemControlTypeId; case ax::mojom::Role::kRuby: return UIA_PaneControlTypeId; case ax::mojom::Role::kSection: return UIA_GroupControlTypeId; case ax::mojom::Role::kScrollBar: return UIA_ScrollBarControlTypeId; case ax::mojom::Role::kScrollView: return UIA_PaneControlTypeId; case ax::mojom::Role::kSearch: return UIA_GroupControlTypeId; case ax::mojom::Role::kSlider: return UIA_SliderControlTypeId; case ax::mojom::Role::kSliderThumb: return UIA_SliderControlTypeId; case ax::mojom::Role::kSpinButton: return UIA_SpinnerControlTypeId; case ax::mojom::Role::kSwitch: return UIA_ButtonControlTypeId; case ax::mojom::Role::kRubyAnnotation: case ax::mojom::Role::kStaticText: return UIA_TextControlTypeId; case ax::mojom::Role::kStatus: return UIA_StatusBarControlTypeId; case ax::mojom::Role::kStrong: return UIA_TextControlTypeId; case ax::mojom::Role::kSplitter: return UIA_SeparatorControlTypeId; case ax::mojom::Role::kSvgRoot: return UIA_ImageControlTypeId; case ax::mojom::Role::kTab: return UIA_TabItemControlTypeId; case ax::mojom::Role::kTable: return UIA_TableControlTypeId; case ax::mojom::Role::kTableHeaderContainer: return UIA_GroupControlTypeId; case ax::mojom::Role::kTabList: return UIA_TabControlTypeId; case ax::mojom::Role::kTabPanel: return UIA_PaneControlTypeId; case ax::mojom::Role::kTerm: return UIA_ListItemControlTypeId; case ax::mojom::Role::kTitleBar: return UIA_DocumentControlTypeId; case ax::mojom::Role::kToggleButton: return UIA_ButtonControlTypeId; case ax::mojom::Role::kTextField: case ax::mojom::Role::kSearchBox: return UIA_EditControlTypeId; case ax::mojom::Role::kTextFieldWithComboBox: return UIA_ComboBoxControlTypeId; case ax::mojom::Role::kAbbr: case ax::mojom::Role::kTime: return UIA_TextControlTypeId; case ax::mojom::Role::kTimer: return UIA_PaneControlTypeId; case ax::mojom::Role::kToolbar: return UIA_ToolBarControlTypeId; case ax::mojom::Role::kTooltip: return UIA_ToolTipControlTypeId; case ax::mojom::Role::kTree: return UIA_TreeControlTypeId; case ax::mojom::Role::kTreeGrid: return UIA_DataGridControlTypeId; case ax::mojom::Role::kTreeItem: return UIA_TreeItemControlTypeId; case ax::mojom::Role::kLineBreak: return UIA_SeparatorControlTypeId; case ax::mojom::Role::kVideo: return UIA_GroupControlTypeId; case ax::mojom::Role::kWebView: return UIA_DocumentControlTypeId; case ax::mojom::Role::kPane: case ax::mojom::Role::kWindow: case ax::mojom::Role::kIgnored: case ax::mojom::Role::kImeCandidate: case ax::mojom::Role::kKeyboard: case ax::mojom::Role::kNone: case ax::mojom::Role::kPresentational: case ax::mojom::Role::kUnknown: return UIA_PaneControlTypeId; } BASE_UNREACHABLE(); return UIA_DocumentControlTypeId; } AXPlatformNodeWin* AXPlatformNodeWin::ComputeUIALabeledBy() { // Not all control types expect a value for this property. if (!CanHaveUIALabeledBy()) return nullptr; // This property only accepts static text elements to be returned. Find the // first static text used to label this node. for (int32_t id : GetData().GetIntListAttribute( ax::mojom::IntListAttribute::kLabelledbyIds)) { auto* node_win = static_cast<AXPlatformNodeWin*>(GetDelegate()->GetFromNodeID(id)); if (!node_win) continue; // If this node is a static text, then simply return the node itself. if (IsValidUiaRelationTarget(node_win) && node_win->GetData().role == ax::mojom::Role::kStaticText) { return node_win; } // Otherwise, find the first static text node in its descendants. for (auto iter = node_win->GetDelegate()->ChildrenBegin(); *iter != *node_win->GetDelegate()->ChildrenEnd(); ++(*iter)) { AXPlatformNodeWin* child = static_cast<AXPlatformNodeWin*>( AXPlatformNode::FromNativeViewAccessible( iter->GetNativeViewAccessible())); if (IsValidUiaRelationTarget(child) && child->GetData().role == ax::mojom::Role::kStaticText) { return child; } } } return nullptr; } bool AXPlatformNodeWin::CanHaveUIALabeledBy() { // Not all control types expect a value for this property. See // https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-supportinguiautocontroltypes // for a complete list of control types. Each one of them has specific // expectations regarding the UIA_LabeledByPropertyId. switch (ComputeUIAControlType()) { case UIA_ButtonControlTypeId: case UIA_CheckBoxControlTypeId: case UIA_DataItemControlTypeId: case UIA_MenuControlTypeId: case UIA_MenuBarControlTypeId: case UIA_RadioButtonControlTypeId: case UIA_ScrollBarControlTypeId: case UIA_SeparatorControlTypeId: case UIA_StatusBarControlTypeId: case UIA_TabItemControlTypeId: case UIA_TextControlTypeId: case UIA_ToolBarControlTypeId: case UIA_ToolTipControlTypeId: case UIA_TreeItemControlTypeId: return false; default: return true; } } bool AXPlatformNodeWin::IsNameExposed() const { const AXNodeData& data = GetData(); switch (data.role) { case ax::mojom::Role::kListMarker: return !GetDelegate()->GetChildCount(); default: return true; } } bool AXPlatformNodeWin::IsUIAControl() const { // UIA provides multiple "views": raw, content and control. We only want to // populate the content and control views with items that make sense to // traverse over. if (GetDelegate()->IsWebContent()) { // Invisible or ignored elements should not show up in control view at all. if (IsInvisibleOrIgnored()) return false; if (IsText()) { // A text leaf can be a UIAControl, but text inside of a heading, link, // button, etc. where the role allows the name to be generated from the // content is not. We want to avoid reading out a button, moving to the // next item, and then reading out the button's text child, causing the // text to be effectively repeated. auto* parent = FromNativeViewAccessible(GetDelegate()->GetParent()); while (parent) { const AXNodeData& data = parent->GetData(); if (IsCellOrTableHeader(data.role)) return false; switch (data.role) { case ax::mojom::Role::kButton: case ax::mojom::Role::kCheckBox: case ax::mojom::Role::kGroup: case ax::mojom::Role::kHeading: case ax::mojom::Role::kLineBreak: case ax::mojom::Role::kLink: case ax::mojom::Role::kListBoxOption: case ax::mojom::Role::kListItem: case ax::mojom::Role::kMenuItem: case ax::mojom::Role::kMenuItemCheckBox: case ax::mojom::Role::kMenuItemRadio: case ax::mojom::Role::kMenuListOption: case ax::mojom::Role::kPdfActionableHighlight: case ax::mojom::Role::kRadioButton: case ax::mojom::Role::kRow: case ax::mojom::Role::kRowGroup: case ax::mojom::Role::kStaticText: case ax::mojom::Role::kSwitch: case ax::mojom::Role::kTab: case ax::mojom::Role::kTooltip: case ax::mojom::Role::kTreeItem: return false; default: break; } parent = FromNativeViewAccessible(parent->GetParent()); } } // end of text only case. const AXNodeData& data = GetData(); // https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-treeoverview#control-view // The control view also includes noninteractive UI items that contribute // to the logical structure of the UI. if (IsControl(data.role) || ComputeUIALandmarkType() || IsTableLike(data.role) || IsList(data.role)) { return true; } if (IsImage(data.role)) { // If the author provides an explicitly empty alt text attribute then // the image is decorational and should not be considered as a control. if (data.role == ax::mojom::Role::kImage && data.GetNameFrom() == ax::mojom::NameFrom::kAttributeExplicitlyEmpty) { return false; } return true; } switch (data.role) { case ax::mojom::Role::kArticle: case ax::mojom::Role::kBlockquote: case ax::mojom::Role::kDetails: case ax::mojom::Role::kFigure: case ax::mojom::Role::kFooter: case ax::mojom::Role::kFooterAsNonLandmark: case ax::mojom::Role::kHeader: case ax::mojom::Role::kHeaderAsNonLandmark: case ax::mojom::Role::kLabelText: case ax::mojom::Role::kListBoxOption: case ax::mojom::Role::kListItem: case ax::mojom::Role::kMeter: case ax::mojom::Role::kProgressIndicator: case ax::mojom::Role::kSection: case ax::mojom::Role::kSplitter: case ax::mojom::Role::kTime: return true; default: break; } // Classify generic containers that are not clickable or focusable and have // no name, description, landmark type, and is not the root of editable // content as not controls. // Doing so helps Narrator find all the content of live regions. if (!data.GetBoolAttribute(ax::mojom::BoolAttribute::kHasAriaAttribute) && !data.GetBoolAttribute(ax::mojom::BoolAttribute::kEditableRoot) && GetNameAsString16().empty() && data.GetStringAttribute(ax::mojom::StringAttribute::kDescription) .empty() && !data.HasState(ax::mojom::State::kFocusable) && !data.IsClickable()) { return false; } return true; } // end of web-content only case. const AXNodeData& data = GetData(); return !((IsReadOnlySupported(data.role) && data.IsReadOnlyOrDisabled()) || data.HasState(ax::mojom::State::kInvisible) || (data.IsIgnored() && !data.HasState(ax::mojom::State::kFocusable))); } std::optional<LONG> AXPlatformNodeWin::ComputeUIALandmarkType() const { const AXNodeData& data = GetData(); switch (data.role) { case ax::mojom::Role::kBanner: case ax::mojom::Role::kComplementary: case ax::mojom::Role::kContentInfo: case ax::mojom::Role::kFooter: case ax::mojom::Role::kHeader: return UIA_CustomLandmarkTypeId; case ax::mojom::Role::kForm: // https://www.w3.org/TR/html-aam-1.0/#html-element-role-mappings // https://w3c.github.io/core-aam/#mapping_role_table // While the HTML-AAM spec states that <form> without an accessible name // should have no corresponding role, removing the role breaks both // aria-setsize and aria-posinset. // The only other difference for UIA is that it should not be a landmark. // If the author provided an accessible name, or the role was explicit, // then allow the form landmark. if (data.HasStringAttribute(ax::mojom::StringAttribute::kName) || data.HasStringAttribute(ax::mojom::StringAttribute::kRole)) { return UIA_FormLandmarkTypeId; } return {}; case ax::mojom::Role::kMain: return UIA_MainLandmarkTypeId; case ax::mojom::Role::kNavigation: return UIA_NavigationLandmarkTypeId; case ax::mojom::Role::kSearch: return UIA_SearchLandmarkTypeId; case ax::mojom::Role::kRegion: case ax::mojom::Role::kSection: if (data.HasStringAttribute(ax::mojom::StringAttribute::kName)) return UIA_CustomLandmarkTypeId; BASE_FALLTHROUGH; default: return {}; } } bool AXPlatformNodeWin::IsInaccessibleDueToAncestor() const { AXPlatformNodeWin* parent = static_cast<AXPlatformNodeWin*>( AXPlatformNode::FromNativeViewAccessible(GetParent())); while (parent) { if (parent->ShouldHideChildrenForUIA()) return true; parent = static_cast<AXPlatformNodeWin*>( FromNativeViewAccessible(parent->GetParent())); } return false; } bool AXPlatformNodeWin::ShouldHideChildrenForUIA() const { if (IsPlainTextField()) return true; auto role = GetData().role; if (HasPresentationalChildren(role)) return true; switch (role) { // Other elements that are expected by UIA to hide their children without // having "Children Presentational: True". // // TODO(bebeaudr): We might be able to remove ax::mojom::Role::kLink once // http://crbug.com/1054514 is fixed. Links should not have to hide their // children. // TODO(virens): |kPdfActionableHighlight| needs to follow a fix similar to // links. At present Pdf highlghts have text nodes as children. But, we may // enable pdf highlights to have complex children like links based on user // feedback. case ax::mojom::Role::kLink: // Links with a single text-only child should hide their subtree. if (GetChildCount() == 1) { AXPlatformNodeBase* only_child = GetFirstChild(); return only_child && only_child->IsText(); } return false; case ax::mojom::Role::kPdfActionableHighlight: return true; default: return false; } } std::u16string AXPlatformNodeWin::GetValue() const { std::u16string value = AXPlatformNodeBase::GetValue(); // If this doesn't have a value and is linked then set its value to the URL // attribute. This allows screen readers to read an empty link's // destination. // TODO(dougt): Look into ensuring that on click handlers correctly provide // a value here. if (value.empty() && (MSAAState() & STATE_SYSTEM_LINKED)) value = GetString16Attribute(ax::mojom::StringAttribute::kUrl); return value; } bool AXPlatformNodeWin::IsPlatformCheckable() const { if (GetData().role == ax::mojom::Role::kToggleButton) return false; return AXPlatformNodeBase::IsPlatformCheckable(); } bool AXPlatformNodeWin::ShouldNodeHaveFocusableState( const AXNodeData& data) const { switch (data.role) { case ax::mojom::Role::kDocument: case ax::mojom::Role::kGraphicsDocument: case ax::mojom::Role::kWebArea: return true; case ax::mojom::Role::kRootWebArea: { AXPlatformNodeBase* parent = FromNativeViewAccessible(GetParent()); return !parent || parent->GetData().role != ax::mojom::Role::kPortal; } case ax::mojom::Role::kIframe: return false; case ax::mojom::Role::kListBoxOption: case ax::mojom::Role::kMenuListOption: if (data.HasBoolAttribute(ax::mojom::BoolAttribute::kSelected)) return true; break; default: break; } return data.HasState(ax::mojom::State::kFocusable); } int AXPlatformNodeWin::MSAAState() const { const AXNodeData& data = GetData(); int msaa_state = 0; // Map the ax::mojom::State to MSAA state. Note that some of the states are // not currently handled. if (data.GetBoolAttribute(ax::mojom::BoolAttribute::kBusy)) msaa_state |= STATE_SYSTEM_BUSY; if (data.HasState(ax::mojom::State::kCollapsed)) msaa_state |= STATE_SYSTEM_COLLAPSED; if (data.HasState(ax::mojom::State::kDefault)) msaa_state |= STATE_SYSTEM_DEFAULT; // TODO(dougt) unhandled ux::ax::mojom::State::kEditable if (data.HasState(ax::mojom::State::kExpanded)) msaa_state |= STATE_SYSTEM_EXPANDED; if (ShouldNodeHaveFocusableState(data)) msaa_state |= STATE_SYSTEM_FOCUSABLE; // Built-in autofill and autocomplete wil also set has popup. if (data.HasIntAttribute(ax::mojom::IntAttribute::kHasPopup)) msaa_state |= STATE_SYSTEM_HASPOPUP; // TODO(dougt) unhandled ux::ax::mojom::State::kHorizontal if (data.HasState(ax::mojom::State::kHovered)) { // Expose whether or not the mouse is over an element, but suppress // this for tests because it can make the test results flaky depending // on the position of the mouse. if (GetDelegate()->ShouldIgnoreHoveredStateForTesting()) msaa_state |= STATE_SYSTEM_HOTTRACKED; } // If the role is IGNORED, we want these elements to be invisible so that // these nodes are hidden from the screen reader. if (IsInvisibleOrIgnored()) msaa_state |= STATE_SYSTEM_INVISIBLE; if (data.HasState(ax::mojom::State::kLinked)) msaa_state |= STATE_SYSTEM_LINKED; // TODO(dougt) unhandled ux::ax::mojom::State::kMultiline if (data.HasState(ax::mojom::State::kMultiselectable)) { msaa_state |= STATE_SYSTEM_EXTSELECTABLE; msaa_state |= STATE_SYSTEM_MULTISELECTABLE; } if (GetDelegate()->IsOffscreen()) msaa_state |= STATE_SYSTEM_OFFSCREEN; if (data.HasState(ax::mojom::State::kProtected)) msaa_state |= STATE_SYSTEM_PROTECTED; // TODO(dougt) unhandled ux::ax::mojom::State::kRequired // TODO(dougt) unhandled ux::ax::mojom::State::kRichlyEditable if (data.IsSelectable()) msaa_state |= STATE_SYSTEM_SELECTABLE; if (data.GetBoolAttribute(ax::mojom::BoolAttribute::kSelected)) msaa_state |= STATE_SYSTEM_SELECTED; // TODO(dougt) unhandled VERTICAL if (data.HasState(ax::mojom::State::kVisited)) msaa_state |= STATE_SYSTEM_TRAVERSED; // // Checked state // switch (data.GetCheckedState()) { case ax::mojom::CheckedState::kNone: case ax::mojom::CheckedState::kFalse: break; case ax::mojom::CheckedState::kTrue: if (data.role == ax::mojom::Role::kToggleButton) { msaa_state |= STATE_SYSTEM_PRESSED; } else if (data.role == ax::mojom::Role::kSwitch) { // ARIA switches are exposed to Windows accessibility as toggle // buttons. For maximum compatibility with ATs, we expose both the // pressed and checked states. msaa_state |= STATE_SYSTEM_PRESSED | STATE_SYSTEM_CHECKED; } else { msaa_state |= STATE_SYSTEM_CHECKED; } break; case ax::mojom::CheckedState::kMixed: msaa_state |= STATE_SYSTEM_MIXED; break; } const auto restriction = static_cast<ax::mojom::Restriction>( GetIntAttribute(ax::mojom::IntAttribute::kRestriction)); switch (restriction) { case ax::mojom::Restriction::kDisabled: msaa_state |= STATE_SYSTEM_UNAVAILABLE; break; case ax::mojom::Restriction::kReadOnly: msaa_state |= STATE_SYSTEM_READONLY; break; default: // READONLY state is complex on Windows. We set STATE_SYSTEM_READONLY // on *some* document structure roles such as paragraph, heading or list // even if the node data isn't marked as read only, as long as the // node is not editable. if (!data.HasState(ax::mojom::State::kRichlyEditable) && ShouldHaveReadonlyStateByDefault(data.role)) { msaa_state |= STATE_SYSTEM_READONLY; } break; } // Windowless plugins should have STATE_SYSTEM_UNAVAILABLE. // // (All of our plugins are windowless.) if (data.role == ax::mojom::Role::kPluginObject || data.role == ax::mojom::Role::kEmbeddedObject) { msaa_state |= STATE_SYSTEM_UNAVAILABLE; } // // Handle STATE_SYSTEM_FOCUSED // gfx::NativeViewAccessible focus = GetDelegate()->GetFocus(); if (focus == const_cast<AXPlatformNodeWin*>(this)->GetNativeViewAccessible()) msaa_state |= STATE_SYSTEM_FOCUSED; // In focused single selection UI menus and listboxes, mirror item selection // to focus. This helps NVDA read the selected option as it changes. if ((data.role == ax::mojom::Role::kListBoxOption || IsMenuItem(data.role)) && data.GetBoolAttribute(ax::mojom::BoolAttribute::kSelected)) { AXPlatformNodeBase* container = FromNativeViewAccessible(GetParent()); if (container && container->GetParent() == focus) { AXNodeData container_data = container->GetData(); if ((container_data.role == ax::mojom::Role::kListBox || container_data.role == ax::mojom::Role::kMenu) && !container_data.HasState(ax::mojom::State::kMultiselectable)) { msaa_state |= STATE_SYSTEM_FOCUSED; } } } // On Windows, the "focus" bit should be set on certain containers, like // menu bars, when visible. // // TODO(dmazzoni): this should probably check if focus is actually inside // the menu bar, but we don't currently track focus inside menu pop-ups, // and Chrome only has one menu visible at a time so this works for now. if (data.role == ax::mojom::Role::kMenuBar && !(data.HasState(ax::mojom::State::kInvisible))) { msaa_state |= STATE_SYSTEM_FOCUSED; } // Handle STATE_SYSTEM_LINKED if (GetData().role == ax::mojom::Role::kLink) msaa_state |= STATE_SYSTEM_LINKED; // Special case for indeterminate progressbar. if (GetData().role == ax::mojom::Role::kProgressIndicator && !HasFloatAttribute(ax::mojom::FloatAttribute::kValueForRange)) msaa_state |= STATE_SYSTEM_MIXED; return msaa_state; } // static std::optional<DWORD> AXPlatformNodeWin::MojoEventToMSAAEvent( ax::mojom::Event event) { switch (event) { case ax::mojom::Event::kAlert: return EVENT_SYSTEM_ALERT; case ax::mojom::Event::kCheckedStateChanged: case ax::mojom::Event::kExpandedChanged: case ax::mojom::Event::kStateChanged: return EVENT_OBJECT_STATECHANGE; case ax::mojom::Event::kFocus: case ax::mojom::Event::kFocusContext: return EVENT_OBJECT_FOCUS; case ax::mojom::Event::kLiveRegionChanged: return EVENT_OBJECT_LIVEREGIONCHANGED; case ax::mojom::Event::kMenuStart: return EVENT_SYSTEM_MENUSTART; case ax::mojom::Event::kMenuEnd: return EVENT_SYSTEM_MENUEND; case ax::mojom::Event::kMenuPopupStart: return EVENT_SYSTEM_MENUPOPUPSTART; case ax::mojom::Event::kMenuPopupEnd: return EVENT_SYSTEM_MENUPOPUPEND; case ax::mojom::Event::kSelection: return EVENT_OBJECT_SELECTION; case ax::mojom::Event::kSelectionAdd: return EVENT_OBJECT_SELECTIONADD; case ax::mojom::Event::kSelectionRemove: return EVENT_OBJECT_SELECTIONREMOVE; case ax::mojom::Event::kTextChanged: return EVENT_OBJECT_NAMECHANGE; case ax::mojom::Event::kTooltipClosed: return EVENT_OBJECT_HIDE; case ax::mojom::Event::kTooltipOpened: return EVENT_OBJECT_SHOW; case ax::mojom::Event::kValueChanged: return EVENT_OBJECT_VALUECHANGE; case ax::mojom::Event::kDocumentSelectionChanged: return EVENT_OBJECT_TEXTSELECTIONCHANGED; default: return std::nullopt; } } // static std::optional<EVENTID> AXPlatformNodeWin::MojoEventToUIAEvent( ax::mojom::Event event) { switch (event) { case ax::mojom::Event::kAlert: return UIA_SystemAlertEventId; case ax::mojom::Event::kDocumentSelectionChanged: return UIA_Text_TextChangedEventId; case ax::mojom::Event::kFocus: case ax::mojom::Event::kFocusContext: case ax::mojom::Event::kFocusAfterMenuClose: return UIA_AutomationFocusChangedEventId; case ax::mojom::Event::kLiveRegionChanged: return UIA_LiveRegionChangedEventId; case ax::mojom::Event::kSelection: return UIA_SelectionItem_ElementSelectedEventId; case ax::mojom::Event::kSelectionAdd: return UIA_SelectionItem_ElementAddedToSelectionEventId; case ax::mojom::Event::kSelectionRemove: return UIA_SelectionItem_ElementRemovedFromSelectionEventId; case ax::mojom::Event::kTooltipClosed: return UIA_ToolTipClosedEventId; case ax::mojom::Event::kTooltipOpened: return UIA_ToolTipOpenedEventId; default: return std::nullopt; } } std::optional<PROPERTYID> AXPlatformNodeWin::MojoEventToUIAProperty( ax::mojom::Event event) { switch (event) { case ax::mojom::Event::kControlsChanged: return UIA_ControllerForPropertyId; case ax::mojom::Event::kCheckedStateChanged: return UIA_ToggleToggleStatePropertyId; case ax::mojom::Event::kRowCollapsed: case ax::mojom::Event::kRowExpanded: return UIA_ExpandCollapseExpandCollapseStatePropertyId; case ax::mojom::Event::kSelection: case ax::mojom::Event::kSelectionAdd: case ax::mojom::Event::kSelectionRemove: return UIA_SelectionItemIsSelectedPropertyId; case ax::mojom::Event::kValueChanged: if (SupportsToggle(GetData().role)) { return UIA_ToggleToggleStatePropertyId; } return std::nullopt; default: return std::nullopt; } } // static BSTR AXPlatformNodeWin::GetValueAttributeAsBstr(AXPlatformNodeWin* target) { // GetValueAttributeAsBstr() has two sets of special cases depending on the // node's role. // The first set apply without regard for the nodes |value| attribute. That is // the nodes value attribute isn't consider for the first set of special // cases. For example, if the node role is ax::mojom::Role::kColorWell, we do // not care at all about the node's ax::mojom::StringAttribute::kValue // attribute. The second set of special cases only apply if the value // attribute for the node is empty. That is, if // ax::mojom::StringAttribute::kValue is empty, we do something special. std::u16string result; // // Color Well special case (Use ax::mojom::IntAttribute::kColorValue) // if (target->GetData().role == ax::mojom::Role::kColorWell) { // static cast because SkColor is a 4-byte unsigned int unsigned int color = static_cast<unsigned int>( target->GetIntAttribute(ax::mojom::IntAttribute::kColorValue)); // This is just ARGB unsigned int red = (((color) >> 16) & 0xFF); unsigned int green = (((color) >> 8) & 0xFF); unsigned int blue = (((color) >> 0) & 0xFF); std::u16string value_text; value_text = base::NumberToString16(red * 100 / 255) + u"% red " + base::NumberToString16(green * 100 / 255) + u"% green " + base::NumberToString16(blue * 100 / 255) + u"% blue"; BSTR value = ::SysAllocString(fml::Utf16ToWideString(value_text).c_str()); BASE_DCHECK(value); return value; } // // Document special case (Use the document's URL) // if (target->GetData().role == ax::mojom::Role::kRootWebArea || target->GetData().role == ax::mojom::Role::kWebArea) { result = base::UTF8ToUTF16(target->GetDelegate()->GetTreeData().url); BSTR value = ::SysAllocString(fml::Utf16ToWideString(result).c_str()); BASE_DCHECK(value); return value; } // // Links (Use ax::mojom::StringAttribute::kUrl) // if (target->GetData().role == ax::mojom::Role::kLink) { result = target->GetString16Attribute(ax::mojom::StringAttribute::kUrl); BSTR value = ::SysAllocString(fml::Utf16ToWideString(result).c_str()); BASE_DCHECK(value); return value; } // For range controls, e.g. sliders and spin buttons, |ax_attr_value| holds // the aria-valuetext if present but not the inner text. The actual value, // provided either via aria-valuenow or the actual control's value is held in // |ax::mojom::FloatAttribute::kValueForRange|. result = target->GetString16Attribute(ax::mojom::StringAttribute::kValue); if (result.empty() && target->GetData().IsRangeValueSupported()) { float fval; if (target->GetFloatAttribute(ax::mojom::FloatAttribute::kValueForRange, &fval)) { result = base::NumberToString16(fval); BSTR value = ::SysAllocString(fml::Utf16ToWideString(result).c_str()); BASE_DCHECK(value); return value; } } if (result.empty() && target->IsRichTextField()) result = target->GetInnerText(); BSTR value = ::SysAllocString(fml::Utf16ToWideString(result).c_str()); BASE_DCHECK(value); return value; } HRESULT AXPlatformNodeWin::GetStringAttributeAsBstr( ax::mojom::StringAttribute attribute, BSTR* value_bstr) const { std::u16string str; if (!GetString16Attribute(attribute, &str)) return S_FALSE; *value_bstr = ::SysAllocString(fml::Utf16ToWideString(str).c_str()); BASE_DCHECK(*value_bstr); return S_OK; } HRESULT AXPlatformNodeWin::GetNameAsBstr(BSTR* value_bstr) const { std::u16string str = GetNameAsString16(); *value_bstr = ::SysAllocString(fml::Utf16ToWideString(str).c_str()); BASE_DCHECK(*value_bstr); return S_OK; } // TODO(gw280): https://github.com/flutter/flutter/issues/78800 // Alert targets void AXPlatformNodeWin::AddAlertTarget() {} void AXPlatformNodeWin::RemoveAlertTarget() {} AXPlatformNodeWin* AXPlatformNodeWin::GetTargetFromChildID( const VARIANT& var_id) { if (V_VT(&var_id) != VT_I4) return nullptr; LONG child_id = V_I4(&var_id); if (child_id == CHILDID_SELF) return this; if (child_id >= 1 && child_id <= GetDelegate()->GetChildCount()) { // Positive child ids are a 1-based child index, used by clients // that want to enumerate all immediate children. AXPlatformNodeBase* base = FromNativeViewAccessible(GetDelegate()->ChildAtIndex(child_id - 1)); return static_cast<AXPlatformNodeWin*>(base); } if (child_id >= 0) return nullptr; // Negative child ids can be used to map to any descendant. AXPlatformNode* node = GetFromUniqueId(-child_id); if (!node) return nullptr; AXPlatformNodeBase* base = FromNativeViewAccessible(node->GetNativeViewAccessible()); if (base && !base->IsDescendantOf(this)) base = nullptr; return static_cast<AXPlatformNodeWin*>(base); } bool AXPlatformNodeWin::IsInTreeGrid() { AXPlatformNodeBase* container = FromNativeViewAccessible(GetParent()); // If parent was a rowgroup, we need to look at the grandparent if (container && container->GetData().role == ax::mojom::Role::kRowGroup) container = FromNativeViewAccessible(container->GetParent()); if (!container) return false; return container->GetData().role == ax::mojom::Role::kTreeGrid; } HRESULT AXPlatformNodeWin::AllocateComArrayFromVector( std::vector<LONG>& results, LONG max, LONG** selected, LONG* n_selected) { BASE_DCHECK(max > 0); BASE_DCHECK(selected); BASE_DCHECK(n_selected); auto count = std::min((LONG)results.size(), max); *n_selected = count; *selected = static_cast<LONG*>(CoTaskMemAlloc(sizeof(LONG) * count)); for (LONG i = 0; i < count; i++) (*selected)[i] = results[i]; return S_OK; } bool AXPlatformNodeWin::IsPlaceholderText() const { if (GetData().role != ax::mojom::Role::kStaticText) return false; AXPlatformNodeWin* parent = static_cast<AXPlatformNodeWin*>(FromNativeViewAccessible(GetParent())); // Static text nodes are always expected to have a parent. BASE_DCHECK(parent); return parent->IsTextField() && parent->HasStringAttribute(ax::mojom::StringAttribute::kPlaceholder); } double AXPlatformNodeWin::GetHorizontalScrollPercent() { if (!IsHorizontallyScrollable()) return UIA_ScrollPatternNoScroll; float x_min = GetIntAttribute(ax::mojom::IntAttribute::kScrollXMin); float x_max = GetIntAttribute(ax::mojom::IntAttribute::kScrollXMax); float x = GetIntAttribute(ax::mojom::IntAttribute::kScrollX); return 100.0 * (x - x_min) / (x_max - x_min); } double AXPlatformNodeWin::GetVerticalScrollPercent() { if (!IsVerticallyScrollable()) return UIA_ScrollPatternNoScroll; float y_min = GetIntAttribute(ax::mojom::IntAttribute::kScrollYMin); float y_max = GetIntAttribute(ax::mojom::IntAttribute::kScrollYMax); float y = GetIntAttribute(ax::mojom::IntAttribute::kScrollY); return 100.0 * (y - y_min) / (y_max - y_min); } BSTR AXPlatformNodeWin::GetFontNameAttributeAsBSTR() const { const std::u16string string = GetInheritedString16Attribute(ax::mojom::StringAttribute::kFontFamily); return ::SysAllocString(fml::Utf16ToWideString(string).c_str()); } BSTR AXPlatformNodeWin::GetStyleNameAttributeAsBSTR() const { std::u16string style_name = GetDelegate()->GetStyleNameAttributeAsLocalizedString(); return ::SysAllocString(fml::Utf16ToWideString(style_name).c_str()); } TextDecorationLineStyle AXPlatformNodeWin::GetUIATextDecorationStyle( const ax::mojom::IntAttribute int_attribute) const { const ax::mojom::TextDecorationStyle text_decoration_style = static_cast<ax::mojom::TextDecorationStyle>( GetIntAttribute(int_attribute)); switch (text_decoration_style) { case ax::mojom::TextDecorationStyle::kNone: return TextDecorationLineStyle::TextDecorationLineStyle_None; case ax::mojom::TextDecorationStyle::kDotted: return TextDecorationLineStyle::TextDecorationLineStyle_Dot; case ax::mojom::TextDecorationStyle::kDashed: return TextDecorationLineStyle::TextDecorationLineStyle_Dash; case ax::mojom::TextDecorationStyle::kSolid: return TextDecorationLineStyle::TextDecorationLineStyle_Single; case ax::mojom::TextDecorationStyle::kDouble: return TextDecorationLineStyle::TextDecorationLineStyle_Double; case ax::mojom::TextDecorationStyle::kWavy: return TextDecorationLineStyle::TextDecorationLineStyle_Wavy; } } // IRawElementProviderSimple support methods. AXPlatformNodeWin::PatternProviderFactoryMethod AXPlatformNodeWin::GetPatternProviderFactoryMethod(PATTERNID pattern_id) { const AXNodeData& data = GetData(); switch (pattern_id) { case UIA_ExpandCollapsePatternId: if (data.SupportsExpandCollapse()) { return &PatternProvider<IExpandCollapseProvider>; } break; case UIA_GridPatternId: if (IsTableLike(data.role)) { return &PatternProvider<IGridProvider>; } break; case UIA_GridItemPatternId: if (IsCellOrTableHeader(data.role)) { return &PatternProvider<IGridItemProvider>; } break; case UIA_InvokePatternId: if (data.IsInvocable()) { return &PatternProvider<IInvokeProvider>; } break; case UIA_RangeValuePatternId: if (data.IsRangeValueSupported()) { return &PatternProvider<IRangeValueProvider>; } break; case UIA_ScrollPatternId: if (IsScrollable()) { return &PatternProvider<IScrollProvider>; } break; case UIA_ScrollItemPatternId: return &PatternProvider<IScrollItemProvider>; break; case UIA_SelectionItemPatternId: if (IsSelectionItemSupported()) { return &PatternProvider<ISelectionItemProvider>; } break; case UIA_SelectionPatternId: if (IsContainerWithSelectableChildren(data.role)) { return &PatternProvider<ISelectionProvider>; } break; case UIA_TablePatternId: // https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/nn-uiautomationcore-itableprovider // This control pattern is analogous to IGridProvider with the distinction // that any control implementing ITableProvider must also expose a column // and/or row header relationship for each child element. if (IsTableLike(data.role)) { std::optional<bool> table_has_headers = GetDelegate()->GetTableHasColumnOrRowHeaderNode(); if (table_has_headers.has_value() && table_has_headers.value()) { return &PatternProvider<ITableProvider>; } } break; case UIA_TableItemPatternId: // https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/nn-uiautomationcore-itableitemprovider // This control pattern is analogous to IGridItemProvider with the // distinction that any control implementing ITableItemProvider must // expose the relationship between the individual cell and its row and // column information. if (IsCellOrTableHeader(data.role)) { std::optional<bool> table_has_headers = GetDelegate()->GetTableHasColumnOrRowHeaderNode(); if (table_has_headers.has_value() && table_has_headers.value()) { return &PatternProvider<ITableItemProvider>; } } break; case UIA_TextEditPatternId: case UIA_TextPatternId: if (IsText() || IsTextField() || data.role == ax::mojom::Role::kRootWebArea) { return &AXPlatformNodeTextProviderWin::CreateIUnknown; } break; case UIA_TogglePatternId: if (SupportsToggle(data.role)) { return &PatternProvider<IToggleProvider>; } break; case UIA_ValuePatternId: if (IsValuePatternSupported(GetDelegate())) { return &PatternProvider<IValueProvider>; } break; case UIA_WindowPatternId: if (HasBoolAttribute(ax::mojom::BoolAttribute::kModal)) { return &PatternProvider<IWindowProvider>; } break; // Not currently implemented. case UIA_AnnotationPatternId: case UIA_CustomNavigationPatternId: case UIA_DockPatternId: case UIA_DragPatternId: case UIA_DropTargetPatternId: case UIA_ItemContainerPatternId: case UIA_MultipleViewPatternId: case UIA_ObjectModelPatternId: case UIA_SpreadsheetPatternId: case UIA_SpreadsheetItemPatternId: case UIA_StylesPatternId: case UIA_SynchronizedInputPatternId: case UIA_TextPattern2Id: case UIA_TransformPatternId: case UIA_TransformPattern2Id: case UIA_VirtualizedItemPatternId: break; // Provided by UIA Core; we should not implement. case UIA_LegacyIAccessiblePatternId: break; } return nullptr; } void AXPlatformNodeWin::FireLiveRegionChangeRecursive() { const auto live_status_attr = ax::mojom::StringAttribute::kLiveStatus; if (HasStringAttribute(live_status_attr) && GetStringAttribute(live_status_attr) != "off") { BASE_DCHECK(GetDelegate()->IsWebContent()); ::UiaRaiseAutomationEvent(this, UIA_LiveRegionChangedEventId); return; } for (int index = 0; index < GetChildCount(); ++index) { auto* child = static_cast<AXPlatformNodeWin*>( FromNativeViewAccessible(ChildAtIndex(index))); // We assume that only web-content will have live regions; also because // this will be called on each fragment-root, there is no need to walk // through non-content nodes. if (child->GetDelegate()->IsWebContent()) child->FireLiveRegionChangeRecursive(); } } AXPlatformNodeWin* AXPlatformNodeWin::GetLowestAccessibleElement() { if (!IsInaccessibleDueToAncestor()) return this; AXPlatformNodeWin* parent = static_cast<AXPlatformNodeWin*>( AXPlatformNode::FromNativeViewAccessible(GetParent())); while (parent) { if (parent->ShouldHideChildrenForUIA()) return parent; parent = static_cast<AXPlatformNodeWin*>( AXPlatformNode::FromNativeViewAccessible(parent->GetParent())); } BASE_UNREACHABLE(); return nullptr; } AXPlatformNodeWin* AXPlatformNodeWin::GetFirstTextOnlyDescendant() { for (auto* child = static_cast<AXPlatformNodeWin*>(GetFirstChild()); child; child = static_cast<AXPlatformNodeWin*>(child->GetNextSibling())) { if (child->IsText()) return child; if (AXPlatformNodeWin* descendant = child->GetFirstTextOnlyDescendant()) return descendant; } return nullptr; } bool AXPlatformNodeWin::IsDescendantOf(AXPlatformNode* ancestor) const { if (!ancestor) { return false; } if (AXPlatformNodeBase::IsDescendantOf(ancestor)) { return true; } // Test if the ancestor is an IRawElementProviderFragmentRoot and if it // matches this node's root fragment. IRawElementProviderFragmentRoot* root; if (SUCCEEDED( const_cast<AXPlatformNodeWin*>(this)->get_FragmentRoot(&root))) { AXPlatformNodeWin* root_win; if (SUCCEEDED(root->QueryInterface(__uuidof(AXPlatformNodeWin), reinterpret_cast<void**>(&root_win)))) { return ancestor == static_cast<AXPlatformNode*>(root_win); } } return false; } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_platform_node_win.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_win.cc", "repo_id": "engine", "token_count": 79135 }
404
// 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 "test_ax_node_helper.h" #include <map> #include <utility> #include "ax_action_data.h" #include "ax_role_properties.h" #include "ax_table_info.h" #include "ax_tree_observer.h" #include "base/numerics/ranges.h" #include "gfx/geometry/rect_conversions.h" namespace ui { namespace { // A global map from AXNodes to TestAXNodeHelpers. std::map<AXNode::AXID, TestAXNodeHelper*> g_node_id_to_helper_map; // A simple implementation of AXTreeObserver to catch when AXNodes are // deleted so we can delete their helpers. class TestAXTreeObserver : public AXTreeObserver { private: void OnNodeDeleted(AXTree* tree, int32_t node_id) override { const auto iter = g_node_id_to_helper_map.find(node_id); if (iter != g_node_id_to_helper_map.end()) { TestAXNodeHelper* helper = iter->second; delete helper; g_node_id_to_helper_map.erase(node_id); } } }; TestAXTreeObserver g_ax_tree_observer; } // namespace // static TestAXNodeHelper* TestAXNodeHelper::GetOrCreate(AXTree* tree, AXNode* node) { if (!tree || !node) return nullptr; if (!tree->HasObserver(&g_ax_tree_observer)) tree->AddObserver(&g_ax_tree_observer); auto iter = g_node_id_to_helper_map.find(node->id()); if (iter != g_node_id_to_helper_map.end()) return iter->second; TestAXNodeHelper* helper = new TestAXNodeHelper(tree, node); g_node_id_to_helper_map[node->id()] = helper; return helper; } TestAXNodeHelper::TestAXNodeHelper(AXTree* tree, AXNode* node) : tree_(tree), node_(node) {} TestAXNodeHelper::~TestAXNodeHelper() = default; gfx::Rect TestAXNodeHelper::GetBoundsRect( const AXCoordinateSystem coordinate_system, const AXClippingBehavior clipping_behavior, AXOffscreenResult* offscreen_result) const { switch (coordinate_system) { case AXCoordinateSystem::kScreenPhysicalPixels: // For unit testing purposes, assume a device scale factor of 1 and fall // through. case AXCoordinateSystem::kScreenDIPs: { // We could optionally add clipping here if ever needed. gfx::RectF bounds = GetLocation(); // For test behavior only, for bounds that are offscreen we currently do // not apply clipping to the bounds but we still return the offscreen // status. if (offscreen_result) { *offscreen_result = DetermineOffscreenResult(bounds); } return gfx::ToEnclosingRect(bounds); } case AXCoordinateSystem::kRootFrame: case AXCoordinateSystem::kFrame: BASE_UNREACHABLE(); return gfx::Rect(); } } gfx::Rect TestAXNodeHelper::GetInnerTextRangeBoundsRect( const int start_offset, const int end_offset, const AXCoordinateSystem coordinate_system, const AXClippingBehavior clipping_behavior, AXOffscreenResult* offscreen_result) const { switch (coordinate_system) { case AXCoordinateSystem::kScreenPhysicalPixels: // For unit testing purposes, assume a device scale factor of 1 and fall // through. case AXCoordinateSystem::kScreenDIPs: { gfx::RectF bounds = GetLocation(); // This implementation currently only deals with text node that has role // kInlineTextBox and kStaticText. // For test purposes, assume node with kStaticText always has a single // child with role kInlineTextBox. if (GetData().role == ax::mojom::Role::kInlineTextBox) { bounds = GetInlineTextRect(start_offset, end_offset); } else if (GetData().role == ax::mojom::Role::kStaticText && InternalChildCount() > 0) { TestAXNodeHelper* child = InternalGetChild(0); if (child != nullptr && child->GetData().role == ax::mojom::Role::kInlineTextBox) { bounds = child->GetInlineTextRect(start_offset, end_offset); } } // For test behavior only, for bounds that are offscreen we currently do // not apply clipping to the bounds but we still return the offscreen // status. if (offscreen_result) { *offscreen_result = DetermineOffscreenResult(bounds); } return gfx::ToEnclosingRect(bounds); } case AXCoordinateSystem::kRootFrame: case AXCoordinateSystem::kFrame: BASE_UNREACHABLE(); return gfx::Rect(); } } const AXNodeData& TestAXNodeHelper::GetData() const { return node_->data(); } gfx::RectF TestAXNodeHelper::GetLocation() const { return GetData().relative_bounds.bounds; } int TestAXNodeHelper::InternalChildCount() const { return static_cast<int>(node_->GetUnignoredChildCount()); } TestAXNodeHelper* TestAXNodeHelper::InternalGetChild(int index) const { BASE_CHECK(index >= 0); BASE_CHECK(index < InternalChildCount()); return GetOrCreate( tree_, node_->GetUnignoredChildAtIndex(static_cast<size_t>(index))); } gfx::RectF TestAXNodeHelper::GetInlineTextRect(const int start_offset, const int end_offset) const { BASE_DCHECK(start_offset >= 0 && end_offset >= 0 && start_offset <= end_offset); const std::vector<int32_t>& character_offsets = GetData().GetIntListAttribute( ax::mojom::IntListAttribute::kCharacterOffsets); gfx::RectF location = GetLocation(); gfx::RectF bounds; switch (static_cast<ax::mojom::WritingDirection>( GetData().GetIntAttribute(ax::mojom::IntAttribute::kTextDirection))) { // Currently only kNone and kLtr are supported text direction. case ax::mojom::WritingDirection::kNone: case ax::mojom::WritingDirection::kLtr: { int start_pixel_offset = start_offset > 0 ? character_offsets[start_offset - 1] : location.x(); int end_pixel_offset = end_offset > 0 ? character_offsets[end_offset - 1] : location.x(); bounds = gfx::RectF(start_pixel_offset, location.y(), end_pixel_offset - start_pixel_offset, location.height()); break; } default: BASE_UNREACHABLE(); } return bounds; } AXOffscreenResult TestAXNodeHelper::DetermineOffscreenResult( gfx::RectF bounds) const { if (!tree_ || !tree_->root()) return AXOffscreenResult::kOnscreen; const AXNodeData& root_web_area_node_data = tree_->root()->data(); gfx::RectF root_web_area_bounds = root_web_area_node_data.relative_bounds.bounds; // For testing, we only look at the current node's bound relative to the root // web area bounds to determine offscreen status. We currently do not look at // the bounds of the immediate parent of the node for determining offscreen // status. // We only determine offscreen result if the root web area bounds is actually // set in the test. We default the offscreen result of every other situation // to AXOffscreenResult::kOnscreen. if (!root_web_area_bounds.IsEmpty()) { bounds.Intersect(root_web_area_bounds); if (bounds.IsEmpty()) return AXOffscreenResult::kOffscreen; } return AXOffscreenResult::kOnscreen; } } // namespace ui
engine/third_party/accessibility/ax/test_ax_node_helper.cc/0
{ "file_path": "engine/third_party/accessibility/ax/test_ax_node_helper.cc", "repo_id": "engine", "token_count": 2623 }
405
// 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. #ifndef ACCESSIBILITY_BASE_NO_DESTRUCTOR_H_ #define ACCESSIBILITY_BASE_NO_DESTRUCTOR_H_ #include <new> #include <utility> namespace base { // A wrapper that makes it easy to create an object of type T with static // storage duration that: // - is only constructed on first access // - never invokes the destructor // in order to satisfy the styleguide ban on global constructors and // destructors. // // Runtime constant example: // const std::string& GetLineSeparator() { // // Forwards to std::string(size_t, char, const Allocator&) constructor. // static const base::NoDestructor<std::string> s(5, '-'); // return *s; // } // // More complex initialization with a lambda: // const std::string& GetSessionNonce() { // static const base::NoDestructor<std::string> nonce([] { // std::string s(16); // crypto::RandString(s.data(), s.size()); // return s; // }()); // return *nonce; // } // // NoDestructor<T> stores the object inline, so it also avoids a pointer // indirection and a malloc. Also note that since C++11 static local variable // initialization is thread-safe and so is this pattern. Code should prefer to // use NoDestructor<T> over: // - A function scoped static T* or T& that is dynamically initialized. // - A global base::LazyInstance<T>. // // Note that since the destructor is never run, this *will* leak memory if used // as a stack or member variable. Furthermore, a NoDestructor<T> should never // have global scope as that may require a static initializer. template <typename T> class NoDestructor { public: // Not constexpr; just write static constexpr T x = ...; if the value should // be a constexpr. template <typename... Args> explicit NoDestructor(Args&&... args) { new (storage_) T(std::forward<Args>(args)...); } // Allows copy and move construction of the contained type, to allow // construction from an initializer list, e.g. for std::vector. explicit NoDestructor(const T& x) { new (storage_) T(x); } explicit NoDestructor(T&& x) { new (storage_) T(std::move(x)); } NoDestructor(const NoDestructor&) = delete; NoDestructor& operator=(const NoDestructor&) = delete; ~NoDestructor() = default; const T& operator*() const { return *get(); } T& operator*() { return *get(); } const T* operator->() const { return get(); } T* operator->() { return get(); } const T* get() const { return reinterpret_cast<const T*>(storage_); } T* get() { return reinterpret_cast<T*>(storage_); } private: alignas(T) char storage_[sizeof(T)]; #if defined(LEAK_SANITIZER) // TODO(https://crbug.com/812277): This is a hack to work around the fact // that LSan doesn't seem to treat NoDestructor as a root for reachability // analysis. This means that code like this: // static base::NoDestructor<std::vector<int>> v({1, 2, 3}); // is considered a leak. Using the standard leak sanitizer annotations to // suppress leaks doesn't work: std::vector is implicitly constructed before // calling the base::NoDestructor constructor. // // Unfortunately, I haven't been able to demonstrate this issue in simpler // reproductions: until that's resolved, hold an explicit pointer to the // placement-new'd object in leak sanitizer mode to help LSan realize that // objects allocated by the contained type are still reachable. T* storage_ptr_ = reinterpret_cast<T*>(storage_); #endif // defined(LEAK_SANITIZER) }; } // namespace base #endif // ACCESSIBILITY_BASE_NO_DESTRUCTOR_H_
engine/third_party/accessibility/base/no_destructor.h/0
{ "file_path": "engine/third_party/accessibility/base/no_destructor.h", "repo_id": "engine", "token_count": 1140 }
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 ACCESSIBILITY_BASE_PLATFORM_DARWIN_SCOPED_NSOBJECT_H_ #define ACCESSIBILITY_BASE_PLATFORM_DARWIN_SCOPED_NSOBJECT_H_ // Include NSObject.h directly because Foundation.h pulls in many dependencies. // (Approx 100k lines of code versus 1.5k for NSObject.h). scoped_nsobject gets // singled out because it is most typically included from other header files. #import <Foundation/NSObject.h> #include "base/compiler_specific.h" #include "base/macros.h" @class NSAutoreleasePool; namespace base { // scoped_nsobject<> is patterned after scoped_ptr<>, but maintains ownership // of an NSObject subclass object. Style deviations here are solely for // compatibility with scoped_ptr<>'s interface, with which everyone is already // familiar. // // scoped_nsobject<> takes ownership of an object (in the constructor or in // reset()) by taking over the caller's existing ownership claim. The caller // must own the object it gives to scoped_nsobject<>, and relinquishes an // ownership claim to that object. scoped_nsobject<> does not call -retain, // callers have to call this manually if appropriate. // // scoped_nsprotocol<> has the same behavior as scoped_nsobject, but can be used // with protocols. // // scoped_nsobject<> is not to be used for NSAutoreleasePools. For // NSAutoreleasePools use ScopedNSAutoreleasePool from // scoped_nsautorelease_pool.h instead. // We check for bad uses of scoped_nsobject and NSAutoreleasePool at compile // time with a template specialization (see below). template <typename NST> class scoped_nsprotocol { public: explicit scoped_nsprotocol(NST object = nil) : object_(object) {} scoped_nsprotocol(const scoped_nsprotocol<NST>& that) : object_([that.object_ retain]) {} template <typename NSU> scoped_nsprotocol(const scoped_nsprotocol<NSU>& that) : object_([that.get() retain]) {} ~scoped_nsprotocol() { [object_ release]; } scoped_nsprotocol& operator=(const scoped_nsprotocol<NST>& that) { reset([that.get() retain]); return *this; } void reset(NST object = nil) { // We intentionally do not check that object != object_ as the caller must // either already have an ownership claim over whatever it passes to this // method, or call it with the |RETAIN| policy which will have ensured that // the object is retained once more when reaching this point. [object_ release]; object_ = object; } bool operator==(NST that) const { return object_ == that; } bool operator!=(NST that) const { return object_ != that; } operator NST() const { return object_; } NST get() const { return object_; } void swap(scoped_nsprotocol& that) { NST temp = that.object_; that.object_ = object_; object_ = temp; } // Shift reference to the autorelease pool to be released later. NST autorelease() { return [release() autorelease]; } private: NST object_; // scoped_nsprotocol<>::release() is like scoped_ptr<>::release. It is NOT a // wrapper for [object_ release]. To force a scoped_nsprotocol<> to call // [object_ release], use scoped_nsprotocol<>::reset(). [[nodiscard]] NST release() { NST temp = object_; object_ = nil; return temp; } }; // Free functions template <class C> void swap(scoped_nsprotocol<C>& p1, scoped_nsprotocol<C>& p2) { p1.swap(p2); } template <class C> bool operator==(C p1, const scoped_nsprotocol<C>& p2) { return p1 == p2.get(); } template <class C> bool operator!=(C p1, const scoped_nsprotocol<C>& p2) { return p1 != p2.get(); } template <typename NST> class scoped_nsobject : public scoped_nsprotocol<NST*> { public: explicit scoped_nsobject(NST* object = nil) : scoped_nsprotocol<NST*>(object) {} scoped_nsobject(const scoped_nsobject<NST>& that) : scoped_nsprotocol<NST*>(that) {} template <typename NSU> scoped_nsobject(const scoped_nsobject<NSU>& that) : scoped_nsprotocol<NST*>(that) {} scoped_nsobject& operator=(const scoped_nsobject<NST>& that) { scoped_nsprotocol<NST*>::operator=(that); return *this; } }; // Specialization to make scoped_nsobject<id> work. template <> class scoped_nsobject<id> : public scoped_nsprotocol<id> { public: explicit scoped_nsobject(id object = nil) : scoped_nsprotocol<id>(object) {} scoped_nsobject(const scoped_nsobject<id>& that) : scoped_nsprotocol<id>(that) {} template <typename NSU> scoped_nsobject(const scoped_nsobject<NSU>& that) : scoped_nsprotocol<id>(that) {} scoped_nsobject& operator=(const scoped_nsobject<id>& that) { scoped_nsprotocol<id>::operator=(that); return *this; } }; // Do not use scoped_nsobject for NSAutoreleasePools, use // ScopedNSAutoreleasePool instead. This is a compile time check. See details // at top of header. template <> class scoped_nsobject<NSAutoreleasePool> { private: explicit scoped_nsobject(NSAutoreleasePool* object = nil); BASE_DISALLOW_COPY_AND_ASSIGN(scoped_nsobject); }; } // namespace base #endif // FLUTTER_BASE_PLATFORM_DARWIN_SCOPED_NSOBJECT_H_
engine/third_party/accessibility/base/platform/darwin/scoped_nsobject.h/0
{ "file_path": "engine/third_party/accessibility/base/platform/darwin/scoped_nsobject.h", "repo_id": "engine", "token_count": 1826 }
407
// 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. #ifndef BASE_WIN_ENUM_VARIANT_H_ #define BASE_WIN_ENUM_VARIANT_H_ #include <wrl/implements.h> #include <memory> #include <vector> #include "base/win/scoped_variant.h" namespace base { namespace win { // A simple implementation of IEnumVARIANT. class BASE_EXPORT EnumVariant : public Microsoft::WRL::RuntimeClass< Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>, IEnumVARIANT> { public: // The constructor allocates a vector of empty ScopedVariants of size |count|. // Use ItemAt to set the value of each item in the array. explicit EnumVariant(ULONG count); // IEnumVARIANT: IFACEMETHODIMP Next(ULONG requested_count, VARIANT* out_elements, ULONG* out_elements_received) override; IFACEMETHODIMP Skip(ULONG skip_count) override; IFACEMETHODIMP Reset() override; IFACEMETHODIMP Clone(IEnumVARIANT** out_cloned_object) override; // Returns a mutable pointer to the item at position |index|. VARIANT* ItemAt(ULONG index); private: ~EnumVariant() override; std::vector<ScopedVariant> items_; ULONG current_index_; }; } // namespace win } // namespace base #endif // BASE_WIN_ENUM_VARIANT_H_
engine/third_party/accessibility/base/win/enum_variant.h/0
{ "file_path": "engine/third_party/accessibility/base/win/enum_variant.h", "repo_id": "engine", "token_count": 517 }
408
// Copyright (c) 2009 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 "insets.h" #include "base/string_utils.h" #include "vector2d.h" namespace gfx { std::string Insets::ToString() const { // Print members in the same order of the constructor parameters. return base::StringPrintf("%d,%d,%d,%d", top(), left(), bottom(), right()); } Insets Insets::Offset(const gfx::Vector2d& vector) const { return gfx::Insets(base::ClampAdd(top(), vector.y()), base::ClampAdd(left(), vector.x()), base::ClampSub(bottom(), vector.y()), base::ClampSub(right(), vector.x())); } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/insets.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/insets.cc", "repo_id": "engine", "token_count": 297 }
409
// 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_f.h" #include <algorithm> #include <limits> #include "ax_build/build_config.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/string_utils.h" #include "insets_f.h" #if defined(OS_IOS) #include <CoreGraphics/CoreGraphics.h> #elif defined(OS_APPLE) #include <ApplicationServices/ApplicationServices.h> #endif namespace gfx { static void AdjustAlongAxis(float dst_origin, float dst_size, float* origin, float* size) { *size = std::min(dst_size, *size); if (*origin < dst_origin) *origin = dst_origin; else *origin = std::min(dst_origin + dst_size, *origin + *size) - *size; } #if defined(OS_APPLE) RectF::RectF(const CGRect& r) : origin_(r.origin.x, r.origin.y), size_(r.size.width, r.size.height) {} CGRect RectF::ToCGRect() const { return CGRectMake(x(), y(), width(), height()); } #endif void RectF::Inset(const InsetsF& insets) { Inset(insets.left(), insets.top(), insets.right(), insets.bottom()); } void RectF::Inset(float left, float top, float right, float bottom) { origin_ += Vector2dF(left, top); set_width(std::max(width() - left - right, 0.0f)); set_height(std::max(height() - top - bottom, 0.0f)); } void RectF::Offset(float horizontal, float vertical) { origin_ += Vector2dF(horizontal, vertical); } void RectF::operator+=(const Vector2dF& offset) { origin_ += offset; } void RectF::operator-=(const Vector2dF& offset) { origin_ -= offset; } InsetsF RectF::InsetsFrom(const RectF& inner) const { return InsetsF(inner.y() - y(), inner.x() - x(), bottom() - inner.bottom(), right() - inner.right()); } bool RectF::operator<(const RectF& other) const { if (origin_ != other.origin_) return origin_ < other.origin_; if (width() == other.width()) return height() < other.height(); return width() < other.width(); } bool RectF::Contains(float point_x, float point_y) const { return point_x >= x() && point_x < right() && point_y >= y() && point_y < bottom(); } bool RectF::Contains(const RectF& rect) const { return rect.x() >= x() && rect.right() <= right() && rect.y() >= y() && rect.bottom() <= bottom(); } bool RectF::Intersects(const RectF& rect) const { return !IsEmpty() && !rect.IsEmpty() && rect.x() < right() && rect.right() > x() && rect.y() < bottom() && rect.bottom() > y(); } void RectF::Intersect(const RectF& rect) { if (IsEmpty() || rect.IsEmpty()) { SetRect(0, 0, 0, 0); return; } float rx = std::max(x(), rect.x()); float ry = std::max(y(), rect.y()); float rr = std::min(right(), rect.right()); float rb = std::min(bottom(), rect.bottom()); if (rx >= rr || ry >= rb) { SetRect(0, 0, 0, 0); return; } SetRect(rx, ry, rr - rx, rb - ry); } void RectF::Union(const RectF& rect) { if (IsEmpty()) { *this = rect; return; } if (rect.IsEmpty()) return; float rx = std::min(x(), rect.x()); float ry = std::min(y(), rect.y()); float rr = std::max(right(), rect.right()); float rb = std::max(bottom(), rect.bottom()); SetRect(rx, ry, rr - rx, rb - ry); } void RectF::Subtract(const RectF& rect) { if (!Intersects(rect)) return; if (rect.Contains(*this)) { SetRect(0, 0, 0, 0); return; } float rx = x(); float ry = y(); float rr = right(); float rb = bottom(); if (rect.y() <= y() && rect.bottom() >= bottom()) { // complete intersection in the y-direction if (rect.x() <= x()) { rx = rect.right(); } else if (rect.right() >= right()) { rr = rect.x(); } } else if (rect.x() <= x() && rect.right() >= right()) { // complete intersection in the x-direction if (rect.y() <= y()) { ry = rect.bottom(); } else if (rect.bottom() >= bottom()) { rb = rect.y(); } } SetRect(rx, ry, rr - rx, rb - ry); } void RectF::AdjustToFit(const RectF& rect) { float new_x = x(); float new_y = y(); float new_width = width(); float new_height = height(); AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width); AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height); SetRect(new_x, new_y, new_width, new_height); } PointF RectF::CenterPoint() const { return PointF(x() + width() / 2, y() + height() / 2); } void RectF::ClampToCenteredSize(const SizeF& size) { float new_width = std::min(width(), size.width()); float new_height = std::min(height(), size.height()); float new_x = x() + (width() - new_width) / 2; float new_y = y() + (height() - new_height) / 2; SetRect(new_x, new_y, new_width, new_height); } void RectF::Transpose() { SetRect(y(), x(), height(), width()); } void RectF::SplitVertically(RectF* left_half, RectF* right_half) const { BASE_DCHECK(left_half); BASE_DCHECK(right_half); left_half->SetRect(x(), y(), width() / 2, height()); right_half->SetRect(left_half->right(), y(), width() - left_half->width(), height()); } bool RectF::SharesEdgeWith(const RectF& rect) const { return (y() == rect.y() && height() == rect.height() && (x() == rect.right() || right() == rect.x())) || (x() == rect.x() && width() == rect.width() && (y() == rect.bottom() || bottom() == rect.y())); } float RectF::ManhattanDistanceToPoint(const PointF& point) const { float x_distance = std::max<float>(0, std::max(x() - point.x(), point.x() - right())); float y_distance = std::max<float>(0, std::max(y() - point.y(), point.y() - bottom())); return x_distance + y_distance; } float RectF::ManhattanInternalDistance(const RectF& rect) const { RectF c(*this); c.Union(rect); static constexpr float kEpsilon = std::numeric_limits<float>::epsilon(); float x = std::max(0.f, c.width() - width() - rect.width() + kEpsilon); float y = std::max(0.f, c.height() - height() - rect.height() + kEpsilon); return x + y; } bool RectF::IsExpressibleAsRect() const { return base::IsValueInRangeForNumericType<int>(x()) && base::IsValueInRangeForNumericType<int>(y()) && base::IsValueInRangeForNumericType<int>(width()) && base::IsValueInRangeForNumericType<int>(height()) && base::IsValueInRangeForNumericType<int>(right()) && base::IsValueInRangeForNumericType<int>(bottom()); } std::string RectF::ToString() const { return base::StringPrintf("%s %s", origin().ToString().c_str(), size().ToString().c_str()); } RectF IntersectRects(const RectF& a, const RectF& b) { RectF result = a; result.Intersect(b); return result; } RectF UnionRects(const RectF& a, const RectF& b) { RectF result = a; result.Union(b); return result; } RectF SubtractRects(const RectF& a, const RectF& b) { RectF result = a; result.Subtract(b); return result; } RectF BoundingRect(const PointF& p1, const PointF& p2) { float rx = std::min(p1.x(), p2.x()); float ry = std::min(p1.y(), p2.y()); float rr = std::max(p1.x(), p2.x()); float rb = std::max(p1.y(), p2.y()); return RectF(rx, ry, rr - rx, rb - ry); } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/rect_f.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/rect_f.cc", "repo_id": "engine", "token_count": 2975 }
410
// 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 <cmath> #include <cstddef> #include <limits> #include "gtest/gtest.h" #include "vector2d.h" #include "vector2d_f.h" namespace gfx { template <typename T, size_t N> constexpr size_t size(const T (&array)[N]) noexcept { return N; } TEST(Vector2dTest, ConversionToFloat) { Vector2d i(3, 4); Vector2dF f = i; EXPECT_EQ(i, f); } TEST(Vector2dTest, IsZero) { Vector2d int_zero(0, 0); Vector2d int_nonzero(2, -2); Vector2dF float_zero(0, 0); Vector2dF float_nonzero(0.1f, -0.1f); EXPECT_TRUE(int_zero.IsZero()); EXPECT_FALSE(int_nonzero.IsZero()); EXPECT_TRUE(float_zero.IsZero()); EXPECT_FALSE(float_nonzero.IsZero()); } TEST(Vector2dTest, Add) { Vector2d i1(3, 5); Vector2d i2(4, -1); const struct { Vector2d expected; Vector2d actual; } int_tests[] = {{Vector2d(3, 5), i1 + Vector2d()}, {Vector2d(3 + 4, 5 - 1), i1 + i2}, {Vector2d(3 - 4, 5 + 1), i1 - i2}}; for (size_t i = 0; i < size(int_tests); ++i) EXPECT_EQ(int_tests[i].expected.ToString(), int_tests[i].actual.ToString()); Vector2dF f1(3.1f, 5.1f); Vector2dF f2(4.3f, -1.3f); const struct { Vector2dF expected; Vector2dF actual; } float_tests[] = {{Vector2dF(3.1F, 5.1F), f1 + Vector2d()}, {Vector2dF(3.1F, 5.1F), f1 + Vector2dF()}, {Vector2dF(3.1f + 4.3f, 5.1f - 1.3f), f1 + f2}, {Vector2dF(3.1f - 4.3f, 5.1f + 1.3f), f1 - f2}}; for (size_t i = 0; i < size(float_tests); ++i) EXPECT_EQ(float_tests[i].expected.ToString(), float_tests[i].actual.ToString()); } TEST(Vector2dTest, Negative) { const struct { Vector2d expected; Vector2d actual; } int_tests[] = {{Vector2d(0, 0), -Vector2d(0, 0)}, {Vector2d(-3, -3), -Vector2d(3, 3)}, {Vector2d(3, 3), -Vector2d(-3, -3)}, {Vector2d(-3, 3), -Vector2d(3, -3)}, {Vector2d(3, -3), -Vector2d(-3, 3)}}; for (size_t i = 0; i < size(int_tests); ++i) EXPECT_EQ(int_tests[i].expected.ToString(), int_tests[i].actual.ToString()); const struct { Vector2dF expected; Vector2dF actual; } float_tests[] = {{Vector2dF(0, 0), -Vector2d(0, 0)}, {Vector2dF(-0.3f, -0.3f), -Vector2dF(0.3f, 0.3f)}, {Vector2dF(0.3f, 0.3f), -Vector2dF(-0.3f, -0.3f)}, {Vector2dF(-0.3f, 0.3f), -Vector2dF(0.3f, -0.3f)}, {Vector2dF(0.3f, -0.3f), -Vector2dF(-0.3f, 0.3f)}}; for (size_t i = 0; i < size(float_tests); ++i) EXPECT_EQ(float_tests[i].expected.ToString(), float_tests[i].actual.ToString()); } TEST(Vector2dTest, Scale) { float double_values[][4] = { {4.5f, 1.2f, 3.3f, 5.6f}, {4.5f, -1.2f, 3.3f, 5.6f}, {4.5f, 1.2f, 3.3f, -5.6f}, {4.5f, 1.2f, -3.3f, -5.6f}, {-4.5f, 1.2f, 3.3f, 5.6f}, {-4.5f, 1.2f, 0, 5.6f}, {-4.5f, 1.2f, 3.3f, 0}, {4.5f, 0, 3.3f, 5.6f}, {0, 1.2f, 3.3f, 5.6f}}; for (size_t i = 0; i < size(double_values); ++i) { Vector2dF v(double_values[i][0], double_values[i][1]); v.Scale(double_values[i][2], double_values[i][3]); EXPECT_EQ(v.x(), double_values[i][0] * double_values[i][2]); EXPECT_EQ(v.y(), double_values[i][1] * double_values[i][3]); Vector2dF v2 = ScaleVector2d(gfx::Vector2dF(double_values[i][0], double_values[i][1]), double_values[i][2], double_values[i][3]); EXPECT_EQ(double_values[i][0] * double_values[i][2], v2.x()); EXPECT_EQ(double_values[i][1] * double_values[i][3], v2.y()); } float single_values[][3] = { {4.5f, 1.2f, 3.3f}, {4.5f, -1.2f, 3.3f}, {4.5f, 1.2f, 3.3f}, {4.5f, 1.2f, -3.3f}, {-4.5f, 1.2f, 3.3f}, {-4.5f, 1.2f, 0}, {-4.5f, 1.2f, 3.3f}, {4.5f, 0, 3.3f}, {0, 1.2f, 3.3f}}; for (size_t i = 0; i < size(single_values); ++i) { Vector2dF v(single_values[i][0], single_values[i][1]); v.Scale(single_values[i][2]); EXPECT_EQ(v.x(), single_values[i][0] * single_values[i][2]); EXPECT_EQ(v.y(), single_values[i][1] * single_values[i][2]); Vector2dF v2 = ScaleVector2d(gfx::Vector2dF(double_values[i][0], double_values[i][1]), double_values[i][2]); EXPECT_EQ(single_values[i][0] * single_values[i][2], v2.x()); EXPECT_EQ(single_values[i][1] * single_values[i][2], v2.y()); } } TEST(Vector2dTest, Length) { int int_values[][2] = { {0, 0}, {10, 20}, {20, 10}, {-10, -20}, {-20, 10}, {10, -20}, }; for (size_t i = 0; i < size(int_values); ++i) { int v0 = int_values[i][0]; int v1 = int_values[i][1]; double length_squared = static_cast<double>(v0) * v0 + static_cast<double>(v1) * v1; double length = std::sqrt(length_squared); Vector2d vector(v0, v1); EXPECT_EQ(static_cast<float>(length_squared), vector.LengthSquared()); EXPECT_EQ(static_cast<float>(length), vector.Length()); } float float_values[][2] = { {0, 0}, {10.5f, 20.5f}, {20.5f, 10.5f}, {-10.5f, -20.5f}, {-20.5f, 10.5f}, {10.5f, -20.5f}, // A large vector that fails if the Length function doesn't use // double precision internally. {1236278317862780234892374893213178027.12122348904204230f, 335890352589839028212313231225425134332.38123f}, }; for (size_t i = 0; i < size(float_values); ++i) { double v0 = float_values[i][0]; double v1 = float_values[i][1]; double length_squared = static_cast<double>(v0) * v0 + static_cast<double>(v1) * v1; double length = std::sqrt(length_squared); Vector2dF vector(v0, v1); EXPECT_DOUBLE_EQ(length_squared, vector.LengthSquared()); EXPECT_FLOAT_EQ(static_cast<float>(length), vector.Length()); } } TEST(Vector2dTest, ClampVector2d) { Vector2d a; a = Vector2d(3, 5); EXPECT_EQ(Vector2d(3, 5).ToString(), a.ToString()); a.SetToMax(Vector2d(2, 4)); EXPECT_EQ(Vector2d(3, 5).ToString(), a.ToString()); a.SetToMax(Vector2d(3, 5)); EXPECT_EQ(Vector2d(3, 5).ToString(), a.ToString()); a.SetToMax(Vector2d(4, 2)); EXPECT_EQ(Vector2d(4, 5).ToString(), a.ToString()); a.SetToMax(Vector2d(8, 10)); EXPECT_EQ(Vector2d(8, 10).ToString(), a.ToString()); a.SetToMin(Vector2d(9, 11)); EXPECT_EQ(Vector2d(8, 10).ToString(), a.ToString()); a.SetToMin(Vector2d(8, 10)); EXPECT_EQ(Vector2d(8, 10).ToString(), a.ToString()); a.SetToMin(Vector2d(11, 9)); EXPECT_EQ(Vector2d(8, 9).ToString(), a.ToString()); a.SetToMin(Vector2d(7, 11)); EXPECT_EQ(Vector2d(7, 9).ToString(), a.ToString()); a.SetToMin(Vector2d(3, 5)); EXPECT_EQ(Vector2d(3, 5).ToString(), a.ToString()); } TEST(Vector2dTest, ClampVector2dF) { Vector2dF a; a = Vector2dF(3.5f, 5.5f); EXPECT_EQ(Vector2dF(3.5f, 5.5f).ToString(), a.ToString()); a.SetToMax(Vector2dF(2.5f, 4.5f)); EXPECT_EQ(Vector2dF(3.5f, 5.5f).ToString(), a.ToString()); a.SetToMax(Vector2dF(3.5f, 5.5f)); EXPECT_EQ(Vector2dF(3.5f, 5.5f).ToString(), a.ToString()); a.SetToMax(Vector2dF(4.5f, 2.5f)); EXPECT_EQ(Vector2dF(4.5f, 5.5f).ToString(), a.ToString()); a.SetToMax(Vector2dF(8.5f, 10.5f)); EXPECT_EQ(Vector2dF(8.5f, 10.5f).ToString(), a.ToString()); a.SetToMin(Vector2dF(9.5f, 11.5f)); EXPECT_EQ(Vector2dF(8.5f, 10.5f).ToString(), a.ToString()); a.SetToMin(Vector2dF(8.5f, 10.5f)); EXPECT_EQ(Vector2dF(8.5f, 10.5f).ToString(), a.ToString()); a.SetToMin(Vector2dF(11.5f, 9.5f)); EXPECT_EQ(Vector2dF(8.5f, 9.5f).ToString(), a.ToString()); a.SetToMin(Vector2dF(7.5f, 11.5f)); EXPECT_EQ(Vector2dF(7.5f, 9.5f).ToString(), a.ToString()); a.SetToMin(Vector2dF(3.5f, 5.5f)); EXPECT_EQ(Vector2dF(3.5f, 5.5f).ToString(), a.ToString()); } TEST(Vector2dTest, IntegerOverflow) { int int_max = std::numeric_limits<int>::max(); int int_min = std::numeric_limits<int>::min(); Vector2d max_vector(int_max, int_max); Vector2d min_vector(int_min, int_min); Vector2d test; test = Vector2d(); test += Vector2d(int_max, int_max); EXPECT_EQ(test, max_vector); test = Vector2d(); test += Vector2d(int_min, int_min); EXPECT_EQ(test, min_vector); test = Vector2d(10, 20); test += Vector2d(int_max, int_max); EXPECT_EQ(test, max_vector); test = Vector2d(-10, -20); test += Vector2d(int_min, int_min); EXPECT_EQ(test, min_vector); test = Vector2d(); test -= Vector2d(int_max, int_max); EXPECT_EQ(test, Vector2d(-int_max, -int_max)); test = Vector2d(); test -= Vector2d(int_min, int_min); EXPECT_EQ(test, max_vector); test = Vector2d(10, 20); test -= Vector2d(int_min, int_min); EXPECT_EQ(test, max_vector); test = Vector2d(-10, -20); test -= Vector2d(int_max, int_max); EXPECT_EQ(test, min_vector); } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/vector2d_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/vector2d_unittest.cc", "repo_id": "engine", "token_count": 4544 }
411
Name: ninja Short Name: ninja URL: https://github.com/ninja-build/ninja Revision: See the CIPD version in DEPS License: Apache License 2.0 License File: https://github.com/ninja-build/ninja/blob/master/COPYING Security Critical: no Description: Ninja is a small build system with a focus on speed, and is used to build this project. The CIPD packages are built using the 3pp pipeline. https://chromium.googlesource.com/infra/infra/+/refs/heads/main/3pp/ninja/ Local Modifications: None
engine/third_party/ninja/README.flutter/0
{ "file_path": "engine/third_party/ninja/README.flutter", "repo_id": "engine", "token_count": 160 }
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. #include "tonic/common/log.h" #include <cstdarg> #include <cstdio> #include <memory> namespace tonic { namespace { std::function<void(const char*)> log_handler; } // namespace void Log(const char* format, ...) { va_list ap; va_start(ap, format); int result = vsnprintf(nullptr, 0, format, ap); va_end(ap); if (result < 0) { return; } int size = result + 1; std::unique_ptr<char[]> message = std::make_unique<char[]>(size); va_start(ap, format); result = vsnprintf(message.get(), size, format, ap); va_end(ap); if (result < 0) { return; } if (log_handler) { log_handler(message.get()); } else { printf("%s\n", message.get()); } } void SetLogHandler(std::function<void(const char*)> handler) { log_handler = handler; } } // namespace tonic
engine/third_party/tonic/common/log.cc/0
{ "file_path": "engine/third_party/tonic/common/log.cc", "repo_id": "engine", "token_count": 357 }
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. #ifndef LIB_TONIC_DART_MESSAGE_HANDLER_H_ #define LIB_TONIC_DART_MESSAGE_HANDLER_H_ #include <functional> #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/logging/dart_error.h" namespace tonic { class DartState; class DartMessageHandler { public: using TaskDispatcher = std::function<void(std::function<void(void)>)>; DartMessageHandler(); ~DartMessageHandler(); // Messages for the current isolate will be scheduled on |runner|. void Initialize(TaskDispatcher dispatcher); // Handle an unhandled error. If the error is fatal then shut down the // isolate. The message handler's isolate must be the current isolate. void UnhandledError(Dart_Handle error); // Did the isolate exit? bool isolate_exited() const { return isolate_exited_; } // Did the isolate have an uncaught exception error? bool isolate_had_uncaught_exception_error() const { return isolate_had_uncaught_exception_error_; } DartErrorHandleType isolate_last_error() const { return isolate_last_error_; } protected: // Called from an unknown thread for each message. void OnMessage(DartState* dart_state); // By default, called on the task runner's thread for each message. void OnHandleMessage(DartState* dart_state); bool handled_first_message() const { return handled_first_message_; } void set_handled_first_message(bool handled_first_message) { handled_first_message_ = handled_first_message; } bool handled_first_message_; bool isolate_exited_; bool isolate_had_uncaught_exception_error_; bool isolate_had_fatal_error_; DartErrorHandleType isolate_last_error_; TaskDispatcher task_dispatcher_; private: static void MessageNotifyCallback(Dart_Isolate dest_isolate); }; } // namespace tonic #endif // LIB_TONIC_DART_MESSAGE_HANDLER_H_
engine/third_party/tonic/dart_message_handler.h/0
{ "file_path": "engine/third_party/tonic/dart_message_handler.h", "repo_id": "engine", "token_count": 622 }
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. #include "flutter/testing/dart_isolate_runner.h" #include "flutter/testing/fixture_test.h" #include "tonic/converter/dart_converter.h" #include "tonic/file_loader/file_loader.h" namespace flutter { namespace testing { using FileLoaderTest = FixtureTest; TEST_F(FileLoaderTest, CanonicalizesFileUrlCorrectly) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings); auto isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings); auto vm_ref = DartVMRef::Create(settings, vm_snapshot, isolate_snapshot); ASSERT_TRUE(vm_ref); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "main", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_TRUE(isolate->RunInIsolateScope([]() { tonic::FileLoader file_loader; std::string original_url = "file:///Users/test/foo"; Dart_Handle dart_url = tonic::StdStringToDart(original_url); auto canonicalized_url = file_loader.CanonicalizeURL(Dart_Null(), dart_url); EXPECT_TRUE(canonicalized_url); EXPECT_EQ(tonic::StdStringFromDart(canonicalized_url), original_url); return true; })); } } // namespace testing } // namespace flutter
engine/third_party/tonic/file_loader/file_loader_unittests.cc/0
{ "file_path": "engine/third_party/tonic/file_loader/file_loader_unittests.cc", "repo_id": "engine", "token_count": 689 }
415
// 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/path.h" #include "filesystem/directory.h" #include "filesystem/scoped_temp_dir.h" #include "gtest/gtest.h" #include "tonic/common/build_config.h" namespace filesystem { void ExpectPlatformPath(std::string expected, std::string actual) { #if defined(OS_WIN) std::replace(expected.begin(), expected.end(), '/', '\\'); #endif EXPECT_EQ(expected, actual); } TEST(Path, SimplifyPath) { ExpectPlatformPath(".", SimplifyPath("")); ExpectPlatformPath(".", SimplifyPath(".")); ExpectPlatformPath("..", SimplifyPath("..")); ExpectPlatformPath("...", SimplifyPath("...")); ExpectPlatformPath("/", SimplifyPath("/")); ExpectPlatformPath("/", SimplifyPath("/.")); ExpectPlatformPath("/", SimplifyPath("/..")); ExpectPlatformPath("/...", SimplifyPath("/...")); ExpectPlatformPath("foo", SimplifyPath("foo")); ExpectPlatformPath("foo", SimplifyPath("foo/")); ExpectPlatformPath("foo", SimplifyPath("foo/.")); ExpectPlatformPath("foo", SimplifyPath("foo/./")); ExpectPlatformPath(".", SimplifyPath("foo/..")); ExpectPlatformPath(".", SimplifyPath("foo/../")); ExpectPlatformPath("foo/...", SimplifyPath("foo/...")); ExpectPlatformPath("foo/...", SimplifyPath("foo/.../")); ExpectPlatformPath("foo/.b", SimplifyPath("foo/.b")); ExpectPlatformPath("foo/.b", SimplifyPath("foo/.b/")); ExpectPlatformPath("/foo", SimplifyPath("/foo")); ExpectPlatformPath("/foo", SimplifyPath("/foo/")); ExpectPlatformPath("/foo", SimplifyPath("/foo/.")); ExpectPlatformPath("/foo", SimplifyPath("/foo/./")); ExpectPlatformPath("/", SimplifyPath("/foo/..")); ExpectPlatformPath("/", SimplifyPath("/foo/../")); ExpectPlatformPath("/foo/...", SimplifyPath("/foo/...")); ExpectPlatformPath("/foo/...", SimplifyPath("/foo/.../")); ExpectPlatformPath("/foo/.b", SimplifyPath("/foo/.b")); ExpectPlatformPath("/foo/.b", SimplifyPath("/foo/.b/")); ExpectPlatformPath("foo/bar", SimplifyPath("foo/bar")); ExpectPlatformPath("foo/bar", SimplifyPath("foo/bar/")); ExpectPlatformPath("foo/bar", SimplifyPath("foo/./bar")); ExpectPlatformPath("foo/bar", SimplifyPath("foo/./bar/")); ExpectPlatformPath("bar", SimplifyPath("foo/../bar")); ExpectPlatformPath("bar", SimplifyPath("foo/baz/../../bar")); ExpectPlatformPath("bar", SimplifyPath("foo/../bar/")); ExpectPlatformPath("foo/.../bar", SimplifyPath("foo/.../bar")); ExpectPlatformPath("foo/.../bar", SimplifyPath("foo/.../bar/")); ExpectPlatformPath("foo/.b/bar", SimplifyPath("foo/.b/bar")); ExpectPlatformPath("foo/.b/bar", SimplifyPath("foo/.b/bar/")); ExpectPlatformPath("/foo/bar", SimplifyPath("/foo/bar")); ExpectPlatformPath("/foo/bar", SimplifyPath("/foo/bar/")); ExpectPlatformPath("/foo/bar", SimplifyPath("/foo/./bar")); ExpectPlatformPath("/foo/bar", SimplifyPath("/foo/./bar/")); ExpectPlatformPath("/bar", SimplifyPath("/foo/../bar")); ExpectPlatformPath("/bar", SimplifyPath("/foo/../bar/")); ExpectPlatformPath("/foo/.../bar", SimplifyPath("/foo/.../bar")); ExpectPlatformPath("/foo/.../bar", SimplifyPath("/foo/.../bar/")); ExpectPlatformPath("/foo/.b/bar", SimplifyPath("/foo/.b/bar")); ExpectPlatformPath("/foo/.b/bar", SimplifyPath("/foo/.b/bar/")); ExpectPlatformPath("../foo", SimplifyPath("../foo")); ExpectPlatformPath("../../bar", SimplifyPath("../foo/../../bar")); ExpectPlatformPath("/bar", SimplifyPath("/foo/../../bar")); // Already clean ExpectPlatformPath(".", SimplifyPath("")); ExpectPlatformPath("abc", SimplifyPath("abc")); ExpectPlatformPath("abc/def", SimplifyPath("abc/def")); ExpectPlatformPath("a/b/c", SimplifyPath("a/b/c")); ExpectPlatformPath(".", SimplifyPath(".")); ExpectPlatformPath("..", SimplifyPath("..")); ExpectPlatformPath("../..", SimplifyPath("../..")); ExpectPlatformPath("../../abc", SimplifyPath("../../abc")); ExpectPlatformPath("/abc", SimplifyPath("/abc")); ExpectPlatformPath("/", SimplifyPath("/")); // Remove trailing slash ExpectPlatformPath("abc", SimplifyPath("abc/")); ExpectPlatformPath("abc/def", SimplifyPath("abc/def/")); ExpectPlatformPath("a/b/c", SimplifyPath("a/b/c/")); ExpectPlatformPath(".", SimplifyPath("./")); ExpectPlatformPath("..", SimplifyPath("../")); ExpectPlatformPath("../..", SimplifyPath("../../")); ExpectPlatformPath("/abc", SimplifyPath("/abc/")); // Remove doubled slash ExpectPlatformPath("abc/def/ghi", SimplifyPath("abc//def//ghi")); ExpectPlatformPath("/abc", SimplifyPath("//abc")); ExpectPlatformPath("/abc", SimplifyPath("///abc")); ExpectPlatformPath("/abc", SimplifyPath("//abc//")); ExpectPlatformPath("abc", SimplifyPath("abc//")); // Remove . elements ExpectPlatformPath("abc/def", SimplifyPath("abc/./def")); ExpectPlatformPath("/abc/def", SimplifyPath("/./abc/def")); ExpectPlatformPath("abc", SimplifyPath("abc/.")); // Remove .. elements ExpectPlatformPath("abc/def/jkl", SimplifyPath("abc/def/ghi/../jkl")); ExpectPlatformPath("abc/jkl", SimplifyPath("abc/def/../ghi/../jkl")); ExpectPlatformPath("abc", SimplifyPath("abc/def/..")); ExpectPlatformPath(".", SimplifyPath("abc/def/../..")); ExpectPlatformPath("/", SimplifyPath("/abc/def/../..")); ExpectPlatformPath("..", SimplifyPath("abc/def/../../..")); ExpectPlatformPath("/", SimplifyPath("/abc/def/../../..")); ExpectPlatformPath("../../mno", SimplifyPath("abc/def/../../../ghi/jkl/../../../mno")); ExpectPlatformPath("/mno", SimplifyPath("/../mno")); // Combinations ExpectPlatformPath("def", SimplifyPath("abc/./../def")); ExpectPlatformPath("def", SimplifyPath("abc//./../def")); ExpectPlatformPath("../../def", SimplifyPath("abc/../../././../def")); #if defined(OS_WIN) ExpectPlatformPath("a\\c", SimplifyPath("a\\b\\..\\c")); ExpectPlatformPath("X:\\a\\c", SimplifyPath("X:/a/b/../c")); ExpectPlatformPath("X:\\a\\b\\c", SimplifyPath("X:/a/b/./c")); ExpectPlatformPath("X:\\c", SimplifyPath("X:/../../c")); #endif } TEST(Path, AbsolutePath) { #if defined(OS_WIN) // We cut out the drive letter as it can be different on every system. EXPECT_EQ(":\\foo\\bar", AbsolutePath("\\foo\\bar").substr(1)); EXPECT_EQ(":\\foo\\bar", AbsolutePath("/foo/bar").substr(1)); EXPECT_EQ(":\\foo\\bar\\", AbsolutePath("\\foo\\bar\\").substr(1)); EXPECT_EQ(":\\foo\\bar\\", AbsolutePath("/foo/bar/").substr(1)); EXPECT_EQ("C:\\foo\\bar\\", AbsolutePath("C:\\foo\\bar\\")); EXPECT_EQ(GetCurrentDirectory() + "\\foo", AbsolutePath("foo")); #else EXPECT_EQ("/foo/bar", AbsolutePath("/foo/bar")); EXPECT_EQ("/foo/bar/", AbsolutePath("/foo/bar/")); EXPECT_EQ(GetCurrentDirectory() + "/foo", AbsolutePath("foo")); #endif EXPECT_EQ(GetCurrentDirectory(), AbsolutePath("")); } TEST(Path, GetDirectoryName) { EXPECT_EQ("foo", GetDirectoryName("foo/")); EXPECT_EQ("foo/bar", GetDirectoryName("foo/bar/")); EXPECT_EQ("foo", GetDirectoryName("foo/bar")); EXPECT_EQ("foo/bar", GetDirectoryName("foo/bar/..")); EXPECT_EQ("foo/bar/..", GetDirectoryName("foo/bar/../..")); EXPECT_EQ("", GetDirectoryName("foo")); EXPECT_EQ("/", GetDirectoryName("/")); EXPECT_EQ("", GetDirectoryName("a")); EXPECT_EQ("/", GetDirectoryName("/a")); EXPECT_EQ("/a", GetDirectoryName("/a/")); EXPECT_EQ("a", GetDirectoryName("a/")); #if defined(OS_WIN) EXPECT_EQ("C:\\", GetDirectoryName("C:\\")); EXPECT_EQ("C:\\foo", GetDirectoryName("C:\\foo\\")); EXPECT_EQ("C:\\foo", GetDirectoryName("C:\\foo\\bar")); EXPECT_EQ("foo\\bar", GetDirectoryName("foo\\bar\\")); EXPECT_EQ("foo", GetDirectoryName("foo\\bar")); EXPECT_EQ("\\", GetDirectoryName("\\")); EXPECT_EQ("\\", GetDirectoryName("\\a")); #endif } TEST(Path, GetBaseName) { EXPECT_EQ("", GetBaseName("foo/")); EXPECT_EQ("", GetBaseName("foo/bar/")); EXPECT_EQ("bar", GetBaseName("foo/bar")); EXPECT_EQ("..", GetBaseName("foo/bar/..")); EXPECT_EQ("..", GetBaseName("foo/bar/../..")); EXPECT_EQ("foo", GetBaseName("foo")); EXPECT_EQ("", GetBaseName("/")); EXPECT_EQ("a", GetBaseName("a")); EXPECT_EQ("a", GetBaseName("/a")); EXPECT_EQ("", GetBaseName("/a/")); EXPECT_EQ("", GetBaseName("a/")); #if defined(OS_WIN) EXPECT_EQ("", GetBaseName("C:\\")); EXPECT_EQ("", GetBaseName("C:\\foo\\")); EXPECT_EQ("bar", GetBaseName("C:\\foo\\bar")); EXPECT_EQ("", GetBaseName("foo\\bar\\")); EXPECT_EQ("bar", GetBaseName("foo\\bar")); EXPECT_EQ("", GetBaseName("\\")); EXPECT_EQ("a", GetBaseName("\\a")); #endif } TEST(Path, DeletePath) { ScopedTempDir dir; std::string sub_dir = dir.path() + "/dir"; CreateDirectory(sub_dir); EXPECT_TRUE(IsDirectory(sub_dir)); EXPECT_TRUE(DeletePath(sub_dir, false)); EXPECT_FALSE(IsDirectory(sub_dir)); } TEST(Path, DeletePathRecursively) { ScopedTempDir dir; std::string sub_dir = dir.path() + "/dir"; CreateDirectory(sub_dir); EXPECT_TRUE(IsDirectory(sub_dir)); std::string sub_sub_dir1 = sub_dir + "/dir1"; CreateDirectory(sub_sub_dir1); EXPECT_TRUE(IsDirectory(sub_sub_dir1)); std::string sub_sub_dir2 = sub_dir + "/dir2"; CreateDirectory(sub_sub_dir2); EXPECT_TRUE(IsDirectory(sub_sub_dir2)); EXPECT_FALSE(DeletePath(sub_dir, false)); EXPECT_TRUE(IsDirectory(sub_dir)); EXPECT_TRUE(IsDirectory(sub_sub_dir1)); EXPECT_TRUE(DeletePath(sub_dir, true)); EXPECT_FALSE(IsDirectory(sub_dir)); EXPECT_FALSE(IsDirectory(sub_sub_dir1)); } } // namespace filesystem
engine/third_party/tonic/filesystem/tests/path_unittest.cc/0
{ "file_path": "engine/third_party/tonic/filesystem/tests/path_unittest.cc", "repo_id": "engine", "token_count": 3489 }
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. import 'dart:ffi'; import 'dart:nativewrappers'; import 'dart:typed_data'; void main() {} class SomeClass { int i; SomeClass(this.i); } @pragma('vm:external-name', 'GiveObjectToNative') external void giveObjectToNative(Object someObject); @pragma('vm:external-name', 'SignalDone') external void signalDone(); @pragma('vm:entry-point') void callGiveObjectToNative() { giveObjectToNative(SomeClass(123)); } @pragma('vm:entry-point') void testClearLater() { giveObjectToNative(SomeClass(123)); signalDone(); } // Test helpers for simple void calls through Tonic. @Native<Void Function()>(symbol: 'Nop', isLeaf: true) external void nop(); @pragma('vm:entry-point') void callNop() { nop(); signalDone(); } // Test helpers for calls with bool through Tonic. @Native<Bool Function(Bool)>(symbol: 'EchoBool') external bool echoBool(bool arg); @pragma('vm:entry-point') void callEchoBool() { if (echoBool(true)) { signalDone(); } } // Test helpers for calls with int through Tonic. @Native<IntPtr Function(IntPtr)>(symbol: 'EchoIntPtr') external int echoIntPtr(int arg); @pragma('vm:entry-point') void callEchoIntPtr() { if (echoIntPtr(23) == 23) { signalDone(); } } // Test helpers for calls with double through Tonic. @Native<Double Function(Double)>(symbol: 'EchoDouble') external double echoDouble(double arg); @pragma('vm:entry-point') void callEchoDouble() { if (echoDouble(23.0) == 23.0) { signalDone(); } } // Test helpers for calls with Dart_Handle through Tonic. @Native<Handle Function(Handle)>(symbol: 'EchoHandle') external Object echoHandle(Object arg); @pragma('vm:entry-point') void callEchoHandle() { if (echoHandle('Hello EchoHandle') == 'Hello EchoHandle') { signalDone(); } } // Test helpers for calls with std::string through Tonic. @Native<Handle Function(Handle)>(symbol: 'EchoString') external String echoString(String arg); @pragma('vm:entry-point') void callEchoString() { if (echoString('Hello EchoString') == 'Hello EchoString') { signalDone(); } } // Test helpers for calls with std::u16string through Tonic. @Native<Handle Function(Handle)>(symbol: 'EchoU16String') external String echoU16String(String arg); @pragma('vm:entry-point') void callEchoU16String() { if (echoU16String('Hello EchoU16String') == 'Hello EchoU16String') { signalDone(); } } // Test helpers for calls with std::vector through Tonic. @Native<Handle Function(Handle)>(symbol: 'EchoVector') external List<String> echoVector(List<String> arg); @pragma('vm:entry-point') void callEchoVector() { if (echoVector(['Hello EchoVector'])[0] == 'Hello EchoVector') { signalDone(); } } // Test helpers for calls with DartWrappable through Tonic. base class MyNativeClass extends NativeFieldWrapperClass1 { MyNativeClass(int value) { _Create(this, value); } @Native<Void Function(Handle, IntPtr)>(symbol: 'CreateNative') external static void _Create(MyNativeClass self, int value); @Native<Int32 Function(Pointer<Void>, Int32, Handle)>(symbol: 'MyNativeClass::MyTestFunction') external static int myTestFunction(MyNativeClass self, int x, Object handle); @Native<Handle Function(Pointer<Void>, Int64)>(symbol: 'MyNativeClass::MyTestMethod') external Object myTestMethod(int a); } @Native<IntPtr Function(Pointer<Void>)>(symbol: 'EchoWrappable') external int echoWrappable(MyNativeClass arg); @pragma('vm:entry-point') void callEchoWrappable() { final myNative = MyNativeClass(0x1234); if (echoWrappable(myNative) == 0x1234) { signalDone(); } } // Test helpers for calls with TypedList<..> through Tonic. @Native<Handle Function(Handle)>(symbol: 'EchoTypedList') external Float32List echoTypedList(Float32List arg); @pragma('vm:entry-point') void callEchoTypedList() { final typedList = Float32List.fromList([99.9, 3.14, 0.01]); if (echoTypedList(typedList) == typedList) { signalDone(); } } // @pragma('vm:entry-point') void callMyTestFunction() { final myNative = MyNativeClass(1234); if (MyNativeClass.myTestFunction(myNative, 34, myNative) == 1268) { signalDone(); } } // @pragma('vm:entry-point') void callMyTestMethod() { final myNative = MyNativeClass(1234); if (myNative.myTestMethod(43) == 1277) { signalDone(); } }
engine/third_party/tonic/tests/fixtures/tonic_test.dart/0
{ "file_path": "engine/third_party/tonic/tests/fixtures/tonic_test.dart", "repo_id": "engine", "token_count": 1549 }
417
/* * Copyright 2019 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 "paragraph_builder_skia.h" #include "paragraph_skia.h" #include "third_party/skia/modules/skparagraph/include/ParagraphStyle.h" #include "third_party/skia/modules/skparagraph/include/TextStyle.h" #include "txt/paragraph_style.h" namespace skt = skia::textlayout; namespace txt { namespace { // Convert txt::FontWeight values (ranging from 0-8) to SkFontStyle::Weight // values (ranging from 100-900). SkFontStyle::Weight GetSkFontStyleWeight(txt::FontWeight font_weight) { return static_cast<SkFontStyle::Weight>(static_cast<int>(font_weight) * 100 + 100); } SkFontStyle MakeSkFontStyle(txt::FontWeight font_weight, txt::FontStyle font_style) { return SkFontStyle( GetSkFontStyleWeight(font_weight), SkFontStyle::Width::kNormal_Width, font_style == txt::FontStyle::normal ? SkFontStyle::Slant::kUpright_Slant : SkFontStyle::Slant::kItalic_Slant); } } // anonymous namespace ParagraphBuilderSkia::ParagraphBuilderSkia( const ParagraphStyle& style, std::shared_ptr<FontCollection> font_collection, const bool impeller_enabled) : base_style_(style.GetTextStyle()), impeller_enabled_(impeller_enabled) { builder_ = skt::ParagraphBuilder::make( TxtToSkia(style), font_collection->CreateSktFontCollection()); } ParagraphBuilderSkia::~ParagraphBuilderSkia() = default; void ParagraphBuilderSkia::PushStyle(const TextStyle& style) { builder_->pushStyle(TxtToSkia(style)); txt_style_stack_.push(style); } void ParagraphBuilderSkia::Pop() { builder_->pop(); txt_style_stack_.pop(); } const TextStyle& ParagraphBuilderSkia::PeekStyle() { return txt_style_stack_.empty() ? base_style_ : txt_style_stack_.top(); } void ParagraphBuilderSkia::AddText(const std::u16string& text) { builder_->addText(text); } void ParagraphBuilderSkia::AddPlaceholder(PlaceholderRun& span) { skt::PlaceholderStyle placeholder_style; placeholder_style.fHeight = span.height; placeholder_style.fWidth = span.width; placeholder_style.fBaseline = static_cast<skt::TextBaseline>(span.baseline); placeholder_style.fBaselineOffset = span.baseline_offset; placeholder_style.fAlignment = static_cast<skt::PlaceholderAlignment>(span.alignment); builder_->addPlaceholder(placeholder_style); } std::unique_ptr<Paragraph> ParagraphBuilderSkia::Build() { return std::make_unique<ParagraphSkia>( builder_->Build(), std::move(dl_paints_), impeller_enabled_); } skt::ParagraphPainter::PaintID ParagraphBuilderSkia::CreatePaintID( const flutter::DlPaint& dl_paint) { dl_paints_.push_back(dl_paint); return dl_paints_.size() - 1; } skt::ParagraphStyle ParagraphBuilderSkia::TxtToSkia(const ParagraphStyle& txt) { skt::ParagraphStyle skia; skt::TextStyle text_style; // Convert the default color of an SkParagraph text style into a DlPaint. flutter::DlPaint dl_paint; dl_paint.setColor(flutter::DlColor(text_style.getColor())); text_style.setForegroundPaintID(CreatePaintID(dl_paint)); text_style.setFontStyle(MakeSkFontStyle(txt.font_weight, txt.font_style)); text_style.setFontSize(SkDoubleToScalar(txt.font_size)); text_style.setHeight(SkDoubleToScalar(txt.height)); text_style.setHeightOverride(txt.has_height_override); text_style.setFontFamilies({SkString(txt.font_family.c_str())}); text_style.setLocale(SkString(txt.locale.c_str())); skia.setTextStyle(text_style); skt::StrutStyle strut_style; strut_style.setFontStyle( MakeSkFontStyle(txt.strut_font_weight, txt.strut_font_style)); strut_style.setFontSize(SkDoubleToScalar(txt.strut_font_size)); strut_style.setHeight(SkDoubleToScalar(txt.strut_height)); strut_style.setHeightOverride(txt.strut_has_height_override); strut_style.setHalfLeading(txt.strut_half_leading); std::vector<SkString> strut_fonts; std::transform(txt.strut_font_families.begin(), txt.strut_font_families.end(), std::back_inserter(strut_fonts), [](const std::string& f) { return SkString(f.c_str()); }); strut_style.setFontFamilies(strut_fonts); strut_style.setLeading(txt.strut_leading); strut_style.setForceStrutHeight(txt.force_strut_height); strut_style.setStrutEnabled(txt.strut_enabled); skia.setStrutStyle(strut_style); skia.setTextAlign(static_cast<skt::TextAlign>(txt.text_align)); skia.setTextDirection(static_cast<skt::TextDirection>(txt.text_direction)); skia.setMaxLines(txt.max_lines); skia.setEllipsis(txt.ellipsis); skia.setTextHeightBehavior( static_cast<skt::TextHeightBehavior>(txt.text_height_behavior)); skia.turnHintingOff(); skia.setReplaceTabCharacters(true); skia.setApplyRoundingHack(false); return skia; } skt::TextStyle ParagraphBuilderSkia::TxtToSkia(const TextStyle& txt) { skt::TextStyle skia; skia.setColor(txt.color); skia.setDecoration(static_cast<skt::TextDecoration>(txt.decoration)); skia.setDecorationColor(txt.decoration_color); skia.setDecorationStyle( static_cast<skt::TextDecorationStyle>(txt.decoration_style)); skia.setDecorationThicknessMultiplier( SkDoubleToScalar(txt.decoration_thickness_multiplier)); skia.setFontStyle(MakeSkFontStyle(txt.font_weight, txt.font_style)); skia.setTextBaseline(static_cast<skt::TextBaseline>(txt.text_baseline)); std::vector<SkString> skia_fonts; std::transform(txt.font_families.begin(), txt.font_families.end(), std::back_inserter(skia_fonts), [](const std::string& f) { return SkString(f.c_str()); }); skia.setFontFamilies(skia_fonts); skia.setFontSize(SkDoubleToScalar(txt.font_size)); skia.setLetterSpacing(SkDoubleToScalar(txt.letter_spacing)); skia.setWordSpacing(SkDoubleToScalar(txt.word_spacing)); skia.setHeight(SkDoubleToScalar(txt.height)); skia.setHeightOverride(txt.has_height_override); skia.setHalfLeading(txt.half_leading); skia.setLocale(SkString(txt.locale.c_str())); if (txt.background.has_value()) { skia.setBackgroundPaintID(CreatePaintID(txt.background.value())); } if (txt.foreground.has_value()) { skia.setForegroundPaintID(CreatePaintID(txt.foreground.value())); } else { flutter::DlPaint dl_paint; dl_paint.setColor(flutter::DlColor(txt.color)); skia.setForegroundPaintID(CreatePaintID(dl_paint)); } skia.resetFontFeatures(); for (const auto& ff : txt.font_features.GetFontFeatures()) { skia.addFontFeature(SkString(ff.first.c_str()), ff.second); } if (!txt.font_variations.GetAxisValues().empty()) { std::vector<SkFontArguments::VariationPosition::Coordinate> coordinates; for (const auto& it : txt.font_variations.GetAxisValues()) { const std::string& axis = it.first; if (axis.length() != 4) { continue; } coordinates.push_back({ SkSetFourByteTag(axis[0], axis[1], axis[2], axis[3]), it.second, }); } SkFontArguments::VariationPosition position = { coordinates.data(), static_cast<int>(coordinates.size())}; skia.setFontArguments( SkFontArguments().setVariationDesignPosition(position)); } skia.resetShadows(); for (const txt::TextShadow& txt_shadow : txt.text_shadows) { skt::TextShadow shadow; shadow.fOffset = txt_shadow.offset; shadow.fBlurSigma = txt_shadow.blur_sigma; shadow.fColor = txt_shadow.color; skia.addShadow(shadow); } return skia; } } // namespace txt
engine/third_party/txt/src/skia/paragraph_builder_skia.cc/0
{ "file_path": "engine/third_party/txt/src/skia/paragraph_builder_skia.cc", "repo_id": "engine", "token_count": 3070 }
418
/* * 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 "paragraph_builder.h" #include "flutter/third_party/txt/src/skia/paragraph_builder_skia.h" #include "paragraph_style.h" #include "third_party/icu/source/common/unicode/unistr.h" namespace txt { //------------------------------------------------------------------------------ /// @brief Creates a |ParagraphBuilder| based on Skia's text layout module. /// /// @param[in] style The style to use for the paragraph. /// @param[in] font_collection The font collection to use for the paragraph. /// @param[in] impeller_enabled Whether Impeller is enabled in the runtime. std::unique_ptr<ParagraphBuilder> ParagraphBuilder::CreateSkiaBuilder( const ParagraphStyle& style, std::shared_ptr<FontCollection> font_collection, const bool impeller_enabled) { return std::make_unique<ParagraphBuilderSkia>(style, font_collection, impeller_enabled); } } // namespace txt
engine/third_party/txt/src/txt/paragraph_builder.cc/0
{ "file_path": "engine/third_party/txt/src/txt/paragraph_builder.cc", "repo_id": "engine", "token_count": 486 }
419
/* * 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 TXT_TEST_FONT_MANAGER_H_ #define TXT_TEST_FONT_MANAGER_H_ #include <memory> #include <string> #include <vector> #include "flutter/fml/macros.h" #include "third_party/skia/include/core/SkFontMgr.h" #include "txt/asset_font_manager.h" #include "txt/font_asset_provider.h" namespace txt { // A font manager intended for tests that matches all requested fonts using // one family. class TestFontManager : public AssetFontManager { public: TestFontManager(std::unique_ptr<FontAssetProvider> font_provider, std::vector<std::string> test_font_family_names); ~TestFontManager() override; private: std::vector<std::string> test_font_family_names_; sk_sp<SkFontStyleSet> onMatchFamily(const char family_name[]) const override; FML_DISALLOW_COPY_AND_ASSIGN(TestFontManager); }; } // namespace txt #endif // TXT_TEST_FONT_MANAGER_H_
engine/third_party/txt/src/txt/test_font_manager.h/0
{ "file_path": "engine/third_party/txt/src/txt/test_font_manager.h", "repo_id": "engine", "token_count": 484 }
420
//--------------------------------------------------------------------------------------------- // Copyright (c) 2022 Google LLC // Licensed under the MIT License. See License.txt in the project root for license information. //--------------------------------------------------------------------------------------------*/ // DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT // // This file is auto generated by flutter/engine:flutter/tools/gen_web_keyboard_keymap based on // https://github.com/microsoft/vscode/tree/@@@COMMIT_ID@@@/src/vs/workbench/services/keybinding/browser/keyboardLayouts // // Edit the following files instead: // // - Script: lib/main.dart // - Templates: data/*.tmpl // // See flutter/engine:flutter/tools/gen_web_keyboard_keymap/README.md for more information. import 'package:test/test.dart'; import 'package:web_locale_keymap/web_locale_keymap.dart'; import 'testing.dart'; void testWin(LocaleKeymap mapping) { group('cz', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'{', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'&', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'Đ', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'[', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r']', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'ł', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'Ł', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'}', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'\', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'đ', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'@', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'|', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'#', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'z', r'Z', r'', r''], 'z'); verifyEntry(mapping, 'KeyZ', <String>[r'y', r'Y', r'', r''], 'y'); }); group('de', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'@', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'z', r'Z', r'', r''], 'z'); verifyEntry(mapping, 'KeyZ', <String>[r'y', r'Y', r'', r''], 'y'); }); group('de-swiss', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'z', r'Z', r'', r''], 'z'); verifyEntry(mapping, 'KeyZ', <String>[r'y', r'Y', r'', r''], 'y'); }); group('dk', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('en', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('en-belgian', () { verifyEntry(mapping, 'KeyA', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'z', r'Z', r'', r''], 'z'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'Semicolon', <String>[r'm', r'M', r'', r''], 'm'); }); group('en-in', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'ā', r'Ā'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'ḍ', r'Ḍ'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'ē', r'Ē'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'ṅ', r'Ṅ'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'ḥ', r'Ḥ'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'ī', r'Ī'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'l̥', r'L̥'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'ṁ', r'Ṁ'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'ṇ', r'Ṇ'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ō', r'Ō'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'æ', r'Æ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'r̥', r'R̥'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ś', r'Ś'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'ṭ', r'Ṭ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'ū', r'Ū'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'ṣ', r'Ṣ'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'ñ', r'Ñ'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('en-intl', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'á', r'Á'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'©', r'¢'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'ð', r'Ð'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'é', r'É'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'í', r'Í'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'ø', r'Ø'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'ñ', r'Ñ'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ó', r'Ó'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'ö', r'Ö'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'ä', r'Ä'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'§'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'þ', r'Þ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'ú', r'Ú'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'å', r'Å'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'ü', r'Ü'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'æ', r'Æ'], 'z'); }); group('en-uk', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'á', r'Á'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'é', r'É'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'í', r'Í'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ó', r'Ó'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'ú', r'Ú'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('es', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('es-latin', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'@', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('fr', () { verifyEntry(mapping, 'KeyA', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'z', r'Z', r'', r''], 'z'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'Semicolon', <String>[r'm', r'M', r'', r''], 'm'); }); group('hu', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'ä', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'{', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'&', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'Đ', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'Ä', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'[', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r']', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Í', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'í', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'ł', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'Ł', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'<', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'}', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'\', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'đ', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'€', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'@', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'|', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'#', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'z', r'Z', r'', r''], 'z'); verifyEntry(mapping, 'KeyZ', <String>[r'y', r'Y', r'>', r''], 'y'); }); group('it', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('no', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('pl', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'ą', r'Ą'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ć', r'Ć'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'ę', r'Ę'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'ł', r'Ł'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'ń', r'Ń'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ó', r'Ó'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ś', r'Ś'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'€', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'ź', r'Ź'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'ż', r'Ż'], 'z'); }); group('pt', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('pt-br', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'₢', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'°', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'/', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'?', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('ru', () { verifyEntry(mapping, 'KeyA', <String>[r'ф', r'Ф', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'и', r'И', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'с', r'С', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'в', r'В', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'у', r'У', r'', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'а', r'А', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'п', r'П', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'р', r'Р', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'ш', r'Ш', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'о', r'О', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'л', r'Л', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'д', r'Д', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'ь', r'Ь', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'т', r'Т', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'щ', r'Щ', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'з', r'З', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'й', r'Й', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'к', r'К', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r'ы', r'Ы', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r'е', r'Е', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'г', r'Г', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'м', r'М', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'ц', r'Ц', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'ч', r'Ч', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'н', r'Н', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'я', r'Я', r'', r''], 'z'); }); group('sv', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); group('thai', () { verifyEntry(mapping, 'KeyA', <String>[r'ฟ', r'ฤ', r'', r''], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'ิ', r'ฺ', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'แ', r'ฉ', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'ก', r'ฏ', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'ำ', r'ฎ', r'', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'ด', r'โ', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'เ', r'ฌ', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'้', r'็', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'ร', r'ณ', r'', r''], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'่', r'๋', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'า', r'ษ', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'ส', r'ศ', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'ท', r'?', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'ื', r'์', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'น', r'ฯ', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'ย', r'ญ', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'ๆ', r'๐', r'', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'พ', r'ฑ', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r'ห', r'ฆ', r'', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r'ะ', r'ธ', r'', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'ี', r'๊', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'อ', r'ฮ', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'ไ', r'"', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'ป', r')', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'ั', r'ํ', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'ผ', r'(', r'', r''], 'z'); }); group('tr', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'æ', r'Æ'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'', r''], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'', r''], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r''], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r''], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'', r''], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'ı', r'I', r'i', r'İ'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'', r''], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'', r''], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'', r''], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'', r''], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'', r''], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'', r''], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'@', r''], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'', r''], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'₺', r''], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'', r''], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'', r''], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'', r''], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'', r''], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'', r''], 'z'); }); } void testLinux(LocaleKeymap mapping) { group('de', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'æ', r'Æ'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'“', r'‘'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'¢', r'©'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'ð', r'Ð'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r'€'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'đ', r'ª'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'ŋ', r'Ŋ'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'ħ', r'Ħ'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'→', r'ı'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'̣', r'̇'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'ĸ', r'&'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'ł', r'Ł'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'º'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'”', r'’'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'þ', r'Þ'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'@', r'Ω'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'¶', r'®'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ſ', r'ẞ'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'ŧ', r'Ŧ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'↓', r'↑'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'„', r'‚'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'ł', r'Ł'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'«', r'‹'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'z', r'Z', r'←', r'¥'], 'z'); verifyEntry(mapping, 'KeyZ', <String>[r'y', r'Y', r'»', r'›'], 'y'); }); group('en', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'a', r'A'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'b', r'B'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'c', r'C'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'd', r'D'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'e', r'E'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'f', r'F'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'g', r'G'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'h', r'H'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'i', r'I'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'j', r'J'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'k', r'K'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'l', r'L'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'm', r'M'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'n', r'N'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'o', r'O'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'p', r'P'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'q', r'Q'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'r', r'R'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r's', r'S'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r't', r'T'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'u', r'U'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'v', r'V'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'w', r'W'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'x', r'X'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'y', r'Y'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'z', r'Z'], 'z'); }); group('es', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'æ', r'Æ'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'”', r'’'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'¢', r'©'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'ð', r'Ð'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r'¢'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'đ', r'ª'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'ŋ', r'Ŋ'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'ħ', r'Ħ'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'→', r'ı'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'̉', r'̛'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'ĸ', r'&'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'ł', r'Ł'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'º'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'n', r'N'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'þ', r'Þ'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'@', r'Ω'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'¶', r'®'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'§'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'ŧ', r'Ŧ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'↓', r'↑'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'“', r'‘'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'ł', r'Ł'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'»', r'>'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'←', r'¥'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'«', r'<'], 'z'); }); group('fr', () { verifyEntry(mapping, 'KeyA', <String>[r'q', r'Q', r'@', r'Ω'], 'q'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'”', r'’'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'¢', r'©'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'ð', r'Ð'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r'¢'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'đ', r'ª'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'ŋ', r'Ŋ'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'ħ', r'Ħ'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'→', r'ı'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'̉', r'̛'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'ĸ', r'&'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'ł', r'Ł'], 'l'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'n', r'N'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'þ', r'Þ'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'a', r'A', r'æ', r'Æ'], 'a'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'¶', r'®'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'§'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'ŧ', r'Ŧ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'↓', r'↑'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'“', r'‘'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'z', r'Z', r'«', r'<'], 'z'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'»', r'>'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'←', r'¥'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'w', r'W', r'ł', r'Ł'], 'w'); verifyEntry(mapping, 'Semicolon', <String>[r'm', r'M', r'µ', r'º'], 'm'); }); group('ru', () { verifyEntry(mapping, 'KeyA', <String>[r'ф', r'Ф', r'ф', r'Ф'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'и', r'И', r'и', r'И'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'с', r'С', r'с', r'С'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'в', r'В', r'в', r'В'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'у', r'У', r'у', r'У'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'а', r'А', r'а', r'А'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'п', r'П', r'п', r'П'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'р', r'Р', r'р', r'Р'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'ш', r'Ш', r'ш', r'Ш'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'о', r'О', r'о', r'О'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'л', r'Л', r'л', r'Л'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'д', r'Д', r'д', r'Д'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'ь', r'Ь', r'ь', r'Ь'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'т', r'Т', r'т', r'Т'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'щ', r'Щ', r'щ', r'Щ'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'з', r'З', r'з', r'З'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'й', r'Й', r'й', r'Й'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'к', r'К', r'к', r'К'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r'ы', r'Ы', r'ы', r'Ы'], 's'); verifyEntry(mapping, 'KeyT', <String>[r'е', r'Е', r'е', r'Е'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'г', r'Г', r'г', r'Г'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'м', r'М', r'м', r'М'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'ц', r'Ц', r'ц', r'Ц'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'ч', r'Ч', r'ч', r'Ч'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'н', r'Н', r'н', r'Н'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'я', r'Я', r'я', r'Я'], 'z'); }); } void testDarwin(LocaleKeymap mapping) { group('de', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'∫', r'‹'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ç', r'Ç'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'™'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r'‰'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'Ï'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'Ì'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'ª', r'Ó'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'⁄', r'Û'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'º', r'ı'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'∆', r'ˆ'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'@', r'fl'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'˘'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'›'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'«', r'»'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'¸'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'‚', r'Í'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'˝'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'Á'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'∑', r'„'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'≈', r'Ù'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'z', r'Z', r'Ω', r'ˇ'], 'z'); verifyEntry(mapping, 'KeyZ', <String>[r'y', r'Y', r'¥', r'‡'], 'y'); }); group('dvorak', () { verifyEntry(mapping, 'Comma', <String>[r'w', r'W', r'∑', r'„'], 'w'); verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'x', r'X', r'≈', r'˛'], 'x'); verifyEntry(mapping, 'KeyC', <String>[r'j', r'J', r'∆', r'Ô'], 'j'); verifyEntry(mapping, 'KeyD', <String>[r'e', r'E', r'Dead', r'´'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'u', r'U', r'Dead', r'¨'], 'u'); verifyEntry(mapping, 'KeyG', <String>[r'i', r'I', r'Dead', r'ˆ'], 'i'); verifyEntry(mapping, 'KeyH', <String>[r'd', r'D', r'∂', r'Î'], 'd'); verifyEntry(mapping, 'KeyI', <String>[r'c', r'C', r'ç', r'Ç'], 'c'); verifyEntry(mapping, 'KeyJ', <String>[r'h', r'H', r'˙', r'Ó'], 'h'); verifyEntry(mapping, 'KeyK', <String>[r't', r'T', r'†', r'ˇ'], 't'); verifyEntry(mapping, 'KeyL', <String>[r'n', r'N', r'Dead', r'˜'], 'n'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'Â'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'b', r'B', r'∫', r'ı'], 'b'); verifyEntry(mapping, 'KeyO', <String>[r'r', r'R', r'®', r'‰'], 'r'); verifyEntry(mapping, 'KeyP', <String>[r'l', r'L', r'¬', r'Ò'], 'l'); verifyEntry(mapping, 'KeyR', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyS', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyT', <String>[r'y', r'Y', r'¥', r'Á'], 'y'); verifyEntry(mapping, 'KeyU', <String>[r'g', r'G', r'©', r'˝'], 'g'); verifyEntry(mapping, 'KeyV', <String>[r'k', r'K', r'˚', r''], 'k'); verifyEntry(mapping, 'KeyX', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyY', <String>[r'f', r'F', r'ƒ', r'Ï'], 'f'); verifyEntry(mapping, 'Period', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'Semicolon', <String>[r's', r'S', r'ß', r'Í'], 's'); verifyEntry(mapping, 'Slash', <String>[r'z', r'Z', r'Ω', r'¸'], 'z'); }); group('en', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'∫', r'ı'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ç', r'Ç'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'Î'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'Dead', r'´'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'Ï'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'˝'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'˙', r'Ó'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Dead', r'ˆ'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'∆', r'Ô'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'˚', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'¬', r'Ò'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'Â'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'˜'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'‰'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'Í'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'ˇ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'¨'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'∑', r'„'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'≈', r'˛'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'¥', r'Á'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'Ω', r'¸'], 'z'); }); group('en-ext', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'Dead', r'̄'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'Dead', r'̆'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'Dead', r'̧'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'ð', r'Ð'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'Dead', r'́'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'Dead'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'Dead', r'̱'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Dead', r'̛'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'Dead', r'̋'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'Dead', r'̊'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'Dead', r'̵'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'Dead', r'̨'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'̃'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'Dead', r'̦'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'‰'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'þ', r'Þ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'̈'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'Dead', r'̌'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'Dead', r'̇'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'Dead', r'̣'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'¥', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'Dead', r'̉'], 'z'); }); group('en-intl', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'∫', r'ı'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ç', r'Ç'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'Î'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'Dead', r'´'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'Ï'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'˝'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'˙', r'Ó'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Dead', r'ˆ'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'∆', r'Ô'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'˚', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'¬', r'Ò'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'Â'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'˜'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'‰'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'Í'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'ˇ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'¨'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'∑', r'„'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'≈', r'˛'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'¥', r'Á'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'Ω', r'¸'], 'z'); }); group('en-uk', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'∫', r'ı'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ç', r'Ç'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'Î'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'Dead', r'‰'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'Ï'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'Ì'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'˙', r'Ó'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Dead', r'È'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'∆', r'Ô'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'˚', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'¬', r'Ò'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'˜'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'ˆ'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'Â'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'Í'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'Ê'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'Ë'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'∑', r'„'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'≈', r'Ù'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'¥', r'Á'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'Ω', r'Û'], 'z'); }); group('es', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'ß', r''], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'©', r' '], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'∆'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r'€'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'fi'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'', r'fl'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'™', r' '], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r' ', r' '], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'¶', r'¯'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'§', r'ˇ'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r' ', r'˘'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'˚'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r' ', r'˙'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r' '], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'∫', r' '], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'‡'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r' ', r' '], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'æ', r'Æ'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'∑', r'›'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'¥', r' '], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'Ω', r'‹'], 'z'); }); group('fr', () { verifyEntry(mapping, 'KeyA', <String>[r'q', r'Q', r'‡', r'Ω'], 'q'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'ß', r'∫'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'©', r'¢'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'∆'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'ê', r'Ê'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'·'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'fi', r'fl'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'Ì', r'Î'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'î', r'ï'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'Ï', r'Í'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'È', r'Ë'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'¬', r'|'], 'l'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'ı'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'œ', r'Œ'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'a', r'A', r'æ', r'Æ'], 'a'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'‚'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'Ò', r'∑'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'™'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'º', r'ª'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'◊', r'√'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'z', r'Z', r'Â', r'Å'], 'z'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'≈', r'⁄'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'Ú', r'Ÿ'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'w', r'W', r'‹', r'›'], 'w'); verifyEntry(mapping, 'Semicolon', <String>[r'm', r'M', r'µ', r'Ó'], 'm'); }); group('it', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'∫', r'Í'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'©', r'Á'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'˘'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'€', r'È'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'˙'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'∞', r'˚'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'∆', r'¸'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'œ', r'Œ'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'ª', r'˝'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'º', r'˛'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'¬', r'ˇ'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'Ú'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'Ó'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'„', r'‚'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'Ì'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'¯'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'™', r'Ò'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'Ù'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'É'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'Ω', r'À'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'†', r'‡'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'æ', r'Æ'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'∑', r' '], 'z'); }); group('jp', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'∫', r'ı'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ç', r'Ç'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'Î'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'Dead', r'´'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'Ï'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'˝'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'˙', r'Ó'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Dead', r'ˆ'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'∆', r'Ô'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'˚', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'¬', r'Ò'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'Â'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'˜'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'‰'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'Í'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'ˇ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'¨'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'∑', r'„'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'≈', r'˛'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'¥', r'Á'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'Ω', r'¸'], 'z'); }); group('jp-roman', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'Dead', r'̄'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'Dead', r'̆'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'Dead', r'̧'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'ð', r'Ð'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'Dead', r'́'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r''], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'Dead'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'Dead', r'̱'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Dead', r'̛'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'Dead', r'̋'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'Dead', r'̊'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'Dead', r'̵'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'Dead', r'̨'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'̃'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'Dead', r'̦'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'‰'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r''], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'þ', r'Þ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'̈'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'Dead', r'̌'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'Dead', r'̇'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'Dead', r'̣'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'¥', r''], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'Dead', r'̉'], 'z'); }); group('ko', () { verifyEntry(mapping, 'KeyA', <String>[r'ㅁ', r'ㅁ', r'a', r'A'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'ㅠ', r'ㅠ', r'b', r'B'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'ㅊ', r'ㅊ', r'c', r'C'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'ㅇ', r'ㅇ', r'd', r'D'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'ㄷ', r'ㄸ', r'e', r'E'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'ㄹ', r'ㄹ', r'f', r'F'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'ㅎ', r'ㅎ', r'g', r'G'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'ㅗ', r'ㅗ', r'h', r'H'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'ㅑ', r'ㅑ', r'i', r'I'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'ㅓ', r'ㅓ', r'j', r'J'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'ㅏ', r'ㅏ', r'k', r'K'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'ㅣ', r'ㅣ', r'l', r'L'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'ㅡ', r'ㅡ', r'm', r'M'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'ㅜ', r'ㅜ', r'n', r'N'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'ㅐ', r'ㅒ', r'o', r'O'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'ㅔ', r'ㅖ', r'p', r'P'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'ㅂ', r'ㅃ', r'q', r'Q'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'ㄱ', r'ㄲ', r'r', r'R'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r'ㄴ', r'ㄴ', r's', r'S'], 's'); verifyEntry(mapping, 'KeyT', <String>[r'ㅅ', r'ㅆ', r't', r'T'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'ㅕ', r'ㅕ', r'u', r'U'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'ㅍ', r'ㅍ', r'v', r'V'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'ㅈ', r'ㅉ', r'w', r'W'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'ㅌ', r'ㅌ', r'x', r'X'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'ㅛ', r'ㅛ', r'y', r'Y'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'ㅋ', r'ㅋ', r'z', r'Z'], 'z'); }); group('pl', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'ą', r'Ą'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'ļ', r'ű'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ć', r'Ć'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'Ž'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'ę', r'Ę'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ń', r'ž'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'Ū'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'ķ', r'Ó'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Dead', r'ť'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'∆', r'Ô'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'Ż', r'ū'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'ł', r'Ł'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'Ķ', r'ų'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'ń', r'Ń'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ó', r'Ó'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'Ļ', r'ł'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'Ō', r'ő'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'£'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ś', r'Ś'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'ś'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'Ť'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'∑', r'„'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'ź', r'Ź'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'ī', r'Á'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'ż', r'Ż'], 'z'); }); group('pt', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'∫', r'ı'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ç', r'Ç'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'Î'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'Dead', r'´'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'Ï'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'˝'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'˙', r'Ó'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Dead', r'ˆ'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'∆', r'Ô'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'˚', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'¬', r'Ò'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'Â'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'˜'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'‰'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'Í'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'ˇ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'¨'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'∑', r'„'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'≈', r'˛'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'¥', r'Á'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'Ω', r'¸'], 'z'); }); group('ru', () { verifyEntry(mapping, 'KeyA', <String>[r'ф', r'Ф', r'ƒ', r'ƒ'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'и', r'И', r'и', r'И'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'с', r'С', r'≠', r'≠'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'в', r'В', r'ћ', r'Ћ'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'у', r'У', r'ќ', r'Ќ'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'а', r'А', r'÷', r'÷'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'п', r'П', r'©', r'©'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'р', r'Р', r'₽', r'₽'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'ш', r'Ш', r'ѕ', r'Ѕ'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'о', r'О', r'°', r'•'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'л', r'Л', r'љ', r'Љ'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'д', r'Д', r'∆', r'∆'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'ь', r'Ь', r'~', r'~'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'т', r'Т', r'™', r'™'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'щ', r'Щ', r'ў', r'Ў'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'з', r'З', r'‘', r'’'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'й', r'Й', r'ј', r'Ј'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'к', r'К', r'®', r'®'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r'ы', r'Ы', r'ы', r'Ы'], 's'); verifyEntry(mapping, 'KeyT', <String>[r'е', r'Е', r'†', r'†'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'г', r'Г', r'ѓ', r'Ѓ'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'м', r'М', r'µ', r'µ'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'ц', r'Ц', r'џ', r'Џ'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'ч', r'Ч', r'≈', r'≈'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'н', r'Н', r'њ', r'Њ'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'я', r'Я', r'ђ', r'Ђ'], 'z'); }); group('sv', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'', r'◊'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'›', r'»'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ç', r'Ç'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'∆'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'é', r'É'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'∫'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'¸', r'¯'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'˛', r'˘'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'ı', r'ˆ'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'√', r'¬'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'ª', r'º'], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'fi', r'fl'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'’', r'”'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'‘', r'“'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'œ', r'Œ'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'•', r'°'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'√'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'∑'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'‡'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'ü', r'Ü'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'‹', r'«'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'Ω', r'˝'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'≈', r'ˇ'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'µ', r'˜'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'÷', r'⁄'], 'z'); }); group('zh-hans', () { verifyEntry(mapping, 'KeyA', <String>[r'a', r'A', r'å', r'Å'], 'a'); verifyEntry(mapping, 'KeyB', <String>[r'b', r'B', r'∫', r'ı'], 'b'); verifyEntry(mapping, 'KeyC', <String>[r'c', r'C', r'ç', r'Ç'], 'c'); verifyEntry(mapping, 'KeyD', <String>[r'd', r'D', r'∂', r'Î'], 'd'); verifyEntry(mapping, 'KeyE', <String>[r'e', r'E', r'Dead', r'´'], 'e'); verifyEntry(mapping, 'KeyF', <String>[r'f', r'F', r'ƒ', r'Ï'], 'f'); verifyEntry(mapping, 'KeyG', <String>[r'g', r'G', r'©', r'˝'], 'g'); verifyEntry(mapping, 'KeyH', <String>[r'h', r'H', r'˙', r'Ó'], 'h'); verifyEntry(mapping, 'KeyI', <String>[r'i', r'I', r'Dead', r'ˆ'], 'i'); verifyEntry(mapping, 'KeyJ', <String>[r'j', r'J', r'∆', r'Ô'], 'j'); verifyEntry(mapping, 'KeyK', <String>[r'k', r'K', r'˚', r''], 'k'); verifyEntry(mapping, 'KeyL', <String>[r'l', r'L', r'¬', r'Ò'], 'l'); verifyEntry(mapping, 'KeyM', <String>[r'm', r'M', r'µ', r'Â'], 'm'); verifyEntry(mapping, 'KeyN', <String>[r'n', r'N', r'Dead', r'˜'], 'n'); verifyEntry(mapping, 'KeyO', <String>[r'o', r'O', r'ø', r'Ø'], 'o'); verifyEntry(mapping, 'KeyP', <String>[r'p', r'P', r'π', r'∏'], 'p'); verifyEntry(mapping, 'KeyQ', <String>[r'q', r'Q', r'œ', r'Œ'], 'q'); verifyEntry(mapping, 'KeyR', <String>[r'r', r'R', r'®', r'‰'], 'r'); verifyEntry(mapping, 'KeyS', <String>[r's', r'S', r'ß', r'Í'], 's'); verifyEntry(mapping, 'KeyT', <String>[r't', r'T', r'†', r'ˇ'], 't'); verifyEntry(mapping, 'KeyU', <String>[r'u', r'U', r'Dead', r'¨'], 'u'); verifyEntry(mapping, 'KeyV', <String>[r'v', r'V', r'√', r'◊'], 'v'); verifyEntry(mapping, 'KeyW', <String>[r'w', r'W', r'∑', r'„'], 'w'); verifyEntry(mapping, 'KeyX', <String>[r'x', r'X', r'≈', r'˛'], 'x'); verifyEntry(mapping, 'KeyY', <String>[r'y', r'Y', r'¥', r'Á'], 'y'); verifyEntry(mapping, 'KeyZ', <String>[r'z', r'Z', r'Ω', r'¸'], 'z'); }); }
engine/third_party/web_locale_keymap/test/test_cases.g.dart/0
{ "file_path": "engine/third_party/web_locale_keymap/test/test_cases.g.dart", "repo_id": "engine", "token_count": 42440 }
421
#!/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 subprocess import sys ANDROID_LOG_CLASS = 'android.util.Log' FLUTTER_LOG_CLASS = 'io.flutter.Log' ANDROIDX_TRACE_CLASS = 'androidx.tracing.Trace' ANDROID_TRACE_CLASS = 'android.tracing.Trace' FLUTTER_TRACE_CLASS = 'io.flutter.util.TraceSection' ANDROID_BUILD_VERSION_CODE_CLASS = 'VERSION_CODES' def CheckBadFiles(bad_files, bad_class, good_class): if bad_files: print('') print('Illegal import %s detected in the following files:' % bad_class) for bad_file in bad_files: print(' - ' + bad_file) print('Use %s instead.' % good_class) print('') return True return False def main(): parser = argparse.ArgumentParser( description='Checks Flutter Android library for forbidden imports' ) parser.add_argument('--stamp', type=str, required=True) parser.add_argument('--files', type=str, required=True, nargs='+') args = parser.parse_args() open(args.stamp, 'a').close() bad_log_files = [] bad_trace_files = [] bad_version_codes_files = [] for file in args.files: if (file.endswith(os.path.join('io', 'flutter', 'Log.java')) or file.endswith(os.path.join('io', 'flutter', 'util', 'TraceSection.java')) or file.endswith(os.path.join('io', 'flutter', 'Build.java'))): continue with open(file) as f: contents = f.read() if ANDROID_LOG_CLASS in contents: bad_log_files.append(file) if ANDROIDX_TRACE_CLASS in contents or ANDROID_TRACE_CLASS in contents: bad_trace_files.append(file) if ANDROID_BUILD_VERSION_CODE_CLASS in contents: bad_version_codes_files.append(file) # Flutter's Log class allows additional configuration around verbosity. # Flutter's tracing class makes sure we do not violate string lengths that # cause crashes at runtime. # Flutter's Build.API_LEVELS class is clearer to read about which API version # is used. has_bad_files = CheckBadFiles(bad_log_files, ANDROID_LOG_CLASS, FLUTTER_LOG_CLASS) or CheckBadFiles( bad_trace_files, 'android[x].tracing.Trace', FLUTTER_TRACE_CLASS ) or CheckBadFiles( bad_version_codes_files, 'android.os.Build.VERSION_CODES', 'io.flutter.Build.API_LEVELS' ) if has_bad_files: return 1 return 0 if __name__ == '__main__': sys.exit(main())
engine/tools/android_illegal_imports.py/0
{ "file_path": "engine/tools/android_illegal_imports.py", "repo_id": "engine", "token_count": 1126 }
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. /// Describes what should be linted by the Clang Tidy tool. sealed class LintTarget { /// Creates a new [LintTarget]. const LintTarget(); } /// Lints all files in the project. final class LintAll extends LintTarget { /// Defines a lint target that lints all files in the project. const LintAll(); } /// Lint all files that have changed since the last commit. /// /// This considers only the last commit, not all commits in the current branch. final class LintChanged extends LintTarget { /// Defines a lint target of files that have changed since the last commit. const LintChanged(); } /// Lint all files that have changed compared to HEAD. /// /// This considers _all_ commits in the current branch, not just the last one. final class LintHead extends LintTarget { /// Defines a lint target of files that have changed compared to HEAD. const LintHead(); } /// Lint all files whose paths match the given regex. final class LintRegex extends LintTarget { /// Creates a new [LintRegex] with the given [regex]. const LintRegex(this.regex); /// The regular expression to match against file paths. final String regex; }
engine/tools/clang_tidy/lib/src/lint_target.dart/0
{ "file_path": "engine/tools/clang_tidy/lib/src/lint_target.dart", "repo_id": "engine", "token_count": 363 }
423
// 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. // ignore_for_file: public_member_api_docs // The purpose of this list of flags in a file separate from the command // definitions is to ensure that flags are named consistently across // subcommands. For example, unless there's a compelling reason to have both, // we'd avoid having one subcommand define an --all flag while another defines // an --everything flag. // Keep this list alphabetized. const String allFlag = 'all'; const String builderFlag = 'builder'; const String configFlag = 'config'; const String dryRunFlag = 'dry-run'; const String quietFlag = 'quiet'; const String rbeFlag = 'rbe'; const String runTestsFlag = 'run-tests'; const String verboseFlag = 'verbose';
engine/tools/engine_tool/lib/src/commands/flags.dart/0
{ "file_path": "engine/tools/engine_tool/lib/src/commands/flags.dart", "repo_id": "engine", "token_count": 221 }
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 '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/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:platform/platform.dart'; import 'package:process_fakes/process_fakes.dart'; import 'package:process_runner/process_runner.dart'; void main() { final Engine? engine = Engine.tryFindWithin(); if (engine == null) { io.stderr.writeln('The current working directory is not a Flutter engine'); io.exitCode = 1; return; } final Map<String, BuilderConfig> configs = <String, BuilderConfig>{}; (Environment, List<List<String>>) linuxEnv(Logger logger) { 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(onStart: (List<String> command) { runHistory.add(command); return FakeProcess(); }, onRun: (List<String> command) { runHistory.add(command); return io.ProcessResult(81, 0, '', ''); }), ), logger: logger, ), runHistory ); } test('fetch command invokes gclient sync -D', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv(logger); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>['fetch']); expect(result, equals(0)); expect(runHistory.length, greaterThanOrEqualTo(1)); expect( runHistory[0], containsStringsInOrder(<String>['gclient', 'sync', '-D']), ); }); test('fetch command has sync alias', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv(logger); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>['sync']); expect(result, equals(0)); expect(runHistory.length, greaterThanOrEqualTo(1)); expect( runHistory[0], containsStringsInOrder(<String>['gclient', 'sync', '-D']), ); }); }
engine/tools/engine_tool/test/fetch_command_test.dart/0
{ "file_path": "engine/tools/engine_tool/test/fetch_command_test.dart", "repo_id": "engine", "token_count": 1076 }
425
#!/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 subprocess import sys def main(): parser = argparse.ArgumentParser( description='Executes a command, then rewrites the depfile, converts all absolute paths to relative' ) parser.add_argument('--depfile', help='Path to the depfile to rewrite', required=True) parser.add_argument('command', nargs='+', help='Positional args for the command to run') args = parser.parse_args() retval = subprocess.call(args.command) if retval != 0: return retval lines = [] with open(args.depfile, 'r') as f: for line in f: lines.append(' '.join(os.path.relpath(p) for p in line.split())) with open(args.depfile, 'w') as f: f.write('\n'.join(lines)) if __name__ == '__main__': sys.exit(main())
engine/tools/fuchsia/depfile_path_to_relative.py/0
{ "file_path": "engine/tools/fuchsia/depfile_path_to_relative.py", "repo_id": "engine", "token_count": 315 }
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("//flutter/common/fuchsia_config.gni") # The inputs to this template are 'binary_path' and a boolean 'unstripped'. # If 'unstripped' is specified, we append '.debug' to the symbols name. template("_copy_debug_symbols") { assert(defined(invoker.binary_path), "'binary_path' needs to be defined.") assert(defined(invoker.unstripped), "'unstripped' needs to be defined.") action(target_name) { forward_variables_from(invoker, [ "deps", "unstripped", "binary_path", "testonly", ]) script = "//flutter/tools/fuchsia/copy_debug_symbols.py" sources = [ binary_path ] _dest_base = "${root_out_dir}/.build-id" args = [ "--executable-name", target_name, "--executable-path", rebase_path(binary_path), "--destination-base", rebase_path(_dest_base), "--read-elf", rebase_path("//buildtools/${host_os}-${host_cpu}/clang/bin/llvm-readelf"), ] if (unstripped) { args += [ "--unstripped" ] } outputs = [ "${_dest_base}/.${target_name}_success" ] } } # Takes a binary and generates its debug symbols following # the Fuchsia packaging convention. template("fuchsia_debug_symbols") { assert(defined(invoker.binary), "'binary' needs to be defined.") _copy_debug_symbols("_${target_name}_stripped") { forward_variables_from(invoker, "*") binary_path = rebase_path("${root_out_dir}/$binary") unstripped = false } _copy_debug_symbols("_${target_name}_unstripped") { forward_variables_from(invoker, "*") binary_path = "${root_out_dir}/exe.unstripped/$binary" unstripped = true } group(target_name) { forward_variables_from(invoker, [ "testonly" ]) deps = [ ":_${target_name}_stripped", ":_${target_name}_unstripped", ] } }
engine/tools/fuchsia/fuchsia_debug_symbols.gni/0
{ "file_path": "engine/tools/fuchsia/fuchsia_debug_symbols.gni", "repo_id": "engine", "token_count": 926 }
427
#!/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 BUILD_CONFIG_TEMPLATE = """ // 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 FILE IS AUTO_GENERATED // DO NOT EDIT THE VALUES HERE - SEE $flutter_root/tools/gen_android_buildconfig.py package io.flutter; public final class BuildConfig {{ private BuildConfig() {{}} public final static boolean DEBUG = {0}; public final static boolean PROFILE = {1}; public final static boolean RELEASE = {2}; public final static boolean JIT_RELEASE = {3}; }} """ def main(): parser = argparse.ArgumentParser(description='Generate BuildConfig.java for Android') parser.add_argument('--runtime-mode', type=str, required=True) parser.add_argument('--out', type=str, required=True) args = parser.parse_args() jit_release = 'jit_release' in args.runtime_mode.lower() release = not jit_release and 'release' in args.runtime_mode.lower() profile = 'profile' in args.runtime_mode.lower() debug = 'debug' in args.runtime_mode.lower() assert debug or profile or release or jit_release with open(os.path.abspath(args.out), 'w+') as output_file: output_file.write( BUILD_CONFIG_TEMPLATE.format( str(debug).lower(), str(profile).lower(), str(release).lower(), str(jit_release).lower() ) ) if __name__ == '__main__': sys.exit(main())
engine/tools/gen_android_buildconfig.py/0
{ "file_path": "engine/tools/gen_android_buildconfig.py", "repo_id": "engine", "token_count": 564 }
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. import 'dart:io' as io; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'src/post_checkout_command.dart'; import 'src/post_merge_command.dart'; import 'src/pre_push_command.dart'; import 'src/pre_rebase_command.dart'; /// Runs the githooks Future<int> run(List<String> args) async { final CommandRunner<bool> runner = CommandRunner<bool> ( 'githooks', 'Githooks implementation for the flutter/engine repo.', ) ..addCommand(PostCheckoutCommand()) ..addCommand(PostMergeCommand()) ..addCommand(PrePushCommand()) ..addCommand(PreRebaseCommand()); // Add top-level arguments. runner.argParser ..addFlag( 'enable-clang-tidy', help: 'Enable running clang-tidy on changed files.', ) ..addOption( 'flutter', abbr: 'f', help: 'The absolute path to the root of the flutter/engine checkout.', ) ..addFlag( 'verbose', abbr: 'v', help: 'Runs with verbose logging', ); if (args.isEmpty) { // The tool was invoked with no arguments. Print usage. runner.printUsage(); return 1; } final ArgResults argResults = runner.parse(args); final String? argMessage = _checkArgs(argResults); if (argMessage != null) { io.stderr.writeln(argMessage); runner.printUsage(); return 1; } final bool commandResult = await runner.runCommand(argResults) ?? false; return commandResult ? 0 : 1; } String? _checkArgs(ArgResults argResults) { if (argResults.command?.name == 'help') { return null; } if (argResults['help'] as bool) { return null; } if (argResults['flutter'] == null) { return 'The --flutter option is required'; } final io.Directory dir = io.Directory(argResults['flutter'] as String); if (!dir.isAbsolute) { return 'The --flutter option must be an absolute path'; } if (!dir.existsSync()) { return 'The directory specified by the --flutter option must exist'; } return null; }
engine/tools/githooks/lib/githooks.dart/0
{ "file_path": "engine/tools/githooks/lib/githooks.dart", "repo_id": "engine", "token_count": 761 }
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 imp import os import unittest SKY_TOOLS = os.path.dirname(os.path.abspath(__file__)) gn = imp.load_source('gn', os.path.join(SKY_TOOLS, 'gn')) class GNTestCase(unittest.TestCase): def _expect_build_dir(self, arg_list, expected_build_dir): args = gn.parse_args(['gn'] + arg_list) self.assertEqual(gn.get_out_dir(args), expected_build_dir) def test_get_out_dir(self): self._expect_build_dir(['--runtime-mode', 'debug'], os.path.join('out', 'host_debug')) self._expect_build_dir(['--runtime-mode', 'release'], os.path.join('out', 'host_release')) self._expect_build_dir(['--ios'], os.path.join('out', 'ios_debug')) self._expect_build_dir(['--ios', '--darwin-extension-safe'], os.path.join('out', 'ios_debug_extension_safe')) self._expect_build_dir(['--ios', '--runtime-mode', 'release'], os.path.join('out', 'ios_release')) self._expect_build_dir(['--ios', '--darwin-extension-safe', '--runtime-mode', 'release'], os.path.join('out', 'ios_release_extension_safe')) self._expect_build_dir(['--android'], os.path.join('out', 'android_debug')) self._expect_build_dir(['--android', '--runtime-mode', 'release'], os.path.join('out', 'android_release')) def _gn_args(self, arg_list): args = gn.parse_args(['gn'] + arg_list) return gn.to_gn_args(args) def test_to_gn_args(self): # This would not necessarily be true on a 32-bit machine? self.assertEqual( self._gn_args(['--ios', '--simulator', '--simulator-cpu', 'x64'])['target_cpu'], 'x64' ) self.assertEqual(self._gn_args(['--ios'])['target_cpu'], 'arm64') def test_cannot_use_android_and_enable_unittests(self): with self.assertRaises(Exception): self._gn_args(['--android', '--enable-unittests']) def test_cannot_use_ios_and_enable_unittests(self): with self.assertRaises(Exception): self._gn_args(['--ios', '--enable-unittests']) def test_parse_size(self): self.assertEqual(gn.parse_size('5B'), 5) self.assertEqual(gn.parse_size('5KB'), 5 * 2**10) self.assertEqual(gn.parse_size('5MB'), 5 * 2**20) self.assertEqual(gn.parse_size('5GB'), 5 * 2**30) if __name__ == '__main__': unittest.main()
engine/tools/gn_test.py/0
{ "file_path": "engine/tools/gn_test.py", "repo_id": "engine", "token_count": 1055 }
430
// 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' as io; import 'package:engine_repo_tools/engine_repo_tools.dart'; import 'package:header_guard_check/header_guard_check.dart'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as p; Future<int> main(List<String> args) async { void withTestRepository(String path, void Function(io.Directory) fn) { // Create a temporary directory and delete it when we're done. final io.Directory tempDir = io.Directory.systemTemp.createTempSync('header_guard_check_test'); final io.Directory repoDir = io.Directory(p.join(tempDir.path, path)); repoDir.createSync(recursive: true); try { fn(repoDir); } finally { tempDir.deleteSync(recursive: true); } } group('HeaderGuardCheck', () { test('by default checks all files', () { withTestRepository('engine/src', (io.Directory repoDir) { final io.Directory flutterDir = io.Directory(p.join(repoDir.path, 'flutter')); flutterDir.createSync(recursive: true); final io.File file1 = io.File(p.join(flutterDir.path, 'foo.h')); file1.createSync(recursive: true); final io.File file2 = io.File(p.join(flutterDir.path, 'bar.h')); file2.createSync(recursive: true); final io.File file3 = io.File(p.join(flutterDir.path, 'baz.h')); file3.createSync(recursive: true); final StringBuffer stdOut = StringBuffer(); final StringBuffer stdErr = StringBuffer(); final HeaderGuardCheck check = HeaderGuardCheck( source: Engine.fromSrcPath(repoDir.path), exclude: const <String>[], stdOut: stdOut, stdErr: stdErr, ); expect(check.run(), completion(1)); expect(stdOut.toString(), contains('foo.h')); expect(stdOut.toString(), contains('bar.h')); expect(stdOut.toString(), contains('baz.h')); }); }); test('if --include is provided, checks specific files', () { withTestRepository('engine/src', (io.Directory repoDir) { final io.Directory flutterDir = io.Directory(p.join(repoDir.path, 'flutter')); flutterDir.createSync(recursive: true); final io.File file1 = io.File(p.join(flutterDir.path, 'foo.h')); file1.createSync(recursive: true); final io.File file2 = io.File(p.join(flutterDir.path, 'bar.h')); file2.createSync(recursive: true); final io.File file3 = io.File(p.join(flutterDir.path, 'baz.h')); file3.createSync(recursive: true); final StringBuffer stdOut = StringBuffer(); final StringBuffer stdErr = StringBuffer(); final HeaderGuardCheck check = HeaderGuardCheck( source: Engine.fromSrcPath(repoDir.path), include: <String>[file1.path, file3.path], exclude: const <String>[], stdOut: stdOut, stdErr: stdErr, ); expect(check.run(), completion(1)); expect(stdOut.toString(), contains('foo.h')); expect(stdOut.toString(), contains('baz.h')); // TODO(matanlurey): https://github.com/flutter/flutter/issues/133569). if (stdOut.toString().contains('bar.h')) { // There is no not(contains(...)) matcher. fail('bar.h should not be checked. Output: $stdOut'); } }); }); test('if --include is provided, checks specific directories', () { withTestRepository('engine/src', (io.Directory repoDir) { final io.Directory flutterDir = io.Directory(p.join(repoDir.path, 'flutter')); flutterDir.createSync(recursive: true); // Create a sub-directory called "impeller". final io.Directory impellerDir = io.Directory(p.join(flutterDir.path, 'impeller')); impellerDir.createSync(recursive: true); // Create one file in both the root and in impeller. final io.File file1 = io.File(p.join(flutterDir.path, 'foo.h')); file1.createSync(recursive: true); final io.File file2 = io.File(p.join(impellerDir.path, 'bar.h')); file2.createSync(recursive: true); final StringBuffer stdOut = StringBuffer(); final StringBuffer stdErr = StringBuffer(); final HeaderGuardCheck check = HeaderGuardCheck( source: Engine.fromSrcPath(repoDir.path), include: <String>[impellerDir.path], exclude: const <String>[], stdOut: stdOut, stdErr: stdErr, ); expect(check.run(), completion(1)); expect(stdOut.toString(), contains('bar.h')); // TODO(matanlurey): https://github.com/flutter/flutter/issues/133569). if (stdOut.toString().contains('foo.h')) { // There is no not(contains(...)) matcher. fail('foo.h should not be checked. Output: $stdOut'); } }); }); }); return 0; }
engine/tools/header_guard_check/test/header_guard_check_test.dart/0
{ "file_path": "engine/tools/header_guard_check/test/header_guard_check_test.dart", "repo_id": "engine", "token_count": 2069 }
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. import 'package:licenses/formatter.dart'; import 'package:litetest/litetest.dart'; void main() { test('Block comments', () { expect(reformat('/* test */'), 'test'); expect(reformat('/*\ntest\n*/'), 'test'); expect(reformat('/*\ntest\n */'), 'test'); expect(reformat('/*\n * test\n*/'), 'test'); expect(reformat('/*\n * test\n */'), 'test'); expect(reformat('/*\n * test\n * test\n */'), 'test\ntest'); expect(reformat('/*\n * test\n + test\n */'), '* test\n+ test'); expect(reformat('test */'), 'test'); }); test('Indenting blocks', () { expect(reformat(' a\nb\n c'), 'a\nb\n c'); // strips leading indents expect(reformat(' a\n b\n c'), 'a\nb\nc'); // strips common one-space indent, then strips stray one-space indents expect(reformat(' a\n b\n c'), 'a\nb\nc'); // strips common two-space indent expect(reformat(' a\n b\n c'), 'a\nb\nc'); // strips common two-space indent, then strips stray one-space indent expect(reformat(' a\n b\n c'), 'a\n b\nc'); // streps common two-space indent expect(reformat(' a\n b\n c'), 'a\n b\nc'); // streps common two-space indent }); test('Leading blocks', () { expect(reformat('#; a\n#; b\n#; c'), 'a\nb\nc'); expect(reformat('#; a\nb\nc'), '#; a\nb\nc'); expect(reformat('#; a\n b\n c'), '#; a\n b\n c'); }); test('Leading indented lines', () { expect(reformat(' a\nb\nc'), 'a\nb\nc'); expect(reformat(' a\n b\nc'), 'a\nb\nc'); expect(reformat(' a\n b\nc'), 'a\nb\nc'); expect(reformat(' a\n b\nc'), 'a\nb\nc'); expect(reformat(' a\n b\nc'), 'a\n b\nc'); expect(reformat(' a\n b\nc'), 'a\n b\nc'); }); test('Leading indented blocks', () { expect(reformat(' a\n a\nb\nc'), 'a\na\nb\nc'); expect(reformat(' a\n a\n b\nc'), 'a\na\nb\nc'); expect(reformat(' a\n a\n b\nc'), 'a\na\nb\nc'); expect(reformat(' a\n a\n b\nc'), 'a\na\nb\nc'); expect(reformat(' a\n a\n b\nc'), 'a\na\n b\nc'); expect(reformat(' a\n a\n b\nc'), 'a\na\n b\nc'); }); test('Specific cases', () { expect(reformat(' Apache\n Version\n Bla bla\n\nBla bla bla'), 'Apache\nVersion\nBla bla\n\nBla bla bla'); expect( reformat( '/* Copyright (c) IBM Corporation, 2000-2012. All rights reserved. */\n' '/* */\n' '/* This software is made available under the terms of the */\n' '/* ICU License -- ICU 1.8.1 and later. */\n' ), 'Copyright (c) IBM Corporation, 2000-2012. All rights reserved.\n' '\n' 'This software is made available under the terms of the\n' 'ICU License -- ICU 1.8.1 and later.' ); expect( reformat( '/* Copyright (c) IBM Corporation, 2000-2012. All rights reserved. */\n' '/* */\n' '/* This software is made available under the terms of the */\n' '/* ICU License -- ICU 1.8.1 and later. */' ), 'Copyright (c) IBM Corporation, 2000-2012. All rights reserved.\n' '\n' 'This software is made available under the terms of the\n' 'ICU License -- ICU 1.8.1 and later.' ); expect( reformat( '/* Copyright (c) IBM Corporation, 2000-2012. All rights reserved. */\n' '/* */\n' '/* This software is made available under the terms of the */\n' '/* ICU License -- ICU 1.8.1 and later.' ), 'Copyright (c) IBM Corporation, 2000-2012. All rights reserved.\n' '\n' 'This software is made available under the terms of the\n' 'ICU License -- ICU 1.8.1 and later.' ); }); }
engine/tools/licenses/test/formatter_test.dart/0
{ "file_path": "engine/tools/licenses/test/formatter_test.dart", "repo_id": "engine", "token_count": 1974 }
432
// 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:ffi' as ffi; import 'dart:io' as io show Directory, Process; import 'package:path/path.dart' as p; import 'package:platform/platform.dart'; import 'package:process_runner/process_runner.dart'; import 'build_config.dart'; /// The base clase for events generated by a command. sealed class RunnerEvent { RunnerEvent(this.name, this.command, this.timestamp); /// The name of the task or command. final String name; /// The command and its arguments. final List<String> command; /// When the event happened. final DateTime timestamp; } /// A [RunnerEvent] representing the start of a command. final class RunnerStart extends RunnerEvent { RunnerStart(super.name, super.command, super.timestamp); @override String toString() { return '[${_timestamp(timestamp)}][$name]: STARTING'; } } /// A [RunnerEvent] representing the progress of a started command. final class RunnerProgress extends RunnerEvent { RunnerProgress( super.name, super.command, super.timestamp, this.what, this.completed, this.total, this.done, ) : percent = (completed * 100) / total; /// What a command is currently working on, for example a build target or /// the name of a test. final String what; /// The number of steps completed. final int completed; /// The total number of steps in the task. final int total; /// How close is the task to being completed, for example the proportion of /// build targets that have finished building. final double percent; /// Whether the command is finished and this is the final progress event. final bool done; @override String toString() { final String ts = '[${_timestamp(timestamp)}]'; final String pct = '${percent.toStringAsFixed(1)}%'; return '$ts[$name]: $pct ($completed/$total) $what'; } } /// A [RunnerEvent] representing the result of a command. final class RunnerResult extends RunnerEvent { RunnerResult(super.name, super.command, super.timestamp, this.result); /// The resuilt of running the command. final ProcessRunnerResult result; /// Whether the command was successful. late final bool ok = result.exitCode == 0; @override String toString() { if (ok) { return '[${_timestamp(timestamp)}][$name]: OK'; } final StringBuffer buffer = StringBuffer(); buffer.writeln('[$timestamp][$name]: FAILED'); buffer.writeln('COMMAND:\n${command.join(' ')}'); buffer.writeln('STDOUT:\n${result.stdout}'); buffer.writeln('STDERR:\n${result.stderr}'); return buffer.toString(); } } final class RunnerError extends RunnerEvent { RunnerError(super.name, super.command, super.timestamp, this.error); /// An error message. final String error; @override String toString() { return '[${_timestamp(timestamp)}][$name]: ERROR: $error'; } } /// The type of a callback that handles [RunnerEvent]s while a [Runner] /// is executing its `run()` method. typedef RunnerEventHandler = void Function(RunnerEvent); /// An abstract base clase for running the various tasks that a build config /// specifies. Derived classes implement the `run()` method. sealed class Runner { Runner( this.platform, this.processRunner, this.abi, this.engineSrcDir, this.dryRun, ); /// Information about the platform that hosts the runner. final Platform platform; /// Runs the subprocesses required to run the element of the build config. final ProcessRunner processRunner; /// The [Abi] of the host platform. final ffi.Abi abi; /// The src/ directory of the engine checkout. final io.Directory engineSrcDir; /// Whether only a dry run is required. Subprocesses will not be spawned. final bool dryRun; /// Uses the [processRunner] to run the commands specified by the build /// config. Future<bool> run(RunnerEventHandler eventHandler); String _interpreter(String language) { // Force python to be python3. if (language.startsWith('python')) { return 'python3'; } // If the language is 'dart', return the Dart binary that is running this // program. if (language == 'dart') { return platform.executable; } // Otherwise use the language verbatim as the interpreter. return language; } } final ProcessRunnerResult _dryRunResult = ProcessRunnerResult( 0, // exit code. <int>[], // stdout. <int>[], // stderr. <int>[], // combined, pid: 0, // pid, ); /// The [Runner] for a [Build]. /// /// Runs the specified `gn` and `ninja` commands, followed by generator tasks, /// and finally tests. final class BuildRunner extends Runner { BuildRunner({ Platform? platform, ProcessRunner? processRunner, ffi.Abi? abi, required io.Directory engineSrcDir, required this.build, this.extraGnArgs = const <String>[], this.extraNinjaArgs = const <String>[], this.extraTestArgs = const <String>[], this.runGn = true, this.runNinja = true, this.runGenerators = true, this.runTests = true, bool dryRun = false, }) : super( platform ?? const LocalPlatform(), processRunner ?? ProcessRunner(), abi ?? ffi.Abi.current(), engineSrcDir, dryRun, ); /// The [Build] to run. final Build build; /// Extra arguments to append to the `gn` command. final List<String> extraGnArgs; /// Extra arguments to append to the `ninja` command. final List<String> extraNinjaArgs; /// Extra arguments to append to *all* test commands. final List<String> extraTestArgs; /// Whether to run the GN step. Defaults to true. final bool runGn; /// Whether to run the ninja step. Defaults to true. final bool runNinja; /// Whether to run the generators. Defaults to true. final bool runGenerators; /// Whether to run the test step. Defaults to true. final bool runTests; @override Future<bool> run(RunnerEventHandler eventHandler) async { if (!build.canRunOn(platform)) { eventHandler(RunnerError( build.name, <String>[], DateTime.now(), 'Build with drone_dimensions "{${build.droneDimensions.join(',')}}" ' 'cannot run on platform ${platform.operatingSystem}', )); return false; } if (runGn) { if (!await _runGn(eventHandler)) { return false; } } if (runNinja) { if (!await _runNinja(eventHandler)) { return false; } } if (runGenerators) { if (!await _runGenerators(eventHandler)) { return false; } } if (runTests) { if (!await _runTests(eventHandler)) { return false; } } return true; } // GN arguments from the build config that can be overridden by extraGnArgs. static const List<(String, String)> _overridableArgs = <(String, String)>[ ('--lto', '--no-lto'), ('--rbe', '--no-rbe'), ('--goma', '--no-goma'), ]; // extraGnArgs overrides the build config args. late final Set<String> _mergedGnArgs = () { // Put the union of the build config args and extraGnArgs in gnArgs. final Set<String> gnArgs = Set<String>.of(build.gn); gnArgs.addAll(extraGnArgs); // If extraGnArgs contains an arg, remove its opposite from gnArgs. for (final (String, String) arg in _overridableArgs) { if (extraGnArgs.contains(arg.$1)) { gnArgs.remove(arg.$2); } if (extraGnArgs.contains(arg.$2)) { gnArgs.remove(arg.$1); } } return gnArgs; }(); Future<bool> _runGn(RunnerEventHandler eventHandler) async { final String gnPath = p.join(engineSrcDir.path, 'flutter', 'tools', 'gn'); final Set<String> gnArgs = _mergedGnArgs; final List<String> command = <String>[gnPath, ...gnArgs]; eventHandler(RunnerStart('${build.name}: GN', command, DateTime.now())); final ProcessRunnerResult processResult; if (dryRun) { processResult = _dryRunResult; } else { processResult = await processRunner.runProcess( command, workingDirectory: engineSrcDir, failOk: true, ); } final RunnerResult result = RunnerResult( '${build.name}: GN', command, DateTime.now(), processResult, ); eventHandler(result); return result.ok; } late final String _hostCpu = () { return switch (abi) { ffi.Abi.linuxArm64 || ffi.Abi.macosArm64 || ffi.Abi.windowsArm64 => 'arm64', ffi.Abi.linuxX64 || ffi.Abi.macosX64 || ffi.Abi.windowsX64 => 'x64', _ => throw StateError('This host platform "$abi" is not supported.'), }; }(); late final String _buildtoolsPath = () { final String os = platform.operatingSystem; final String platformDir = switch (os) { Platform.linux => 'linux-$_hostCpu', Platform.macOS => 'mac-$_hostCpu', Platform.windows => 'windows-$_hostCpu', _ => throw StateError('This host OS "$os" is not supported.'), }; return p.join(engineSrcDir.path, 'buildtools', platformDir); }(); Future<bool> _bootstrapRbe( RunnerEventHandler eventHandler, { bool shutdown = false, }) async { final String reclientPath = p.join(_buildtoolsPath, 'reclient'); final String exe = platform.isWindows ? '.exe' : ''; final String bootstrapPath = p.join(reclientPath, 'bootstrap$exe'); final String reproxyPath = p.join(reclientPath, 'reproxy$exe'); final String os = platform.operatingSystem; final String reclientConfigFile = switch (os) { Platform.linux => 'reclient-linux.cfg', Platform.macOS => 'reclient-mac.cfg', Platform.windows => 'reclient-win.cfg', _ => throw StateError('This host OS "$os" is not supported.'), }; final String reclientConfigPath = p.join( engineSrcDir.path, 'flutter', 'build', 'rbe', reclientConfigFile, ); final List<String> bootstrapCommand = <String>[ bootstrapPath, '--re_proxy=$reproxyPath', '--automatic_auth=true', if (shutdown) '--shutdown' else ...<String>['--cfg=$reclientConfigPath'], ]; if (!processRunner.processManager.canRun(bootstrapPath)) { eventHandler(RunnerError( build.name, <String>[], DateTime.now(), '"$bootstrapPath" not found.', )); return false; } eventHandler(RunnerStart( '${build.name}: RBE ${shutdown ? 'shutdown' : 'startup'}', bootstrapCommand, DateTime.now(), )); final ProcessRunnerResult bootstrapResult; if (dryRun) { bootstrapResult = _dryRunResult; } else { bootstrapResult = await processRunner.runProcess( bootstrapCommand, failOk: true, ); } eventHandler(RunnerResult( '${build.name}: RBE ${shutdown ? 'shutdown' : 'startup'}', bootstrapCommand, DateTime.now(), bootstrapResult, )); return bootstrapResult.exitCode == 0; } Future<bool> _runNinja(RunnerEventHandler eventHandler) async { if (_isRbe) { if (!await _bootstrapRbe(eventHandler)) { return false; } } bool success = false; try { final String ninjaPath = p.join( engineSrcDir.path, 'flutter', 'third_party', 'ninja', 'ninja', ); final String outDir = p.join( engineSrcDir.path, 'out', build.ninja.config, ); final List<String> command = <String>[ ninjaPath, '-C', outDir, if (_isGomaOrRbe) ...<String>['-j', '200'], ...extraNinjaArgs, ...build.ninja.targets, ]; eventHandler( RunnerStart('${build.name}: ninja', command, DateTime.now()), ); final ProcessRunnerResult processResult; if (dryRun) { processResult = _dryRunResult; } else { final io.Process process = await processRunner.processManager.start( command, workingDirectory: engineSrcDir.path, ); final List<int> stderrOutput = <int>[]; final List<int> stdoutOutput = <int>[]; final Completer<void> stdoutComplete = Completer<void>(); final Completer<void> stderrComplete = Completer<void>(); process.stdout .transform<String>(const Utf8Decoder()) .transform(const LineSplitter()) .listen( (String line) { if (_ninjaProgress(eventHandler, command, line)) { return; } final List<int> bytes = utf8.encode('$line\n'); stdoutOutput.addAll(bytes); }, onDone: () async => stdoutComplete.complete(), ); process.stderr.listen( stderrOutput.addAll, onDone: () async => stderrComplete.complete(), ); await Future.wait<void>(<Future<void>>[ stdoutComplete.future, stderrComplete.future, ]); final int exitCode = await process.exitCode; processResult = ProcessRunnerResult( exitCode, stdoutOutput, // stdout. stderrOutput, // stderr. <int>[], // combined, pid: process.pid, // pid, ); } eventHandler(RunnerResult( '${build.name}: ninja', command, DateTime.now(), processResult, )); success = processResult.exitCode == 0; } finally { if (_isRbe) { // Ignore failures to shutdown. await _bootstrapRbe(eventHandler, shutdown: true); } } return success; } // Parse lines of the form '[6232/6269] LINK ./accessibility_unittests'. // Returns false if the line is not a ninja progress line. bool _ninjaProgress( RunnerEventHandler eventHandler, List<String> command, String line, ) { // Grab the '[6232/6269]' part. final String maybeProgress = line.split(' ')[0]; if (maybeProgress.length < 3 || maybeProgress[0] != '[' || maybeProgress[maybeProgress.length - 1] != ']') { return false; } // Extract the two numbers by stripping the '[' and ']' and splitting on // the '/'. final List<String> progress = maybeProgress.substring(1, maybeProgress.length - 1).split('/'); if (progress.length < 2) { return false; } final int? completed = int.tryParse(progress[0]); final int? total = int.tryParse(progress[1]); if (completed == null || total == null) { return false; } eventHandler(RunnerProgress( '${build.name}: ninja', command, DateTime.now(), line.replaceFirst(maybeProgress, '').trim(), completed, total, completed == total, // True when done. )); return true; } late final bool _isGoma = _mergedGnArgs.contains('--goma'); late final bool _isRbe = _mergedGnArgs.contains('--rbe'); late final bool _isGomaOrRbe = _isGoma || _isRbe; Future<bool> _runGenerators(RunnerEventHandler eventHandler) async { for (final BuildTask task in build.generators) { final BuildTaskRunner runner = BuildTaskRunner( processRunner: processRunner, platform: platform, abi: abi, engineSrcDir: engineSrcDir, task: task, dryRun: dryRun, ); if (!await runner.run(eventHandler)) { return false; } } return true; } Future<bool> _runTests(RunnerEventHandler eventHandler) async { for (final BuildTest test in build.tests) { final BuildTestRunner runner = BuildTestRunner( processRunner: processRunner, platform: platform, abi: abi, engineSrcDir: engineSrcDir, test: test, extraTestArgs: extraTestArgs, dryRun: dryRun, ); if (!await runner.run(eventHandler)) { return false; } } return true; } } /// The [Runner] for a [BuildTask] of a generator of a [Build]. final class BuildTaskRunner extends Runner { BuildTaskRunner({ Platform? platform, ProcessRunner? processRunner, ffi.Abi? abi, required io.Directory engineSrcDir, required this.task, bool dryRun = false, }) : super( platform ?? const LocalPlatform(), processRunner ?? ProcessRunner(), abi ?? ffi.Abi.current(), engineSrcDir, dryRun, ); /// The task to run. final BuildTask task; @override Future<bool> run(RunnerEventHandler eventHandler) async { final String interpreter = _interpreter(task.language); for (final String script in task.scripts) { final List<String> command = <String>[ if (interpreter.isNotEmpty) interpreter, script, ...task.parameters, ]; eventHandler(RunnerStart(task.name, command, DateTime.now())); final ProcessRunnerResult processResult; if (dryRun) { processResult = _dryRunResult; } else { processResult = await processRunner.runProcess( command, workingDirectory: engineSrcDir, failOk: true, ); } final RunnerResult result = RunnerResult( task.name, command, DateTime.now(), processResult, ); eventHandler(result); if (!result.ok) { return false; } } return true; } } /// The [Runner] for a [BuildTest] of a [Build]. final class BuildTestRunner extends Runner { BuildTestRunner({ Platform? platform, ProcessRunner? processRunner, ffi.Abi? abi, required io.Directory engineSrcDir, required this.test, this.extraTestArgs = const <String>[], bool dryRun = false, }) : super( platform ?? const LocalPlatform(), processRunner ?? ProcessRunner(), abi ?? ffi.Abi.current(), engineSrcDir, dryRun, ); /// The test to run. final BuildTest test; /// Extra arguments to append to the test command. final List<String> extraTestArgs; @override Future<bool> run(RunnerEventHandler eventHandler) async { final String interpreter = _interpreter(test.language); final List<String> command = <String>[ if (interpreter.isNotEmpty) interpreter, test.script, ...test.parameters, ...extraTestArgs, ]; eventHandler(RunnerStart(test.name, command, DateTime.now())); final ProcessRunnerResult processResult; if (dryRun) { processResult = _dryRunResult; } else { // TODO(zanderso): We could detect here that we're running e.g. C++ unit // tests via run_tests.py, and parse the stdout to generate RunnerProgress // events. processResult = await processRunner.runProcess( command, workingDirectory: engineSrcDir, failOk: true, printOutput: true, ); } final RunnerResult result = RunnerResult( test.name, command, DateTime.now(), processResult, ); eventHandler(result); return result.ok; } } String _timestamp(DateTime time) { String threeDigits(int n) { return switch (n) { >= 100 => '$n', >= 10 => '0$n', _ => '00$n', }; } String twoDigits(int n) { return switch (n) { >= 10 => '$n', _ => '0$n', }; } final String y = time.year.toString(); final String m = twoDigits(time.month); final String d = twoDigits(time.day); final String hh = twoDigits(time.hour); final String mm = twoDigits(time.minute); final String ss = twoDigits(time.second); final String ms = threeDigits(time.millisecond); return '$y-$m-${d}T$hh:$mm:$ss.$ms${time.isUtc ? 'Z' : ''}'; }
engine/tools/pkg/engine_build_configs/lib/src/build_config_runner.dart/0
{ "file_path": "engine/tools/pkg/engine_build_configs/lib/src/build_config_runner.dart", "repo_id": "engine", "token_count": 7749 }
433
# `process_fakes` Fake implementations of `Process` and `ProcessManager` for testing. This is not a great package, and is the bare minimum needed for fairly basic tooling that uses `ProcessManager`. If we ever need a more complete solution we should look at upstreaming [`flutter_tools/.../fake_proecss_manager.dart`](https://github.com/flutter/flutter/blob/a9183f696c8e12617d05a26b0b5e80035e515f2a/packages/flutter_tools/test/src/fake_process_manager.dart#L223)
engine/tools/pkg/process_fakes/README.md/0
{ "file_path": "engine/tools/pkg/process_fakes/README.md", "repo_id": "engine", "token_count": 152 }
434
// 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_proc_table.h" #include <utility> #include "flutter/fml/logging.h" #define ACQUIRE_PROC(name, context) \ if (!(name = AcquireProc("vk" #name, context))) { \ return false; \ } #define ACQUIRE_PROC_EITHER(name, name2, context) \ if (!(name = AcquireProc("vk" #name, context)) && \ !(name2 = AcquireProc("vk" #name2, context))) { \ return false; \ } namespace vulkan { VulkanProcTable::VulkanProcTable() : VulkanProcTable("libvulkan.so"){}; VulkanProcTable::VulkanProcTable(const char* so_path) : handle_(nullptr), acquired_mandatory_proc_addresses_(false) { acquired_mandatory_proc_addresses_ = OpenLibraryHandle(so_path) && SetupGetInstanceProcAddress() && SetupLoaderProcAddresses(); } VulkanProcTable::VulkanProcTable( PFN_vkGetInstanceProcAddr get_instance_proc_addr) : handle_(nullptr), acquired_mandatory_proc_addresses_(false) { GetInstanceProcAddr = get_instance_proc_addr; acquired_mandatory_proc_addresses_ = SetupLoaderProcAddresses(); } VulkanProcTable::~VulkanProcTable() { CloseLibraryHandle(); } bool VulkanProcTable::HasAcquiredMandatoryProcAddresses() const { return acquired_mandatory_proc_addresses_; } bool VulkanProcTable::IsValid() const { return instance_ && device_; } bool VulkanProcTable::AreInstanceProcsSetup() const { return instance_; } bool VulkanProcTable::AreDeviceProcsSetup() const { return device_; } bool VulkanProcTable::SetupGetInstanceProcAddress() { if (!handle_) { return true; } GetInstanceProcAddr = NativeGetInstanceProcAddr(); if (!GetInstanceProcAddr) { FML_DLOG(WARNING) << "Could not acquire vkGetInstanceProcAddr."; return false; } return true; } PFN_vkGetInstanceProcAddr VulkanProcTable::NativeGetInstanceProcAddr() const { if (GetInstanceProcAddr) { return GetInstanceProcAddr; } auto instance_proc = const_cast<uint8_t*>(handle_->ResolveSymbol("vkGetInstanceProcAddr")); return reinterpret_cast<PFN_vkGetInstanceProcAddr>(instance_proc); } bool VulkanProcTable::SetupLoaderProcAddresses() { VulkanHandle<VkInstance> null_instance(VK_NULL_HANDLE, nullptr); ACQUIRE_PROC(CreateInstance, null_instance); ACQUIRE_PROC(EnumerateInstanceExtensionProperties, null_instance); ACQUIRE_PROC(EnumerateInstanceLayerProperties, null_instance); return true; } bool VulkanProcTable::SetupInstanceProcAddresses( const VulkanHandle<VkInstance>& handle) { ACQUIRE_PROC(CreateDevice, handle); ACQUIRE_PROC(DestroyDevice, handle); ACQUIRE_PROC(DestroyInstance, handle); ACQUIRE_PROC(EnumerateDeviceLayerProperties, handle); ACQUIRE_PROC(EnumeratePhysicalDevices, handle); ACQUIRE_PROC(GetDeviceProcAddr, handle); ACQUIRE_PROC(GetPhysicalDeviceFeatures, handle); ACQUIRE_PROC(GetPhysicalDeviceQueueFamilyProperties, handle); ACQUIRE_PROC(GetPhysicalDeviceProperties, handle); ACQUIRE_PROC(GetPhysicalDeviceMemoryProperties, handle); ACQUIRE_PROC_EITHER(GetPhysicalDeviceMemoryProperties2, GetPhysicalDeviceMemoryProperties2KHR, handle); #if FML_OS_ANDROID ACQUIRE_PROC(GetPhysicalDeviceSurfaceCapabilitiesKHR, handle); ACQUIRE_PROC(GetPhysicalDeviceSurfaceFormatsKHR, handle); ACQUIRE_PROC(GetPhysicalDeviceSurfacePresentModesKHR, handle); ACQUIRE_PROC(GetPhysicalDeviceSurfaceSupportKHR, handle); ACQUIRE_PROC(DestroySurfaceKHR, handle); ACQUIRE_PROC(CreateAndroidSurfaceKHR, handle); #endif // FML_OS_ANDROID // The debug report functions are optional. We don't want proc acquisition to // fail here because the optional methods were not present (since ACQUIRE_PROC // returns false on failure). Wrap the optional proc acquisitions in an // anonymous lambda and invoke it. We don't really care about the result since // users of Debug reporting functions check for their presence explicitly. [this, &handle]() -> bool { ACQUIRE_PROC(CreateDebugReportCallbackEXT, handle); ACQUIRE_PROC(DestroyDebugReportCallbackEXT, handle); return true; }(); instance_ = VulkanHandle<VkInstance>{handle, nullptr}; return true; } bool VulkanProcTable::SetupDeviceProcAddresses( const VulkanHandle<VkDevice>& handle) { ACQUIRE_PROC(AllocateCommandBuffers, handle); ACQUIRE_PROC(AllocateMemory, handle); ACQUIRE_PROC(BeginCommandBuffer, handle); ACQUIRE_PROC(BindImageMemory, handle); ACQUIRE_PROC(CmdPipelineBarrier, handle); ACQUIRE_PROC(CreateCommandPool, handle); ACQUIRE_PROC(CreateFence, handle); ACQUIRE_PROC(CreateImage, handle); ACQUIRE_PROC(CreateSemaphore, handle); ACQUIRE_PROC(DestroyCommandPool, handle); ACQUIRE_PROC(DestroyFence, handle); ACQUIRE_PROC(DestroyImage, handle); ACQUIRE_PROC(DestroySemaphore, handle); ACQUIRE_PROC(DeviceWaitIdle, handle); ACQUIRE_PROC(EndCommandBuffer, handle); ACQUIRE_PROC(FreeCommandBuffers, handle); ACQUIRE_PROC(FreeMemory, handle); ACQUIRE_PROC(GetDeviceQueue, handle); ACQUIRE_PROC(GetImageMemoryRequirements, handle); ACQUIRE_PROC(QueueSubmit, handle); ACQUIRE_PROC(QueueWaitIdle, handle); ACQUIRE_PROC(ResetCommandBuffer, handle); ACQUIRE_PROC(ResetFences, handle); ACQUIRE_PROC(WaitForFences, handle); ACQUIRE_PROC(MapMemory, handle); ACQUIRE_PROC(UnmapMemory, handle); ACQUIRE_PROC(FlushMappedMemoryRanges, handle); ACQUIRE_PROC(InvalidateMappedMemoryRanges, handle); ACQUIRE_PROC(BindBufferMemory, handle); ACQUIRE_PROC(GetBufferMemoryRequirements, handle); ACQUIRE_PROC(CreateBuffer, handle); ACQUIRE_PROC(DestroyBuffer, handle); ACQUIRE_PROC(CmdCopyBuffer, handle); ACQUIRE_PROC_EITHER(GetBufferMemoryRequirements2, GetBufferMemoryRequirements2KHR, handle); ACQUIRE_PROC_EITHER(GetImageMemoryRequirements2, GetImageMemoryRequirements2KHR, handle); ACQUIRE_PROC_EITHER(BindBufferMemory2, BindBufferMemory2KHR, handle); ACQUIRE_PROC_EITHER(BindImageMemory2, BindImageMemory2KHR, handle); #ifndef TEST_VULKAN_PROCS #if FML_OS_ANDROID ACQUIRE_PROC(AcquireNextImageKHR, handle); ACQUIRE_PROC(CreateSwapchainKHR, handle); ACQUIRE_PROC(DestroySwapchainKHR, handle); ACQUIRE_PROC(GetSwapchainImagesKHR, handle); ACQUIRE_PROC(QueuePresentKHR, handle); #endif // FML_OS_ANDROID #if OS_FUCHSIA ACQUIRE_PROC(ImportSemaphoreZirconHandleFUCHSIA, handle); ACQUIRE_PROC(GetSemaphoreZirconHandleFUCHSIA, handle); ACQUIRE_PROC(GetMemoryZirconHandleFUCHSIA, handle); ACQUIRE_PROC(CreateBufferCollectionFUCHSIA, handle); ACQUIRE_PROC(DestroyBufferCollectionFUCHSIA, handle); ACQUIRE_PROC(SetBufferCollectionImageConstraintsFUCHSIA, handle); ACQUIRE_PROC(GetBufferCollectionPropertiesFUCHSIA, handle); #endif // OS_FUCHSIA #endif // TEST_VULKAN_PROCS device_ = VulkanHandle<VkDevice>{handle, nullptr}; return true; } bool VulkanProcTable::OpenLibraryHandle(const char* path) { handle_ = fml::NativeLibrary::Create(path); if (!handle_) { FML_DLOG(ERROR) << "Could not open Vulkan library handle: " << path; return false; } return true; } bool VulkanProcTable::CloseLibraryHandle() { handle_ = nullptr; return true; } PFN_vkVoidFunction VulkanProcTable::AcquireProc( const char* proc_name, const VulkanHandle<VkInstance>& instance) const { if (proc_name == nullptr || !GetInstanceProcAddr) { return nullptr; } // A VK_NULL_HANDLE as the instance is an acceptable parameter. return reinterpret_cast<PFN_vkVoidFunction>( GetInstanceProcAddr(instance, proc_name)); } PFN_vkVoidFunction VulkanProcTable::AcquireProc( const char* proc_name, const VulkanHandle<VkDevice>& device) const { if (proc_name == nullptr || !device || !GetDeviceProcAddr) { return nullptr; } return GetDeviceProcAddr(device, proc_name); } } // namespace vulkan
engine/vulkan/procs/vulkan_proc_table.cc/0
{ "file_path": "engine/vulkan/procs/vulkan_proc_table.cc", "repo_id": "engine", "token_count": 2955 }
435
// 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_NATIVE_SURFACE_H_ #define FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_H_ #include "flutter/fml/macros.h" #include "flutter/vulkan/procs/vulkan_handle.h" #include "flutter/vulkan/procs/vulkan_proc_table.h" #include "third_party/skia/include/core/SkSize.h" namespace vulkan { class VulkanNativeSurface { public: virtual ~VulkanNativeSurface() = default; virtual const char* GetExtensionName() const = 0; virtual uint32_t GetSkiaExtensionName() const = 0; virtual VkSurfaceKHR CreateSurfaceHandle( VulkanProcTable& vk, const VulkanHandle<VkInstance>& instance) const = 0; virtual bool IsValid() const = 0; virtual SkISize GetSize() const = 0; }; } // namespace vulkan #endif // FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_H_
engine/vulkan/vulkan_native_surface.h/0
{ "file_path": "engine/vulkan/vulkan_native_surface.h", "repo_id": "engine", "token_count": 349 }
436
# Copyright 2022 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 BUILD.gn is kept separate from //flutter/BUILD.gn because # //flutter/BUILD.gn pulls in Flutter SDK dependencies which will crash # when the target CPU is WASM. import("//flutter/common/config.gni") # This is the default target when building when the target CPU is WASM. group("wasm") { deps = [ "//flutter/web_sdk:flutter_web_sdk_archive" ] }
engine/wasm/BUILD.gn/0
{ "file_path": "engine/wasm/BUILD.gn", "repo_id": "engine", "token_count": 160 }
437
# Copyright 2019 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/build/dart/dart.gni") import("//flutter/common/config.gni") import("$dart_src/build/dart/dart_action.gni") dart_sdk_package_config = "$dart_src/.dart_tool/package_config.json" template("sdk_rewriter") { ui = defined(invoker.ui) && invoker.ui if (!ui) { assert(defined(invoker.library_name), "Must pass 'library_name'") assert(defined(invoker.api_file), "Must pass 'api_file'") } assert(defined(invoker.input_dir), "Must pass 'input_dir'") assert(defined(invoker.output_dir), "Must pass 'output_dir'") prebuilt_dart_action(target_name) { packages = dart_sdk_package_config pool = "//flutter/build/dart:dart_pool" script = "//flutter/web_sdk/sdk_rewriter.dart" depfile = "$target_gen_dir/$target_name.d" stamp_location = "$target_gen_dir/$target_name.stamp" outputs = [ stamp_location, invoker.output_dir, ] build_dir = rebase_path(root_out_dir) input_dir = rebase_path(invoker.input_dir) output_dir = rebase_path(invoker.output_dir) args = [ "--build-dir=$build_dir", "--output-dir=$output_dir", "--input-dir=$input_dir", "--depfile", rebase_path(depfile), "--stamp", rebase_path(stamp_location, root_build_dir), ] if (defined(invoker.exclude_pattern)) { args += [ "--exclude-pattern", invoker.exclude_pattern, ] } if (defined(invoker.is_public) && invoker.is_public) { args += [ "--public" ] } if (ui) { args += [ "--ui" ] } else { library_name = invoker.library_name api_file = rebase_path(invoker.api_file) args += [ "--library-name=$library_name", "--api-file=$api_file", ] } } } template("web_ui_ui_web_with_output") { sdk_rewriter(target_name) { library_name = "ui_web" is_public = true api_file = "//flutter/lib/web_ui/lib/ui_web/src/ui_web.dart" input_dir = "//flutter/lib/web_ui/lib/ui_web/src/ui_web/" output_dir = invoker.output_dir } }
engine/web_sdk/web_sdk.gni/0
{ "file_path": "engine/web_sdk/web_sdk.gni", "repo_id": "engine", "token_count": 963 }
438
<component name="libraryTable"> <library name="com.google.protobuf:protobuf-java:3.5.1" type="repository"> <properties maven-id="com.google.protobuf:protobuf-java:3.5.1" /> <CLASSES> <root url="jar://$MAVEN_REPOSITORY$/com/google/protobuf/protobuf-java/3.5.1/protobuf-java-3.5.1.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component>
flutter-intellij/.idea/libraries/com_google_protobuf_protobuf_java_3_5_1.xml/0
{ "file_path": "flutter-intellij/.idea/libraries/com_google_protobuf_protobuf_java_3_5_1.xml", "repo_id": "flutter-intellij", "token_count": 174 }
439
/* * 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.tests.gui import com.intellij.testGuiFramework.framework.RunWithIde import com.intellij.testGuiFramework.impl.GuiTestCase import com.intellij.testGuiFramework.launcher.ide.CommunityIde import com.intellij.testGuiFramework.util.step import io.flutter.tests.gui.fixtures.flutterPerfFixture import org.fest.swing.timing.Pause.pause import org.junit.Test import kotlin.test.expect @RunWithIde(CommunityIde::class) class PerfTest : GuiTestCase() { @Test fun checkPerfView() { ProjectCreator.importProject() ideFrame { launchFlutterApp() val monitor = flutterPerfFixture(this) monitor.populate() pause() step("Exercise FPS tab") { val perf = monitor.perfTabFixture() expect(false, perf.controlCheckboxes()::isEmpty) val performanceCheckbox = perf.performanceCheckbox() expect(true, performanceCheckbox::isEnabled) val repaintCheckbox = perf.repaintCheckbox() expect(true, repaintCheckbox::isEnabled) val frames = perf.frameRenderingPanel() var currCount = frames.componentCount() var prevCount = currCount expect(true) { currCount >= 0 } step("Drive UI and cause app to refresh") { performanceCheckbox.click() performanceCheckbox.click() currCount = frames.componentCount() expect(true) { currCount > prevCount } prevCount = currCount repaintCheckbox.click() repaintCheckbox.click() currCount = frames.componentCount() expect(true) { currCount > prevCount } prevCount = currCount } } step("Check memory tab") { val mem = monitor.memoryTabFixture() expect(false, mem.heapDisplayLabels()::isEmpty) expect(true, mem.heapDisplay()::isEnabled) } runner().stop() } } }
flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/PerfTest.kt/0
{ "file_path": "flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/PerfTest.kt", "repo_id": "flutter-intellij", "token_count": 812 }
440
/* * 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; import com.intellij.ide.DataManager; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.ide.scratch.ScratchRootType; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.diagnostic.ErrorReportSubmitter; import com.intellij.openapi.diagnostic.IdeaLoggingEvent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diagnostic.SubmittedReportInfo; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileTypes.PlainTextLanguage; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import io.flutter.run.daemon.DaemonApi; import io.flutter.sdk.FlutterSdk; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; import static com.intellij.openapi.actionSystem.CommonDataKeys.PROJECT; import static io.flutter.run.daemon.DaemonApi.COMPLETION_EXCEPTION_PREFIX; // Not sure how others debug this but here's one technique. // Edit com.intellij.ide.plugins.PluginManagerCore. // Add this line at the top of getPluginByClassName(): // if (true) return getPlugins()[getPlugins().length-1].getPluginId(); // DEBUG do not merge public class FlutterErrorReportSubmitter extends ErrorReportSubmitter { private static final Logger LOG = Logger.getInstance(FlutterErrorReportSubmitter.class); private static final String[] KNOWN_ERRORS = new String[]{"Bad state: No element"}; @NotNull @Override public String getReportActionText() { return "Create Flutter Bug Report"; } //@Override public boolean submit(@NotNull IdeaLoggingEvent[] events, @Nullable String additionalInfo, @NotNull Component parentComponent, @NotNull Consumer<? super SubmittedReportInfo> consumer) { if (events.length == 0) { // Don't remove the cast until a later version of Android Studio. fail(((Consumer<SubmittedReportInfo>)consumer)); return false; } String stackTrace = null; String errorMessage = null; for (IdeaLoggingEvent event : events) { String stackTraceText = event.getThrowableText(); if (stackTraceText.startsWith(COMPLETION_EXCEPTION_PREFIX)) { stackTraceText = stackTraceText.substring(COMPLETION_EXCEPTION_PREFIX.length()); if (stackTraceText.startsWith(DaemonApi.FLUTTER_ERROR_PREFIX)) { final String message = stackTraceText.substring(DaemonApi.FLUTTER_ERROR_PREFIX.length()); final int start = message.indexOf(": ") + 2; if (start == 0) continue; int end = message.indexOf('\n'); if (end < 0) end = message.length(); final String error = message.substring(start, end); stackTrace = message.substring(end + 1); for (String err : KNOWN_ERRORS) { if (error.contains(err)) { if (end != message.length()) { // Dart stack trace included so extract it and set the issue target to the Flutter repo. errorMessage = err; final int endOfDartStack = stackTrace.indexOf("\\n\"\n"); if (endOfDartStack > 0) { // Get only the part between quotes. If the format is wrong just use the whole thing. stackTrace = stackTrace.substring(1, endOfDartStack); } break; } } } } } } final DataContext dataContext = DataManager.getInstance().getDataContext(parentComponent); final Project project = PROJECT.getData(dataContext); if (project == null) { // Don't remove the cast until a later version of Android Studio. fail(((Consumer<SubmittedReportInfo>)consumer)); return false; } final StringBuilder builder = new StringBuilder(); builder.append("Please file this bug report at "); builder.append("https://github.com/flutter/flutter-intellij/issues/new"); builder.append(".\n"); builder.append("\n"); builder.append("---\n"); builder.append("\n"); builder.append("## What happened\n"); builder.append("\n"); if (additionalInfo != null) { builder.append(additionalInfo.trim()).append("\n"); } else { builder.append("(please describe what you were doing when this exception occurred)\n"); } builder.append("\n"); builder.append("## Version information\n"); builder.append("\n"); // IntelliJ version final ApplicationInfo info = ApplicationInfo.getInstance(); builder.append(info.getVersionName()).append(" `").append(info.getFullVersion()).append("`"); final PluginId pid = FlutterUtils.getPluginId(); final IdeaPluginDescriptor flutterPlugin = PluginManagerCore.getPlugin(pid); //noinspection ConstantConditions builder.append(" • Flutter plugin `").append(pid.getIdString()).append(' ').append(flutterPlugin.getVersion()).append("`"); final IdeaPluginDescriptor dartPlugin = PluginManagerCore.getPlugin(PluginId.getId("Dart")); if (dartPlugin != null) { builder.append(" • Dart plugin `").append(dartPlugin.getVersion()).append("`"); } builder.append("\n\n"); final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project); if (sdk == null) { builder.append("No Flutter sdk configured.\n"); } else { final String flutterVersion = getFlutterVersion(sdk); if (flutterVersion != null) { builder.append(flutterVersion.trim()).append("\n"); } else { builder.append("Error getting Flutter sdk information.\n"); } } builder.append("\n"); if (stackTrace == null) { for (IdeaLoggingEvent event : events) { builder.append("## Exception\n"); builder.append("\n"); builder.append(event.getMessage()).append("\n"); builder.append("\n"); if (event.getThrowable() != null) { builder.append("```\n"); builder.append(event.getThrowableText().trim()).append("\n"); builder.append("```\n"); builder.append("\n"); } } } else { builder.append("## Exception\n"); builder.append("\n"); builder.append(errorMessage).append("\n"); builder.append("\n"); builder.append("```\n"); builder.append(stackTrace.replaceAll("\\\\n", "\n")).append("\n"); builder.append("```\n"); builder.append("\n"); } for (IdeaLoggingEvent event : events) { FlutterInitializer.getAnalytics().sendException(event.getThrowableText(), false); } final String text = builder.toString().trim() + "\n"; // Create scratch file. final ScratchRootType scratchRoot = ScratchRootType.getInstance(); final VirtualFile file = scratchRoot.createScratchFile(project, "bug-report.md", PlainTextLanguage.INSTANCE, text); if (file == null) { // Don't remove the cast until a later version of Android Studio. fail(((Consumer<SubmittedReportInfo>)consumer)); return false; } // Open the file. new OpenFileDescriptor(project, file).navigate(true); consumer.consume(new SubmittedReportInfo( null, "", SubmittedReportInfo.SubmissionStatus.NEW_ISSUE)); return true; } private static String getFlutterVersion(final FlutterSdk sdk) { try { final String flutterPath = sdk.getHomePath() + "/bin/flutter"; final ProcessBuilder builder = new ProcessBuilder(flutterPath, "--version"); final Process process = builder.start(); if (!process.waitFor(3, TimeUnit.SECONDS)) { return null; } return new String(readFully(process.getInputStream()), StandardCharsets.UTF_8); } catch (IOException | InterruptedException ioe) { return null; } } private static void fail(@NotNull Consumer<SubmittedReportInfo> consumer) { consumer.consume(new SubmittedReportInfo( null, null, SubmittedReportInfo.SubmissionStatus.FAILED)); } private static byte[] readFully(InputStream in) throws IOException { //noinspection resource final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] temp = new byte[4096]; int count = in.read(temp); while (count > 0) { out.write(temp, 0, count); count = in.read(temp); } return out.toByteArray(); } }
flutter-intellij/flutter-idea/src/io/flutter/FlutterErrorReportSubmitter.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/FlutterErrorReportSubmitter.java", "repo_id": "flutter-intellij", "token_count": 3374 }
441
/* * 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.actions; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.ColoredProcessHandler; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import io.flutter.FlutterUtils; import io.flutter.bazel.Workspace; import io.flutter.console.FlutterConsoles; import io.flutter.pub.PubRoot; import io.flutter.sdk.FlutterSdk; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.nio.charset.StandardCharsets; public class FlutterDoctorAction extends FlutterSdkAction { private static final Logger LOG = Logger.getInstance(FlutterDoctorAction.class); public void startCommand(@NotNull Project project, @NotNull FlutterSdk sdk, @Nullable PubRoot root) { sdk.flutterDoctor().startInConsole(project); } @Override public void startCommand(@NotNull Project project, @NotNull FlutterSdk sdk, @Nullable PubRoot root, @NotNull DataContext context) { startCommand(project, sdk, root); } @Override public void startCommandInBazelContext(@NotNull Project project, @NotNull Workspace workspace, @NotNull AnActionEvent event) { final String doctorScript = workspace.getDoctorScript(); if (doctorScript != null) { runWorkspaceFlutterDoctorScript(project, workspace.getRoot().getPath(), doctorScript); } else { FlutterUtils.warn(LOG, "No \"doctorScript\" script in the flutter.json file."); } } private void runWorkspaceFlutterDoctorScript(@NotNull Project project, @NotNull String workDir, @NotNull String doctorScript) { final GeneralCommandLine cmdLine = new GeneralCommandLine().withWorkDirectory(workDir); cmdLine.setCharset(StandardCharsets.UTF_8); cmdLine.setExePath(FileUtil.toSystemDependentName(doctorScript)); final ColoredProcessHandler handler; try { handler = new ColoredProcessHandler(cmdLine); FlutterConsoles.displayProcessLater(handler, project, null, handler::startNotify); } catch (ExecutionException e) { LOG.error(e); } } @Override public boolean enableActionInBazelContext() { return true; } }
flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterDoctorAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterDoctorAction.java", "repo_id": "flutter-intellij", "token_count": 819 }
442
/* * 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.openapi.actionSystem.AnAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; /** * Store and retrieve actions relative to a Project. */ public class ProjectActions { private static final Key<Map<String, AnAction>> PROJECT_ACTIONS_KEY = Key.create("ProjectActions"); public static void registerAction(@NotNull Project project, @NotNull String id, @NotNull AnAction action) { Map<String, AnAction> actions = project.getUserData(PROJECT_ACTIONS_KEY); if (actions == null) { actions = new HashMap<>(); project.putUserData(PROJECT_ACTIONS_KEY, actions); } actions.put(id, action); } @Nullable public static AnAction getAction(@NotNull Project project, @NotNull String id) { final Map<String, AnAction> actions = project.getUserData(PROJECT_ACTIONS_KEY); return actions == null ? null : actions.get(id); } public static void unregisterAction(@NotNull Project project, @NotNull String id) { final Map<String, AnAction> actions = project.getUserData(PROJECT_ACTIONS_KEY); if (actions != null) { actions.remove(id); } } private ProjectActions() { } }
flutter-intellij/flutter-idea/src/io/flutter/actions/ProjectActions.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/ProjectActions.java", "repo_id": "flutter-intellij", "token_count": 492 }
443
package io.flutter.analytics; import org.jetbrains.annotations.NotNull; import java.time.Instant; public class RequestDetails { private final String method; private final Instant startTime; public RequestDetails(@NotNull String method, @NotNull Instant startTime) { this.method = method; this.startTime = startTime; } @NotNull public String method() { return method; } @NotNull public Instant startTime() { return startTime; } @NotNull public String toString() { return method + ": " + startTime.toEpochMilli(); } }
flutter-intellij/flutter-idea/src/io/flutter/analytics/RequestDetails.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/analytics/RequestDetails.java", "repo_id": "flutter-intellij", "token_count": 185 }
444
/* * 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.intellij.execution.process.ColoredProcessHandler; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.ui.content.Content; import com.intellij.ui.content.MessageView; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Methods that use the appropriate Flutter console. * <p> * We share one Flutter console per Module, and have one global Flutter console (for tasks which don't * take a module, like 'flutter doctor'). */ public class FlutterConsoles { private FlutterConsoles() { } /** * Shows a process's output on the appropriate console. (Asynchronous.) * * @param module if not null, show in this module's console. */ public static void displayProcessLater(@NotNull ColoredProcessHandler process, @NotNull Project project, @Nullable Module module, @NotNull Runnable onReady) { // Getting a MessageView has to happen on the UI thread. ApplicationManager.getApplication().invokeLater(() -> { final MessageView messageView = MessageView.getInstance(project); messageView.runWhenInitialized(() -> { final FlutterConsole console = findOrCreate(project, module); console.watchProcess(process); console.bringToFront(); onReady.run(); }); }); } public static void displayMessage(@NotNull Project project, @Nullable Module module, @NotNull String message) { displayMessage(project, module, message, false); } public static void displayMessage(@NotNull Project project, @Nullable Module module, @NotNull String message, boolean clearContent) { // Getting a MessageView has to happen on the UI thread. ApplicationManager.getApplication().invokeLater(() -> { final MessageView messageView = MessageView.getInstance(project); messageView.runWhenInitialized(() -> { final FlutterConsole console = findOrCreate(project, module); if (clearContent) { console.view.clear(); } console.view.print(message, ConsoleViewContentType.NORMAL_OUTPUT); console.bringToFront(); }); }); } @NotNull static FlutterConsole findOrCreate(@NotNull Project project, @Nullable Module module) { for (Content content : MessageView.getInstance(project).getContentManager().getContents()) { final FlutterConsole console = content.getUserData(KEY); if (console != null && console.module == module) { assert (project == console.project); return console; } } final FlutterConsole console = FlutterConsole.create(project, module); console.content.putUserData(FlutterConsoles.KEY, console); return console; } static final Key<FlutterConsole> KEY = Key.create("FLUTTER_CONSOLE_KEY"); }
flutter-intellij/flutter-idea/src/io/flutter/console/FlutterConsoles.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/console/FlutterConsoles.java", "repo_id": "flutter-intellij", "token_count": 1117 }
445
/* * 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 java.awt.*; public class ExpressionParsingUtils { public static Integer parseNumberFromCallParam(String callText, String prefix) { if (callText.startsWith(prefix) && callText.endsWith(")")) { String val = callText.substring(prefix.length(), callText.length() - 1).trim(); final int index = val.indexOf(','); if (index != -1) { val = val.substring(0, index); } try { return val.startsWith("0x") ? Integer.parseUnsignedInt(val.substring(2), 16) : Integer.parseUnsignedInt(val); } catch (NumberFormatException ignored) { } } return null; } public static Color parseColor(String text) { final Color color = parseColor(text, "const Color("); if (color != null) return color; return parseColor(text, "Color("); } public static Color parseColor(String text, String colorText) { final Integer val = parseNumberFromCallParam(text, colorText); if (val == null) return null; try { final int value = val; //noinspection UseJBColor return new Color((int)(value >> 16) & 0xFF, (int)(value >> 8) & 0xFF, (int)value & 0xFF, (int)(value >> 24) & 0xFF); } catch (IllegalArgumentException e) { return null; } } public static Color parseColorComponents(String callText, String prefix, boolean isARGB) { if (callText.startsWith(prefix) && callText.endsWith(")")) { final String colorString = callText.substring(prefix.length(), callText.length() - 1).trim(); final String[] maybeNumbers = colorString.split(","); if (maybeNumbers.length < 4) { return null; } return isARGB ? parseARGBColorComponents(maybeNumbers) : parseRGBOColorComponents(maybeNumbers); } return null; } private static Color parseARGBColorComponents(String[] maybeNumbers) { if (maybeNumbers.length < 4) { return null; } final int[] argb = new int[4]; for (int i = 0; i < 4; ++i) { final String maybeNumber = maybeNumbers[i].trim(); try { if (maybeNumber.startsWith("0x")) { argb[i] = Integer.parseUnsignedInt(maybeNumber.substring(2), 16); } else { argb[i] = Integer.parseUnsignedInt(maybeNumber); } } catch (NumberFormatException ignored) { return null; } } try { //noinspection UseJBColor return new Color(argb[1], argb[2], argb[3], argb[0]); } catch (IllegalArgumentException e) { return null; } } private static Color parseRGBOColorComponents(String[] maybeNumbers) { final float[] rgbo = new float[4]; for (int i = 0; i < 4; ++i) { final String maybeNumber = maybeNumbers[i].trim(); try { if (i == 3) { rgbo[i] = Float.parseFloat(maybeNumber); if (rgbo[3] < 0.0f || rgbo[3] > 1.0f) { return null; } } else { if (maybeNumber.startsWith("0x")) { rgbo[i] = (float)Integer.parseUnsignedInt(maybeNumber.substring(2), 16) / 255; } else { rgbo[i] = (float)Integer.parseUnsignedInt(maybeNumber) / 255; } if (rgbo[i] < 0.0f || rgbo[i] > 1.0f) { return null; } } } catch (NumberFormatException ignored) { return null; } } //noinspection UseJBColor return new Color(rgbo[0], rgbo[1], rgbo[2], rgbo[3]); } }
flutter-intellij/flutter-idea/src/io/flutter/editor/ExpressionParsingUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/ExpressionParsingUtils.java", "repo_id": "flutter-intellij", "token_count": 1577 }
446
/* * 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.ui.popup.Balloon; import com.intellij.ui.colorpicker.ColorPickerBuilder; import com.intellij.ui.colorpicker.LightCalloutPopup; import com.intellij.ui.colorpicker.MaterialGraphicalColorPipetteProvider; import kotlin.Unit; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; public class IntellijColorPickerProvider implements ColorPickerProvider { private LightCalloutPopup popup; @Override public void show(Color initialColor, JComponent component, Point offset, Balloon.Position position, ColorListener colorListener, Runnable onCancel, Runnable onOk) { if (popup != null) { popup.close(); } popup = new ColorPickerBuilder() .setOriginalColor(initialColor) // TODO(jacobr): we would like to add the saturation and brightness // component but for some reason it throws exceptions even though there // are examples of it being used identically without throwing exceptions // elsewhere in the IntelliJ code base. //.addSaturationBrightnessComponent() .addColorAdjustPanel(new MaterialGraphicalColorPipetteProvider()) .addColorValuePanel().withFocus() .addOperationPanel( (okColor) -> { onOk.run(); return Unit.INSTANCE; }, (cancelColor) -> { onCancel.run(); return Unit.INSTANCE; } ).withFocus() .setFocusCycleRoot(true) .focusWhenDisplay(true) .addKeyAction( KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { onCancel.run(); } } ) .addKeyAction( KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { onOk.run(); } } ) .addColorListener(colorListener::colorChanged, true) .build(); popup.show(component, offset, position); } @Override public void dispose() { if (popup != null) { popup.close(); } popup = null; } }
flutter-intellij/flutter-idea/src/io/flutter/editor/IntellijColorPickerProvider.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/IntellijColorPickerProvider.java", "repo_id": "flutter-intellij", "token_count": 1069 }
447
/* * 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.util.Disposer; import io.flutter.inspector.DiagnosticsNode; import io.flutter.inspector.InspectorGroupManagerService; import io.flutter.inspector.InspectorObjectGroupManager; import io.flutter.inspector.InspectorService; import io.flutter.run.daemon.FlutterApp; import java.awt.*; import java.util.ArrayList; /** * Base class for a controller managing UI describing a widget. * <p> * See PreviewViewController which extends this class to render previews of * widgets. This class is also intented to be extended to support rendering * visualizations of widget properties inline in a text editor. */ public abstract class WidgetViewController implements EditorMouseEventService.Listener, Disposable { protected boolean isSelected = false; protected final WidgetViewModelData data; protected boolean visible = false; Rectangle visibleRect; DiagnosticsNode inspectorSelection; final InspectorGroupManagerService.Client groupClient; protected abstract void onFlutterFrame(); public InspectorObjectGroupManager getGroupManagner() { return groupClient.getGroupManager(); } public FlutterApp getApp() { return groupClient.getApp(); } InspectorObjectGroupManager getGroups() { return groupClient.getGroupManager(); } public ArrayList<DiagnosticsNode> elements; public int activeIndex = 0; WidgetViewController(WidgetViewModelData data, Disposable parent) { this.data = data; Disposer.register(parent, this); groupClient = new InspectorGroupManagerService.Client(this) { @Override public void onInspectorAvailabilityChanged() { WidgetViewController.this.onInspectorAvailabilityChanged(); } @Override public void requestRepaint(boolean force) { onFlutterFrame(); } @Override public void onFlutterFrame() { WidgetViewController.this.onFlutterFrame(); } public void onSelectionChanged(DiagnosticsNode selection) { WidgetViewController.this.onSelectionChanged(selection); } }; data.context.inspectorGroupManagerService.addListener(groupClient, parent); } /** * Subclasses can override this method to be notified when whether the widget is visible in IntelliJ. * <p> * This is whether the UI for this component is visible not whether the widget is visible on the device. */ public void onVisibleChanged() { } public boolean updateVisiblityLocked(Rectangle newRectangle) { return false; } public void onInspectorAvailabilityChanged() { setElements(null); inspectorSelection = null; onVisibleChanged(); forceRender(); } public abstract void forceRender(); public InspectorService getInspectorService() { return groupClient.getInspectorService(); } @Override public void dispose() { } public void onSelectionChanged(DiagnosticsNode selection) { final InspectorObjectGroupManager manager = getGroups(); if (manager != null) { manager.cancelNext(); } } abstract InspectorService.Location getLocation(); public boolean isElementsEmpty() { return elements == null || elements.isEmpty(); } public void setElements(ArrayList<DiagnosticsNode> elements) { this.elements = elements; } public void onActiveElementsChanged() { if (isElementsEmpty()) return; final InspectorObjectGroupManager manager = getGroups(); if (manager == null) return; if (isSelected) { manager.getCurrent().setSelection( getSelectedElement().getValueRef(), false, true ); } } public DiagnosticsNode getSelectedElement() { if (isElementsEmpty()) return null; return elements.get(0); } }
flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetViewController.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetViewController.java", "repo_id": "flutter-intellij", "token_count": 1238 }
448
/* * 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.jxbrowser; import com.intellij.openapi.application.ApplicationListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.teamdev.jxbrowser.engine.Engine; import com.teamdev.jxbrowser.engine.EngineOptions; import com.teamdev.jxbrowser.engine.PasswordStore; import io.flutter.FlutterInitializer; import java.io.File; import java.nio.file.Paths; import static com.teamdev.jxbrowser.engine.RenderingMode.HARDWARE_ACCELERATED; import static com.teamdev.jxbrowser.engine.RenderingMode.OFF_SCREEN; public class EmbeddedBrowserEngine { private static final Logger LOG = Logger.getInstance(EmbeddedBrowserEngine.class); private final Engine engine; public static EmbeddedBrowserEngine getInstance() { return ServiceManager.getService(EmbeddedBrowserEngine.class); } public EmbeddedBrowserEngine() { final String dataPath = JxBrowserManager.DOWNLOAD_PATH + File.separatorChar + "user-data"; LOG.info("JxBrowser user data path: " + dataPath); final EngineOptions.Builder optionsBuilder = EngineOptions.newBuilder(SystemInfo.isMac ? HARDWARE_ACCELERATED : OFF_SCREEN) .userDataDir(Paths.get(dataPath)) .passwordStore(PasswordStore.BASIC) .addSwitch("--disable-features=NativeNotifications"); if (SystemInfo.isLinux) { optionsBuilder.addSwitch("--force-device-scale-factor=1"); } final EngineOptions options = optionsBuilder.build(); Engine temp; try { temp = Engine.newInstance(options); } catch (Exception ex) { temp = null; LOG.info(ex); FlutterInitializer.getAnalytics().sendExpectedException("jxbrowser-engine", ex); } engine = temp; ApplicationManager.getApplication().addApplicationListener(new ApplicationListener() { @Override public boolean canExitApplication() { try { if (engine != null && !engine.isClosed()) { engine.close(); } } catch (Exception ex) { LOG.info(ex); FlutterInitializer.getAnalytics().sendExpectedException("jxbrowswer-engine-close", ex); } return true; } }); } public Engine getEngine() { return engine; } }
flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/EmbeddedBrowserEngine.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/EmbeddedBrowserEngine.java", "repo_id": "flutter-intellij", "token_count": 888 }
449
/* * Copyright (C) 2020 The Android Open Source Project * * 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. */ package io.flutter.module.settings; import com.google.common.base.Objects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * A boolean-backed AbstractProperty derived from the Android Studio observable BoolValueProperty. * This version can only be initialized once, making it useful to the FlutterCreateAdditionalSettings object. */ public final class InitializeOnceBoolValueProperty { private Boolean myValue; private boolean isSet = false; public InitializeOnceBoolValueProperty(@NotNull Boolean value) { myValue = value; } public InitializeOnceBoolValueProperty() { this(false); } @NotNull public Boolean get() { return myValue; } protected void setDirectly(@NotNull Boolean value) { myValue = value; } public final void initialize(@NotNull Boolean value) { if (isSet) { return; } setDirectly(value); isSet = true; } public final void set(@NotNull Boolean value) { if (!isValueEqual(value)) { //setNotificationsEnabled(false); setDirectly(value); //setNotificationsEnabled(true); //notifyInvalidated(); } } protected boolean isValueEqual(@Nullable Boolean value) { return Objects.equal(get(), value); } @Override public String toString() { return get().toString(); } public final void addConstraint(Object constraint) { // This is only a partial implementation of the Android Studio class. If someone tries to use constraints more implementation is needed. throw new Error("constraints not supported"); } public final void addListener(Object listener) { // This is only a partial implementation of the Android Studio class. If someone tries to use listeners more implementation is needed. throw new Error("listeners not supported"); } }
flutter-intellij/flutter-idea/src/io/flutter/module/settings/InitializeOnceBoolValueProperty.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/settings/InitializeOnceBoolValueProperty.java", "repo_id": "flutter-intellij", "token_count": 710 }
450
/* * 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.perf; import com.intellij.openapi.Disposable; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.messages.MessageBusConnection; import io.flutter.FlutterInitializer; import io.flutter.FlutterUtils; import io.flutter.run.FlutterAppManager; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.StreamSubscription; import io.flutter.view.FlutterViewMessages; import io.flutter.vmService.ServiceExtensions; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * A singleton for the current Project. This class watches for changes to the * current Flutter app, and orchestrates displaying rebuild counts and other * widget performance stats for widgets created in the active source files. * Performance stats are displayed directly in the TextEditor windows so that * users can see them as they look at the source code. * <p> * Rebuild counts provide an easy way to understand the coarse grained * performance of an application and avoid common pitfalls. * <p> * FlutterWidgetPerfManager tracks which source files are visible and * passes that information to FlutterWidgetPerf which performs the work to * actually fetch performance information and display them. */ public class FlutterWidgetPerfManager implements Disposable, FlutterApp.FlutterAppListener { // Whether each of the performance metrics tracked should be tracked by // default when starting a new application. public static boolean trackRebuildWidgetsDefault = false; public static boolean trackRepaintWidgetsDefault = false; public FlutterWidgetPerf getCurrentStats() { return currentStats; } private FlutterWidgetPerf currentStats; private FlutterApp app; private final Project project; private boolean trackRebuildWidgets = trackRebuildWidgetsDefault; private boolean trackRepaintWidgets = trackRepaintWidgetsDefault; private boolean debugIsActive; private final Set<PerfModel> listeners = new HashSet<>(); /** * File editors visible to the user that might contain widgets. */ private Set<TextEditor> lastSelectedEditors = new HashSet<>(); private final List<StreamSubscription<Boolean>> streamSubscriptions = new ArrayList<>(); @NotNull public Set<TextEditor> getSelectedEditors() { return lastSelectedEditors; } private FlutterWidgetPerfManager(@NotNull Project project) { this.project = project; Disposer.register(project, this); FlutterAppManager.getInstance(project).getActiveAppAsStream().listen( this::updateCurrentAppChanged, true); project.getMessageBus().connect().subscribe( FlutterViewMessages.FLUTTER_DEBUG_TOPIC, (event) -> debugActive(project, event) ); final MessageBusConnection connection = project.getMessageBus().connect(project); updateSelectedEditors(); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() { public void selectionChanged(@NotNull FileEditorManagerEvent event) { if (updateSelectedEditors()) { notifyPerf(); } } }); } /** * @return whether the set of selected editors actually changed. */ private boolean updateSelectedEditors() { final FileEditor[] editors = FileEditorManager.getInstance(project).getSelectedEditors(); final Set<TextEditor> newEditors = new HashSet<>(); for (FileEditor editor : editors) { if (editor instanceof TextEditor) { final VirtualFile file = editor.getFile(); if (FlutterUtils.couldContainWidgets(file)) { newEditors.add((TextEditor)editor); } } } if (newEditors.equals(lastSelectedEditors)) { return false; } lastSelectedEditors = newEditors; return true; } /** * Initialize the rebuild count manager for the given project. */ public static void init(@NotNull Project project) { // Call getInstance() will init FlutterWidgetPerfManager for the given project. getInstance(project); } @Nullable public static FlutterWidgetPerfManager getInstance(@NotNull Project project) { return project.getService(FlutterWidgetPerfManager.class); } public boolean isTrackRebuildWidgets() { return trackRebuildWidgets; } public void setTrackRebuildWidgets(boolean value) { if (value == trackRebuildWidgets) { return; } trackRebuildWidgets = value; onProfilingFlagsChanged(); if (debugIsActive && app != null && app.isSessionActive()) { updateTrackWidgetRebuilds(); } // Send analytics. if (trackRebuildWidgets) { FlutterInitializer.getAnalytics().sendEvent("intellij", "TrackWidgetRebuilds"); } } public boolean isTrackRepaintWidgets() { return trackRepaintWidgets; } public void setTrackRepaintWidgets(boolean value) { if (value == trackRepaintWidgets) { return; } trackRepaintWidgets = value; onProfilingFlagsChanged(); if (debugIsActive && app != null && app.isSessionActive()) { updateTrackWidgetRepaints(); } // Send analytics. if (trackRepaintWidgets) { FlutterInitializer.getAnalytics().sendEvent("intellij", "TrackRepaintWidgets"); } } private void onProfilingFlagsChanged() { if (currentStats != null) { currentStats.setProfilingEnabled(isProfilingEnabled()); } } private boolean isProfilingEnabled() { return trackRebuildWidgets || trackRepaintWidgets; } private void debugActive(Project project, FlutterViewMessages.FlutterDebugEvent event) { debugIsActive = true; if (app == null) { return; } app.addStateListener(this); syncBooleanServiceExtension(ServiceExtensions.trackRebuildWidgets.getExtension(), () -> trackRebuildWidgets); syncBooleanServiceExtension(ServiceExtensions.trackRepaintWidgets.getExtension(), () -> trackRepaintWidgets); currentStats = new FlutterWidgetPerf( isProfilingEnabled(), new VmServiceWidgetPerfProvider(app), (TextEditor textEditor) -> new EditorPerfDecorations(textEditor, app), path -> new DocumentFileLocationMapper(path, app.getProject()) ); for (PerfModel listener : listeners) { currentStats.addPerfListener(listener); } } public void stateChanged(FlutterApp.State newState) { switch (newState) { case RELOADING: if (currentStats != null) currentStats.clear(); break; case RESTARTING: if (currentStats != null) currentStats.onRestart(); break; case STARTED: notifyPerf(); break; } } public void notifyAppRestarted() { currentStats.clear(); } public void notifyAppReloaded() { currentStats.clear(); } private void updateTrackWidgetRebuilds() { app.maybeCallBooleanExtension(ServiceExtensions.trackRebuildWidgets.getExtension(), trackRebuildWidgets) .whenCompleteAsync((v, e) -> notifyPerf()); } private void updateTrackWidgetRepaints() { app.maybeCallBooleanExtension(ServiceExtensions.trackRepaintWidgets.getExtension(), trackRepaintWidgets) .whenCompleteAsync((v, e) -> notifyPerf()); } private void syncBooleanServiceExtension(String serviceExtension, Computable<Boolean> valueProvider) { final StreamSubscription<Boolean> subscription = app.hasServiceExtension(serviceExtension, (supported) -> { if (supported) { app.callBooleanExtension(serviceExtension, valueProvider.compute()); } }); if (subscription != null) { streamSubscriptions.add(subscription); } } private void updateCurrentAppChanged(@Nullable FlutterApp app) { // TODO(jacobr): we currently only support showing stats for the last app // that was run. After the initial CL lands we should fix this to track // multiple running apps if needed. The most important use case is if the // user has one profile app and one debug app running at the same time. // We should track stats for all running apps and display the aggregated // stats. A well behaved flutter app should not be painting frames very // frequently when a user is not interacting with it so showing aggregated // stats for all apps should match user expectations without forcing users // to manage which app they have selected. if (app == this.app) { return; } debugIsActive = false; if (this.app != null) { this.app.removeStateListener(this); } this.app = app; for (StreamSubscription<Boolean> subscription : streamSubscriptions) { subscription.dispose(); } streamSubscriptions.clear(); if (currentStats != null) { currentStats.dispose(); currentStats = null; } } private void notifyPerf() { if (!trackRepaintWidgets && !trackRebuildWidgets && currentStats != null) { // TODO(jacobr): consider just marking as idle. currentStats.clear(); } if (currentStats == null) { return; } if (lastSelectedEditors.isEmpty()) { currentStats.showFor(lastSelectedEditors); return; } final Set<TextEditor> editors = new HashSet<>(); for (TextEditor editor : lastSelectedEditors) { final VirtualFile file = editor.getFile(); if (file != null && !app.isReloading() || !app.isLatestVersionRunning(file)) { // We skip querying files that have been modified locally as we // cannot safely display the profile information so there is no // point in tracking it. editors.add(editor); } } currentStats.showFor(editors); } @Override public void dispose() { if (currentStats != null) { currentStats.dispose(); currentStats = null; listeners.clear(); } } public void addPerfListener(PerfModel listener) { listeners.add(listener); if (currentStats != null) { currentStats.addPerfListener(listener); } } public void removePerfListener(PerfModel listener) { listeners.remove(listener); if (currentStats != null) { currentStats.removePerfListener(listener); } } }
flutter-intellij/flutter-idea/src/io/flutter/perf/FlutterWidgetPerfManager.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/FlutterWidgetPerfManager.java", "repo_id": "flutter-intellij", "token_count": 3505 }
451
/* * 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.perf; import com.google.gson.JsonObject; /** * Interface defining events relevant to tracking widget performance. * <p> * See FlutterWidgetPerf which is the cannonical implementation. */ public interface WidgetPerfListener { void requestRepaint(When when); void onWidgetPerfEvent(PerfReportKind kind, JsonObject json); void onNavigation(); void addPerfListener(PerfModel listener); void removePerfListener(PerfModel listener); }
flutter-intellij/flutter-idea/src/io/flutter/perf/WidgetPerfListener.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/WidgetPerfListener.java", "repo_id": "flutter-intellij", "token_count": 179 }
452
/* * 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.preview; import io.flutter.editor.PreviewViewController; import io.flutter.editor.PreviewViewControllerBase; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; /** * Class that provides the glue to render the preview view in a regular JPanel. */ public class PreviewViewModelPanel extends JPanel { final PreviewViewControllerBase preview; @Override public void paint(Graphics g) { super.paint(g); preview.paint(g, 16); } public PreviewViewModelPanel(PreviewViewController preview) { this.preview = preview; addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e) { // The PreviewViewController does not care about drag events. // If it ever does, this code will need to be updated. } @Override public void mouseMoved(MouseEvent e) { preview.onMouseMoved(e); } }); addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { // The PreviewViewController does not care about click events instead // relying on mouseReleased events. // If it ever does, this code will need to be updated. } @Override public void mousePressed(MouseEvent e) { preview.onMousePressed(e); } @Override public void mouseReleased(MouseEvent e) { preview.onMouseReleased(e); } @Override public void mouseEntered(MouseEvent e) { preview.onMouseEntered(e); } @Override public void mouseExited(MouseEvent e) { preview.onMouseExited(e); } }); } }
flutter-intellij/flutter-idea/src/io/flutter/preview/PreviewViewModelPanel.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/preview/PreviewViewModelPanel.java", "repo_id": "flutter-intellij", "token_count": 696 }
453
/* * 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.run; import io.flutter.sdk.XcodeUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Objects; public class FlutterDevice { private final @NotNull String myDeviceId; private final @NotNull String myDeviceName; private final @Nullable String myPlatform; private final boolean myEmulator; private final @Nullable String myCategory; private final @Nullable String myPlatformType; private final boolean myEphemeral; public FlutterDevice(@NotNull String deviceId, @NotNull String deviceName, @Nullable String platform, boolean emulator) { this(deviceId, deviceName, platform, emulator, null, null, null); } public FlutterDevice( @NotNull String deviceId, @NotNull String deviceName, @Nullable String platform, boolean emulator, @Nullable String category, @Nullable String platformType, @Nullable Boolean ephemeral ) { myDeviceId = deviceId; myDeviceName = deviceName.replaceAll("_", " "); myPlatform = platform; myEmulator = emulator; myCategory = category; myPlatformType = platformType; myEphemeral = ephemeral == null ? true : ephemeral; } @NotNull public String deviceId() { return myDeviceId; } @NotNull public String deviceName() { return myDeviceName; } @Nullable public String platform() { return myPlatform; } public boolean emulator() { return myEmulator; } /** * One of 'web', 'mobile', or 'desktop'. */ @Nullable public String category() { return myCategory; } @Nullable public String platformType() { return myPlatformType; } /** * Whether the device is persistent on the machine. * <p> * Web and desktop devices are generally non-ephemeral; mobile devices are generally ephemeral */ public boolean ephemeral() { return myEphemeral; } public boolean isIOS() { return myPlatform != null && (myPlatform.equals("ios") || myPlatform.startsWith("darwin")); } @Override public boolean equals(Object other) { //noinspection SimplifiableIfStatement if (other instanceof FlutterDevice) { return Objects.equals(myDeviceName, ((FlutterDevice)other).deviceName()) && Objects.equals(myDeviceId, ((FlutterDevice)other).deviceId()) && Objects.equals(myPlatform, ((FlutterDevice)other).platform()); } else { return false; } } @Override public int hashCode() { return Objects.hash(myDeviceName, myDeviceId, myPlatform); } @Override public String toString() { return myDeviceName; } /** * Given a collection of devices, return a unique name for this device. */ @NotNull public String getUniqueName(Collection<FlutterDevice> devices) { for (final FlutterDevice other : devices) { if (other == this) { continue; } if (other.presentationName().equals(presentationName())) { return presentationName() + " (" + deviceId() + ")"; } } return presentationName(); } /** * Bring the window representing this device to the foreground. This is a no-op for * non-emulator, non-iOS devices. */ public void bringToFront() { if (emulator() && isIOS()) { // Bring the iOS simulator to front. XcodeUtils.openSimulator(null); } } /** * Return the "flutter-tester" device. */ public static FlutterDevice getTester() { return new FlutterDevice("flutter-tester", "Flutter test device", null, false); } @NotNull public String presentationName() { if (category() != null) { return deviceName() + " (" + category() + ")"; } else { return deviceName(); } } }
flutter-intellij/flutter-idea/src/io/flutter/run/FlutterDevice.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/FlutterDevice.java", "repo_id": "flutter-intellij", "token_count": 1316 }
454
/* * 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.run; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.*; import com.intellij.execution.filters.TextConsoleBuilder; import com.intellij.execution.filters.UrlFilter; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.RunConfigurationWithSuppressedDefaultRunAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.refactoring.listeners.RefactoringElementListener; import com.intellij.refactoring.listeners.UndoRefactoringElementAdapter; import com.intellij.util.PathUtil; import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters; import com.intellij.util.xmlb.XmlSerializer; import com.jetbrains.lang.dart.ide.runner.DartConsoleFilter; import io.flutter.FlutterUtils; import io.flutter.console.FlutterConsoleFilter; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.FlutterApp; import io.flutter.sdk.FlutterSdkManager; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import static java.nio.file.FileVisitResult.CONTINUE; /** * Run configuration used for launching a Flutter app using the Flutter SDK. */ public class SdkRunConfig extends LocatableConfigurationBase<LaunchState> implements LaunchState.RunConfig, RefactoringListenerProvider, RunConfigurationWithSuppressedDefaultRunAction { private static final Logger LOG = Logger.getInstance(SdkRunConfig.class); private boolean firstRun = true; private @NotNull SdkFields fields = new SdkFields(); public SdkRunConfig(final @NotNull Project project, final @NotNull ConfigurationFactory factory, final @NotNull String name) { super(project, factory, name); } @NotNull public SdkFields getFields() { return fields; } public void setFields(@NotNull SdkFields newFields) { fields = newFields; } @Override public void checkConfiguration() throws RuntimeConfigurationException { fields.checkRunnable(getProject()); } @NotNull @Override public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() { return new FlutterConfigurationEditorForm(getProject()); } public static class RecursiveDeleter extends SimpleFileVisitor<Path> { private final PathMatcher matcher; RecursiveDeleter(String pattern) { matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { final Path name = file.getFileName(); if (name != null && matcher.matches(name)) { try { Files.delete(file); } catch (IOException e) { FlutterUtils.warn(LOG, e); // TODO(jacobr): consider aborting. } } return CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { return CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { FlutterUtils.warn(LOG, exc); return CONTINUE; } } @NotNull @Override public LaunchState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment env) throws ExecutionException { final SdkFields launchFields = fields.copy(); try { launchFields.checkRunnable(env.getProject()); } catch (RuntimeConfigurationError e) { throw new ExecutionException(e); } final MainFile mainFile = MainFile.verify(launchFields.getFilePath(), env.getProject()).get(); final Project project = env.getProject(); final RunMode mode = RunMode.fromEnv(env); final Module module = ModuleUtilCore.findModuleForFile(mainFile.getFile(), env.getProject()); final LaunchState.CreateAppCallback createAppCallback = (@Nullable FlutterDevice device) -> { if (device == null) return null; final GeneralCommandLine command = getCommand(env, device); // Workaround for https://github.com/flutter/flutter/issues/16766 // TODO(jacobr): remove once flutter tool incremental building works // properly with --track-widget-creation. final Path buildPath = command.getWorkDirectory().toPath().resolve("build"); final Path cachedParametersPath = buildPath.resolve("last_build_run.json"); final String[] parametersToTrack = {"--preview-dart-2", "--track-widget-creation"}; final JsonArray jsonArray = new JsonArray(); for (String parameter : command.getParametersList().getList()) { for (String allowedParameter : parametersToTrack) { if (parameter.startsWith(allowedParameter)) { jsonArray.add(new JsonPrimitive(parameter)); break; } } } final String json = new Gson().toJson(jsonArray); String existingJson = null; if (Files.exists(cachedParametersPath)) { try { existingJson = new String(Files.readAllBytes(cachedParametersPath), StandardCharsets.UTF_8); } catch (IOException e) { FlutterUtils.warn(LOG, "Unable to get existing json from " + cachedParametersPath); } } if (!StringUtil.equals(json, existingJson)) { // We don't have proof the current run is consistent with the existing run. // Be safe and delete cached files that could cause problems due to // https://github.com/flutter/flutter/issues/16766 // We could just delete app.dill and snapshot_blob.bin.d.fingerprint // but it is safer to just delete everything as we won't be broken by future changes // to the underlying Flutter build rules. try { if (Files.exists(buildPath)) { if (Files.isDirectory(buildPath)) { Files.walkFileTree(buildPath, new RecursiveDeleter("*.{fingerprint,dill}")); } } else { Files.createDirectory(buildPath); } Files.write(cachedParametersPath, json.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { FlutterUtils.warn(LOG, e); } } final FlutterApp app = FlutterApp.start(env, project, module, mode, device, command, StringUtil.capitalize(mode.mode()) + "App", "StopApp"); // Stop the app if the Flutter SDK changes. final FlutterSdkManager.Listener sdkListener = new FlutterSdkManager.Listener() { @Override public void flutterSdkRemoved() { app.shutdownAsync(); } }; FlutterSdkManager.getInstance(project).addListener(sdkListener); Disposer.register(app, () -> FlutterSdkManager.getInstance(project).removeListener(sdkListener)); return app; }; final LaunchState launcher = new LaunchState(env, mainFile.getAppDir(), mainFile.getFile(), this, createAppCallback); addConsoleFilters(launcher, env, mainFile, module); return launcher; } protected void addConsoleFilters(@NotNull LaunchState launcher, @NotNull ExecutionEnvironment env, @NotNull MainFile mainFile, @Nullable Module module) { // Set up additional console filters. final TextConsoleBuilder builder = launcher.getConsoleBuilder(); // file:, package:, and dart: references builder.addFilter(new DartConsoleFilter(env.getProject(), mainFile.getFile())); //// links often found when running tests //builder.addFilter(new DartRelativePathsConsoleFilter(env.getProject(), mainFile.getAppDir().getPath())); if (module != null) { // various flutter run links builder.addFilter(new FlutterConsoleFilter(module)); } // general urls builder.addFilter(new UrlFilter()); } @NotNull @Override public GeneralCommandLine getCommand(@NotNull ExecutionEnvironment env, @NotNull FlutterDevice device) throws ExecutionException { final SdkFields launchFields = fields.copy(); final Project project = env.getProject(); final RunMode mode = RunMode.fromEnv(env); final boolean initialFirstRun = firstRun; firstRun = false; return fields.createFlutterSdkRunCommand(project, mode, FlutterLaunchMode.fromEnv(env), device, initialFirstRun); } @Override @Nullable public String suggestedName() { final String filePath = fields.getFilePath(); return filePath == null ? null : PathUtil.getFileName(filePath); } @Override public SdkRunConfig clone() { final SdkRunConfig clone = (SdkRunConfig)super.clone(); clone.fields = fields.copy(); return clone; } @Override public void writeExternal(@NotNull final Element element) throws WriteExternalException { super.writeExternal(element); XmlSerializer.serializeInto(getFields(), element, new SkipDefaultValuesSerializationFilters()); } @Override public void readExternal(@NotNull final Element element) throws InvalidDataException { super.readExternal(element); XmlSerializer.deserializeInto(getFields(), element); } @Nullable @Override public RefactoringElementListener getRefactoringElementListener(final PsiElement element) { final String filePath = getFields().getFilePath(); if (filePath == null) return null; final String affectedPath = getAffectedPath(element); if (affectedPath == null) return null; if (element instanceof PsiFile && filePath.equals(affectedPath)) { return new RenameRefactoringListener(affectedPath); } if (element instanceof PsiDirectory && filePath.startsWith(affectedPath + "/")) { return new RenameRefactoringListener(affectedPath); } return null; } private String getAffectedPath(PsiElement element) { if (!(element instanceof PsiFileSystemItem)) return null; final VirtualFile file = ((PsiFileSystemItem)element).getVirtualFile(); return file == null ? null : file.getPath(); } private class RenameRefactoringListener extends UndoRefactoringElementAdapter { private @NotNull String myAffectedPath; private RenameRefactoringListener(final @NotNull String affectedPath) { myAffectedPath = affectedPath; } private String getNewPathAndUpdateAffectedPath(final @NotNull PsiElement newElement) { final String oldPath = fields.getFilePath(); final VirtualFile newFile = newElement instanceof PsiFileSystemItem ? ((PsiFileSystemItem)newElement).getVirtualFile() : null; if (newFile != null && oldPath != null && oldPath.startsWith(myAffectedPath)) { final String newPath = newFile.getPath() + oldPath.substring(myAffectedPath.length()); myAffectedPath = newFile.getPath(); // needed if refactoring will be undone return newPath; } return oldPath; } @Override protected void refactored(@NotNull final PsiElement element, @Nullable final String oldQualifiedName) { final boolean generatedName = getName().equals(suggestedName()); final String filePath = fields.getFilePath(); final String newPath = getNewPathAndUpdateAffectedPath(element); fields.setFilePath(newPath); if (generatedName) { setGeneratedName(); } } } }
flutter-intellij/flutter-idea/src/io/flutter/run/SdkRunConfig.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/SdkRunConfig.java", "repo_id": "flutter-intellij", "token_count": 4362 }
455
<?xml version="1.0" encoding="UTF-8"?> <form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="io.flutter.run.bazelTest.FlutterBazelTestConfigurationEditorForm"> <grid id="27dc6" binding="myMainPanel" default-binding="true" layout-manager="GridLayoutManager" row-count="11" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> <margin top="0" left="0" bottom="0" right="0"/> <constraints> <xy x="20" y="20" width="720" height="320"/> </constraints> <properties/> <border type="none"/> <children> <component id="7b563" class="javax.swing.JLabel" binding="myBuildTargetLabel"> <constraints> <grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <labelFor value="ada9f"/> <text value="&amp;Target:"/> </properties> </component> <component id="ada9f" class="javax.swing.JTextField" binding="myBuildTarget"> <constraints> <grid row="4" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/> </constraints> <properties/> </component> <vspacer id="3f5de"> <constraints> <grid row="10" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/> </constraints> </vspacer> <component id="eff55" class="javax.swing.JLabel" binding="myBuildTargetHintLabel"> <constraints> <grid row="5" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <enabled value="false"/> <text value="The Bazel target (e.g. //a/b/c:name)."/> </properties> </component> <component id="60b32" class="javax.swing.JLabel" binding="myTestNameLabel"> <constraints> <grid row="6" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <text value="Test Name:"/> </properties> </component> <component id="e602a" class="javax.swing.JLabel" binding="myTestNameHintLabel"> <constraints> <grid row="7" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <enabled value="false"/> <text value="Some pattern to match test names by."/> </properties> </component> <component id="6457d" class="javax.swing.JTextField" binding="myTestName"> <constraints> <grid row="6" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false"> <preferred-size width="150" height="-1"/> </grid> </constraints> <properties/> </component> <component id="55076" class="javax.swing.JLabel" binding="myEntryFileLabel"> <constraints> <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <inheritsPopupMenu value="true"/> <labelFor value=""/> <text value="Dart &amp;entrypoint:"/> </properties> </component> <component id="bff6f" class="javax.swing.JLabel" binding="myEntryFileHintLabel"> <constraints> <grid row="3" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <enabled value="false"/> <text value="The absolute entry-point path for the application (e.g. /.../lib/main_test.dart)."/> </properties> </component> <component id="17e7a" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myEntryFile"> <constraints> <grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/> </constraints> <properties> <focusable value="true"/> </properties> </component> <component id="e0e39" class="javax.swing.JComboBox" binding="scope"> <constraints> <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="0" indent="0" use-parent-layout="false"> <preferred-size width="150" height="-1"/> </grid> </constraints> <properties/> </component> <component id="42f6b" class="javax.swing.JLabel" binding="scopeLabel"> <constraints> <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"> <preferred-size width="110" height="-1"/> </grid> </constraints> <properties> <text value="Test &amp;scope:"/> </properties> </component> <component id="4e13d" class="javax.swing.JLabel" binding="scopeLabelHint"> <constraints> <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <enabled value="false"/> <text value="Scope of the test: either file, bazel target pattern, or specific tests in a file filtered by name."/> </properties> </component> <component id="7c2a2" class="javax.swing.JLabel" binding="myAdditionalArgsLabel"> <constraints> <grid row="8" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <text value="Additional args:"/> </properties> </component> <component id="c9f7c" class="javax.swing.JLabel" binding="myAdditionalArgsLabelHint"> <constraints> <grid row="9" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <enabled value="false"/> <text value="Additional arguments to pass to the test runner (eg --watch)."/> </properties> </component> <component id="bc12b" class="javax.swing.JTextField" binding="myAdditionalArgs"> <constraints> <grid row="8" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false"> <preferred-size width="150" height="-1"/> </grid> </constraints> <properties/> </component> </children> </grid> </form>
flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/FlutterBazelTestConfigurationEditorForm.form/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/FlutterBazelTestConfigurationEditorForm.form", "repo_id": "flutter-intellij", "token_count": 3239 }
456
/* * 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.run.daemon; import com.google.common.base.Charsets; import com.google.gson.*; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import io.flutter.FlutterUtils; import io.flutter.settings.FlutterSettings; import io.flutter.utils.JsonUtils; import io.flutter.utils.StdoutJsonParser; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Function; /** * Sends JSON commands to a flutter daemon process, assigning a new id to each one. * * <p>Also handles dispatching incoming responses and events. * * <p>The protocol is specified in * <a href="https://github.com/flutter/flutter/wiki/The-flutter-daemon-mode" * >The Flutter Daemon Mode</a>. */ public class DaemonApi { public static final String FLUTTER_ERROR_PREFIX = "error from"; public static final String COMPLETION_EXCEPTION_PREFIX = "java.util.concurrent.CompletionException: java.io.IOException: "; private static final int STDERR_LINES_TO_KEEP = 100; private static final Gson GSON = new Gson(); private static final Logger LOG = Logger.getInstance(DaemonApi.class); @NotNull private final Consumer<String> callback; private final AtomicInteger nextId = new AtomicInteger(); private final Map<Integer, Command> pending = new LinkedHashMap<>(); private final StdoutJsonParser stdoutParser = new StdoutJsonParser(); /** * A ring buffer holding the last few lines that the process sent to stderr. */ private final Deque<String> stderr = new ArrayDeque<>(); /** * Creates an Api that sends JSON to a callback. */ DaemonApi(@NotNull Consumer<String> callback) { this.callback = callback; } /** * Creates an Api that sends JSON to a process. */ DaemonApi(@NotNull ProcessHandler process) { this((String json) -> sendCommand(json, process)); } CompletableFuture<List<String>> daemonGetSupportedPlatforms(@NotNull String projectRoot) { return send("daemon.getSupportedPlatforms", new DaemonGetSupportedPlatforms(projectRoot)); } CompletableFuture<Boolean> daemonShutdown() { return send("daemon.shutdown", new DaemonShutdown()); } CompletableFuture<RestartResult> restartApp(@NotNull String appId, boolean fullRestart, boolean pause, @NotNull String reason) { return send("app.restart", new AppRestart(appId, fullRestart, pause, reason)); } CompletableFuture<Boolean> stopApp(@NotNull String appId) { return send("app.stop", new AppStop(appId)); } CompletableFuture<DevToolsAddress> devToolsServe() { return send("devtools.serve", new DevToolsServe()); } CompletableFuture<Boolean> detachApp(@NotNull String appId) { return send("app.detach", new AppDetach(appId)); } void cancelPending() { // We used to complete the commands with exceptions here (completeExceptionally), but that generally was surfaced // to the user as an exception in the tool. We now choose to not complete the command at all. synchronized (pending) { pending.clear(); } } /** * Used to invoke an arbitrary service protocol extension. */ CompletableFuture<JsonObject> callAppServiceExtension(@NotNull String appId, @NotNull String methodName, @NotNull Map<String, Object> params) { return send("app.callServiceExtension", new AppServiceExtension(appId, methodName, params)); } CompletableFuture<Void> enableDeviceEvents() { return send("device.enable", null); } /** * Receive responses and events from a process until it shuts down. */ void listen(@NotNull ProcessHandler process, @NotNull DaemonEvent.Listener listener) { process.addProcessListener(new ProcessAdapter() { @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { if (outputType.equals(ProcessOutputTypes.STDERR)) { // Append text to last line in buffer. final String last = stderr.peekLast(); if (last != null && !last.endsWith("\n")) { stderr.removeLast(); stderr.add(last + event.getText()); } else { stderr.add(event.getText()); } // Trim buffer size. while (stderr.size() > STDERR_LINES_TO_KEEP) { stderr.removeFirst(); } } else if (outputType.equals(ProcessOutputTypes.STDOUT)) { final String text = event.getText(); if (FlutterSettings.getInstance().isVerboseLogging()) { LOG.info("[<-- " + text.trim() + "]"); } stdoutParser.appendOutput(text); for (String line : stdoutParser.getAvailableLines()) { final JsonObject obj = parseAndValidateDaemonEvent(line); if (obj != null) { dispatch(obj, listener); } } } } @Override public void processWillTerminate(@NotNull ProcessEvent event, boolean willBeDestroyed) { listener.processWillTerminate(); } @Override public void processTerminated(@NotNull ProcessEvent event) { listener.processTerminated(event.getExitCode()); } }); // All hooked up and ready to receive events. process.startNotify(); } /** * Parses some JSON and handles it as either a command's response or an event. */ void dispatch(@NotNull JsonObject obj, @Nullable DaemonEvent.Listener eventListener) { final JsonPrimitive idField = obj.getAsJsonPrimitive("id"); if (idField == null) { // It's an event. if (eventListener != null) { DaemonEvent.dispatch(obj, eventListener); } } else { final Command cmd = takePending(idField.getAsInt()); if (cmd == null) { return; } final JsonElement error = obj.get("error"); if (error != null) { final JsonElement trace = obj.get("trace"); String message = FLUTTER_ERROR_PREFIX + " " + cmd.method + ": " + error; if (trace != null) { message += "\n" + trace; } // Be sure to keep this statement in sync with COMPLETION_EXCEPTION_PREFIX. cmd.completeExceptionally(new IOException(message)); } else { cmd.complete(obj.get("result")); } } } @Nullable private Command takePending(int id) { final Command cmd; synchronized (pending) { cmd = pending.remove(id); } if (cmd == null) { FlutterUtils.warn(LOG, "received a response for a request that wasn't sent: " + id); return null; } return cmd; } private <T> CompletableFuture<T> send(String method, @Nullable Params<T> params) { // Synchronize on nextId to ensure that we send one command at a time and they are numbered in the order they are sent. synchronized (nextId) { final int id = nextId.getAndIncrement(); final Command<T> command = new Command<>(method, params, id); final String json = command.toString(); //noinspection NestedSynchronizedStatement synchronized (pending) { pending.put(id, command); } callback.accept(json); return command.done; } } /** * Returns the last lines written to stderr. */ public String getStderrTail() { final String[] lines = stderr.toArray(new String[]{ }); return String.join("", lines); } /** * Parse the given string; if it is valid JSON - and a valid Daemon message - then return * the parsed JsonObject. */ public static JsonObject parseAndValidateDaemonEvent(String message) { if (!message.startsWith("[{")) { return null; } message = message.trim(); if (!message.endsWith("}]")) { return null; } message = message.substring(1, message.length() - 1); final JsonObject obj; try { final JsonElement element = JsonUtils.parseString(message); obj = element.getAsJsonObject(); } catch (JsonSyntaxException e) { return null; } // obj must contain either an "id" (int), or an "event" field final JsonPrimitive eventField = obj.getAsJsonPrimitive("event"); if (eventField != null) { final String eventName = eventField.getAsString(); if (eventName == null) { return null; } final JsonObject params = obj.getAsJsonObject("params"); return params == null ? null : obj; } else { // id final JsonPrimitive idField = obj.getAsJsonPrimitive("id"); if (idField == null || !idField.isNumber()) { return null; } try { idField.getAsInt(); return obj; } catch (NumberFormatException e) { return null; } } } private static void sendCommand(String json, ProcessHandler handler) { final PrintWriter stdin = getStdin(handler); if (stdin == null) { FlutterUtils.warn(LOG, "can't write command to Flutter process: " + json); return; } stdin.write('['); stdin.write(json); stdin.write("]\n"); if (FlutterSettings.getInstance().isVerboseLogging()) { LOG.info("[--> " + json + "]"); } if (stdin.checkError()) { FlutterUtils.warn(LOG, "can't write command to Flutter process: " + json); } } @Nullable private static PrintWriter getStdin(ProcessHandler processHandler) { final OutputStream stdin = processHandler.getProcessInput(); if (stdin == null) return null; return new PrintWriter(new OutputStreamWriter(stdin, Charsets.UTF_8)); } public static class RestartResult { private int code; private String message; public boolean ok() { return code == 0; } public int getCode() { return code; } public String getMessage() { return message; } @Override public String toString() { return getCode() + ":" + getMessage(); } } /** * A pending command to a Flutter process. */ private static class Command<T> { final @NotNull String method; final @Nullable JsonElement params; final int id; transient final @Nullable Function<JsonElement, T> parseResult; transient final CompletableFuture<T> done = new CompletableFuture<>(); Command(@NotNull String method, @Nullable Params<T> params, int id) { this.method = method; // GSON has trouble with params as a field, because it has both a generic type and subclasses. // But it handles it okay at top-level. this.params = GSON.toJsonTree(params); this.id = id; this.parseResult = params == null ? null : params::parseResult; } void complete(@Nullable JsonElement result) { if (parseResult == null) { done.complete(null); return; } try { done.complete(parseResult.apply(result)); } catch (Exception e) { FlutterUtils.warn(LOG, "Unable to parse response from Flutter daemon. Command was: " + this, e); done.completeExceptionally(e); } } void completeExceptionally(Throwable t) { done.completeExceptionally(t); } @Override public String toString() { return GSON.toJson(this); } } private abstract static class Params<T> { @Nullable abstract T parseResult(@Nullable JsonElement result); } private static class AppRestart extends Params<RestartResult> { @NotNull final String appId; final boolean fullRestart; final boolean pause; @NotNull final String reason; AppRestart(@NotNull String appId, boolean fullRestart, boolean pause, @NotNull String reason) { this.appId = appId; this.fullRestart = fullRestart; this.pause = pause; this.reason = reason; } @Override RestartResult parseResult(JsonElement result) { return GSON.fromJson(result, RestartResult.class); } } private static class DaemonShutdown extends Params<Boolean> { @Nullable @Override Boolean parseResult(@Nullable JsonElement result) { return true; } } private static class AppStop extends Params<Boolean> { @NotNull final String appId; AppStop(@NotNull String appId) { this.appId = appId; } @Override Boolean parseResult(JsonElement result) { return GSON.fromJson(result, Boolean.class); } } private static class AppDetach extends Params<Boolean> { @NotNull final String appId; AppDetach(@NotNull String appId) { this.appId = appId; } @Override Boolean parseResult(JsonElement result) { return GSON.fromJson(result, Boolean.class); } } private static class AppServiceExtension extends Params<JsonObject> { final String appId; final String methodName; final Map<String, Object> params; AppServiceExtension(String appId, String methodName, Map<String, Object> params) { this.appId = appId; this.methodName = methodName; this.params = params; } @Override JsonObject parseResult(JsonElement result) { if (result instanceof JsonObject) { return (JsonObject)result; } final JsonObject obj = new JsonObject(); obj.add("result", result); return obj; } } private static class DaemonGetSupportedPlatforms extends Params<List<String>> { final String projectRoot; DaemonGetSupportedPlatforms(String projectRoot) { this.projectRoot = projectRoot; } @Override List<String> parseResult(JsonElement result) { // {"platforms":["ios","android"]} if (!(result instanceof JsonObject)) { return Collections.emptyList(); } final JsonElement obj = ((JsonObject)result).get("platforms"); if (!(obj instanceof JsonArray)) { return Collections.emptyList(); } final List<String> platforms = new ArrayList<>(); for (int i = 0; i < ((JsonArray)obj).size(); i++) { final JsonElement element = ((JsonArray)obj).get(i); platforms.add(element.getAsString()); } return platforms; } } public static class DevToolsAddress { public String host; public int port; public DevToolsAddress(String host, int port) { this.host = host; this.port = port; } } private static class DevToolsServe extends Params<DevToolsAddress> { @Override DevToolsAddress parseResult(JsonElement result) { if (!(result instanceof JsonObject)) { return null; } final String host = ((JsonObject)result).get("host").getAsString(); final int port = ((JsonObject)result).get("port").getAsInt(); if (host.isEmpty() || port == 0) { return null; } return new DevToolsAddress(host, port); } } }
flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DaemonApi.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DaemonApi.java", "repo_id": "flutter-intellij", "token_count": 5816 }
457
/* * 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.run.test; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionResult; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.executors.DefaultDebugExecutor; import com.intellij.execution.process.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.GenericProgramRunner; import com.intellij.execution.runners.RunContentBuilder; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.util.TimeoutUtil; import com.intellij.xdebugger.XDebugProcess; import com.intellij.xdebugger.XDebugProcessStarter; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerManager; import com.jetbrains.lang.dart.util.DartUrlResolver; import io.flutter.FlutterUtils; import io.flutter.ObservatoryConnector; import io.flutter.run.FlutterPositionMapper; import io.flutter.run.common.CommonTestConfigUtils; import io.flutter.sdk.FlutterSdk; import io.flutter.settings.FlutterSettings; import io.flutter.utils.JsonUtils; import io.flutter.utils.StdoutJsonParser; import io.flutter.utils.VmServiceListenerAdapter; import io.flutter.vmService.VmServiceConsumers; import io.flutter.vmService.VmServiceConsumers.EmptyResumeConsumer; import org.dartlang.vm.service.VmService; import org.dartlang.vm.service.consumer.VMConsumer; import org.dartlang.vm.service.element.ElementList; import org.dartlang.vm.service.element.Event; import org.dartlang.vm.service.element.EventKind; import org.dartlang.vm.service.element.Isolate; import org.dartlang.vm.service.element.IsolateRef; import org.dartlang.vm.service.element.RPCError; import org.dartlang.vm.service.element.VM; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; /** * Runs a Flutter test configuration in the debugger. */ public class FlutterTestRunner extends GenericProgramRunner { @NotNull @Override public String getRunnerId() { return "FlutterDebugTestRunner"; } @Override public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) { if (!(DefaultDebugExecutor.EXECUTOR_ID.equals(executorId) || ToolWindowId.RUN.equals(executorId)) || !(profile instanceof TestConfig)) { return false; } final FlutterSdk sdk = FlutterSdk.getFlutterSdk(((TestConfig)profile).getProject()); if (sdk == null || !sdk.getVersion().flutterTestSupportsMachineMode()) { return false; } final TestConfig config = (TestConfig)profile; return config.getFields().getScope() != TestFields.Scope.DIRECTORY; } @Nullable @Override protected RunContentDescriptor doExecute(@NotNull RunProfileState state, @NotNull ExecutionEnvironment env) throws ExecutionException { if (env.getExecutor().getId().equals(ToolWindowId.RUN)) { return run((TestLaunchState)state, env); } else { return runInDebugger((TestLaunchState)state, env); } } protected RunContentDescriptor run(@NotNull TestLaunchState launcher, @NotNull ExecutionEnvironment env) throws ExecutionException { final ExecutionResult executionResult = launcher.execute(env.getExecutor(), this); final ObservatoryConnector connector = new Connector(executionResult.getProcessHandler()); ApplicationManager.getApplication().executeOnPooledThread(() -> { // Poll, waiting for "flutter run" to give us a websocket. // This is adapted from DartVmServiceDebugProcess::scheduleConnect. String url = connector.getWebSocketUrl(); while (url == null) { if (launcher.isTerminated()) { return; } TimeoutUtil.sleep(100); url = connector.getWebSocketUrl(); } if (launcher.isTerminated()) { return; } final VmService vmService; try { vmService = VmService.connect(url); } catch (IOException | RuntimeException e) { if (!launcher.isTerminated()) { launcher.notifyTextAvailable( "Failed to connect to the VM service at: " + url + "\n" + e + "\n", ProcessOutputTypes.STDERR); } return; } // Listen for debug 'PauseStart' events for isolates after the initial connect and resume those isolates. vmService.streamListen(VmService.DEBUG_STREAM_ID, VmServiceConsumers.EMPTY_SUCCESS_CONSUMER); vmService.addVmServiceListener(new VmServiceListenerAdapter() { @Override public void received(String streamId, Event event) { if (EventKind.PauseStart.equals(event.getKind())) { resumePausedAtStartIsolate(launcher, vmService, event.getIsolate()); } } }); // Resume any isolates paused at the initial connect. vmService.getVM(new VMConsumer() { @Override public void received(VM response) { final ElementList<IsolateRef> isolates = response.getIsolates(); for (IsolateRef isolateRef : isolates) { resumePausedAtStartIsolate(launcher, vmService, isolateRef); } } @Override public void onError(RPCError error) { if (!launcher.isTerminated()) { launcher.notifyTextAvailable( "Error connecting to VM: " + error.getCode() + " " + error.getMessage() + "\n", ProcessOutputTypes.STDERR); } } }); }); return new RunContentBuilder(executionResult, env).showRunContent(env.getContentToReuse()); } private void resumePausedAtStartIsolate(@NotNull TestLaunchState launcher, @NotNull VmService vmService, @NotNull IsolateRef isolateRef) { if (isolateRef.getIsSystemIsolate()) { return; } vmService.getIsolate(isolateRef.getId(), new VmServiceConsumers.GetIsolateConsumerWrapper() { @Override public void received(Isolate isolate) { final Event event = isolate.getPauseEvent(); final EventKind eventKind = event.getKind(); if (eventKind == EventKind.PauseStart) { vmService.resume(isolateRef.getId(), new EmptyResumeConsumer() { @Override public void onError(RPCError error) { if (!launcher.isTerminated()) { launcher.notifyTextAvailable( "Error resuming isolate " + isolateRef.getId() + ": " + error.getCode() + " " + error.getMessage() + "\n", ProcessOutputTypes.STDERR); } } }); } } }); } protected RunContentDescriptor runInDebugger(@NotNull TestLaunchState launcher, @NotNull ExecutionEnvironment env) throws ExecutionException { // Start process and create console. final ExecutionResult executionResult = launcher.execute(env.getExecutor(), this); final ObservatoryConnector connector = new Connector(executionResult.getProcessHandler()); // Set up source file mapping. final DartUrlResolver resolver = DartUrlResolver.getInstance(env.getProject(), launcher.getTestFileOrDir()); final FlutterPositionMapper.Analyzer analyzer = FlutterPositionMapper.Analyzer.create(env.getProject(), launcher.getTestFileOrDir()); final FlutterPositionMapper mapper = new FlutterPositionMapper(env.getProject(), launcher.getPubRoot().getRoot(), resolver, analyzer); // Create the debug session. final XDebuggerManager manager = XDebuggerManager.getInstance(env.getProject()); final XDebugSession session = manager.startSession(env, new XDebugProcessStarter() { @Override @NotNull public XDebugProcess start(@NotNull final XDebugSession session) { return new TestDebugProcess(env, session, executionResult, resolver, connector, mapper); } }); return session.getRunContentDescriptor(); } /** * Provides observatory URI, as received from the test process. */ private static final class Connector implements ObservatoryConnector { private final StdoutJsonParser stdoutParser = new StdoutJsonParser(); private final ProcessListener listener; private String observatoryUri; public Connector(ProcessHandler handler) { listener = new ProcessAdapter() { @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { if (!outputType.equals(ProcessOutputTypes.STDOUT)) { return; } final String text = event.getText(); if (FlutterSettings.getInstance().isVerboseLogging()) { LOG.info("[<-- " + text.trim() + "]"); } stdoutParser.appendOutput(text); for (String line : stdoutParser.getAvailableLines()) { if (line.startsWith("[{")) { line = line.trim(); final String json = line.substring(1, line.length() - 1); dispatchJson(json); } } } @Override public void processWillTerminate(@NotNull ProcessEvent event, boolean willBeDestroyed) { handler.removeProcessListener(listener); } }; handler.addProcessListener(listener); } @Nullable @Override public String getWebSocketUrl() { if (observatoryUri == null || !observatoryUri.startsWith("http:")) { return null; } return CommonTestConfigUtils.convertHttpServiceProtocolToWs(observatoryUri); } @Nullable @Override public String getBrowserUrl() { return observatoryUri; } @Nullable @Override public String getRemoteBaseUrl() { return null; } @Override public void onDebuggerPaused(@NotNull Runnable resume) { } @Override public void onDebuggerResumed() { } private void dispatchJson(String json) { final JsonObject obj; try { final JsonElement elem = JsonUtils.parseString(json); obj = elem.getAsJsonObject(); } catch (JsonSyntaxException e) { FlutterUtils.warn(LOG, "Unable to parse JSON from Flutter test", e); return; } final JsonPrimitive primId = obj.getAsJsonPrimitive("id"); if (primId != null) { // Not an event. LOG.info("Ignored JSON from Flutter test: " + json); return; } final JsonPrimitive primEvent = obj.getAsJsonPrimitive("event"); if (primEvent == null) { FlutterUtils.warn(LOG, "Missing event field in JSON from Flutter test: " + obj); return; } final String eventName = primEvent.getAsString(); if (eventName == null) { FlutterUtils.warn(LOG, "Unexpected event field in JSON from Flutter test: " + obj); return; } final JsonObject params = obj.getAsJsonObject("params"); if (params == null) { FlutterUtils.warn(LOG, "Missing parameters in event from Flutter test: " + obj); return; } if (eventName.equals("test.startedProcess")) { final JsonPrimitive primUri = params.getAsJsonPrimitive("observatoryUri"); if (primUri != null) { observatoryUri = primUri.getAsString(); } } } } private static final Logger LOG = Logger.getInstance(FlutterTestRunner.class); }
flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestRunner.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestRunner.java", "repo_id": "flutter-intellij", "token_count": 4460 }
458
/* * 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.survey; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class FlutterSurvey { final String uniqueId; final ZonedDateTime startDate; final ZonedDateTime endDate; final String title; final String urlPrefix; FlutterSurvey(String uniqueId, String startDate, String endDate, String title, String urlPrefix) { this.uniqueId = uniqueId; this.startDate = parseDate(startDate); this.endDate = parseDate(endDate); this.title = title; this.urlPrefix = urlPrefix; } private static ZonedDateTime parseDate(String date) { return ZonedDateTime.from(DateTimeFormatter.ISO_ZONED_DATE_TIME.parse(date)); } public static FlutterSurvey fromJson(@NotNull JsonObject json) { return new FlutterSurvey(json.getAsJsonPrimitive("uniqueId").getAsString(), json.getAsJsonPrimitive("startDate").getAsString(), json.getAsJsonPrimitive("endDate").getAsString(), json.getAsJsonPrimitive("title").getAsString(), json.getAsJsonPrimitive("url").getAsString() ); } boolean isSurveyOpen() { final ZonedDateTime now = ZonedDateTime.now(); return (now.isEqual(startDate) || now.isAfter(startDate)) && now.isBefore(endDate); } }
flutter-intellij/flutter-idea/src/io/flutter/survey/FlutterSurvey.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/survey/FlutterSurvey.java", "repo_id": "flutter-intellij", "token_count": 604 }
459
/* * 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.utils; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.function.Consumer; /** * Simple class for listening for a value that can be repeatedly updated. * <p> * The benefit of using this class instead of listening for events is you * don't have to worry about missing values posted to the stream before your * code started listening which can lead to hard to find bugs. * <p> * The benefit of using this class over awaiting a Future is that the value can * update multiple times. * <p> * The value associated with the EventStream can be set on any thread. * <p> * The class is inspired by listen method on the Stream class in Dart. */ public class EventStream<T> { protected final HashSet<StreamSubscription<T>> subscriptions = new LinkedHashSet<>(); private volatile T currentValue; public EventStream() { this(null); } public EventStream(T initialValue) { currentValue = initialValue; } public T getValue() { return currentValue; } /** * Returns whether the value was changed. */ public boolean setValue(T value) { final List<StreamSubscription<T>> regularSubscriptions = new ArrayList<>(); final List<StreamSubscription<T>> uiThreadSubscriptions = new ArrayList<>(); synchronized (this) { if (currentValue == value) { return false; } currentValue = value; for (StreamSubscription<T> subscription : subscriptions) { if (subscription.onUIThread) { uiThreadSubscriptions.add(subscription); } else { regularSubscriptions.add(subscription); } } for (StreamSubscription<T> subscription : regularSubscriptions) { subscription.notify(value); } } if (!uiThreadSubscriptions.isEmpty()) { AsyncUtils.invokeLater(() -> { synchronized (this) { if (value != currentValue) { // This update is obsolete. return; } for (StreamSubscription<T> subscription : uiThreadSubscriptions) { subscription.notify(value); } } }); } return true; } /** * Listens for changes to the value tracked by the EventStream. * onData is always called immediately with the current value specified * by the EventStream. * * @param onData is called every time the value associated with the EventStream changes. * @return a StreamSubscription object that is used to cancel the subscription. */ public StreamSubscription<T> listen(Consumer<T> onData) { return listen(onData, false); } /** * Listens for changes to the value tracked by the EventStream. * onData is always called immediately with the current value specified * by the EventStream. * * @param onData is called every time the value associated with the EventStream changes. * @param onUIThread specifies that callbacks are made on the UI thread. * @return a StreamSubscription object that is used to cancel the subscription. */ public StreamSubscription<T> listen(Consumer<T> onData, boolean onUIThread) { final StreamSubscription<T> subscription = new StreamSubscription<>(onData, onUIThread, this); final T cachedCurrentValue; synchronized (this) { cachedCurrentValue = currentValue; subscriptions.add(subscription); } onData.accept(cachedCurrentValue); return subscription; } protected void removeSubscription(StreamSubscription<T> subscription) { synchronized (this) { subscriptions.remove(subscription); } } }
flutter-intellij/flutter-idea/src/io/flutter/utils/EventStream.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/EventStream.java", "repo_id": "flutter-intellij", "token_count": 1251 }
460
/* * 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.utils; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.editor.colors.ColorKey; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class UIUtils { @Nullable public static JComponent getComponentOfActionEvent(@NotNull AnActionEvent e) { final Presentation presentation = e.getPresentation(); JComponent component = (JComponent)presentation.getClientProperty("button"); if (component == null && e.getInputEvent().getSource() instanceof JComponent) { component = (JComponent)e.getInputEvent().getSource(); } return component; } /** * All editor notifications in the Flutter plugin should get and set the background color from this method, which will ensure if any are * changed, they are all changed. */ @NotNull public static ColorKey getEditorNotificationBackgroundColor() { return EditorColors.GUTTER_BACKGROUND; } /** * Unstable API warning: only use this in the deprecated inspector. * @return best-guess for the current project based on the top-most window. */ @Nullable public static Project findVisibleProject() { final WindowManager wm = WindowManager.getInstance(); if (wm == null) return null; final JFrame jframe = wm.findVisibleFrame(); if (jframe == null) return null; for (IdeFrame frame : wm.getAllProjectFrames()) { if (frame.getComponent() == jframe.getRootPane()) { return frame.getProject(); } } return null; } }
flutter-intellij/flutter-idea/src/io/flutter/utils/UIUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/UIUtils.java", "repo_id": "flutter-intellij", "token_count": 633 }
461
/* * 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.view; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.Disposer; import com.intellij.ui.components.JBCheckBox; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.StreamSubscription; import io.flutter.vmService.ServiceExtensionState; import io.flutter.vmService.ToggleableServiceExtensionDescription; import org.jetbrains.annotations.NotNull; import javax.swing.*; /** * This class performs the same role as FlutterViewToggleableAction but * renders the UI as a simple JCheckbox instead of as a DumbAwareAction * enabling embedding UI to turn on and off the service extension * in a JPanel. */ public class BoolServiceExtensionCheckbox implements Disposable { private final JCheckBox checkbox; private StreamSubscription<ServiceExtensionState> currentValueSubscription; BoolServiceExtensionCheckbox( FlutterApp app, @NotNull ToggleableServiceExtensionDescription<Boolean> extensionDescription, String tooltip) { checkbox = new JBCheckBox(extensionDescription.getDisabledText()); checkbox.setHorizontalAlignment(JLabel.LEFT); checkbox.setToolTipText(tooltip); assert (app.getVMServiceManager() != null); app.hasServiceExtension(extensionDescription.getExtension(), checkbox::setEnabled, app); checkbox.addActionListener((l) -> { final boolean newValue = checkbox.isSelected(); app.getVMServiceManager().setServiceExtensionState( extensionDescription.getExtension(), newValue, newValue); if (app.isSessionActive()) { app.callBooleanExtension(extensionDescription.getExtension(), newValue); } }); currentValueSubscription = app.getVMServiceManager().getServiceExtensionState(extensionDescription.getExtension()).listen( (state) -> { if (checkbox.isSelected() != state.isEnabled()) { checkbox.setSelected(state.isEnabled()); } }, true); } JCheckBox getComponent() { return checkbox; } @Override public void dispose() { if (currentValueSubscription != null) { Disposer.dispose(currentValueSubscription); currentValueSubscription = null; } } }
flutter-intellij/flutter-idea/src/io/flutter/view/BoolServiceExtensionCheckbox.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/BoolServiceExtensionCheckbox.java", "repo_id": "flutter-intellij", "token_count": 790 }
462
/* * 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.vmService; import com.intellij.openapi.diagnostic.Logger; import org.dartlang.vm.service.consumer.GetMemoryUsageConsumer; import org.dartlang.vm.service.element.IsolateRef; import org.dartlang.vm.service.element.MemoryUsage; import org.dartlang.vm.service.element.RPCError; import org.dartlang.vm.service.element.Sentinel; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; public class HeapMonitor { private static final Logger LOG = Logger.getInstance(HeapMonitor.class); private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); private static final int POLL_PERIOD_IN_MS = 1000; public interface HeapListener { void handleMemoryUsage(List<MemoryUsage> memoryUsages); } public static class HeapSample { final int bytes; final int external; public long getSampleTime() { return sampleTime; } public final long sampleTime; public HeapSample(int bytes, int external) { this.bytes = bytes; this.external = external; this.sampleTime = System.currentTimeMillis(); } public int getBytes() { return bytes; } public int getExternal() { return external; } @Override public String toString() { return "bytes: " + bytes; } } private final List<HeapMonitor.HeapListener> heapListeners = new ArrayList<>(); private ScheduledFuture<?> pollingScheduler; @NotNull private final VmServiceWrapper vmServiceWrapper; public HeapMonitor(@NotNull VmServiceWrapper vmServiceWrapper) { this.vmServiceWrapper = vmServiceWrapper; } public void addListener(@NotNull HeapMonitor.HeapListener listener) { heapListeners.add(listener); } public void removeListener(@NotNull HeapMonitor.HeapListener listener) { heapListeners.add(listener); } public boolean hasListeners() { return !heapListeners.isEmpty(); } public void start() { pollingScheduler = executor.scheduleWithFixedDelay(this::poll, 100, POLL_PERIOD_IN_MS, TimeUnit.MILLISECONDS); } private int pollingClients = 0; public void addPollingClient() { pollingClients++; } public void removePollingClient() { pollingClients--; } private void poll() { if (pollingClients > 0) { collectMemoryUsage(); } } private void collectMemoryUsage() { final List<IsolateRef> isolateRefs = vmServiceWrapper.getExistingIsolates(); if (isolateRefs.isEmpty()) { return; } final List<MemoryUsage> memoryUsage = new ArrayList<>(); final CountDownLatch latch = new CountDownLatch(isolateRefs.size()); for (IsolateRef isolateRef : isolateRefs) { vmServiceWrapper.getVmService().getMemoryUsage(isolateRef.getId(), new GetMemoryUsageConsumer() { @Override public void received(MemoryUsage usage) { memoryUsage.add(usage); latch.countDown(); } @Override public void received(Sentinel sentinel) { latch.countDown(); } @Override public void onError(RPCError error) { // TODO(devoncarew): Remove rpcInternalError once https://github.com/dart-lang/webdev/issues/781 // lands and rolls into flutter. final int rpcInternalError = -32603; final int rpcMethodNotFound = -32601; // {"jsonrpc":"2.0","error":{"code":-32603,"message":"UnimplementedError..."}} if (error.getCode() == rpcInternalError || error.getCode() == rpcMethodNotFound) { handleMemoryApiNotSupported(); } latch.countDown(); } }); } try { latch.await(); } catch (InterruptedException ignored) { } if (pollingScheduler != null) { heapListeners.forEach(listener -> listener.handleMemoryUsage(memoryUsage)); } } private void handleMemoryApiNotSupported() { stop(); } public void stop() { if (pollingScheduler != null) { pollingScheduler.cancel(false); pollingScheduler = null; } } }
flutter-intellij/flutter-idea/src/io/flutter/vmService/HeapMonitor.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/HeapMonitor.java", "repo_id": "flutter-intellij", "token_count": 1576 }
463
package io.flutter.vmService.frame; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.intellij.icons.AllIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.LayeredIcon; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.frame.*; import com.intellij.xdebugger.frame.presentation.XKeywordValuePresentation; import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation; import com.intellij.xdebugger.frame.presentation.XStringValuePresentation; import io.flutter.utils.TypedDataList; import io.flutter.vmService.DartVmServiceDebugProcess; import io.flutter.vmService.VmServiceConsumers; import org.dartlang.vm.service.consumer.GetObjectConsumer; import org.dartlang.vm.service.element.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.nio.ByteBuffer; import java.text.MessageFormat; import java.util.Base64; // TODO: implement some combination of XValue.getEvaluationExpression() / // XValue.calculateEvaluationExpression() in order to support evaluate expression in variable values. // See https://youtrack.jetbrains.com/issue/WEB-17629. public class DartVmServiceValue extends XNamedValue { private static final LayeredIcon FINAL_FIELD_ICON = new LayeredIcon(AllIcons.Nodes.Field, AllIcons.Nodes.FinalMark); private static final LayeredIcon STATIC_FIELD_ICON = new LayeredIcon(AllIcons.Nodes.Field, AllIcons.Nodes.StaticMark); private static final LayeredIcon STATIC_FINAL_FIELD_ICON = new LayeredIcon(AllIcons.Nodes.Field, AllIcons.Nodes.StaticMark, AllIcons.Nodes.FinalMark); private static final String JSON_STRING_TEMPLATE = "'{'\"type\":\"@Instance\",\"class\":'{'\"type\":\"@Class\",\"fixedId\":\"true\",\"id\":\"classes/91\"," + "\"name\":\"_OneByteString\"'}',\"kind\":\"String\",\"length\":\"{0}\",\"valueAsString\":\"{1}\"'}'"; @NotNull private final DartVmServiceDebugProcess myDebugProcess; @NotNull private final String myIsolateId; @NotNull private final InstanceRef myInstanceRef; @Nullable private final LocalVarSourceLocation myLocalVarSourceLocation; @Nullable private final FieldRef myFieldRef; private final boolean myIsException; public DartVmServiceValue(@NotNull final DartVmServiceDebugProcess debugProcess, @NotNull final String isolateId, @NotNull final String name, @NotNull final InstanceRef instanceRef, @Nullable final LocalVarSourceLocation localVarSourceLocation, @Nullable final FieldRef fieldRef, boolean isException) { super(name); myDebugProcess = debugProcess; myIsolateId = isolateId; myInstanceRef = instanceRef; myLocalVarSourceLocation = localVarSourceLocation; myFieldRef = fieldRef; myIsException = isException; } @Override public boolean canNavigateToSource() { return myLocalVarSourceLocation != null || myFieldRef != null; } @Override public void computeSourcePosition(@NotNull final XNavigatable navigatable) { if (myLocalVarSourceLocation != null) { reportSourcePosition(myDebugProcess, navigatable, myIsolateId, myLocalVarSourceLocation.myScriptRef, myLocalVarSourceLocation.myTokenPos); } else if (myFieldRef != null) { doComputeSourcePosition(myDebugProcess, navigatable, myIsolateId, myFieldRef); } else { navigatable.setSourcePosition(null); } } static void doComputeSourcePosition(@NotNull final DartVmServiceDebugProcess debugProcess, @NotNull final XNavigatable navigatable, @NotNull final String isolateId, @NotNull final FieldRef fieldRef) { debugProcess.getVmServiceWrapper().getObject(isolateId, fieldRef.getId(), new GetObjectConsumer() { @Override public void received(final Obj field) { final SourceLocation location = ((Field)field).getLocation(); reportSourcePosition(debugProcess, navigatable, isolateId, location == null ? null : location.getScript(), location == null ? -1 : location.getTokenPos()); } @Override public void received(final Sentinel sentinel) { navigatable.setSourcePosition(null); } @Override public void onError(final RPCError error) { navigatable.setSourcePosition(null); } }); } @Override public boolean canNavigateToTypeSource() { return true; } @Override public void computeTypeSourcePosition(@NotNull final XNavigatable navigatable) { myDebugProcess.getVmServiceWrapper().getObject(myIsolateId, myInstanceRef.getClassRef().getId(), new GetObjectConsumer() { @Override public void received(final Obj classObj) { final SourceLocation location = ((ClassObj)classObj).getLocation(); reportSourcePosition(myDebugProcess, navigatable, myIsolateId, location == null ? null : location.getScript(), location == null ? -1 : location.getTokenPos()); } @Override public void received(final Sentinel response) { navigatable.setSourcePosition(null); } @Override public void onError(final RPCError error) { navigatable.setSourcePosition(null); } }); } private static void reportSourcePosition(@NotNull final DartVmServiceDebugProcess debugProcess, @NotNull final XNavigatable navigatable, @NotNull final String isolateId, @Nullable final ScriptRef script, final int tokenPos) { if (script == null || tokenPos <= 0) { navigatable.setSourcePosition(null); return; } ApplicationManager.getApplication().executeOnPooledThread(() -> { final XSourcePosition sourcePosition = debugProcess.getSourcePosition(isolateId, script, tokenPos); ApplicationManager.getApplication().runReadAction(() -> navigatable.setSourcePosition(sourcePosition)); }); } @Override public void computePresentation(@NotNull final XValueNode node, @NotNull final XValuePlace place) { if (computeVarHavingStringValuePresentation(node)) return; if (computeRegExpPresentation(node)) return; if (computeMapPresentation(node)) return; if (computeListPresentation(node)) return; // computeDefaultPresentation is called internally here when no result is received. // The reason for this is that the async method used cannot be properly waited. computeDefaultPresentation(node); // todo handle other special kinds: Type, TypeParameter, Pattern, may be some others as well } private Icon getIcon() { if (myIsException) return AllIcons.Debugger.Db_exception_breakpoint; if (myFieldRef != null) { if (myFieldRef.isStatic() && (myFieldRef.isFinal() || myFieldRef.isConst())) { return STATIC_FINAL_FIELD_ICON; } if (myFieldRef.isStatic()) { return STATIC_FIELD_ICON; } if (myFieldRef.isFinal() || myFieldRef.isConst()) { return FINAL_FIELD_ICON; } return AllIcons.Nodes.Field; } final InstanceKind kind = myInstanceRef.getKind(); if (kind == InstanceKind.Map || isListKind(kind)) return AllIcons.Debugger.Db_array; if (kind == InstanceKind.Null || kind == InstanceKind.Bool || kind == InstanceKind.Double || kind == InstanceKind.Int || kind == InstanceKind.String) { return AllIcons.Debugger.Db_primitive; } return AllIcons.Debugger.Value; } private boolean computeVarHavingStringValuePresentation(@NotNull final XValueNode node) { // getValueAsString() is provided for the instance kinds: Null, Bool, Double, Int, String (value may be truncated), Float32x4, Float64x2, Int32x4, StackTrace switch (myInstanceRef.getKind()) { case Null: case Bool: node.setPresentation(getIcon(), new XKeywordValuePresentation(myInstanceRef.getValueAsString()), false); break; case Double: case Int: node.setPresentation(getIcon(), new XNumericValuePresentation(myInstanceRef.getValueAsString()), false); break; case String: final String presentableValue = StringUtil.replace(myInstanceRef.getValueAsString(), "\"", "\\\""); node.setPresentation(getIcon(), new XStringValuePresentation(presentableValue), false); if (myInstanceRef.getValueAsStringIsTruncated()) { addFullStringValueEvaluator(node, myInstanceRef); } break; case StackTrace: node.setFullValueEvaluator(new ImmediateFullValueEvaluator("Click to see stack trace...", myInstanceRef.getValueAsString())); node.setPresentation(getIcon(), myInstanceRef.getClassRef().getName(), "", true); break; default: return false; } return true; } private void addFullStringValueEvaluator(@NotNull final XValueNode node, @NotNull final InstanceRef stringInstanceRef) { assert stringInstanceRef.getKind() == InstanceKind.String : stringInstanceRef; node.setFullValueEvaluator(new XFullValueEvaluator() { @Override public void startEvaluation(@NotNull final XFullValueEvaluationCallback callback) { myDebugProcess.getVmServiceWrapper().getObject(myIsolateId, stringInstanceRef.getId(), new GetObjectConsumer() { @Override public void received(Obj instance) { assert instance instanceof Instance && ((Instance)instance).getKind() == InstanceKind.String : instance; callback.evaluated(((Instance)instance).getValueAsString()); } @Override public void received(Sentinel response) { callback.errorOccurred(response.getValueAsString()); } @Override public void onError(RPCError error) { callback.errorOccurred(error.getMessage()); } }); } }); } private boolean computeRegExpPresentation(@NotNull final XValueNode node) { if (myInstanceRef.getKind() == InstanceKind.RegExp) { // The pattern is always an instance of kind String. final InstanceRef pattern = myInstanceRef.getPattern(); assert pattern.getKind() == InstanceKind.String : pattern; final String patternString = StringUtil.replace(pattern.getValueAsString(), "\"", "\\\""); node.setPresentation(getIcon(), new XStringValuePresentation(patternString) { @Nullable @Override public String getType() { return myInstanceRef.getClassRef().getName(); } }, true); if (pattern.getValueAsStringIsTruncated()) { addFullStringValueEvaluator(node, pattern); } return true; } return false; } private boolean computeMapPresentation(@NotNull final XValueNode node) { if (myInstanceRef.getKind() == InstanceKind.Map) { final String value = "size = " + myInstanceRef.getLength(); node.setPresentation(getIcon(), myInstanceRef.getClassRef().getName(), value, myInstanceRef.getLength() > 0); return true; } return false; } private boolean computeListPresentation(@NotNull final XValueNode node) { if (isListKind(myInstanceRef.getKind())) { final String value = "size = " + myInstanceRef.getLength(); node.setPresentation(getIcon(), myInstanceRef.getClassRef().getName(), value, myInstanceRef.getLength() > 0); return true; } return false; } private void computeDefaultPresentation(@NotNull final XValueNode node) { final String typeName = myInstanceRef.getClassRef().getName(); InstanceKind kind = myInstanceRef.getKind(); // other InstanceKinds that can't have children don't reach this method. boolean canHaveChildren = kind != InstanceKind.Int32x4 && kind != InstanceKind.Float32x4 && kind != InstanceKind.Float64x2; // Check if the string value is populated. if (myInstanceRef.getValueAsString() != null && !myInstanceRef.getValueAsStringIsTruncated()) { node.setPresentation(getIcon(), typeName, myInstanceRef.getValueAsString(), canHaveChildren); return; } myDebugProcess.getVmServiceWrapper().callToString(myIsolateId, myInstanceRef.getId(), new VmServiceConsumers.InvokeConsumerWrapper() { @Override public void received(final InstanceRef toStringInstanceRef) { if (toStringInstanceRef.getKind() == InstanceKind.String) { final String value = toStringInstanceRef.getValueAsString(); // We don't need to show the default implementation of toString() ("Instance of ..."). if (value.startsWith("Instance of ")) { node.setPresentation(getIcon(), typeName, "", canHaveChildren); } else { if (toStringInstanceRef.getValueAsStringIsTruncated()) { addFullStringValueEvaluator(node, toStringInstanceRef); } node.setPresentation(getIcon(), typeName, value, canHaveChildren); } } else { preesentationFallback(node); } } @Override public void noGoodResult() { preesentationFallback(node); } private void preesentationFallback(@NotNull final XValueNode node) { if (myInstanceRef.getValueAsString() != null) { node.setPresentation( getIcon(), typeName, myInstanceRef.getValueAsString() + (myInstanceRef.getValueAsStringIsTruncated() ? "..." : ""), true); } else { node.setPresentation(getIcon(), typeName, "", true); } } }); } @Override public void computeChildren(@NotNull final XCompositeNode node) { if (myInstanceRef.isNull()) { node.addChildren(XValueChildrenList.EMPTY, true); return; } if ((isListKind(myInstanceRef.getKind()) || myInstanceRef.getKind() == InstanceKind.Map)) { computeCollectionChildren(myInstanceRef, 0, node); } else { myDebugProcess.getVmServiceWrapper().getObject(myIsolateId, myInstanceRef.getId(), new GetObjectConsumer() { @Override public void received(Obj instance) { addFields(node, ((Instance)instance).getFields()); } @Override public void received(Sentinel sentinel) { node.setErrorMessage(sentinel.getValueAsString()); } @Override public void onError(RPCError error) { node.setErrorMessage(error.getMessage()); } }); } } private void computeCollectionChildren(@NotNull InstanceRef instanceRef, int offset, @NotNull final XCompositeNode node) { final int count = Math.min(instanceRef.getLength() - offset, XCompositeNode.MAX_CHILDREN_TO_SHOW); myDebugProcess.getVmServiceWrapper().getCollectionObject(myIsolateId, myInstanceRef.getId(), offset, count, new GetObjectConsumer() { @Override public void received(Obj instance) { InstanceKind kind = instanceRef.getKind(); if (isListKind(kind)) { addListChildren(offset, node, (Instance)instance); } else if (kind == InstanceKind.Map) { addMapChildren(offset, node, ((Instance)instance).getAssociations()); } else { assert false : kind; } if (offset + count < instanceRef.getLength()) { node.tooManyChildren(instanceRef.getLength() - offset - count , () -> computeCollectionChildren(instanceRef, offset + count, node)); } } @Override public void received(Sentinel sentinel) { node.setErrorMessage(sentinel.getValueAsString()); } @Override public void onError(RPCError error) { node.setErrorMessage(error.getMessage()); } }); } private void addListChildren(int offset, @NotNull XCompositeNode node, @NotNull Instance instance) { ElementList<InstanceRef> listElementsRef = instance.getElements(); if (listElementsRef != null) { final XValueChildrenList childrenList = new XValueChildrenList(listElementsRef.size()); int index = offset; for (InstanceRef listElement : listElementsRef) { childrenList.add(new DartVmServiceValue(myDebugProcess, myIsolateId, String.valueOf(index++), listElement, null, null, false)); } node.addChildren(childrenList, true); return; } if (instance.getBytes() != null) { // true for typed data //noinspection ConstantConditions byte @NotNull [] bytes = Base64.getDecoder().decode(instance.getBytes()); TypedDataList data = getTypedDataList(bytes); XValueChildrenList childrenList = new XValueChildrenList(data.size()); for (int i = 0; i < data.size(); i++) { childrenList.add( new DartVmServiceValue(myDebugProcess, myIsolateId, String.valueOf(i), instanceRefForString(data.getValue(i)), null, null, false)); } node.addChildren(childrenList, true); return; } if (instance.getKind() == InstanceKind.List) { node.addChildren(XValueChildrenList.EMPTY, true); return; } // Show contents of special lists using toList() method myDebugProcess.getVmServiceWrapper().callToList(myIsolateId, instance.getId(), new VmServiceConsumers.InvokeConsumerWrapper() { @Override public void received(InstanceRef toListInstanceRef) { if (toListInstanceRef.getKind() == InstanceKind.List) { computeCollectionChildren(toListInstanceRef, offset, node); } else { node.addChildren(XValueChildrenList.EMPTY, true); } } @Override public void noGoodResult() { node.addChildren(XValueChildrenList.EMPTY, true); } }); } private InstanceRef instanceRefForString(@NotNull String value) { String json = MessageFormat.format(JSON_STRING_TEMPLATE, value.length(), value); JsonObject ref = new Gson().fromJson(json, JsonObject.class); //noinspection ConstantConditions return new InstanceRef(ref); } private TypedDataList getTypedDataList(byte @NotNull [] bytes) { ByteBuffer buffer = ByteBuffer.wrap(bytes); //noinspection ConstantConditions switch (myInstanceRef.getKind()) { case Uint8List: case Uint8ClampedList: return new TypedDataList.Uint8List(bytes); case Int8List: return new TypedDataList.Int8List(bytes); case Uint16List: return new TypedDataList.Uint16List(bytes); case Int16List: return new TypedDataList.Int16List(bytes); case Uint32List: return new TypedDataList.Uint32List(bytes); case Int32List: case Int32x4List: return new TypedDataList.Int32List(bytes); case Uint64List: return new TypedDataList.Uint64List(bytes); case Int64List: return new TypedDataList.Int64List(bytes); case Float32List: case Float32x4List: return new TypedDataList.Float32List(bytes); case Float64List: case Float64x2List: return new TypedDataList.Float64List(bytes); default: return new TypedDataList.Int8List(bytes); } } private void addMapChildren(int offset, @NotNull final XCompositeNode node, @NotNull final ElementList<MapAssociation> mapAssociations) { final XValueChildrenList childrenList = new XValueChildrenList(mapAssociations.size()); int index = offset; for (MapAssociation mapAssociation : mapAssociations) { final InstanceRef keyInstanceRef = mapAssociation.getKey(); final InstanceRef valueInstanceRef = mapAssociation.getValue(); childrenList.add(String.valueOf(index++), new XValue() { @Override public void computePresentation(@NotNull XValueNode node, @NotNull XValuePlace place) { final String value = getShortPresentableValue(keyInstanceRef) + " -> " + getShortPresentableValue(valueInstanceRef); node.setPresentation(AllIcons.Debugger.Value, "map entry", value, true); } @Override public void computeChildren(@NotNull XCompositeNode node) { final DartVmServiceValue key = new DartVmServiceValue(myDebugProcess, myIsolateId, "key", keyInstanceRef, null, null, false); final DartVmServiceValue value = new DartVmServiceValue(myDebugProcess, myIsolateId, "value", valueInstanceRef, null, null, false); node.addChildren(XValueChildrenList.singleton(key), false); node.addChildren(XValueChildrenList.singleton(value), true); } }); } node.addChildren(childrenList, true); } private void addFields(@NotNull final XCompositeNode node, @Nullable final ElementList<BoundField> fields) { if (fields == null) { node.addChildren(new XValueChildrenList(0), true); } else { final XValueChildrenList childrenList = new XValueChildrenList(fields.size()); if (getInstanceRef().getKind() == InstanceKind.Record) { for (BoundField field : fields) { assert field != null; if (field.getJson() == null) { continue; } Object name = field.getName(); InstanceRef value = field.getValue(); if (name != null && value != null) { final String n; if (name instanceof String) { n = (String)name; } else { n = "$" + (int)name; } childrenList.add(new DartVmServiceValue(myDebugProcess, myIsolateId, n, value, null, null, false)); } } } else { for (BoundField field : fields) { assert field != null; final InstanceRef value = field.getValue(); final Object name = field.getName(); if (name != null && value != null) { childrenList.add(new DartVmServiceValue(myDebugProcess, myIsolateId, (String)name, value, null, null, false)); } } } node.addChildren(childrenList, true); } } @NotNull private static String getShortPresentableValue(@NotNull final InstanceRef instanceRef) { // getValueAsString() is provided for the instance kinds: Null, Bool, Double, Int, String (value may be truncated), Float32x4, Float64x2, Int32x4, StackTrace switch (instanceRef.getKind()) { case String: String string = instanceRef.getValueAsString(); if (string.length() > 103) string = string.substring(0, 100) + "..."; return "\"" + StringUtil.replace(string, "\"", "\\\"") + "\""; case Null: case Bool: case Double: case Int: case Float32x4: case Float64x2: case Int32x4: // case StackTrace: getValueAsString() is too long for StackTrace return instanceRef.getValueAsString(); default: return "[" + instanceRef.getClassRef().getName() + "]"; } } private static boolean isListKind(@NotNull final InstanceKind kind) { // List, Uint8ClampedList, Uint8List, Uint16List, Uint32List, Uint64List, Int8List, Int16List, Int32List, Int64List, Float32List, Float64List, Int32x4List, Float32x4List, Float64x2List return kind == InstanceKind.List || kind == InstanceKind.Uint8ClampedList || kind == InstanceKind.Uint8List || kind == InstanceKind.Uint16List || kind == InstanceKind.Uint32List || kind == InstanceKind.Uint64List || kind == InstanceKind.Int8List || kind == InstanceKind.Int16List || kind == InstanceKind.Int32List || kind == InstanceKind.Int64List || kind == InstanceKind.Float32List || kind == InstanceKind.Float64List || kind == InstanceKind.Int32x4List || kind == InstanceKind.Float32x4List || kind == InstanceKind.Float64x2List; } @NotNull public InstanceRef getInstanceRef() { return myInstanceRef; } static class LocalVarSourceLocation { @NotNull private final ScriptRef myScriptRef; private final int myTokenPos; public LocalVarSourceLocation(@NotNull final ScriptRef scriptRef, final int tokenPos) { myScriptRef = scriptRef; myTokenPos = tokenPos; } } }
flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartVmServiceValue.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartVmServiceValue.java", "repo_id": "flutter-intellij", "token_count": 9610 }
464
SF:lib/main.dart DA:3,0 DA:4,0 DA:9,1 DA:11,1 DA:13,1 DA:25,1 DA:31,2 DA:44,1 DA:45,1 DA:51,1 DA:52,2 DA:58,2 DA:62,1 DA:70,1 DA:71,1 DA:74,3 DA:76,1 DA:79,1 DA:95,1 DA:96,1 DA:99,1 DA:100,2 DA:101,3 DA:106,1 DA:107,1 DA:109,1 LF:26 LH:24 end_of_record
flutter-intellij/flutter-idea/testData/coverage/lcov.info/0
{ "file_path": "flutter-intellij/flutter-idea/testData/coverage/lcov.info", "repo_id": "flutter-intellij", "token_count": 181 }
465
/* * 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.utils.math; import java.util.ArrayList; import static org.junit.Assert.assertEquals; /** * This code is ported from the Dart vector_math package. */ public class TestUtils { static final double errorThreshold = 0.0005; public static void relativeTest(Matrix4 output, Matrix4 expectedOutput) { for (int i = 0; i < 16; i++) { relativeTest(output.get(i), expectedOutput.get(i)); } } public static void relativeTest(Vector4 output, Vector4 expectedOutput) { for (int i = 0; i < 4; i++) { relativeTest(output.getStorage()[i], expectedOutput.getStorage()[i]); } } public static void relativeTest(double output, double expectedOutput) { assertEquals(output, expectedOutput, errorThreshold); } public static void absoluteTest(Matrix4 output, Matrix4 expectedOutput) { for (int i = 0; i < 16; i++) { absoluteTest(output.get(i), expectedOutput.get(i)); } } public static void absoluteTest(double output, double expectedOutput) { assertEquals(Math.abs(output), Math.abs(expectedOutput), errorThreshold); } public static Matrix4 parseMatrix4(String input) { input = input.trim(); String[] rows = input.split("\n"); ArrayList<Double> values = new ArrayList<Double>(); int col_count = 0; for (int i = 0; i < rows.length; i++) { rows[i] = rows[i].trim(); String[] cols = rows[i].split(" "); for (int j = 0; j < cols.length; j++) { cols[j] = cols[j].trim(); } for (int j = 0; j < cols.length; j++) { if (cols[j].isEmpty()) { continue; } if (i == 0) { col_count++; } values.add(Double.parseDouble(cols[j])); } } Matrix4 m = new Matrix4(); for (int j = 0; j < rows.length; j++) { for (int i = 0; i < col_count; i++) { m.set(m.index(j, i), values.get(j * col_count + i)); //m[i][j] = values[j*col_count+i]; } } return m; } }
flutter-intellij/flutter-idea/testSrc/integration/io/flutter/utils/math/TestUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/integration/io/flutter/utils/math/TestUtils.java", "repo_id": "flutter-intellij", "token_count": 854 }
466
/* * 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.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.testFramework.fixtures.CodeInsightTestFixture; import com.intellij.testFramework.fixtures.EditorTestFixture; import io.flutter.dart.FlutterDartAnalysisServer; import io.flutter.dart.FlutterOutlineListener; import io.flutter.testing.CodeInsightProjectFixture; import io.flutter.testing.Testing; import org.dartlang.analysis.server.protocol.FlutterOutline; import org.jetbrains.annotations.NotNull; import org.junit.*; import java.util.HashMap; import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.*; public class ActiveEditorsOutlineServiceTest { private static final String fileContents = "void main() {\n" + " group('group 1', () {\n" + " test('test 1', () {});\n" + " });\n" + "}"; // The outline service doesn't care too much what the outline's contents are, only that the outlines update. // However, the request method uses the outline's length to determine if the outline is up-to-date. private static final FlutterOutline firstFlutterOutline = new FlutterOutline("First", 0, 0, 0, 0, "", null, null, null, null, null, null); private static final FlutterOutline secondFlutterOutline = new FlutterOutline("Second", 0, 0, 0, 0, "", null, null, null, null, null, null); private static final FlutterOutline outlineWithCorrectLength = new FlutterOutline("Third", 0, fileContents.length(), 0, 0, "", null, null, null, null, null, null); @Rule public final CodeInsightProjectFixture projectFixture = Testing.makeCodeInsightModule(); CodeInsightTestFixture innerFixture; Project project; Module module; ActiveEditorsOutlineService service; Listener listener; TestFlutterDartAnalysisServer flutterDas; PsiFile mainFile; String mainPath; @Before public void setUp() { innerFixture = projectFixture.getInner(); project = projectFixture.getProject(); flutterDas = new TestFlutterDartAnalysisServer(project); service = new ActiveEditorsOutlineService(project); listener = new Listener(); service.addListener(listener); mainFile = innerFixture.addFileToProject("lib/main.dart", fileContents); mainPath = mainFile.getVirtualFile().getCanonicalPath(); } @After public void tearDown() { service.dispose(); } // NOTE: we have no simple way of writing a test that includes calls from the Dart Analysis Server. Instead, the tests // below mock out the behavior by notifying the Flutter Dart Analysis Server's listeners of changes when the DAS should do this. @Test @Ignore("https://github.com/flutter/flutter-intellij/issues/3583") public void notifiesWhenOutlinesChange() throws Exception { assertThat(listener.outlineChanged.keySet(), not(hasItem(mainPath))); assertThat(listener.outlineChanged.get(mainPath), equalTo(null)); assertThat(listener.mostRecentOutline, equalTo(null)); assertThat(listener.editorsChanged, equalTo(0)); Testing.runOnDispatchThread(() -> innerFixture.openFileInEditor(mainFile.getVirtualFile())); final Editor editor = innerFixture.getEditor(); final EditorTestFixture editorTestFixture = new EditorTestFixture(project, editor, mainFile.getVirtualFile()); flutterDas.updateOutline(mainPath, firstFlutterOutline); assertThat(listener.outlineChanged.keySet(), hasItem(mainPath)); assertThat(listener.outlineChanged.get(mainPath), equalTo(1)); assertThat(listener.mostRecentOutline, equalTo(firstFlutterOutline)); // Move the caret inside of the name of the test group. Testing.runOnDispatchThread(() -> editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(1, 10))); assertThat(listener.outlineChanged.get(mainPath), equalTo(1)); assertThat(listener.mostRecentOutline, equalTo(firstFlutterOutline)); Testing.runOnDispatchThread(() -> editorTestFixture.type("longer name")); flutterDas.updateOutline(mainFile.getVirtualFile().getCanonicalPath(), secondFlutterOutline); assertThat(listener.outlineChanged.get(mainPath), equalTo(2)); assertThat(listener.mostRecentOutline, equalTo(secondFlutterOutline)); } @Test @Ignore("https://github.com/flutter/flutter-intellij/issues/3583") public void notifiesOutlineChangedWhenOpeningAndClosingFiles() throws Exception { assertThat(listener.outlineChanged.keySet(), not(hasItem(mainPath))); assertThat(listener.outlineChanged.get(mainPath), equalTo(null)); assertThat(listener.mostRecentOutline, equalTo(null)); assertThat(listener.editorsChanged, equalTo(0)); Testing.runOnDispatchThread(() -> innerFixture.openFileInEditor(mainFile.getVirtualFile())); final Editor editor = innerFixture.getEditor(); final EditorTestFixture editorTestFixture = new EditorTestFixture(project, editor, mainFile.getVirtualFile()); flutterDas.updateOutline(mainPath, firstFlutterOutline); assertThat(listener.outlineChanged.keySet(), hasItem(mainPath)); assertThat(listener.outlineChanged.get(mainPath), equalTo(1)); assertThat(listener.mostRecentPath, equalTo(mainPath)); assertThat(listener.mostRecentOutline, equalTo(firstFlutterOutline)); // Open another file. final PsiFile fileTwo = innerFixture.addFileToProject("lib/main_two.dart", fileContents); final String fileTwoPath = fileTwo.getVirtualFile().getCanonicalPath(); final EditorTestFixture editorTestFixtureTwo = new EditorTestFixture(project, editor, fileTwo.getVirtualFile()); Testing.runOnDispatchThread(() -> innerFixture.openFileInEditor(fileTwo.getVirtualFile())); flutterDas.updateOutline(fileTwoPath, secondFlutterOutline); assertThat(listener.outlineChanged.keySet(), hasItem(fileTwoPath)); assertThat(listener.outlineChanged.get(fileTwoPath), equalTo(1)); assertThat(listener.outlineChanged.get(mainPath), equalTo(1)); assertThat(listener.mostRecentPath, equalTo(fileTwoPath)); assertThat(listener.mostRecentOutline, equalTo(secondFlutterOutline)); // NOTE: We can't test what happens when closing an editor because CodeInsightTestFixture always has one open editor. Testing.runOnDispatchThread(() -> innerFixture.openFileInEditor(mainFile.getVirtualFile())); final EditorTestFixture editorTestFixtureThree = new EditorTestFixture(project, editor, mainFile.getVirtualFile()); flutterDas.updateOutline(mainPath, firstFlutterOutline); assertThat(listener.outlineChanged.get(fileTwoPath), equalTo(1)); assertThat(listener.outlineChanged.get(mainPath), equalTo(2)); assertThat(listener.mostRecentPath, equalTo(mainPath)); assertThat(listener.mostRecentOutline, equalTo(firstFlutterOutline)); } @Test @Ignore("https://github.com/flutter/flutter-intellij/issues/3583") public void getIfUpdatedDeterminesOutlineValidity() throws Exception { Testing.runOnDispatchThread(() -> { innerFixture.openFileInEditor(mainFile.getVirtualFile()); assertThat(service.getIfUpdated(mainFile), nullValue()); flutterDas.updateOutline(mainPath, firstFlutterOutline); assertThat(service.getIfUpdated(mainFile), nullValue()); flutterDas.updateOutline(mainPath, secondFlutterOutline); assertThat(service.getIfUpdated(mainFile), nullValue()); flutterDas.updateOutline(mainPath, outlineWithCorrectLength); assertThat(service.getIfUpdated(mainFile), equalTo(outlineWithCorrectLength)); }); } private static class Listener implements ActiveEditorsOutlineService.Listener { int editorsChanged = 0; final Map<String, Integer> outlineChanged = new HashMap<>(); FlutterOutline mostRecentOutline = null; String mostRecentPath = null; @Override public void onOutlineChanged(@NotNull String path, FlutterOutline outline) { final Integer changes = outlineChanged.get(path); outlineChanged.put(path, changes == null ? 1 : changes + 1); mostRecentPath = path; mostRecentOutline = outline; } } private static class TestFlutterDartAnalysisServer extends FlutterDartAnalysisServer { public TestFlutterDartAnalysisServer(@NotNull Project project) { super(project); } void updateOutline(@NotNull String path, @NotNull FlutterOutline outline) { for (FlutterOutlineListener listener : fileOutlineListeners.get(path)) { listener.outlineUpdated(path, outline, null); } } } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/editor/ActiveEditorsOutlineServiceTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/editor/ActiveEditorsOutlineServiceTest.java", "repo_id": "flutter-intellij", "token_count": 2983 }
467
/* * 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.perf; import org.junit.Test; import static org.junit.Assert.assertEquals; public class SlidingWindowStatsTest { @Test public void simpleSlidingWindowStats() { final SlidingWindowStats stats = new SlidingWindowStats(); assertEquals(0, stats.getTotal()); stats.add(1, 0); stats.add(1, 1); assertEquals(2, stats.getTotal()); stats.add(1, 2); stats.add(1, 3); assertEquals(4, stats.getTotal()); assertEquals(4, stats.getTotalWithinWindow(0)); assertEquals(3, stats.getTotalWithinWindow(1)); assertEquals(2, stats.getTotalWithinWindow(2)); assertEquals(1, stats.getTotalWithinWindow(3)); } @Test public void totalSinceNavigation() { final SlidingWindowStats stats = new SlidingWindowStats(); assertEquals(0, stats.getTotal()); stats.add(1, 0); stats.add(1, 1); assertEquals(2, stats.getTotalSinceNavigation()); assertEquals(2, stats.getTotal()); stats.onNavigation(); assertEquals(0, stats.getTotalSinceNavigation()); assertEquals(2, stats.getTotal()); stats.add(1, 2); assertEquals(1, stats.getTotalSinceNavigation()); } private void add1000Times(SlidingWindowStats stats, int timeStamp) { for (int i = 0; i < 1000; i++) { stats.add(1, timeStamp); } } @Test public void duplicateSlidingWindowStatTimestamps() { final SlidingWindowStats stats = new SlidingWindowStats(); assertEquals(0, stats.getTotal()); add1000Times(stats, 0); add1000Times(stats, 1); assertEquals(2000, stats.getTotal()); add1000Times(stats, 2); add1000Times(stats, 3); assertEquals(4000, stats.getTotal()); assertEquals(4000, stats.getTotalWithinWindow(0)); assertEquals(3000, stats.getTotalWithinWindow(1)); assertEquals(2000, stats.getTotalWithinWindow(2)); assertEquals(1000, stats.getTotalWithinWindow(3)); add1000Times(stats, 4); add1000Times(stats, 5); add1000Times(stats, 6); add1000Times(stats, 7); add1000Times(stats, 8); add1000Times(stats, 9); add1000Times(stats, 10); assertEquals(11000, stats.getTotal()); assertEquals(11000, stats.getTotalWithinWindow(0)); add1000Times(stats, 11); } @Test public void clearSlidingWindowStats() { final SlidingWindowStats stats = new SlidingWindowStats(); stats.add(1, 0); stats.add(1, 1); stats.add(1, 2); stats.add(1, 3); assertEquals(4, stats.getTotal()); assertEquals(4, stats.getTotalWithinWindow(0)); stats.clear(); stats.add(1, 4); stats.add(1, 5); assertEquals(2, stats.getTotal()); assertEquals(1, stats.getTotalWithinWindow(5)); assertEquals(2, stats.getTotalWithinWindow(0)); stats.clear(); // Intentionally shift timestamps backwards as could happen after a hot // reload. stats.add(1, 0); stats.add(1, 1); stats.add(1, 2); stats.add(1, 3); assertEquals(4, stats.getTotal()); assertEquals(4, stats.getTotalWithinWindow(0)); stats.add(1, 4); stats.add(1, 5); stats.add(1, 6); stats.add(1, 7); stats.add(1, 8); stats.add(1, 9); stats.add(1, 10); assertEquals(11, stats.getTotal()); assertEquals(11, stats.getTotalWithinWindow(0)); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/perf/SlidingWindowStatsTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/perf/SlidingWindowStatsTest.java", "repo_id": "flutter-intellij", "token_count": 1313 }
468