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. #include "include/flutter/flutter_engine.h" #include <algorithm> #include <iostream> namespace flutter { FlutterEngine::FlutterEngine() {} FlutterEngine::~FlutterEngine() {} bool FlutterEngine::Start(const std::string& icu_data_path, const std::string& assets_path, const std::vector<std::string>& arguments, const std::string& aot_library_path) { if (engine_) { std::cerr << "Cannot run an already running engine. Create a new instance " "or call ShutDown first." << std::endl; return false; } FlutterDesktopEngineProperties c_engine_properties = {}; c_engine_properties.assets_path = assets_path.c_str(); c_engine_properties.icu_data_path = icu_data_path.c_str(); c_engine_properties.aot_library_path = aot_library_path.c_str(); std::vector<const char*> engine_switches; std::transform( arguments.begin(), arguments.end(), std::back_inserter(engine_switches), [](const std::string& arg) -> const char* { return arg.c_str(); }); if (!engine_switches.empty()) { c_engine_properties.switches = &engine_switches[0]; c_engine_properties.switches_count = engine_switches.size(); } engine_ = UniqueEnginePtr(FlutterDesktopRunEngine(c_engine_properties), FlutterDesktopShutDownEngine); if (!engine_) { std::cerr << "Failed to start engine." << std::endl; return false; } return true; } void FlutterEngine::ShutDown() { engine_ = nullptr; } FlutterDesktopPluginRegistrarRef FlutterEngine::GetRegistrarForPlugin( const std::string& plugin_name) { if (!engine_) { std::cerr << "Cannot get plugin registrar on an engine that isn't running; " "call Run first." << std::endl; return nullptr; } return FlutterDesktopGetPluginRegistrar(engine_.get(), plugin_name.c_str()); } void FlutterEngine::RunEventLoopWithTimeout(std::chrono::milliseconds timeout) { if (!engine_) { std::cerr << "Cannot run event loop without a running engine; call " "Run first." << std::endl; return; } uint32_t timeout_milliseconds; if (timeout == std::chrono::milliseconds::max()) { // The C API uses 0 to represent no timeout, so convert |max| to 0. timeout_milliseconds = 0; } else if (timeout.count() > UINT32_MAX) { timeout_milliseconds = UINT32_MAX; } else { timeout_milliseconds = static_cast<uint32_t>(timeout.count()); } FlutterDesktopRunEngineEventLoopWithTimeout(engine_.get(), timeout_milliseconds); } } // namespace flutter
engine/shell/platform/glfw/client_wrapper/flutter_engine.cc/0
{ "file_path": "engine/shell/platform/glfw/client_wrapper/flutter_engine.cc", "repo_id": "engine", "token_count": 1127 }
354
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/glfw/glfw_event_loop.h" #include <GLFW/glfw3.h> #include <atomic> #include <utility> namespace flutter { GLFWEventLoop::GLFWEventLoop(std::thread::id main_thread_id, const TaskExpiredCallback& on_task_expired) : EventLoop(main_thread_id, on_task_expired) {} GLFWEventLoop::~GLFWEventLoop() = default; void GLFWEventLoop::WaitUntil(const TaskTimePoint& time) { const auto now = TaskTimePoint::clock::now(); // Make sure the seconds are not integral. using Seconds = std::chrono::duration<double, std::ratio<1>>; const auto duration_to_wait = std::chrono::duration_cast<Seconds>(time - now); if (duration_to_wait.count() > 0.0) { ::glfwWaitEventsTimeout(duration_to_wait.count()); } else { // Avoid engine task priority inversion by making sure GLFW events are // always processed even when there is no need to wait for pending engine // tasks. ::glfwPollEvents(); } } void GLFWEventLoop::Wake() { ::glfwPostEmptyEvent(); } } // namespace flutter
engine/shell/platform/glfw/glfw_event_loop.cc/0
{ "file_path": "engine/shell/platform/glfw/glfw_event_loop.cc", "repo_id": "engine", "token_count": 438 }
355
# 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("//build/config/linux/pkg_config.gni") import("//flutter/shell/platform/glfw/config.gni") pkg_config("x11") { packages = [ "x11" ] } pkg_config("gtk") { packages = [ "gtk+-3.0" ] } pkg_config("egl") { packages = [ "egl" ] } pkg_config("epoxy") { packages = [ "epoxy" ] }
engine/shell/platform/linux/config/BUILD.gn/0
{ "file_path": "engine/shell/platform/linux/config/BUILD.gn", "repo_id": "engine", "token_count": 172 }
356
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/public/flutter_linux/fl_dart_project.h" #include <gmodule.h> struct _FlDartProject { GObject parent_instance; gchar* aot_library_path; gchar* assets_path; gchar* icu_data_path; gchar** dart_entrypoint_args; }; G_DEFINE_TYPE(FlDartProject, fl_dart_project, G_TYPE_OBJECT) // Gets the directory the current executable is in. static gchar* get_executable_dir() { g_autoptr(GError) error = nullptr; g_autofree gchar* exe_path = g_file_read_link("/proc/self/exe", &error); if (exe_path == nullptr) { g_critical("Failed to determine location of executable: %s", error->message); return nullptr; } return g_path_get_dirname(exe_path); } static void fl_dart_project_dispose(GObject* object) { FlDartProject* self = FL_DART_PROJECT(object); g_clear_pointer(&self->aot_library_path, g_free); g_clear_pointer(&self->assets_path, g_free); g_clear_pointer(&self->icu_data_path, g_free); g_clear_pointer(&self->dart_entrypoint_args, g_strfreev); G_OBJECT_CLASS(fl_dart_project_parent_class)->dispose(object); } static void fl_dart_project_class_init(FlDartProjectClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_dart_project_dispose; } static void fl_dart_project_init(FlDartProject* self) {} G_MODULE_EXPORT FlDartProject* fl_dart_project_new() { FlDartProject* self = FL_DART_PROJECT(g_object_new(fl_dart_project_get_type(), nullptr)); g_autofree gchar* executable_dir = get_executable_dir(); self->aot_library_path = g_build_filename(executable_dir, "lib", "libapp.so", nullptr); self->assets_path = g_build_filename(executable_dir, "data", "flutter_assets", nullptr); self->icu_data_path = g_build_filename(executable_dir, "data", "icudtl.dat", nullptr); return self; } G_MODULE_EXPORT void fl_dart_project_set_aot_library_path(FlDartProject* self, const gchar* path) { g_return_if_fail(FL_IS_DART_PROJECT(self)); g_clear_pointer(&self->aot_library_path, g_free); self->aot_library_path = g_strdup(path); } G_MODULE_EXPORT const gchar* fl_dart_project_get_aot_library_path( FlDartProject* self) { g_return_val_if_fail(FL_IS_DART_PROJECT(self), nullptr); return self->aot_library_path; } G_MODULE_EXPORT void fl_dart_project_set_assets_path(FlDartProject* self, gchar* path) { g_return_if_fail(FL_IS_DART_PROJECT(self)); g_clear_pointer(&self->assets_path, g_free); self->assets_path = g_strdup(path); } G_MODULE_EXPORT const gchar* fl_dart_project_get_assets_path( FlDartProject* self) { g_return_val_if_fail(FL_IS_DART_PROJECT(self), nullptr); return self->assets_path; } G_MODULE_EXPORT void fl_dart_project_set_icu_data_path(FlDartProject* self, gchar* path) { g_return_if_fail(FL_IS_DART_PROJECT(self)); g_clear_pointer(&self->icu_data_path, g_free); self->icu_data_path = g_strdup(path); } G_MODULE_EXPORT const gchar* fl_dart_project_get_icu_data_path( FlDartProject* self) { g_return_val_if_fail(FL_IS_DART_PROJECT(self), nullptr); return self->icu_data_path; } G_MODULE_EXPORT gchar** fl_dart_project_get_dart_entrypoint_arguments( FlDartProject* self) { g_return_val_if_fail(FL_IS_DART_PROJECT(self), nullptr); return self->dart_entrypoint_args; } G_MODULE_EXPORT void fl_dart_project_set_dart_entrypoint_arguments( FlDartProject* self, char** argv) { g_return_if_fail(FL_IS_DART_PROJECT(self)); g_clear_pointer(&self->dart_entrypoint_args, g_strfreev); self->dart_entrypoint_args = g_strdupv(argv); }
engine/shell/platform/linux/fl_dart_project.cc/0
{ "file_path": "engine/shell/platform/linux/fl_dart_project.cc", "repo_id": "engine", "token_count": 1675 }
357
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_CHANNEL_RESPONDER_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_CHANNEL_RESPONDER_H_ #include <gdk/gdk.h> #include "flutter/shell/platform/linux/fl_key_responder.h" #include "flutter/shell/platform/linux/fl_keyboard_manager.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" typedef FlValue* (*FlValueConverter)(FlValue*); /** * FlKeyChannelResponderMock: * * Allows mocking of FlKeyChannelResponder methods and values. Only used in * unittests. */ typedef struct _FlKeyChannelResponderMock { /** * FlKeyChannelResponderMock::value_converter: * If #value_converter is not nullptr, then this function is applied to the * reply of the message, whose return value is taken as the message reply. */ FlValueConverter value_converter; /** * FlKeyChannelResponderMock::channel_name: * Mocks the channel name to send the message. */ const char* channel_name; } FlKeyChannelResponderMock; G_BEGIN_DECLS #define FL_TYPE_KEY_CHANNEL_RESPONDER fl_key_channel_responder_get_type() G_DECLARE_FINAL_TYPE(FlKeyChannelResponder, fl_key_channel_responder, FL, KEY_CHANNEL_RESPONDER, GObject); /** * FlKeyChannelResponder: * * A #FlKeyResponder that handles events by sending the raw event data * in JSON through the message channel. * * This class communicates with the RawKeyboard API in the framework. */ /** * fl_key_channel_responder_new: * @messenger: the messenger that the message channel should be built on. * @mock: options to mock several functionalities. Only used in unittests. * * Creates a new #FlKeyChannelResponder. * * Returns: a new #FlKeyChannelResponder. */ FlKeyChannelResponder* fl_key_channel_responder_new( FlBinaryMessenger* messenger, FlKeyChannelResponderMock* mock = nullptr); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_CHANNEL_RESPONDER_H_
engine/shell/platform/linux/fl_key_channel_responder.h/0
{ "file_path": "engine/shell/platform/linux/fl_key_channel_responder.h", "repo_id": "engine", "token_count": 830 }
358
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/public/flutter_linux/fl_message_codec.h" #include "gtest/gtest.h" G_DECLARE_FINAL_TYPE(FlTestCodec, fl_test_codec, FL, TEST_CODEC, FlMessageCodec) // Implement the FlMessageCodec API for the following tests to check it works as // expected. struct _FlTestCodec { FlMessageCodec parent_instance; }; G_DEFINE_TYPE(FlTestCodec, fl_test_codec, fl_message_codec_get_type()) // Implements FlMessageCodec::encode_message. static GBytes* fl_test_codec_encode_message(FlMessageCodec* codec, FlValue* value, GError** error) { EXPECT_TRUE(FL_IS_TEST_CODEC(codec)); if (fl_value_get_type(value) == FL_VALUE_TYPE_INT) { char c = '0' + fl_value_get_int(value); return g_bytes_new(&c, 1); } else { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "ERROR"); return nullptr; } } // Implements FlMessageCodec::decode_message. static FlValue* fl_test_codec_decode_message(FlMessageCodec* codec, GBytes* message, GError** error) { EXPECT_TRUE(FL_IS_TEST_CODEC(codec)); size_t data_length; const uint8_t* data = static_cast<const uint8_t*>(g_bytes_get_data(message, &data_length)); if (data_length < 1) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA, "No data"); return FALSE; } if (data_length > 1) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA, "FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA"); return FALSE; } return fl_value_new_int(data[0] - '0'); } static void fl_test_codec_class_init(FlTestCodecClass* klass) { FL_MESSAGE_CODEC_CLASS(klass)->encode_message = fl_test_codec_encode_message; FL_MESSAGE_CODEC_CLASS(klass)->decode_message = fl_test_codec_decode_message; } static void fl_test_codec_init(FlTestCodec* self) {} static FlTestCodec* fl_test_codec_new() { return FL_TEST_CODEC(g_object_new(fl_test_codec_get_type(), nullptr)); } TEST(FlMessageCodecTest, EncodeMessage) { g_autoptr(FlTestCodec) codec = fl_test_codec_new(); g_autoptr(FlValue) value = fl_value_new_int(1); g_autoptr(GError) error = nullptr; g_autoptr(GBytes) message = fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, &error); EXPECT_NE(message, nullptr); EXPECT_EQ(error, nullptr); EXPECT_EQ(g_bytes_get_size(message), static_cast<gsize>(1)); EXPECT_EQ(static_cast<const uint8_t*>(g_bytes_get_data(message, nullptr))[0], '1'); } TEST(FlMessageCodecTest, EncodeMessageError) { g_autoptr(FlTestCodec) codec = fl_test_codec_new(); g_autoptr(FlValue) value = fl_value_new_null(); g_autoptr(GError) error = nullptr; g_autoptr(GBytes) message = fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, &error); EXPECT_EQ(message, nullptr); EXPECT_TRUE(g_error_matches(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED)); } TEST(FlMessageCodecTest, DecodeMessageEmpty) { g_autoptr(FlTestCodec) codec = fl_test_codec_new(); g_autoptr(GBytes) message = g_bytes_new(nullptr, 0); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) value = fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), message, &error); EXPECT_EQ(value, nullptr); EXPECT_TRUE(g_error_matches(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA)); } TEST(FlMessageCodecTest, DecodeMessage) { g_autoptr(FlTestCodec) codec = fl_test_codec_new(); uint8_t data[] = {'1'}; g_autoptr(GBytes) message = g_bytes_new(data, 1); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) value = fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), message, &error); EXPECT_NE(value, nullptr); EXPECT_EQ(error, nullptr); ASSERT_TRUE(fl_value_get_type(value) == FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), 1); } TEST(FlMessageCodecTest, DecodeMessageExtraData) { g_autoptr(FlTestCodec) codec = fl_test_codec_new(); uint8_t data[] = {'1', '2'}; g_autoptr(GBytes) message = g_bytes_new(data, 2); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) value = fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), message, &error); EXPECT_EQ(value, nullptr); EXPECT_TRUE(g_error_matches(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA)); }
engine/shell/platform/linux/fl_message_codec_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_message_codec_test.cc", "repo_id": "engine", "token_count": 2247 }
359
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_platform_plugin.h" #include <gtk/gtk.h> #include <cstring> #include "flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h" static constexpr char kChannelName[] = "flutter/platform"; static constexpr char kBadArgumentsError[] = "Bad Arguments"; static constexpr char kUnknownClipboardFormatError[] = "Unknown Clipboard Format"; static constexpr char kInProgressError[] = "In Progress"; static constexpr char kGetClipboardDataMethod[] = "Clipboard.getData"; static constexpr char kSetClipboardDataMethod[] = "Clipboard.setData"; static constexpr char kClipboardHasStringsMethod[] = "Clipboard.hasStrings"; static constexpr char kExitApplicationMethod[] = "System.exitApplication"; static constexpr char kRequestAppExitMethod[] = "System.requestAppExit"; static constexpr char kInitializationCompleteMethod[] = "System.initializationComplete"; static constexpr char kPlaySoundMethod[] = "SystemSound.play"; static constexpr char kSystemNavigatorPopMethod[] = "SystemNavigator.pop"; static constexpr char kTextKey[] = "text"; static constexpr char kValueKey[] = "value"; static constexpr char kExitTypeKey[] = "type"; static constexpr char kExitTypeCancelable[] = "cancelable"; static constexpr char kExitTypeRequired[] = "required"; static constexpr char kExitResponseKey[] = "response"; static constexpr char kExitResponseCancel[] = "cancel"; static constexpr char kExitResponseExit[] = "exit"; static constexpr char kTextPlainFormat[] = "text/plain"; static constexpr char kSoundTypeAlert[] = "SystemSoundType.alert"; static constexpr char kSoundTypeClick[] = "SystemSoundType.click"; struct _FlPlatformPlugin { GObject parent_instance; FlMethodChannel* channel; FlMethodCall* exit_application_method_call; GCancellable* cancellable; bool app_initialization_complete; }; G_DEFINE_TYPE(FlPlatformPlugin, fl_platform_plugin, G_TYPE_OBJECT) // Sends the method call response to Flutter. static void send_response(FlMethodCall* method_call, FlMethodResponse* response) { g_autoptr(GError) error = nullptr; if (!fl_method_call_respond(method_call, response, &error)) { g_warning("Failed to send method call response: %s", error->message); } } // Called when clipboard text received. static void clipboard_text_cb(GtkClipboard* clipboard, const gchar* text, gpointer user_data) { g_autoptr(FlMethodCall) method_call = FL_METHOD_CALL(user_data); g_autoptr(FlValue) result = nullptr; if (text != nullptr) { result = fl_value_new_map(); fl_value_set_string_take(result, kTextKey, fl_value_new_string(text)); } g_autoptr(FlMethodResponse) response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); send_response(method_call, response); } // Called when clipboard text received during has_strings. static void clipboard_text_has_strings_cb(GtkClipboard* clipboard, const gchar* text, gpointer user_data) { g_autoptr(FlMethodCall) method_call = FL_METHOD_CALL(user_data); g_autoptr(FlValue) result = fl_value_new_map(); fl_value_set_string_take( result, kValueKey, fl_value_new_bool(text != nullptr && strlen(text) > 0)); g_autoptr(FlMethodResponse) response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); send_response(method_call, response); } // Called when Flutter wants to copy to the clipboard. static FlMethodResponse* clipboard_set_data(FlPlatformPlugin* self, FlValue* args) { if (fl_value_get_type(args) != FL_VALUE_TYPE_MAP) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Argument map missing or malformed", nullptr)); } FlValue* text_value = fl_value_lookup_string(args, kTextKey); if (text_value == nullptr || fl_value_get_type(text_value) != FL_VALUE_TYPE_STRING) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Missing clipboard text", nullptr)); } GtkClipboard* clipboard = gtk_clipboard_get_default(gdk_display_get_default()); gtk_clipboard_set_text(clipboard, fl_value_get_string(text_value), -1); return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Called when Flutter wants to paste from the clipboard. static FlMethodResponse* clipboard_get_data_async(FlPlatformPlugin* self, FlMethodCall* method_call) { FlValue* args = fl_method_call_get_args(method_call); if (fl_value_get_type(args) != FL_VALUE_TYPE_STRING) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Expected string", nullptr)); } const gchar* format = fl_value_get_string(args); if (strcmp(format, kTextPlainFormat) != 0) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kUnknownClipboardFormatError, "GTK clipboard API only supports text", nullptr)); } GtkClipboard* clipboard = gtk_clipboard_get_default(gdk_display_get_default()); gtk_clipboard_request_text(clipboard, clipboard_text_cb, g_object_ref(method_call)); // Will respond later. return nullptr; } // Called when Flutter wants to know if the content of the clipboard is able to // be pasted, without actually accessing the clipboard content itself. static FlMethodResponse* clipboard_has_strings_async( FlPlatformPlugin* self, FlMethodCall* method_call) { GtkClipboard* clipboard = gtk_clipboard_get_default(gdk_display_get_default()); gtk_clipboard_request_text(clipboard, clipboard_text_has_strings_cb, g_object_ref(method_call)); // Will respond later. return nullptr; } // Get the exit response from a System.requestAppExit method call. static gchar* get_exit_response(FlMethodResponse* response) { if (response == nullptr) { return nullptr; } g_autoptr(GError) error = nullptr; FlValue* result = fl_method_response_get_result(response, &error); if (result == nullptr) { g_warning("Error returned from System.requestAppExit: %s", error->message); return nullptr; } if (fl_value_get_type(result) != FL_VALUE_TYPE_MAP) { g_warning("System.requestAppExit result argument map missing or malformed"); return nullptr; } FlValue* response_value = fl_value_lookup_string(result, kExitResponseKey); if (fl_value_get_type(response_value) != FL_VALUE_TYPE_STRING) { g_warning("Invalid response from System.requestAppExit"); return nullptr; } return g_strdup(fl_value_get_string(response_value)); } // Quit this application static void quit_application() { GApplication* app = g_application_get_default(); if (app == nullptr) { // Unable to gracefully quit, so just exit the process. exit(0); } // GtkApplication windows contain a reference back to the application. // Break them so the application object can cleanup. // See https://gitlab.gnome.org/GNOME/gtk/-/issues/6190 if (GTK_IS_APPLICATION(app)) { GList* windows = gtk_application_get_windows(GTK_APPLICATION(app)); for (GList* link = windows; link != NULL; link = link->next) { GtkWidget* window = GTK_WIDGET(link->data); gtk_window_set_application(GTK_WINDOW(window), NULL); } } g_application_quit(app); } // Handle response of System.requestAppExit. static void request_app_exit_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { FlPlatformPlugin* self = FL_PLATFORM_PLUGIN(user_data); g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) method_response = fl_method_channel_invoke_method_finish(FL_METHOD_CHANNEL(object), result, &error); g_autofree gchar* exit_response = nullptr; if (method_response == nullptr) { if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { return; } g_warning("Failed to complete System.requestAppExit: %s", error->message); } else { exit_response = get_exit_response(method_response); } // If something went wrong, then just exit. if (exit_response == nullptr) { exit_response = g_strdup(kExitResponseExit); } if (g_str_equal(exit_response, kExitResponseExit)) { quit_application(); } else if (g_str_equal(exit_response, kExitResponseCancel)) { // Canceled - no action to take. } // If request was due to a request from Flutter, pass result back. if (self->exit_application_method_call != nullptr) { g_autoptr(FlValue) exit_result = fl_value_new_map(); fl_value_set_string_take(exit_result, kExitResponseKey, fl_value_new_string(exit_response)); g_autoptr(FlMethodResponse) exit_response = FL_METHOD_RESPONSE(fl_method_success_response_new(exit_result)); if (!fl_method_call_respond(self->exit_application_method_call, exit_response, &error)) { g_warning("Failed to send response to System.exitApplication: %s", error->message); } g_clear_object(&self->exit_application_method_call); } } // Send a request to Flutter to exit the application, but only if it's ready for // a request. static void request_app_exit(FlPlatformPlugin* self, const char* type) { g_autoptr(FlValue) args = fl_value_new_map(); if (!self->app_initialization_complete || g_str_equal(type, kExitTypeRequired)) { quit_application(); return; } fl_value_set_string_take(args, kExitTypeKey, fl_value_new_string(type)); fl_method_channel_invoke_method(self->channel, kRequestAppExitMethod, args, self->cancellable, request_app_exit_response_cb, self); } // Called when the Dart app has finished initialization and is ready to handle // requests. For the Flutter framework, this means after the ServicesBinding has // been initialized and it sends a System.initializationComplete message. static FlMethodResponse* system_intitialization_complete( FlPlatformPlugin* self, FlMethodCall* method_call) { self->app_initialization_complete = TRUE; return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Called when Flutter wants to exit the application. static FlMethodResponse* system_exit_application(FlPlatformPlugin* self, FlMethodCall* method_call) { FlValue* args = fl_method_call_get_args(method_call); if (fl_value_get_type(args) != FL_VALUE_TYPE_MAP) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Argument map missing or malformed", nullptr)); } FlValue* type_value = fl_value_lookup_string(args, kExitTypeKey); if (type_value == nullptr || fl_value_get_type(type_value) != FL_VALUE_TYPE_STRING) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Missing type argument", nullptr)); } const char* type = fl_value_get_string(type_value); // Save method call to respond to when our request to Flutter completes. if (self->exit_application_method_call != nullptr) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kInProgressError, "Request already in progress", nullptr)); } self->exit_application_method_call = FL_METHOD_CALL(g_object_ref(method_call)); // Requested to immediately quit if the app hasn't yet signaled that it is // ready to handle requests, or if the type of exit requested is "required". if (!self->app_initialization_complete || g_str_equal(type, kExitTypeRequired)) { quit_application(); g_autoptr(FlValue) exit_result = fl_value_new_map(); fl_value_set_string_take(exit_result, kExitResponseKey, fl_value_new_string(kExitResponseExit)); return FL_METHOD_RESPONSE(fl_method_success_response_new(exit_result)); } // Send the request back to Flutter to follow the standard process. request_app_exit(self, type); // Will respond later. return nullptr; } // Called when Flutter wants to play a sound. static FlMethodResponse* system_sound_play(FlPlatformPlugin* self, FlValue* args) { if (fl_value_get_type(args) != FL_VALUE_TYPE_STRING) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Expected string", nullptr)); } const gchar* type = fl_value_get_string(args); if (strcmp(type, kSoundTypeAlert) == 0) { GdkDisplay* display = gdk_display_get_default(); if (display != nullptr) { gdk_display_beep(display); } } else if (strcmp(type, kSoundTypeClick) == 0) { // We don't make sounds for keyboard on desktops. } else { g_warning("Ignoring unknown sound type %s in SystemSound.play.\n", type); } return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Called when Flutter wants to quit the application. static FlMethodResponse* system_navigator_pop(FlPlatformPlugin* self) { quit_application(); return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Called when a method call is received from Flutter. static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { FlPlatformPlugin* self = FL_PLATFORM_PLUGIN(user_data); const gchar* method = fl_method_call_get_name(method_call); FlValue* args = fl_method_call_get_args(method_call); g_autoptr(FlMethodResponse) response = nullptr; if (strcmp(method, kSetClipboardDataMethod) == 0) { response = clipboard_set_data(self, args); } else if (strcmp(method, kGetClipboardDataMethod) == 0) { response = clipboard_get_data_async(self, method_call); } else if (strcmp(method, kClipboardHasStringsMethod) == 0) { response = clipboard_has_strings_async(self, method_call); } else if (strcmp(method, kExitApplicationMethod) == 0) { response = system_exit_application(self, method_call); } else if (strcmp(method, kInitializationCompleteMethod) == 0) { response = system_intitialization_complete(self, method_call); } else if (strcmp(method, kPlaySoundMethod) == 0) { response = system_sound_play(self, args); } else if (strcmp(method, kSystemNavigatorPopMethod) == 0) { response = system_navigator_pop(self); } else { response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); } if (response != nullptr) { send_response(method_call, response); } } static void fl_platform_plugin_dispose(GObject* object) { FlPlatformPlugin* self = FL_PLATFORM_PLUGIN(object); g_cancellable_cancel(self->cancellable); g_clear_object(&self->channel); g_clear_object(&self->exit_application_method_call); g_clear_object(&self->cancellable); G_OBJECT_CLASS(fl_platform_plugin_parent_class)->dispose(object); } static void fl_platform_plugin_class_init(FlPlatformPluginClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_platform_plugin_dispose; } static void fl_platform_plugin_init(FlPlatformPlugin* self) { self->cancellable = g_cancellable_new(); } FlPlatformPlugin* fl_platform_plugin_new(FlBinaryMessenger* messenger) { g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr); FlPlatformPlugin* self = FL_PLATFORM_PLUGIN(g_object_new(fl_platform_plugin_get_type(), nullptr)); g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new(); self->channel = fl_method_channel_new(messenger, kChannelName, FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(self->channel, method_call_cb, self, nullptr); self->app_initialization_complete = FALSE; return self; } void fl_platform_plugin_request_app_exit(FlPlatformPlugin* self) { g_return_if_fail(FL_IS_PLATFORM_PLUGIN(self)); // Request a cancellable exit. request_app_exit(self, kExitTypeCancelable); }
engine/shell/platform/linux/fl_platform_plugin.cc/0
{ "file_path": "engine/shell/platform/linux/fl_platform_plugin.cc", "repo_id": "engine", "token_count": 6164 }
360
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_scrolling_view_delegate.h" G_DEFINE_INTERFACE(FlScrollingViewDelegate, fl_scrolling_view_delegate, G_TYPE_OBJECT) static void fl_scrolling_view_delegate_default_init( FlScrollingViewDelegateInterface* iface) {} void fl_scrolling_view_delegate_send_mouse_pointer_event( FlScrollingViewDelegate* self, FlutterPointerPhase phase, size_t timestamp, double x, double y, double scroll_delta_x, double scroll_delta_y, int64_t buttons) { g_return_if_fail(FL_IS_SCROLLING_VIEW_DELEGATE(self)); FL_SCROLLING_VIEW_DELEGATE_GET_IFACE(self)->send_mouse_pointer_event( self, phase, timestamp, x, y, scroll_delta_x, scroll_delta_y, buttons); } void fl_scrolling_view_delegate_send_pointer_pan_zoom_event( FlScrollingViewDelegate* self, size_t timestamp, double x, double y, FlutterPointerPhase phase, double pan_x, double pan_y, double scale, double rotation) { g_return_if_fail(FL_IS_SCROLLING_VIEW_DELEGATE(self)); FL_SCROLLING_VIEW_DELEGATE_GET_IFACE(self)->send_pointer_pan_zoom_event( self, timestamp, x, y, phase, pan_x, pan_y, scale, rotation); }
engine/shell/platform/linux/fl_scrolling_view_delegate.cc/0
{ "file_path": "engine/shell/platform/linux/fl_scrolling_view_delegate.cc", "repo_id": "engine", "token_count": 566 }
361
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_task_runner.h" #include "flutter/shell/platform/linux/fl_engine_private.h" static constexpr int kMicrosecondsPerNanosecond = 1000; static constexpr int kMillisecondsPerMicrosecond = 1000; struct _FlTaskRunner { GObject parent_instance; FlEngine* engine; GMutex mutex; GCond cond; guint timeout_source_id; GList /*<FlTaskRunnerTask>*/* pending_tasks; gboolean blocking_main_thread; }; typedef struct _FlTaskRunnerTask { // absolute time of task (based on g_get_monotonic_time) gint64 task_time_micros; FlutterTask task; } FlTaskRunnerTask; G_DEFINE_TYPE(FlTaskRunner, fl_task_runner, G_TYPE_OBJECT) // Removes expired tasks from the task queue and executes them. // The execution is performed with mutex unlocked. static void fl_task_runner_process_expired_tasks_locked(FlTaskRunner* self) { GList* expired_tasks = nullptr; gint64 current_time = g_get_monotonic_time(); GList* l = self->pending_tasks; while (l != nullptr) { FlTaskRunnerTask* task = static_cast<FlTaskRunnerTask*>(l->data); if (task->task_time_micros <= current_time) { GList* link = l; l = l->next; self->pending_tasks = g_list_remove_link(self->pending_tasks, link); expired_tasks = g_list_concat(expired_tasks, link); } else { l = l->next; } } g_mutex_unlock(&self->mutex); l = expired_tasks; while (l != nullptr && self->engine) { FlTaskRunnerTask* task = static_cast<FlTaskRunnerTask*>(l->data); fl_engine_execute_task(self->engine, &task->task); l = l->next; } g_list_free_full(expired_tasks, g_free); g_mutex_lock(&self->mutex); } static void fl_task_runner_tasks_did_change_locked(FlTaskRunner* self); // Invoked from a timeout source. Removes and executes expired tasks // and reschedules timeout if needed. static gboolean fl_task_runner_on_expired_timeout(gpointer data) { FlTaskRunner* self = FL_TASK_RUNNER(data); g_autoptr(GMutexLocker) locker = g_mutex_locker_new(&self->mutex); (void)locker; // unused variable g_object_ref(self); self->timeout_source_id = 0; fl_task_runner_process_expired_tasks_locked(self); // reschedule timeout fl_task_runner_tasks_did_change_locked(self); g_object_unref(self); return FALSE; } // Returns the absolute time of next expired task (in microseconds, based on // g_get_monotonic_time). If no task is scheduled returns G_MAXINT64. static gint64 fl_task_runner_next_task_expiration_time_locked( FlTaskRunner* self) { gint64 min_time = G_MAXINT64; GList* l = self->pending_tasks; while (l != nullptr) { FlTaskRunnerTask* task = static_cast<FlTaskRunnerTask*>(l->data); min_time = MIN(min_time, task->task_time_micros); l = l->next; } return min_time; } static void fl_task_runner_tasks_did_change_locked(FlTaskRunner* self) { if (self->blocking_main_thread) { // Wake up blocked thread g_cond_signal(&self->cond); } else { // Reschedule timeout if (self->timeout_source_id != 0) { g_source_remove(self->timeout_source_id); self->timeout_source_id = 0; } gint64 min_time = fl_task_runner_next_task_expiration_time_locked(self); if (min_time != G_MAXINT64) { gint64 remaining = MAX(min_time - g_get_monotonic_time(), 0); self->timeout_source_id = g_timeout_add(remaining / kMillisecondsPerMicrosecond + 1, fl_task_runner_on_expired_timeout, self); } } } static void engine_weak_notify_cb(gpointer user_data, GObject* where_the_object_was) { FlTaskRunner* self = FL_TASK_RUNNER(user_data); self->engine = nullptr; } void fl_task_runner_dispose(GObject* object) { FlTaskRunner* self = FL_TASK_RUNNER(object); // this should never happen because the task runner is retained while blocking // main thread g_assert(!self->blocking_main_thread); if (self->engine != nullptr) { g_object_weak_unref(G_OBJECT(self->engine), engine_weak_notify_cb, self); self->engine = nullptr; } g_mutex_clear(&self->mutex); g_cond_clear(&self->cond); g_list_free_full(self->pending_tasks, g_free); if (self->timeout_source_id != 0) { g_source_remove(self->timeout_source_id); } G_OBJECT_CLASS(fl_task_runner_parent_class)->dispose(object); } static void fl_task_runner_class_init(FlTaskRunnerClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_task_runner_dispose; } static void fl_task_runner_init(FlTaskRunner* self) { g_mutex_init(&self->mutex); g_cond_init(&self->cond); } FlTaskRunner* fl_task_runner_new(FlEngine* engine) { FlTaskRunner* res = FL_TASK_RUNNER(g_object_new(fl_task_runner_get_type(), nullptr)); res->engine = engine; g_object_weak_ref(G_OBJECT(engine), engine_weak_notify_cb, res); return res; } void fl_task_runner_post_task(FlTaskRunner* self, FlutterTask task, uint64_t target_time_nanos) { g_autoptr(GMutexLocker) locker = g_mutex_locker_new(&self->mutex); (void)locker; // unused variable FlTaskRunnerTask* runner_task = g_new0(FlTaskRunnerTask, 1); runner_task->task = task; runner_task->task_time_micros = target_time_nanos / kMicrosecondsPerNanosecond; self->pending_tasks = g_list_append(self->pending_tasks, runner_task); fl_task_runner_tasks_did_change_locked(self); } void fl_task_runner_block_main_thread(FlTaskRunner* self) { g_autoptr(GMutexLocker) locker = g_mutex_locker_new(&self->mutex); (void)locker; // unused variable g_return_if_fail(self->blocking_main_thread == FALSE); g_object_ref(self); self->blocking_main_thread = true; while (self->blocking_main_thread) { g_cond_wait_until(&self->cond, &self->mutex, fl_task_runner_next_task_expiration_time_locked(self)); fl_task_runner_process_expired_tasks_locked(self); } // Tasks might have changed in the meanwhile, reschedule timeout fl_task_runner_tasks_did_change_locked(self); g_object_unref(self); } void fl_task_runner_release_main_thread(FlTaskRunner* self) { g_autoptr(GMutexLocker) locker = g_mutex_locker_new(&self->mutex); (void)locker; // unused variable g_return_if_fail(self->blocking_main_thread == TRUE); self->blocking_main_thread = FALSE; g_cond_signal(&self->cond); }
engine/shell/platform/linux/fl_task_runner.cc/0
{ "file_path": "engine/shell/platform/linux/fl_task_runner.cc", "repo_id": "engine", "token_count": 2554 }
362
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/public/flutter_linux/fl_value.h" #include <gmodule.h> #include "gtest/gtest.h" TEST(FlDartProjectTest, Null) { g_autoptr(FlValue) value = fl_value_new_null(); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_NULL); } TEST(FlValueTest, NullEqual) { g_autoptr(FlValue) value1 = fl_value_new_null(); g_autoptr(FlValue) value2 = fl_value_new_null(); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, NullToString) { g_autoptr(FlValue) value = fl_value_new_null(); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "null"); } TEST(FlValueTest, BoolTrue) { g_autoptr(FlValue) value = fl_value_new_bool(TRUE); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_BOOL); EXPECT_TRUE(fl_value_get_bool(value)); } TEST(FlValueTest, BoolFalse) { g_autoptr(FlValue) value = fl_value_new_bool(FALSE); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_BOOL); EXPECT_FALSE(fl_value_get_bool(value)); } TEST(FlValueTest, BoolEqual) { g_autoptr(FlValue) value1 = fl_value_new_bool(TRUE); g_autoptr(FlValue) value2 = fl_value_new_bool(TRUE); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, BoolNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_bool(TRUE); g_autoptr(FlValue) value2 = fl_value_new_bool(FALSE); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, BoolTrueToString) { g_autoptr(FlValue) value = fl_value_new_bool(TRUE); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "true"); } TEST(FlValueTest, BoolFalseToString) { g_autoptr(FlValue) value = fl_value_new_bool(FALSE); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "false"); } TEST(FlValueTest, IntZero) { g_autoptr(FlValue) value = fl_value_new_int(0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), 0); } TEST(FlValueTest, IntOne) { g_autoptr(FlValue) value = fl_value_new_int(1); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), 1); } TEST(FlValueTest, IntMinusOne) { g_autoptr(FlValue) value = fl_value_new_int(-1); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), -1); } TEST(FlValueTest, IntMin) { g_autoptr(FlValue) value = fl_value_new_int(G_MININT64); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), G_MININT64); } TEST(FlValueTest, IntMax) { g_autoptr(FlValue) value = fl_value_new_int(G_MAXINT64); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(value), G_MAXINT64); } TEST(FlValueTest, IntEqual) { g_autoptr(FlValue) value1 = fl_value_new_int(42); g_autoptr(FlValue) value2 = fl_value_new_int(42); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, IntNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_int(42); g_autoptr(FlValue) value2 = fl_value_new_int(99); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, IntToString) { g_autoptr(FlValue) value = fl_value_new_int(42); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "42"); } TEST(FlValueTest, FloatZero) { g_autoptr(FlValue) value = fl_value_new_float(0.0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), 0.0); } TEST(FlValueTest, FloatOne) { g_autoptr(FlValue) value = fl_value_new_float(1.0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), 1.0); } TEST(FlValueTest, FloatMinusOne) { g_autoptr(FlValue) value = fl_value_new_float(-1.0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), -1.0); } TEST(FlValueTest, FloatPi) { g_autoptr(FlValue) value = fl_value_new_float(M_PI); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_float(value), M_PI); } TEST(FlValueTest, FloatEqual) { g_autoptr(FlValue) value1 = fl_value_new_float(M_PI); g_autoptr(FlValue) value2 = fl_value_new_float(M_PI); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, FloatNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_float(M_PI); g_autoptr(FlValue) value2 = fl_value_new_float(M_E); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, FloatToString) { g_autoptr(FlValue) value = fl_value_new_float(M_PI); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "3.1415926535897931"); } TEST(FlValueTest, String) { g_autoptr(FlValue) value = fl_value_new_string("hello"); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "hello"); } TEST(FlValueTest, StringEmpty) { g_autoptr(FlValue) value = fl_value_new_string(""); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), ""); } TEST(FlValueTest, StringSized) { g_autoptr(FlValue) value = fl_value_new_string_sized("hello", 2); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), "he"); } TEST(FlValueTest, StringSizedNullptr) { g_autoptr(FlValue) value = fl_value_new_string_sized(nullptr, 0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), ""); } TEST(FlValueTest, StringSizedZeroLength) { g_autoptr(FlValue) value = fl_value_new_string_sized("hello", 0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(value), ""); } TEST(FlValueTest, StringEqual) { g_autoptr(FlValue) value1 = fl_value_new_string("hello"); g_autoptr(FlValue) value2 = fl_value_new_string("hello"); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, StringNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_string("hello"); g_autoptr(FlValue) value2 = fl_value_new_string("world"); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, StringToString) { g_autoptr(FlValue) value = fl_value_new_string("hello"); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "hello"); } TEST(FlValueTest, Uint8List) { uint8_t data[] = {0x00, 0x01, 0xFE, 0xFF}; g_autoptr(FlValue) value = fl_value_new_uint8_list(data, 4); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_UINT8_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(4)); EXPECT_EQ(fl_value_get_uint8_list(value)[0], 0x00); EXPECT_EQ(fl_value_get_uint8_list(value)[1], 0x01); EXPECT_EQ(fl_value_get_uint8_list(value)[2], 0xFE); EXPECT_EQ(fl_value_get_uint8_list(value)[3], 0xFF); } TEST(FlValueTest, Uint8ListNullptr) { g_autoptr(FlValue) value = fl_value_new_uint8_list(nullptr, 0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_UINT8_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlValueTest, Uint8ListEqual) { uint8_t data1[] = {1, 2, 3}; g_autoptr(FlValue) value1 = fl_value_new_uint8_list(data1, 3); uint8_t data2[] = {1, 2, 3}; g_autoptr(FlValue) value2 = fl_value_new_uint8_list(data2, 3); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Uint8ListEmptyEqual) { g_autoptr(FlValue) value1 = fl_value_new_uint8_list(nullptr, 0); g_autoptr(FlValue) value2 = fl_value_new_uint8_list(nullptr, 0); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Uint8ListNotEqualSameSize) { uint8_t data1[] = {1, 2, 3}; g_autoptr(FlValue) value1 = fl_value_new_uint8_list(data1, 3); uint8_t data2[] = {1, 2, 4}; g_autoptr(FlValue) value2 = fl_value_new_uint8_list(data2, 3); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Uint8ListNotEqualDifferentSize) { uint8_t data1[] = {1, 2, 3}; g_autoptr(FlValue) value1 = fl_value_new_uint8_list(data1, 3); uint8_t data2[] = {1, 2, 3, 4}; g_autoptr(FlValue) value2 = fl_value_new_uint8_list(data2, 4); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Uint8ListEmptyNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_uint8_list(nullptr, 0); uint8_t data[] = {1, 2, 3}; g_autoptr(FlValue) value2 = fl_value_new_uint8_list(data, 3); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Uint8ListToString) { uint8_t data[] = {0x00, 0x01, 0xFE, 0xFF}; g_autoptr(FlValue) value = fl_value_new_uint8_list(data, 4); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "[0, 1, 254, 255]"); } TEST(FlValueTest, Int32List) { int32_t data[] = {0, -1, G_MAXINT32, G_MININT32}; g_autoptr(FlValue) value = fl_value_new_int32_list(data, 4); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT32_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(4)); EXPECT_EQ(fl_value_get_int32_list(value)[0], 0); EXPECT_EQ(fl_value_get_int32_list(value)[1], -1); EXPECT_EQ(fl_value_get_int32_list(value)[2], G_MAXINT32); EXPECT_EQ(fl_value_get_int32_list(value)[3], G_MININT32); } TEST(FlValueTest, Int32ListNullptr) { g_autoptr(FlValue) value = fl_value_new_int32_list(nullptr, 0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT32_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlValueTest, Int32ListEqual) { int32_t data1[] = {0, G_MAXINT32, G_MININT32}; g_autoptr(FlValue) value1 = fl_value_new_int32_list(data1, 3); int32_t data2[] = {0, G_MAXINT32, G_MININT32}; g_autoptr(FlValue) value2 = fl_value_new_int32_list(data2, 3); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int32ListEmptyEqual) { g_autoptr(FlValue) value1 = fl_value_new_int32_list(nullptr, 0); g_autoptr(FlValue) value2 = fl_value_new_int32_list(nullptr, 0); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int32ListNotEqualSameSize) { int32_t data1[] = {0, G_MAXINT32, G_MININT32}; g_autoptr(FlValue) value1 = fl_value_new_int32_list(data1, 3); int32_t data2[] = {0, G_MININT32, G_MAXINT32}; g_autoptr(FlValue) value2 = fl_value_new_int32_list(data2, 3); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int32ListNotEqualDifferentSize) { int32_t data1[] = {0, G_MAXINT32, G_MININT32}; g_autoptr(FlValue) value1 = fl_value_new_int32_list(data1, 3); int32_t data2[] = {0, G_MAXINT32, G_MININT32, -1}; g_autoptr(FlValue) value2 = fl_value_new_int32_list(data2, 4); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int32ListEmptyNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_int32_list(nullptr, 0); int32_t data[] = {0, G_MAXINT32, G_MININT32}; g_autoptr(FlValue) value2 = fl_value_new_int32_list(data, 3); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int32ListToString) { int32_t data[] = {0, G_MAXINT32, G_MININT32}; g_autoptr(FlValue) value = fl_value_new_int32_list(data, 3); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "[0, 2147483647, -2147483648]"); } TEST(FlValueTest, Int64List) { int64_t data[] = {0, -1, G_MAXINT64, G_MININT64}; g_autoptr(FlValue) value = fl_value_new_int64_list(data, 4); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT64_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(4)); EXPECT_EQ(fl_value_get_int64_list(value)[0], 0); EXPECT_EQ(fl_value_get_int64_list(value)[1], -1); EXPECT_EQ(fl_value_get_int64_list(value)[2], G_MAXINT64); EXPECT_EQ(fl_value_get_int64_list(value)[3], G_MININT64); } TEST(FlValueTest, Int64ListNullptr) { g_autoptr(FlValue) value = fl_value_new_int64_list(nullptr, 0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT64_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlValueTest, Int64ListEqual) { int64_t data1[] = {0, G_MAXINT64, G_MININT64}; g_autoptr(FlValue) value1 = fl_value_new_int64_list(data1, 3); int64_t data2[] = {0, G_MAXINT64, G_MININT64}; g_autoptr(FlValue) value2 = fl_value_new_int64_list(data2, 3); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int64ListEmptyEqual) { g_autoptr(FlValue) value1 = fl_value_new_int64_list(nullptr, 0); g_autoptr(FlValue) value2 = fl_value_new_int64_list(nullptr, 0); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int64ListNotEqualSameSize) { int64_t data1[] = {0, G_MAXINT64, G_MININT64}; g_autoptr(FlValue) value1 = fl_value_new_int64_list(data1, 3); int64_t data2[] = {0, G_MININT64, G_MAXINT64}; g_autoptr(FlValue) value2 = fl_value_new_int64_list(data2, 3); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int64ListNotEqualDifferentSize) { int64_t data1[] = {0, G_MAXINT64, G_MININT64}; g_autoptr(FlValue) value1 = fl_value_new_int64_list(data1, 3); int64_t data2[] = {0, G_MAXINT64, G_MININT64, -1}; g_autoptr(FlValue) value2 = fl_value_new_int64_list(data2, 4); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int64ListEmptyNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_int64_list(nullptr, 0); int64_t data[] = {0, G_MAXINT64, G_MININT64}; g_autoptr(FlValue) value2 = fl_value_new_int64_list(data, 3); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int64ListToString) { int64_t data[] = {0, G_MAXINT64, G_MININT64}; g_autoptr(FlValue) value = fl_value_new_int64_list(data, 3); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "[0, 9223372036854775807, -9223372036854775808]"); } TEST(FlValueTest, FloatList) { double data[] = {0.0, -1.0, M_PI}; g_autoptr(FlValue) value = fl_value_new_float_list(data, 3); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(3)); EXPECT_EQ(fl_value_get_float_list(value)[0], 0); EXPECT_EQ(fl_value_get_float_list(value)[1], -1.0); EXPECT_EQ(fl_value_get_float_list(value)[2], M_PI); } TEST(FlValueTest, FloatListNullptr) { g_autoptr(FlValue) value = fl_value_new_float_list(nullptr, 0); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlValueTest, FloatListEqual) { double data1[] = {0, -0.5, M_PI}; g_autoptr(FlValue) value1 = fl_value_new_float_list(data1, 3); double data2[] = {0, -0.5, M_PI}; g_autoptr(FlValue) value2 = fl_value_new_float_list(data2, 3); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, FloatListEmptyEqual) { g_autoptr(FlValue) value1 = fl_value_new_float_list(nullptr, 0); g_autoptr(FlValue) value2 = fl_value_new_float_list(nullptr, 0); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, FloatListNotEqualSameSize) { double data1[] = {0, -0.5, M_PI}; g_autoptr(FlValue) value1 = fl_value_new_float_list(data1, 3); double data2[] = {0, -0.5, M_E}; g_autoptr(FlValue) value2 = fl_value_new_float_list(data2, 3); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, FloatListNotEqualDifferentSize) { double data1[] = {0, -0.5, M_PI}; g_autoptr(FlValue) value1 = fl_value_new_float_list(data1, 3); double data2[] = {0, -0.5, M_PI, 42}; g_autoptr(FlValue) value2 = fl_value_new_float_list(data2, 4); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, FloatListEmptyNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_float_list(nullptr, 0); double data[] = {0, -0.5, M_PI}; g_autoptr(FlValue) value2 = fl_value_new_float_list(data, 3); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, FloatListToString) { double data[] = {0, -0.5, M_PI}; g_autoptr(FlValue) value = fl_value_new_float_list(data, 3); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "[0.0, -0.5, 3.1415926535897931]"); } TEST(FlValueTest, ListEmpty) { g_autoptr(FlValue) value = fl_value_new_list(); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlValueTest, ListAdd) { g_autoptr(FlValue) value = fl_value_new_list(); g_autoptr(FlValue) child = fl_value_new_null(); fl_value_append(value, child); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(1)); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 0)), FL_VALUE_TYPE_NULL); } TEST(FlValueTest, ListAddTake) { g_autoptr(FlValue) value = fl_value_new_list(); fl_value_append_take(value, fl_value_new_null()); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(1)); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 0)), FL_VALUE_TYPE_NULL); } TEST(FlValueTest, ListChildTypes) { g_autoptr(FlValue) value = fl_value_new_list(); fl_value_append_take(value, fl_value_new_null()); fl_value_append_take(value, fl_value_new_bool(TRUE)); fl_value_append_take(value, fl_value_new_int(42)); fl_value_append_take(value, fl_value_new_float(M_PI)); fl_value_append_take(value, fl_value_new_uint8_list(nullptr, 0)); fl_value_append_take(value, fl_value_new_int32_list(nullptr, 0)); fl_value_append_take(value, fl_value_new_int64_list(nullptr, 0)); fl_value_append_take(value, fl_value_new_float_list(nullptr, 0)); fl_value_append_take(value, fl_value_new_list()); fl_value_append_take(value, fl_value_new_map()); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(10)); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 0)), FL_VALUE_TYPE_NULL); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 1)), FL_VALUE_TYPE_BOOL); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 2)), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 3)), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 4)), FL_VALUE_TYPE_UINT8_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 5)), FL_VALUE_TYPE_INT32_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 6)), FL_VALUE_TYPE_INT64_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 7)), FL_VALUE_TYPE_FLOAT_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 8)), FL_VALUE_TYPE_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_list_value(value, 9)), FL_VALUE_TYPE_MAP); } TEST(FlValueTest, ListStrv) { g_auto(GStrv) words = g_strsplit("hello:world", ":", -1); g_autoptr(FlValue) value = fl_value_new_list_from_strv(words); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(2)); ASSERT_EQ(fl_value_get_type(fl_value_get_list_value(value, 0)), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(fl_value_get_list_value(value, 0)), "hello"); ASSERT_EQ(fl_value_get_type(fl_value_get_list_value(value, 1)), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(fl_value_get_list_value(value, 1)), "world"); } TEST(FlValueTest, ListStrvEmpty) { g_auto(GStrv) words = g_strsplit("", ":", -1); g_autoptr(FlValue) value = fl_value_new_list_from_strv(words); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlValueTest, ListEqual) { g_autoptr(FlValue) value1 = fl_value_new_list(); fl_value_append_take(value1, fl_value_new_int(1)); fl_value_append_take(value1, fl_value_new_int(2)); fl_value_append_take(value1, fl_value_new_int(3)); g_autoptr(FlValue) value2 = fl_value_new_list(); fl_value_append_take(value2, fl_value_new_int(1)); fl_value_append_take(value2, fl_value_new_int(2)); fl_value_append_take(value2, fl_value_new_int(3)); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, ListEmptyEqual) { g_autoptr(FlValue) value1 = fl_value_new_list(); g_autoptr(FlValue) value2 = fl_value_new_list(); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, ListNotEqualSameSize) { g_autoptr(FlValue) value1 = fl_value_new_list(); fl_value_append_take(value1, fl_value_new_int(1)); fl_value_append_take(value1, fl_value_new_int(2)); fl_value_append_take(value1, fl_value_new_int(3)); g_autoptr(FlValue) value2 = fl_value_new_list(); fl_value_append_take(value2, fl_value_new_int(1)); fl_value_append_take(value2, fl_value_new_int(2)); fl_value_append_take(value2, fl_value_new_int(4)); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, ListNotEqualDifferentSize) { g_autoptr(FlValue) value1 = fl_value_new_list(); fl_value_append_take(value1, fl_value_new_int(1)); fl_value_append_take(value1, fl_value_new_int(2)); fl_value_append_take(value1, fl_value_new_int(3)); g_autoptr(FlValue) value2 = fl_value_new_list(); fl_value_append_take(value2, fl_value_new_int(1)); fl_value_append_take(value2, fl_value_new_int(2)); fl_value_append_take(value2, fl_value_new_int(3)); fl_value_append_take(value2, fl_value_new_int(4)); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, ListEmptyNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_list(); g_autoptr(FlValue) value2 = fl_value_new_list(); fl_value_append_take(value2, fl_value_new_int(1)); fl_value_append_take(value2, fl_value_new_int(2)); fl_value_append_take(value2, fl_value_new_int(3)); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, ListToString) { g_autoptr(FlValue) value = fl_value_new_list(); fl_value_append_take(value, fl_value_new_null()); fl_value_append_take(value, fl_value_new_bool(TRUE)); fl_value_append_take(value, fl_value_new_int(42)); fl_value_append_take(value, fl_value_new_float(M_PI)); fl_value_append_take(value, fl_value_new_uint8_list(nullptr, 0)); fl_value_append_take(value, fl_value_new_int32_list(nullptr, 0)); fl_value_append_take(value, fl_value_new_int64_list(nullptr, 0)); fl_value_append_take(value, fl_value_new_float_list(nullptr, 0)); fl_value_append_take(value, fl_value_new_list()); fl_value_append_take(value, fl_value_new_map()); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "[null, true, 42, 3.1415926535897931, [], [], [], [], [], {}]"); } TEST(FlValueTest, MapEmpty) { g_autoptr(FlValue) value = fl_value_new_map(); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(0)); } TEST(FlValueTest, MapSet) { g_autoptr(FlValue) value = fl_value_new_map(); g_autoptr(FlValue) k = fl_value_new_string("count"); g_autoptr(FlValue) v = fl_value_new_int(42); fl_value_set(value, k, v); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(1)); ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 0)), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 0)), "count"); ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 0)), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(fl_value_get_map_value(value, 0)), 42); } TEST(FlValueTest, MapSetTake) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_string("count"), fl_value_new_int(42)); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(1)); ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 0)), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 0)), "count"); ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 0)), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(fl_value_get_map_value(value, 0)), 42); } TEST(FlValueTest, MapSetString) { g_autoptr(FlValue) value = fl_value_new_map(); g_autoptr(FlValue) v = fl_value_new_int(42); fl_value_set_string(value, "count", v); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(1)); ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 0)), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 0)), "count"); ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 0)), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(fl_value_get_map_value(value, 0)), 42); } TEST(FlValueTest, MapSetStringTake) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_string_take(value, "count", fl_value_new_int(42)); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(1)); ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 0)), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 0)), "count"); ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 0)), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(fl_value_get_map_value(value, 0)), 42); } TEST(FlValueTest, MapLookup) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_string_take(value, "one", fl_value_new_int(1)); fl_value_set_string_take(value, "two", fl_value_new_int(2)); fl_value_set_string_take(value, "three", fl_value_new_int(3)); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP); g_autoptr(FlValue) two_key = fl_value_new_string("two"); FlValue* v = fl_value_lookup(value, two_key); ASSERT_NE(v, nullptr); ASSERT_EQ(fl_value_get_type(v), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(v), 2); g_autoptr(FlValue) four_key = fl_value_new_string("four"); v = fl_value_lookup(value, four_key); ASSERT_EQ(v, nullptr); } TEST(FlValueTest, MapLookupString) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_string_take(value, "one", fl_value_new_int(1)); fl_value_set_string_take(value, "two", fl_value_new_int(2)); fl_value_set_string_take(value, "three", fl_value_new_int(3)); FlValue* v = fl_value_lookup_string(value, "two"); ASSERT_NE(v, nullptr); ASSERT_EQ(fl_value_get_type(v), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(v), 2); v = fl_value_lookup_string(value, "four"); ASSERT_EQ(v, nullptr); } TEST(FlValueTest, MapValueypes) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_string("null"), fl_value_new_null()); fl_value_set_take(value, fl_value_new_string("bool"), fl_value_new_bool(TRUE)); fl_value_set_take(value, fl_value_new_string("int"), fl_value_new_int(42)); fl_value_set_take(value, fl_value_new_string("float"), fl_value_new_float(M_PI)); fl_value_set_take(value, fl_value_new_string("uint8_list"), fl_value_new_uint8_list(nullptr, 0)); fl_value_set_take(value, fl_value_new_string("int32_list"), fl_value_new_int32_list(nullptr, 0)); fl_value_set_take(value, fl_value_new_string("int64_list"), fl_value_new_int64_list(nullptr, 0)); fl_value_set_take(value, fl_value_new_string("float_list"), fl_value_new_float_list(nullptr, 0)); fl_value_set_take(value, fl_value_new_string("list"), fl_value_new_list()); fl_value_set_take(value, fl_value_new_string("map"), fl_value_new_map()); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(10)); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 0)), FL_VALUE_TYPE_NULL); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 1)), FL_VALUE_TYPE_BOOL); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 2)), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 3)), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 4)), FL_VALUE_TYPE_UINT8_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 5)), FL_VALUE_TYPE_INT32_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 6)), FL_VALUE_TYPE_INT64_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 7)), FL_VALUE_TYPE_FLOAT_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 8)), FL_VALUE_TYPE_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_value(value, 9)), FL_VALUE_TYPE_MAP); } TEST(FlValueTest, MapKeyTypes) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_null(), fl_value_new_string("null")); fl_value_set_take(value, fl_value_new_bool(TRUE), fl_value_new_string("bool")); fl_value_set_take(value, fl_value_new_int(42), fl_value_new_string("int")); fl_value_set_take(value, fl_value_new_float(M_PI), fl_value_new_string("float")); fl_value_set_take(value, fl_value_new_uint8_list(nullptr, 0), fl_value_new_string("uint8_list")); fl_value_set_take(value, fl_value_new_int32_list(nullptr, 0), fl_value_new_string("int32_list")); fl_value_set_take(value, fl_value_new_int64_list(nullptr, 0), fl_value_new_string("int64_list")); fl_value_set_take(value, fl_value_new_float_list(nullptr, 0), fl_value_new_string("float_list")); fl_value_set_take(value, fl_value_new_list(), fl_value_new_string("list")); fl_value_set_take(value, fl_value_new_map(), fl_value_new_string("map")); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP); ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(10)); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 0)), FL_VALUE_TYPE_NULL); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 1)), FL_VALUE_TYPE_BOOL); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 2)), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 3)), FL_VALUE_TYPE_FLOAT); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 4)), FL_VALUE_TYPE_UINT8_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 5)), FL_VALUE_TYPE_INT32_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 6)), FL_VALUE_TYPE_INT64_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 7)), FL_VALUE_TYPE_FLOAT_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 8)), FL_VALUE_TYPE_LIST); EXPECT_EQ(fl_value_get_type(fl_value_get_map_key(value, 9)), FL_VALUE_TYPE_MAP); } TEST(FlValueTest, MapEqual) { g_autoptr(FlValue) value1 = fl_value_new_map(); fl_value_set_string_take(value1, "one", fl_value_new_int(1)); fl_value_set_string_take(value1, "two", fl_value_new_int(2)); fl_value_set_string_take(value1, "three", fl_value_new_int(3)); g_autoptr(FlValue) value2 = fl_value_new_map(); fl_value_set_string_take(value2, "one", fl_value_new_int(1)); fl_value_set_string_take(value2, "two", fl_value_new_int(2)); fl_value_set_string_take(value2, "three", fl_value_new_int(3)); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, MapEqualDifferentOrder) { g_autoptr(FlValue) value1 = fl_value_new_map(); fl_value_set_string_take(value1, "one", fl_value_new_int(1)); fl_value_set_string_take(value1, "two", fl_value_new_int(2)); fl_value_set_string_take(value1, "three", fl_value_new_int(3)); g_autoptr(FlValue) value2 = fl_value_new_map(); fl_value_set_string_take(value2, "one", fl_value_new_int(1)); fl_value_set_string_take(value2, "three", fl_value_new_int(3)); fl_value_set_string_take(value2, "two", fl_value_new_int(2)); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, MapEmptyEqual) { g_autoptr(FlValue) value1 = fl_value_new_map(); g_autoptr(FlValue) value2 = fl_value_new_map(); EXPECT_TRUE(fl_value_equal(value1, value2)); } TEST(FlValueTest, MapNotEqualSameSizeDifferentKeys) { g_autoptr(FlValue) value1 = fl_value_new_map(); fl_value_set_string_take(value1, "one", fl_value_new_int(1)); fl_value_set_string_take(value1, "two", fl_value_new_int(2)); fl_value_set_string_take(value1, "three", fl_value_new_int(3)); g_autoptr(FlValue) value2 = fl_value_new_map(); fl_value_set_string_take(value2, "one", fl_value_new_int(1)); fl_value_set_string_take(value2, "two", fl_value_new_int(2)); fl_value_set_string_take(value2, "four", fl_value_new_int(3)); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, MapNotEqualSameSizeDifferentValues) { g_autoptr(FlValue) value1 = fl_value_new_map(); fl_value_set_string_take(value1, "one", fl_value_new_int(1)); fl_value_set_string_take(value1, "two", fl_value_new_int(2)); fl_value_set_string_take(value1, "three", fl_value_new_int(3)); g_autoptr(FlValue) value2 = fl_value_new_map(); fl_value_set_string_take(value2, "one", fl_value_new_int(1)); fl_value_set_string_take(value2, "two", fl_value_new_int(2)); fl_value_set_string_take(value2, "three", fl_value_new_int(4)); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, MapNotEqualDifferentSize) { g_autoptr(FlValue) value1 = fl_value_new_map(); fl_value_set_string_take(value1, "one", fl_value_new_int(1)); fl_value_set_string_take(value1, "two", fl_value_new_int(2)); fl_value_set_string_take(value1, "three", fl_value_new_int(3)); g_autoptr(FlValue) value2 = fl_value_new_map(); fl_value_set_string_take(value2, "one", fl_value_new_int(1)); fl_value_set_string_take(value2, "two", fl_value_new_int(2)); fl_value_set_string_take(value2, "three", fl_value_new_int(3)); fl_value_set_string_take(value2, "four", fl_value_new_int(4)); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, MapEmptyNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_map(); g_autoptr(FlValue) value2 = fl_value_new_map(); fl_value_set_string_take(value2, "one", fl_value_new_int(1)); fl_value_set_string_take(value2, "two", fl_value_new_int(2)); fl_value_set_string_take(value2, "three", fl_value_new_int(3)); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, MapToString) { g_autoptr(FlValue) value = fl_value_new_map(); fl_value_set_take(value, fl_value_new_string("null"), fl_value_new_null()); fl_value_set_take(value, fl_value_new_string("bool"), fl_value_new_bool(TRUE)); fl_value_set_take(value, fl_value_new_string("int"), fl_value_new_int(42)); fl_value_set_take(value, fl_value_new_string("float"), fl_value_new_float(M_PI)); fl_value_set_take(value, fl_value_new_string("uint8_list"), fl_value_new_uint8_list(nullptr, 0)); fl_value_set_take(value, fl_value_new_string("int32_list"), fl_value_new_int32_list(nullptr, 0)); fl_value_set_take(value, fl_value_new_string("int64_list"), fl_value_new_int64_list(nullptr, 0)); fl_value_set_take(value, fl_value_new_string("float_list"), fl_value_new_float_list(nullptr, 0)); fl_value_set_take(value, fl_value_new_string("list"), fl_value_new_list()); fl_value_set_take(value, fl_value_new_string("map"), fl_value_new_map()); fl_value_set_take(value, fl_value_new_null(), fl_value_new_string("null")); fl_value_set_take(value, fl_value_new_bool(TRUE), fl_value_new_string("bool")); fl_value_set_take(value, fl_value_new_int(42), fl_value_new_string("int")); fl_value_set_take(value, fl_value_new_float(M_PI), fl_value_new_string("float")); fl_value_set_take(value, fl_value_new_uint8_list(nullptr, 0), fl_value_new_string("uint8_list")); fl_value_set_take(value, fl_value_new_int32_list(nullptr, 0), fl_value_new_string("int32_list")); fl_value_set_take(value, fl_value_new_int64_list(nullptr, 0), fl_value_new_string("int64_list")); fl_value_set_take(value, fl_value_new_float_list(nullptr, 0), fl_value_new_string("float_list")); fl_value_set_take(value, fl_value_new_list(), fl_value_new_string("list")); fl_value_set_take(value, fl_value_new_map(), fl_value_new_string("map")); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "{null: null, bool: true, int: 42, float: 3.1415926535897931, " "uint8_list: [], int32_list: [], int64_list: [], float_list: " "[], list: [], map: {}, null: null, true: bool, 42: int, " "3.1415926535897931: float, []: uint8_list, []: int32_list, []: " "int64_list, []: float_list, []: list, {}: map}"); } TEST(FlDartProjectTest, Custom) { g_autoptr(FlValue) value = fl_value_new_custom(128, g_strdup("Hello World"), g_free); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_CUSTOM); ASSERT_EQ(fl_value_get_custom_type(value), 128); ASSERT_STREQ(reinterpret_cast<const gchar*>(fl_value_get_custom_value(value)), "Hello World"); } TEST(FlDartProjectTest, CustomNoDestroyNotify) { g_autoptr(FlValue) value = fl_value_new_custom(128, "Hello World", nullptr); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_CUSTOM); ASSERT_EQ(fl_value_get_custom_type(value), 128); ASSERT_STREQ(reinterpret_cast<const gchar*>(fl_value_get_custom_value(value)), "Hello World"); } TEST(FlDartProjectTest, CustomObject) { g_autoptr(GObject) v = G_OBJECT(g_object_new(G_TYPE_OBJECT, nullptr)); g_autoptr(FlValue) value = fl_value_new_custom_object(128, v); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_CUSTOM); ASSERT_EQ(fl_value_get_custom_type(value), 128); ASSERT_TRUE(G_IS_OBJECT(fl_value_get_custom_value_object(value))); } TEST(FlDartProjectTest, CustomObjectTake) { g_autoptr(FlValue) value = fl_value_new_custom_object_take( 128, G_OBJECT(g_object_new(G_TYPE_OBJECT, nullptr))); ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_CUSTOM); ASSERT_EQ(fl_value_get_custom_type(value), 128); ASSERT_TRUE(G_IS_OBJECT(fl_value_get_custom_value_object(value))); } TEST(FlValueTest, CustomEqual) { g_autoptr(FlValue) value1 = fl_value_new_custom(128, "Hello World", nullptr); g_autoptr(FlValue) value2 = fl_value_new_custom(128, "Hello World", nullptr); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, CustomToString) { g_autoptr(FlValue) value = fl_value_new_custom(128, nullptr, nullptr); g_autofree gchar* text = fl_value_to_string(value); EXPECT_STREQ(text, "(custom 128)"); } TEST(FlValueTest, EqualSameObject) { g_autoptr(FlValue) value = fl_value_new_null(); EXPECT_TRUE(fl_value_equal(value, value)); } TEST(FlValueTest, NullIntNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_null(); g_autoptr(FlValue) value2 = fl_value_new_int(0); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, NullBoolNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_bool(FALSE); g_autoptr(FlValue) value2 = fl_value_new_int(0); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, StringUint8ListNotEqual) { uint8_t data[] = {'h', 'e', 'l', 'l', 'o'}; g_autoptr(FlValue) value1 = fl_value_new_uint8_list(data, 5); g_autoptr(FlValue) value2 = fl_value_new_string("hello"); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Uint8ListInt32ListNotEqual) { uint8_t data8[] = {0, 1, 2, 3, 4}; int32_t data32[] = {0, 1, 2, 3, 4}; g_autoptr(FlValue) value1 = fl_value_new_uint8_list(data8, 5); g_autoptr(FlValue) value2 = fl_value_new_int32_list(data32, 5); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int32ListInt64ListNotEqual) { int32_t data32[] = {0, 1, 2, 3, 4}; int64_t data64[] = {0, 1, 2, 3, 4}; g_autoptr(FlValue) value1 = fl_value_new_int32_list(data32, 5); g_autoptr(FlValue) value2 = fl_value_new_int64_list(data64, 5); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, Int64ListFloatListNotEqual) { int64_t data64[] = {0, 1, 2, 3, 4}; double dataf[] = {0.0, 1.0, 2.0, 3.0, 4.0}; g_autoptr(FlValue) value1 = fl_value_new_int64_list(data64, 5); g_autoptr(FlValue) value2 = fl_value_new_float_list(dataf, 5); EXPECT_FALSE(fl_value_equal(value1, value2)); } TEST(FlValueTest, ListMapNotEqual) { g_autoptr(FlValue) value1 = fl_value_new_list(); g_autoptr(FlValue) value2 = fl_value_new_map(); EXPECT_FALSE(fl_value_equal(value1, value2)); }
engine/shell/platform/linux/fl_value_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_value_test.cc", "repo_id": "engine", "token_count": 18566 }
363
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_MESSAGE_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_MESSAGE_CODEC_H_ #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif #include <gmodule.h> #include "fl_message_codec.h" G_BEGIN_DECLS /** * FlJsonMessageCodecError: * @FL_JSON_MESSAGE_CODEC_ERROR_INVALID_UTF8: Message is not valid UTF-8. * @FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON: Message is not valid JSON. * @FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE: Invalid object key * type. * * Errors for #FlJsonMessageCodec objects to set on failures. */ #define FL_JSON_MESSAGE_CODEC_ERROR fl_json_message_codec_error_quark() typedef enum { // NOLINTBEGIN(readability-identifier-naming) FL_JSON_MESSAGE_CODEC_ERROR_INVALID_UTF8, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON, FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE, // NOLINTEND(readability-identifier-naming) } FlJsonMessageCodecError; G_MODULE_EXPORT GQuark fl_json_message_codec_error_quark(void) G_GNUC_CONST; G_MODULE_EXPORT G_DECLARE_FINAL_TYPE(FlJsonMessageCodec, fl_json_message_codec, FL, JSON_CODEC, FlMessageCodec) /** * FlJsonMessageCodec: * * #FlJsonMessageCodec is an #FlMessageCodec that implements the encodes * #FlValue to/from JSON. This codec encodes and decodes #FlValue of type * #FL_VALUE_TYPE_NULL, #FL_VALUE_TYPE_BOOL, #FL_VALUE_TYPE_INT, * #FL_VALUE_TYPE_FLOAT, #FL_VALUE_TYPE_STRING, #FL_VALUE_TYPE_UINT8_LIST, * #FL_VALUE_TYPE_INT32_LIST, #FL_VALUE_TYPE_INT64_LIST, * #FL_VALUE_TYPE_FLOAT_LIST, #FL_VALUE_TYPE_LIST, and #FL_VALUE_TYPE_MAP. * * #FlJsonMessageCodec matches the JSONMessageCodec class in the Flutter * services library. */ /** * fl_json_message_codec_new: * * Creates an #FlJsonMessageCodec. * * Returns: a new #FlJsonMessageCodec. */ FlJsonMessageCodec* fl_json_message_codec_new(); /** * fl_json_message_codec_encode: * @codec: an #FlJsonMessageCodec. * @value: value to encode. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Encodes a value to a JSON string. * * Returns: a JSON representation of this value or %NULL on error. */ gchar* fl_json_message_codec_encode(FlJsonMessageCodec* codec, FlValue* value, GError** error); /** * fl_json_message_codec_decode: * @codec: an #FlJsonMessageCodec. * @text: UTF-8 text in JSON format. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Decodes a value from a JSON string. * * Returns: an #FlValue or %NULL on error. */ FlValue* fl_json_message_codec_decode(FlJsonMessageCodec* codec, const gchar* text, GError** error); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_JSON_MESSAGE_CODEC_H_
engine/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h", "repo_id": "engine", "token_count": 1440 }
364
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VALUE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VALUE_H_ #include <glib-object.h> #include <glib.h> #include <stdbool.h> #include <stdint.h> #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif G_BEGIN_DECLS /** * FlValue: * * #FlValue is an object that contains the data types used in the platform * channel used by Flutter. * * In Dart the values are represented as follows: * - #FL_VALUE_TYPE_NULL: Null * - #FL_VALUE_TYPE_BOOL: bool * - #FL_VALUE_TYPE_INT: num * - #FL_VALUE_TYPE_FLOAT: num * - #FL_VALUE_TYPE_STRING: String * - #FL_VALUE_TYPE_UINT8_LIST: Uint8List * - #FL_VALUE_TYPE_INT32_LIST: Int32List * - #FL_VALUE_TYPE_INT64_LIST: Int64List * - #FL_VALUE_TYPE_FLOAT32_LIST: Float32List * - #FL_VALUE_TYPE_FLOAT_LIST: Float64List * - #FL_VALUE_TYPE_LIST: List<dynamic> * - #FL_VALUE_TYPE_MAP: Map<dynamic> * - #FL_VALUE_TYPE_CUSTOM: (custom type) * * See #FlMessageCodec to encode and decode these values. */ typedef struct _FlValue FlValue; /** * FlValueType: * @FL_VALUE_TYPE_NULL: The null value. * @FL_VALUE_TYPE_BOOL: A boolean. * @FL_VALUE_TYPE_INT: A 64 bit signed integer. * @FL_VALUE_TYPE_FLOAT: A 64 bit floating point number. * @FL_VALUE_TYPE_STRING: UTF-8 text. * @FL_VALUE_TYPE_UINT8_LIST: An ordered list of unsigned 8 bit integers. * @FL_VALUE_TYPE_INT32_LIST: An ordered list of 32 bit integers. * @FL_VALUE_TYPE_INT64_LIST: An ordered list of 64 bit integers. * @FL_VALUE_TYPE_FLOAT_LIST: An ordered list of floating point numbers. * @FL_VALUE_TYPE_LIST: An ordered list of #FlValue objects. * @FL_VALUE_TYPE_MAP: A map of #FlValue objects keyed by #FlValue object. * @FL_VALUE_TYPE_FLOAT32_LIST: An ordered list of 32bit floating point numbers. * @FL_VALUE_TYPE_CUSTOM: A custom value. * * Types of #FlValue. */ typedef enum { // Parts of the public API, so fixing the names is a breaking change. // NOLINTBEGIN(readability-identifier-naming) FL_VALUE_TYPE_NULL, FL_VALUE_TYPE_BOOL, FL_VALUE_TYPE_INT, FL_VALUE_TYPE_FLOAT, FL_VALUE_TYPE_STRING, FL_VALUE_TYPE_UINT8_LIST, FL_VALUE_TYPE_INT32_LIST, FL_VALUE_TYPE_INT64_LIST, FL_VALUE_TYPE_FLOAT_LIST, FL_VALUE_TYPE_LIST, FL_VALUE_TYPE_MAP, FL_VALUE_TYPE_FLOAT32_LIST, FL_VALUE_TYPE_CUSTOM, // NOLINTEND(readability-identifier-naming) } FlValueType; /** * fl_value_new_null: * * Creates an #FlValue that contains a null value. The equivalent Dart type is * null. * * Returns: a new #FlValue. */ FlValue* fl_value_new_null(); /** * fl_value_new_bool: * @value: the value. * * Creates an #FlValue that contains a boolean value. The equivalent Dart type * is a bool. * * Returns: a new #FlValue. */ FlValue* fl_value_new_bool(bool value); /** * fl_value_new_int: * @value: the value. * * Creates an #FlValue that contains an integer number. The equivalent Dart type * is a num. * * Returns: a new #FlValue. */ FlValue* fl_value_new_int(int64_t value); /** * fl_value_new_float: * @value: the value. * * Creates an #FlValue that contains a floating point number. The equivalent * Dart type is a num. * * Returns: a new #FlValue. */ FlValue* fl_value_new_float(double value); /** * fl_value_new_string: * @value: a %NULL-terminated UTF-8 string. * * Creates an #FlValue that contains UTF-8 text. The equivalent Dart type is a * String. * * Returns: a new #FlValue. */ FlValue* fl_value_new_string(const gchar* value); /** * fl_value_new_string_sized: * @value: a buffer containing UTF-8 text. It does not require a nul terminator. * @value_length: the number of bytes to use from @value. * * Creates an #FlValue that contains UTF-8 text. The equivalent Dart type is a * String. * * Returns: a new #FlValue. */ FlValue* fl_value_new_string_sized(const gchar* value, size_t value_length); /** * fl_value_new_uint8_list: * @value: an array of unsigned 8 bit integers. * @value_length: number of elements in @value. * * Creates an ordered list containing 8 bit unsigned integers. The data is * copied. The equivalent Dart type is a Uint8List. * * Returns: a new #FlValue. */ FlValue* fl_value_new_uint8_list(const uint8_t* value, size_t value_length); /** * fl_value_new_uint8_list_from_bytes: * @value: a #GBytes. * * Creates an ordered list containing 8 bit unsigned integers. The data is * copied. The equivalent Dart type is a Uint8List. * * Returns: a new #FlValue. */ FlValue* fl_value_new_uint8_list_from_bytes(GBytes* value); /** * fl_value_new_int32_list: * @value: an array of signed 32 bit integers. * @value_length: number of elements in @value. * * Creates an ordered list containing 32 bit integers. The equivalent Dart type * is a Int32List. * * Returns: a new #FlValue. */ FlValue* fl_value_new_int32_list(const int32_t* value, size_t value_length); /** * fl_value_new_int64_list: * @value: an array of signed 64 bit integers. * @value_length: number of elements in @value. * * Creates an ordered list containing 64 bit integers. The equivalent Dart type * is a Int64List. * * Returns: a new #FlValue. */ FlValue* fl_value_new_int64_list(const int64_t* value, size_t value_length); /** * fl_value_new_float32_list: * @value: an array of floating point numbers. * @value_length: number of elements in @value. * * Creates an ordered list containing 32 bit floating point numbers. * The equivalent Dart type is a Float32List. * * Returns: a new #FlValue. */ FlValue* fl_value_new_float32_list(const float* value, size_t value_length); /** * fl_value_new_float_list: * @value: an array of floating point numbers. * @value_length: number of elements in @value. * * Creates an ordered list containing floating point numbers. The equivalent * Dart type is a Float64List. * * Returns: a new #FlValue. */ FlValue* fl_value_new_float_list(const double* value, size_t value_length); /** * fl_value_new_list: * * Creates an ordered list. Children can be added to the list using * fl_value_append(). The children are accessed using fl_value_get_length() * and fl_value_get_list_value(). The equivalent Dart type is a List<dynamic>. * * The following example shows a simple list of values: * * |[<!-- language="C" --> * g_autoptr(FlValue) value = fl_value_new_list (); * fl_value_append_take (value, fl_value_new_string ("one"); * fl_value_append_take (value, fl_value_new_int (2); * fl_value_append_take (value, fl_value_new_double (3.0); * ]| * * This value can be decoded using: * * |[<!-- language="C" --> * g_assert (fl_value_get_type (value) == FL_VALUE_TYPE_LIST); * for (size_t i = 0; i < fl_value_get_length (value); i++) { * FlValue *child = fl_value_get_list_value (value, i); * process_value (child); * } * ]| * * Returns: a new #FlValue. */ FlValue* fl_value_new_list(); /** * fl_value_new_list_from_strv: * @value: a %NULL-terminated array of strings. * * Creates an ordered list containing #FlString values. * * Returns: a new #FlValue. */ FlValue* fl_value_new_list_from_strv(const gchar* const* value); /** * fl_value_new_map: * * Creates an ordered associative array. Children can be added to the map * using fl_value_set(), fl_value_set_take(), fl_value_set_string(), * fl_value_set_string_take(). The children are accessed using * fl_value_get_length(), fl_value_get_map_key(), fl_value_get_map_value(), * fl_value_lookup() and fl_value_lookup_string(). The equivalent Dart type is a * Map<dynamic>. * * The following example shows how to create a map of values keyed by strings: * * |[<!-- language="C" --> * g_autoptr(FlValue) value = fl_value_new_map (); * fl_value_set_string_take (value, "name", fl_value_new_string ("Gandalf")); * fl_value_set_string_take (value, "occupation", * fl_value_new_string ("Wizard")); * fl_value_set_string_take (value, "age", fl_value_new_int (2019)); * ]| * * This value can be decoded using: * |[<!-- language="C" --> * g_assert (fl_value_get_type (value) == FL_VALUE_TYPE_MAP); * FlValue *name = fl_value_lookup_string (value, "name"); * g_assert (fl_value_get_type (name) == FL_VALUE_TYPE_STRING); * FlValue *age = fl_value_lookup_string (value, "age"); * g_assert (fl_value_get_type (age) == FL_VALUE_TYPE_INT); * g_message ("Next customer is %s (%d years old)", * fl_value_get_string (name), * fl_value_get_int (age)); * ]| * * Returns: a new #FlValue. */ FlValue* fl_value_new_map(); /** * fl_value_new_custom: * @type: an ID for this type. * @value: pointer to the custom value. * @destroy_notify: function to call when @value is no longer required. * * Creates a new custom data type. The Dart side of the channel must have * equivalent custom code to access this object. * * Returns: a new #FlValue. */ FlValue* fl_value_new_custom(int type, gconstpointer value, GDestroyNotify destroy_notify); /** * fl_value_new_custom_object: * @type: an ID for this type. * @object: the custom object. * * Creates a new custom data type. The Dart side of the channel must have * equivalent custom code to access this object. * * Returns: a new #FlValue. */ FlValue* fl_value_new_custom_object(int type, GObject* object); /** * fl_value_new_custom_object_take: * @type: an ID for this type. * @object: (transfer full): the custom object. * * Creates a new custom data type. The Dart side of the channel must have * equivalent custom code to access this object. Ownership of @object is taken. * * Returns: a new #FlValue. */ FlValue* fl_value_new_custom_object_take(int type, GObject* object); /** * fl_value_ref: * @value: an #FlValue. * * Increases the reference count of an #FlValue. * * Returns: the value that was referenced. */ FlValue* fl_value_ref(FlValue* value); /** * fl_value_unref: * @value: an #FlValue. * * Decreases the reference count of an #FlValue. When the reference count hits * zero @value is destroyed and no longer valid. */ void fl_value_unref(FlValue* value); /** * fl_value_get_type: * @value: an #FlValue. * * Gets the type of @value. * * Returns: an #FlValueType. */ FlValueType fl_value_get_type(FlValue* value); /** * fl_value_equal: * @a: an #FlValue. * @b: an #FlValue. * * Compares two #FlValue to see if they are equivalent. Two values are * considered equivalent if they are of the same type and their data is the same * including any child values. For values of type #FL_VALUE_TYPE_MAP the order * of the values does not matter. * * Returns: %TRUE if both values are equivalent. */ bool fl_value_equal(FlValue* a, FlValue* b); /** * fl_value_append: * @value: an #FlValue of type #FL_VALUE_TYPE_LIST. * @child: an #FlValue. * * Adds @child to the end of @value. Calling this with an #FlValue that is not * of type #FL_VALUE_TYPE_LIST is a programming error. */ void fl_value_append(FlValue* value, FlValue* child); /** * fl_value_append_take: * @value: an #FlValue of type #FL_VALUE_TYPE_LIST. * @child: (transfer full): an #FlValue. * * Adds @child to the end of @value. Ownership of @child is taken by @value. * Calling this with an #FlValue that is not of type #FL_VALUE_TYPE_LIST is a * programming error. */ void fl_value_append_take(FlValue* value, FlValue* child); /** * fl_value_set: * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. * @key: an #FlValue. * @child_value: an #FlValue. * * Sets @key in @value to @child_value. If an existing value was in the map with * the same key it is replaced. Calling this with an #FlValue that is not of * type #FL_VALUE_TYPE_MAP is a programming error. */ void fl_value_set(FlValue* value, FlValue* key, FlValue* child_value); /** * fl_value_set_take: * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. * @key: (transfer full): an #FlValue. * @child_value: (transfer full): an #FlValue. * * Sets @key in @value to @child_value. Ownership of both @key and @child_value * is taken by @value. If an existing value was in the map with the same key it * is replaced. Calling this with an #FlValue that is not of type * #FL_VALUE_TYPE_MAP is a programming error. */ void fl_value_set_take(FlValue* value, FlValue* key, FlValue* child_value); /** * fl_value_set_string: * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. * @key: a UTF-8 text key. * @child_value: an #FlValue. * * Sets a value in the map with a text key. If an existing value was in the map * with the same key it is replaced. Calling this with an #FlValue that is not * of type #FL_VALUE_TYPE_MAP is a programming error. */ void fl_value_set_string(FlValue* value, const gchar* key, FlValue* child_value); /** * fl_value_set_string_take: * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. * @key: a UTF-8 text key. * @child_value: (transfer full): an #FlValue. * * Sets a value in the map with a text key, taking ownership of the value. If an * existing value was in the map with the same key it is replaced. Calling this * with an #FlValue that is not of type #FL_VALUE_TYPE_MAP is a programming * error. */ void fl_value_set_string_take(FlValue* value, const gchar* key, FlValue* child_value); /** * fl_value_get_bool: * @value: an #FlValue of type #FL_VALUE_TYPE_BOOL. * * Gets the boolean value of @value. Calling this with an #FlValue that is * not of type #FL_VALUE_TYPE_BOOL is a programming error. * * Returns: a boolean value. */ bool fl_value_get_bool(FlValue* value); /** * fl_value_get_int: * @value: an #FlValue of type #FL_VALUE_TYPE_INT. * * Gets the integer number of @value. Calling this with an #FlValue that is * not of type #FL_VALUE_TYPE_INT is a programming error. * * Returns: an integer number. */ int64_t fl_value_get_int(FlValue* value); /** * fl_value_get_float: * @value: an #FlValue of type #FL_VALUE_TYPE_FLOAT. * * Gets the floating point number of @value. Calling this with an #FlValue * that is not of type #FL_VALUE_TYPE_FLOAT is a programming error. * * Returns: a floating point number. */ double fl_value_get_float(FlValue* value); /** * fl_value_get_string: * @value: an #FlValue of type #FL_VALUE_TYPE_STRING. * * Gets the UTF-8 text contained in @value. Calling this with an #FlValue * that is not of type #FL_VALUE_TYPE_STRING is a programming error. * * Returns: a UTF-8 encoded string. */ const gchar* fl_value_get_string(FlValue* value); /** * fl_value_get_length: * @value: an #FlValue of type #FL_VALUE_TYPE_UINT8_LIST, * #FL_VALUE_TYPE_INT32_LIST, #FL_VALUE_TYPE_INT64_LIST, * #FL_VALUE_TYPE_FLOAT32_LIST, #FL_VALUE_TYPE_FLOAT_LIST, #FL_VALUE_TYPE_LIST * or #FL_VALUE_TYPE_MAP. * * Gets the number of elements @value contains. This is only valid for list * and map types. Calling this with other types is a programming error. * * Returns: the number of elements inside @value. */ size_t fl_value_get_length(FlValue* value); /** * fl_value_get_uint8_list: * @value: an #FlValue of type #FL_VALUE_TYPE_UINT8_LIST. * * Gets the array of unisigned 8 bit integers @value contains. The data * contains fl_value_get_length() elements. Calling this with an #FlValue that * is not of type #FL_VALUE_TYPE_UINT8_LIST is a programming error. * * Returns: an array of unsigned 8 bit integers. */ const uint8_t* fl_value_get_uint8_list(FlValue* value); /** * fl_value_get_int32_list: * @value: an #FlValue of type #FL_VALUE_TYPE_INT32_LIST. * * Gets the array of 32 bit integers @value contains. The data contains * fl_value_get_length() elements. Calling this with an #FlValue that is not of * type #FL_VALUE_TYPE_INT32_LIST is a programming error. * * Returns: an array of 32 bit integers. */ const int32_t* fl_value_get_int32_list(FlValue* value); /** * fl_value_get_int64_list: * @value: an #FlValue of type #FL_VALUE_TYPE_INT64_LIST. * * Gets the array of 64 bit integers @value contains. The data contains * fl_value_get_length() elements. Calling this with an #FlValue that is not of * type #FL_VALUE_TYPE_INT64_LIST is a programming error. * * Returns: an array of 64 bit integers. */ const int64_t* fl_value_get_int64_list(FlValue* value); /** * fl_value_get_float32_list: * @value: an #FlValue of type #FL_VALUE_TYPE_FLOAT32_LIST. * * Gets the array of floating point numbers @value contains. The data * contains fl_value_get_length() elements. Calling this with an #FlValue that * is not of type #FL_VALUE_TYPE_FLOAT32_LIST is a programming error. * * Returns: an array of floating point numbers. */ const float* fl_value_get_float32_list(FlValue* value); /** * fl_value_get_float_list: * @value: an #FlValue of type #FL_VALUE_TYPE_FLOAT_LIST. * * Gets the array of floating point numbers @value contains. The data * contains fl_value_get_length() elements. Calling this with an #FlValue that * is not of type #FL_VALUE_TYPE_FLOAT_LIST is a programming error. * * Returns: an array of floating point numbers. */ const double* fl_value_get_float_list(FlValue* value); /** * fl_value_get_list_value: * @value: an #FlValue of type #FL_VALUE_TYPE_LIST. * @index: an index in the list. * * Gets a child element of the list. It is a programming error to request an * index that is outside the size of the list as returned from * fl_value_get_length(). Calling this with an #FlValue that is not of type * #FL_VALUE_TYPE_LIST is a programming error. * * Returns: an #FlValue. */ FlValue* fl_value_get_list_value(FlValue* value, size_t index); /** * fl_value_get_map_key: * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. * @index: an index in the map. * * Gets a key from the map. It is a programming error to request an index that * is outside the size of the list as returned from fl_value_get_length(). * Calling this with an #FlValue that is not of type #FL_VALUE_TYPE_MAP is a * programming error. * * Returns: an #FlValue. */ FlValue* fl_value_get_map_key(FlValue* value, size_t index); /** * fl_value_get_map_value: * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. * @index: an index in the map. * * Gets a value from the map. It is a programming error to request an index that * is outside the size of the list as returned from fl_value_get_length(). * Calling this with an #FlValue that is not of type #FL_VALUE_TYPE_MAP is a * programming error. * * Returns: an #FlValue. */ FlValue* fl_value_get_map_value(FlValue* value, size_t index); /** * fl_value_lookup: * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. * @key: a key value. * * Gets the map entry that matches @key. Keys are checked using * fl_value_equal(). Calling this with an #FlValue that is not of type * #FL_VALUE_TYPE_MAP is a programming error. * * Map lookups are not optimized for performance - if you have a large map or * need frequent access you should copy the data into another structure, e.g. * #GHashTable. * * Returns: (allow-none): the value with this key or %NULL if not one present. */ FlValue* fl_value_lookup(FlValue* value, FlValue* key); /** * fl_value_lookup_string: * @value: an #FlValue of type #FL_VALUE_TYPE_MAP. * @key: a key value. * * Gets the map entry that matches @key. Keys are checked using * fl_value_equal(). Calling this with an #FlValue that is not of type * #FL_VALUE_TYPE_MAP is a programming error. * * Map lookups are not optimized for performance - if you have a large map or * need frequent access you should copy the data into another structure, e.g. * #GHashTable. * * Returns: (allow-none): the value with this key or %NULL if not one present. */ FlValue* fl_value_lookup_string(FlValue* value, const gchar* key); /** * fl_value_get_custom_type: * @value: an #FlValue of type #FL_VALUE_TYPE_CUSTOM. * * Gets the type ID for this custom type. * * Returns: a type ID. */ int fl_value_get_custom_type(FlValue* value); /** * fl_value_get_custom_value: * @value: an #FlValue of type #FL_VALUE_TYPE_CUSTOM. * * Gets the address of the custom value. * * Returns: a pointer to the custom value. */ gconstpointer fl_value_get_custom_value(FlValue* value); /** * fl_value_get_custom_value_object: * @value: an #FlValue of type #FL_VALUE_TYPE_CUSTOM. * * Gets the custom value as an object. * * Returns: an object. */ GObject* fl_value_get_custom_value_object(FlValue* value); /** * fl_value_to_string: * @value: an #FlValue. * * Converts an #FlValue to a text representation, suitable for logging purposes. * The text is formatted to be the equivalent of Dart toString() methods. * * Returns: UTF-8 text. */ gchar* fl_value_to_string(FlValue* value); G_DEFINE_AUTOPTR_CLEANUP_FUNC(FlValue, fl_value_unref) G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_VALUE_H_
engine/shell/platform/linux/public/flutter_linux/fl_value.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_value.h", "repo_id": "engine", "token_count": 7424 }
365
// 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_IM_CONTEXT_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_IM_CONTEXT_H_ #include <gtk/gtk.h> #include "gmock/gmock.h" namespace flutter { namespace testing { class MockIMContext { public: ~MockIMContext(); // This was an existing use of operator overloading. It's against our style // guide but enabling clang tidy on header files is a higher priority than // fixing this. // NOLINTNEXTLINE(google-explicit-constructor) operator GtkIMContext*(); MOCK_METHOD(void, gtk_im_context_set_client_window, (GtkIMContext * context, GdkWindow* window)); MOCK_METHOD(void, gtk_im_context_get_preedit_string, (GtkIMContext * context, gchar** str, PangoAttrList** attrs, gint* cursor_pos)); MOCK_METHOD(gboolean, gtk_im_context_filter_keypress, (GtkIMContext * context, GdkEventKey* event)); MOCK_METHOD(gboolean, gtk_im_context_focus_in, (GtkIMContext * context)); MOCK_METHOD(void, gtk_im_context_focus_out, (GtkIMContext * context)); MOCK_METHOD(void, gtk_im_context_reset, (GtkIMContext * context)); MOCK_METHOD(void, gtk_im_context_set_cursor_location, (GtkIMContext * context, GdkRectangle* area)); MOCK_METHOD(void, gtk_im_context_set_use_preedit, (GtkIMContext * context, gboolean use_preedit)); MOCK_METHOD( void, gtk_im_context_set_surrounding, (GtkIMContext * context, const gchar* text, gint len, gint cursor_index)); MOCK_METHOD(gboolean, gtk_im_context_get_surrounding, (GtkIMContext * context, gchar** text, gint* cursor_index)); private: GtkIMContext* instance_ = nullptr; }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_IM_CONTEXT_H_
engine/shell/platform/linux/testing/mock_im_context.h/0
{ "file_path": "engine/shell/platform/linux/testing/mock_im_context.h", "repo_id": "engine", "token_count": 904 }
366
# Windows Platform Embedder This code is the glue between the Flutter engine and the Windows platform. It is responsible for: 1. Launching the Flutter engine. 2. Providing a view for the Flutter engine to render into. 3. Dispatching events to the Flutter engine. For more information on embedders, see the [Flutter architectural overview](https://docs.flutter.dev/resources/architectural-overview). > [!CAUTION] > This is a best effort attempt to document the Windows embedder. It is not > guaranteed to be up to date or complete. If you find a discrepancy, please > [send a pull request](https://github.com/flutter/engine/compare)! See also: 1. [Flutter tool's Windows logic](https://github.com/flutter/flutter/tree/master/packages/flutter_tools/lib/src/windows) - Builds and runs Flutter Windows apps on the command line. 1. [Windows app template](https://github.com/flutter/flutter/tree/master/packages/flutter_tools/templates/app_shared/windows.tmpl) - The entrypoint for Flutter Windows app. This launches the Windows embedder. 1. [`platform-windows` GitHub issues label](https://github.com/flutter/flutter/issues?q=is%3Aopen+label%3Aplatform-windows+sort%3Aupdated-desc) 1. [`#hackers-desktop` Discord channel](https://discord.com/channels/608014603317936148/608020180177780791) ## Developing See: 1. [Setting up the Engine development environment](https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment) 2. [Compiling for Windows](https://github.com/flutter/flutter/wiki/Compiling-the-engine#compiling-for-windows) 3. [Debugging Windows builds with Visual Studio](https://github.com/flutter/flutter/wiki/Debugging-the-engine#debugging-windows-builds-with-visual-studio) ### Notable files Some notable files include: 1. [`flutter_windows_engine.h`](https://github.com/flutter/engine/blob/main/shell/platform/windows/flutter_windows_engine.h) - Connects the Windows embedder to the Flutter engine. 1. [`flutter_windows_view.h`](https://github.com/flutter/engine/blob/main/shell/platform/windows/flutter_windows_view.h) - The logic for a Flutter view. 1. [`flutter_window.h`](https://github.com/flutter/engine/blob/main/shell/platform/windows/flutter_window.h) - Integrates a Flutter view with Windows (using a win32 child window). 1. [`//shell/platform/embedder/embedder.h`](https://github.com/flutter/engine/blob/main/shell/platform/embedder/embedder.h) - The API boundary between the Windows embedder and the Flutter engine.
engine/shell/platform/windows/README.md/0
{ "file_path": "engine/shell/platform/windows/README.md", "repo_id": "engine", "token_count": 768 }
367
// 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_VIEW_CONTROLLER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_CONTROLLER_H_ #include <flutter_windows.h> #include <windows.h> #include <memory> #include <optional> #include "dart_project.h" #include "flutter_engine.h" #include "flutter_view.h" namespace flutter { // A controller for a view displaying Flutter content. // // This is the primary wrapper class for the desktop C API. // If you use this class, you should not call any of the setup or teardown // methods in the C API directly, as this class will do that internally. class FlutterViewController { public: // Creates a FlutterView that can be parented into a Windows View hierarchy // either using HWNDs. // // |dart_project| will be used to configure the engine backing this view. explicit FlutterViewController(int width, int height, const DartProject& project); virtual ~FlutterViewController(); // Prevent copying. FlutterViewController(FlutterViewController const&) = delete; FlutterViewController& operator=(FlutterViewController const&) = delete; // Returns the view controller's view ID. FlutterViewId view_id() const; // Returns the engine running Flutter content in this view. FlutterEngine* engine() const { return engine_.get(); } // Returns the view managed by this controller. FlutterView* view() const { return view_.get(); } // Requests new frame from the engine and repaints the view. void ForceRedraw(); // Allows the Flutter engine and any interested plugins an opportunity to // handle the given message. // // If a result is returned, then the message was handled in such a way that // further handling should not be done. std::optional<LRESULT> HandleTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); private: // Handle for interacting with the C API's view controller, if any. FlutterDesktopViewControllerRef controller_ = nullptr; // The backing engine std::unique_ptr<FlutterEngine> engine_; // The owned FlutterView. std::unique_ptr<FlutterView> view_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_CONTROLLER_H_
engine/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h/0
{ "file_path": "engine/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h", "repo_id": "engine", "token_count": 960 }
368
// 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_DIRECT_MANIPULATION_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_DIRECT_MANIPULATION_H_ #include "flutter/fml/memory/ref_counted.h" #include <wrl/client.h> #include "directmanipulation.h" namespace flutter { class FlutterWindow; class WindowBindingHandlerDelegate; class DirectManipulationEventHandler; // Owner for a DirectManipulation event handler, contains the link between // DirectManipulation and WindowBindingHandlerDelegate. class DirectManipulationOwner { public: explicit DirectManipulationOwner(FlutterWindow* window); virtual ~DirectManipulationOwner() = default; // Initialize a DirectManipulation viewport with specified width and height. // These should match the width and height of the application window. int Init(unsigned int width, unsigned int height); // Resize the DirectManipulation viewport. Should be called when the // application window is resized. void ResizeViewport(unsigned int width, unsigned int height); // Set the WindowBindingHandlerDelegate which will receive callbacks based on // DirectManipulation updates. void SetBindingHandlerDelegate( WindowBindingHandlerDelegate* binding_handler_delegate); // Called when DM_POINTERHITTEST occurs with an acceptable pointer type. Will // start DirectManipulation for that interaction. virtual void SetContact(UINT contactId); // Called to get updates from DirectManipulation. Should be called frequently // to provide smooth updates. void Update(); // Release child event handler and OS resources. void Destroy(); // The target that should be updated when DirectManipulation provides a new // pan/zoom transformation. WindowBindingHandlerDelegate* binding_handler_delegate; private: // The window gesture input is occuring on. FlutterWindow* window_; // Cookie needed to register child event handler with viewport. DWORD viewportHandlerCookie_; // Object needed for operation of the DirectManipulation API. Microsoft::WRL::ComPtr<IDirectManipulationManager> manager_; // Object needed for operation of the DirectManipulation API. Microsoft::WRL::ComPtr<IDirectManipulationUpdateManager> updateManager_; // Object needed for operation of the DirectManipulation API. Microsoft::WRL::ComPtr<IDirectManipulationViewport> viewport_; // Child needed for operation of the DirectManipulation API. fml::RefPtr<DirectManipulationEventHandler> handler_; FML_DISALLOW_COPY_AND_ASSIGN(DirectManipulationOwner); }; // Implements DirectManipulation event handling interfaces, receives calls from // system when gesture events occur. class DirectManipulationEventHandler : public fml::RefCountedThreadSafe<DirectManipulationEventHandler>, public IDirectManipulationViewportEventHandler, public IDirectManipulationInteractionEventHandler { friend class DirectManipulationOwner; FML_FRIEND_REF_COUNTED_THREAD_SAFE(DirectManipulationEventHandler); FML_FRIEND_MAKE_REF_COUNTED(DirectManipulationEventHandler); public: explicit DirectManipulationEventHandler(DirectManipulationOwner* owner) : owner_(owner) {} // |IUnknown| STDMETHODIMP QueryInterface(REFIID iid, void** ppv) override; // |IUnknown| ULONG STDMETHODCALLTYPE AddRef() override; // |IUnknown| ULONG STDMETHODCALLTYPE Release() override; // |IDirectManipulationViewportEventHandler| HRESULT STDMETHODCALLTYPE OnViewportStatusChanged( IDirectManipulationViewport* viewport, DIRECTMANIPULATION_STATUS current, DIRECTMANIPULATION_STATUS previous) override; // |IDirectManipulationViewportEventHandler| HRESULT STDMETHODCALLTYPE OnViewportUpdated( IDirectManipulationViewport* viewport) override; // |IDirectManipulationViewportEventHandler| HRESULT STDMETHODCALLTYPE OnContentUpdated( IDirectManipulationViewport* viewport, IDirectManipulationContent* content) override; // |IDirectManipulationInteractionEventHandler| HRESULT STDMETHODCALLTYPE OnInteraction( IDirectManipulationViewport2* viewport, DIRECTMANIPULATION_INTERACTION_TYPE interaction) override; private: struct GestureData { float scale; float pan_x; float pan_y; }; // Convert transform array to Flutter-usable values. GestureData ConvertToGestureData(float transform[6]); // Unique identifier to associate with all gesture event updates. int32_t GetDeviceId(); // Parent object, used to store the target for gesture event updates. DirectManipulationOwner* owner_; // We need to reset some parts of DirectManipulation after each gesture // A flag is needed to ensure that false events created as the reset occurs // are not sent to the flutter framework. bool during_synthesized_reset_ = false; // Store whether current events are from synthetic inertia rather than user // input. bool during_inertia_ = false; // The transform might not be able to be reset before the next gesture, so // the initial state needs to be stored for reference. GestureData initial_gesture_data_ = { 1, // scale 0, // pan_x 0, // pan_y }; // Store the difference between the last pan offsets to determine if inertia // has been cancelled in the middle of an animation. float last_pan_x_ = 0.0; float last_pan_y_ = 0.0; float last_pan_delta_x_ = 0.0; float last_pan_delta_y_ = 0.0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_DIRECT_MANIPULATION_H_
engine/shell/platform/windows/direct_manipulation.h/0
{ "file_path": "engine/shell/platform/windows/direct_manipulation.h", "repo_id": "engine", "token_count": 1676 }
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_EGL_WINDOW_SURFACE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_WINDOW_SURFACE_H_ #include <EGL/egl.h> #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/egl/surface.h" namespace flutter { namespace egl { // An EGL surface used to render a Flutter view to a win32 HWND. // // This enables automatic error logging and mocking. class WindowSurface : public Surface { public: WindowSurface(EGLDisplay display, EGLContext context, EGLSurface surface, size_t width, size_t height); // If enabled, makes the surface's buffer swaps block until the v-blank. // // If disabled, allows one thread to swap multiple buffers per v-blank // but can result in screen tearing if the system compositor is disabled. // // The surface must be current before calling this. virtual bool SetVSyncEnabled(bool enabled); // Get the surface's width in physical pixels. virtual size_t width() const; // Get the surface's height in physical pixels. virtual size_t height() const; // Get whether the surface's buffer swap blocks until the v-blank. virtual bool vsync_enabled() const; private: size_t width_ = 0; size_t height_ = 0; bool vsync_enabled_ = true; FML_DISALLOW_COPY_AND_ASSIGN(WindowSurface); }; } // namespace egl } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_WINDOW_SURFACE_H_
engine/shell/platform/windows/egl/window_surface.h/0
{ "file_path": "engine/shell/platform/windows/egl/window_surface.h", "repo_id": "engine", "token_count": 560 }
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/flutter_window.h" #include <WinUser.h> #include <dwmapi.h> #include <chrono> #include <map> #include "flutter/fml/logging.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/windows/dpi_utils.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" #include "flutter/shell/platform/windows/keyboard_utils.h" namespace flutter { namespace { // The Windows DPI system is based on this // constant for machines running at 100% scaling. constexpr int base_dpi = 96; static const int kMinTouchDeviceId = 0; static const int kMaxTouchDeviceId = 128; static const int kLinesPerScrollWindowsDefault = 3; // Maps a Flutter cursor name to an HCURSOR. // // Returns the arrow cursor for unknown constants. // // This map must be kept in sync with Flutter framework's // services/mouse_cursor.dart. static HCURSOR GetCursorByName(const std::string& cursor_name) { static auto* cursors = new std::map<std::string, const wchar_t*>{ {"allScroll", IDC_SIZEALL}, {"basic", IDC_ARROW}, {"click", IDC_HAND}, {"forbidden", IDC_NO}, {"help", IDC_HELP}, {"move", IDC_SIZEALL}, {"none", nullptr}, {"noDrop", IDC_NO}, {"precise", IDC_CROSS}, {"progress", IDC_APPSTARTING}, {"text", IDC_IBEAM}, {"resizeColumn", IDC_SIZEWE}, {"resizeDown", IDC_SIZENS}, {"resizeDownLeft", IDC_SIZENESW}, {"resizeDownRight", IDC_SIZENWSE}, {"resizeLeft", IDC_SIZEWE}, {"resizeLeftRight", IDC_SIZEWE}, {"resizeRight", IDC_SIZEWE}, {"resizeRow", IDC_SIZENS}, {"resizeUp", IDC_SIZENS}, {"resizeUpDown", IDC_SIZENS}, {"resizeUpLeft", IDC_SIZENWSE}, {"resizeUpRight", IDC_SIZENESW}, {"resizeUpLeftDownRight", IDC_SIZENWSE}, {"resizeUpRightDownLeft", IDC_SIZENESW}, {"wait", IDC_WAIT}, }; const wchar_t* idc_name = IDC_ARROW; auto it = cursors->find(cursor_name); if (it != cursors->end()) { idc_name = it->second; } return ::LoadCursor(nullptr, idc_name); } static constexpr int32_t kDefaultPointerDeviceId = 0; // This method is only valid during a window message related to mouse/touch // input. // See // https://docs.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages?redirectedfrom=MSDN#distinguishing-pen-input-from-mouse-and-touch. static FlutterPointerDeviceKind GetFlutterPointerDeviceKind() { constexpr LPARAM kTouchOrPenSignature = 0xFF515700; constexpr LPARAM kTouchSignature = kTouchOrPenSignature | 0x80; constexpr LPARAM kSignatureMask = 0xFFFFFF00; LPARAM info = GetMessageExtraInfo(); if ((info & kSignatureMask) == kTouchOrPenSignature) { if ((info & kTouchSignature) == kTouchSignature) { return kFlutterPointerDeviceKindTouch; } return kFlutterPointerDeviceKindStylus; } return kFlutterPointerDeviceKindMouse; } // Translates button codes from Win32 API to FlutterPointerMouseButtons. static uint64_t ConvertWinButtonToFlutterButton(UINT button) { switch (button) { case WM_LBUTTONDOWN: case WM_LBUTTONUP: return kFlutterPointerButtonMousePrimary; case WM_RBUTTONDOWN: case WM_RBUTTONUP: return kFlutterPointerButtonMouseSecondary; case WM_MBUTTONDOWN: case WM_MBUTTONUP: return kFlutterPointerButtonMouseMiddle; case XBUTTON1: return kFlutterPointerButtonMouseBack; case XBUTTON2: return kFlutterPointerButtonMouseForward; } FML_LOG(WARNING) << "Mouse button not recognized: " << button; return 0; } } // namespace FlutterWindow::FlutterWindow( int width, int height, std::shared_ptr<WindowsProcTable> windows_proc_table, std::unique_ptr<TextInputManager> text_input_manager) : touch_id_generator_(kMinTouchDeviceId, kMaxTouchDeviceId), windows_proc_table_(std::move(windows_proc_table)), text_input_manager_(std::move(text_input_manager)), ax_fragment_root_(nullptr) { // Get the DPI of the primary monitor as the initial DPI. If Per-Monitor V2 is // supported, |current_dpi_| should be updated in the // kWmDpiChangedBeforeParent message. current_dpi_ = GetDpiForHWND(nullptr); // Get initial value for wheel scroll lines // TODO: Listen to changes for this value // https://github.com/flutter/flutter/issues/107248 UpdateScrollOffsetMultiplier(); if (windows_proc_table_ == nullptr) { windows_proc_table_ = std::make_unique<WindowsProcTable>(); } if (text_input_manager_ == nullptr) { text_input_manager_ = std::make_unique<TextInputManager>(); } keyboard_manager_ = std::make_unique<KeyboardManager>(this); InitializeChild("FLUTTERVIEW", width, height); current_cursor_ = ::LoadCursor(nullptr, IDC_ARROW); } // Base constructor for mocks FlutterWindow::FlutterWindow() : touch_id_generator_(kMinTouchDeviceId, kMaxTouchDeviceId) {} FlutterWindow::~FlutterWindow() { Destroy(); } void FlutterWindow::SetView(WindowBindingHandlerDelegate* window) { binding_handler_delegate_ = window; if (direct_manipulation_owner_) { direct_manipulation_owner_->SetBindingHandlerDelegate(window); } if (restored_ && window) { OnWindowStateEvent(WindowStateEvent::kShow); } if (focused_ && window) { OnWindowStateEvent(WindowStateEvent::kFocus); } } float FlutterWindow::GetDpiScale() { return static_cast<float>(GetCurrentDPI()) / static_cast<float>(base_dpi); } PhysicalWindowBounds FlutterWindow::GetPhysicalWindowBounds() { return {GetCurrentWidth(), GetCurrentHeight()}; } void FlutterWindow::UpdateFlutterCursor(const std::string& cursor_name) { SetFlutterCursor(GetCursorByName(cursor_name)); } void FlutterWindow::SetFlutterCursor(HCURSOR cursor) { current_cursor_ = cursor; ::SetCursor(current_cursor_); } void FlutterWindow::OnDpiScale(unsigned int dpi) {}; // When DesktopWindow notifies that a WM_Size message has come in // lets FlutterEngine know about the new size. void FlutterWindow::OnResize(unsigned int width, unsigned int height) { if (binding_handler_delegate_ != nullptr) { binding_handler_delegate_->OnWindowSizeChanged(width, height); } } void FlutterWindow::OnPaint() { if (binding_handler_delegate_ != nullptr) { binding_handler_delegate_->OnWindowRepaint(); } } void FlutterWindow::OnPointerMove(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id, int modifiers_state) { binding_handler_delegate_->OnPointerMove(x, y, device_kind, device_id, modifiers_state); } void FlutterWindow::OnPointerDown(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id, UINT button) { uint64_t flutter_button = ConvertWinButtonToFlutterButton(button); if (flutter_button != 0) { binding_handler_delegate_->OnPointerDown( x, y, device_kind, device_id, static_cast<FlutterPointerMouseButtons>(flutter_button)); } } void FlutterWindow::OnPointerUp(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id, UINT button) { uint64_t flutter_button = ConvertWinButtonToFlutterButton(button); if (flutter_button != 0) { binding_handler_delegate_->OnPointerUp( x, y, device_kind, device_id, static_cast<FlutterPointerMouseButtons>(flutter_button)); } } void FlutterWindow::OnPointerLeave(double x, double y, FlutterPointerDeviceKind device_kind, int32_t device_id) { binding_handler_delegate_->OnPointerLeave(x, y, device_kind, device_id); } void FlutterWindow::OnSetCursor() { ::SetCursor(current_cursor_); } void FlutterWindow::OnText(const std::u16string& text) { binding_handler_delegate_->OnText(text); } void FlutterWindow::OnKey(int key, int scancode, int action, char32_t character, bool extended, bool was_down, KeyEventCallback callback) { binding_handler_delegate_->OnKey(key, scancode, action, character, extended, was_down, std::move(callback)); } void FlutterWindow::OnComposeBegin() { binding_handler_delegate_->OnComposeBegin(); } void FlutterWindow::OnComposeCommit() { binding_handler_delegate_->OnComposeCommit(); } void FlutterWindow::OnComposeEnd() { binding_handler_delegate_->OnComposeEnd(); } void FlutterWindow::OnComposeChange(const std::u16string& text, int cursor_pos) { binding_handler_delegate_->OnComposeChange(text, cursor_pos); } void FlutterWindow::OnUpdateSemanticsEnabled(bool enabled) { binding_handler_delegate_->OnUpdateSemanticsEnabled(enabled); } void FlutterWindow::OnScroll(double delta_x, double delta_y, FlutterPointerDeviceKind device_kind, int32_t device_id) { POINT point; GetCursorPos(&point); ScreenToClient(GetWindowHandle(), &point); binding_handler_delegate_->OnScroll(point.x, point.y, delta_x, delta_y, GetScrollOffsetMultiplier(), device_kind, device_id); } void FlutterWindow::OnCursorRectUpdated(const Rect& rect) { // Convert the rect from Flutter logical coordinates to device coordinates. auto scale = GetDpiScale(); Point origin(rect.left() * scale, rect.top() * scale); Size size(rect.width() * scale, rect.height() * scale); UpdateCursorRect(Rect(origin, size)); } void FlutterWindow::OnResetImeComposing() { AbortImeComposing(); } bool FlutterWindow::OnBitmapSurfaceCleared() { HDC dc = ::GetDC(GetWindowHandle()); bool result = ::PatBlt(dc, 0, 0, current_width_, current_height_, BLACKNESS); ::ReleaseDC(GetWindowHandle(), dc); return result; } bool FlutterWindow::OnBitmapSurfaceUpdated(const void* allocation, size_t row_bytes, size_t height) { HDC dc = ::GetDC(GetWindowHandle()); BITMAPINFO bmi = {}; bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = row_bytes / 4; bmi.bmiHeader.biHeight = -height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = 0; int ret = ::SetDIBitsToDevice(dc, 0, 0, row_bytes / 4, height, 0, 0, 0, height, allocation, &bmi, DIB_RGB_COLORS); ::ReleaseDC(GetWindowHandle(), dc); return ret != 0; } gfx::NativeViewAccessible FlutterWindow::GetNativeViewAccessible() { if (binding_handler_delegate_ == nullptr) { return nullptr; } return binding_handler_delegate_->GetNativeViewAccessible(); } PointerLocation FlutterWindow::GetPrimaryPointerLocation() { POINT point; GetCursorPos(&point); ScreenToClient(GetWindowHandle(), &point); return {(size_t)point.x, (size_t)point.y}; } void FlutterWindow::OnThemeChange() { binding_handler_delegate_->OnHighContrastChanged(); } ui::AXFragmentRootDelegateWin* FlutterWindow::GetAxFragmentRootDelegate() { return binding_handler_delegate_->GetAxFragmentRootDelegate(); } AlertPlatformNodeDelegate* FlutterWindow::GetAlertDelegate() { CreateAxFragmentRoot(); return alert_delegate_.get(); } ui::AXPlatformNodeWin* FlutterWindow::GetAlert() { CreateAxFragmentRoot(); return alert_node_.get(); } void FlutterWindow::OnWindowStateEvent(WindowStateEvent event) { switch (event) { case WindowStateEvent::kShow: restored_ = true; break; case WindowStateEvent::kHide: restored_ = false; focused_ = false; break; case WindowStateEvent::kFocus: focused_ = true; break; case WindowStateEvent::kUnfocus: focused_ = false; break; } HWND hwnd = GetWindowHandle(); if (hwnd && binding_handler_delegate_) { binding_handler_delegate_->OnWindowStateEvent(hwnd, event); } } void FlutterWindow::TrackMouseLeaveEvent(HWND hwnd) { if (!tracking_mouse_leave_) { TRACKMOUSEEVENT tme; tme.cbSize = sizeof(tme); tme.hwndTrack = hwnd; tme.dwFlags = TME_LEAVE; TrackMouseEvent(&tme); tracking_mouse_leave_ = true; } } void FlutterWindow::HandleResize(UINT width, UINT height) { current_width_ = width; current_height_ = height; if (direct_manipulation_owner_) { direct_manipulation_owner_->ResizeViewport(width, height); } OnResize(width, height); } FlutterWindow* FlutterWindow::GetThisFromHandle(HWND const window) noexcept { return reinterpret_cast<FlutterWindow*>( GetWindowLongPtr(window, GWLP_USERDATA)); } void FlutterWindow::UpdateScrollOffsetMultiplier() { UINT lines_per_scroll = kLinesPerScrollWindowsDefault; // Get lines per scroll wheel value from Windows SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &lines_per_scroll, 0); // This logic is based off Chromium's implementation // https://source.chromium.org/chromium/chromium/src/+/main:ui/events/blink/web_input_event_builders_win.cc;l=319-331 scroll_offset_multiplier_ = static_cast<float>(lines_per_scroll) * 100.0 / 3.0; } void FlutterWindow::InitializeChild(const char* title, unsigned int width, unsigned int height) { Destroy(); std::wstring converted_title = NarrowToWide(title); WNDCLASS window_class = RegisterWindowClass(converted_title); auto* result = CreateWindowEx( 0, window_class.lpszClassName, converted_title.c_str(), WS_CHILD | WS_VISIBLE, CW_DEFAULT, CW_DEFAULT, width, height, HWND_MESSAGE, nullptr, window_class.hInstance, this); if (result == nullptr) { auto error = GetLastError(); LPWSTR message = nullptr; size_t size = FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&message), 0, NULL); OutputDebugString(message); LocalFree(message); } SetUserObjectInformationA(GetCurrentProcess(), UOI_TIMERPROC_EXCEPTION_SUPPRESSION, FALSE, 1); // SetTimer is not precise, if a 16 ms interval is requested, it will instead // often fire in an interval of 32 ms. Providing a value of 14 will ensure it // runs every 16 ms, which will allow for 60 Hz trackpad gesture events, which // is the maximal frequency supported by SetTimer. SetTimer(result, kDirectManipulationTimer, 14, nullptr); direct_manipulation_owner_ = std::make_unique<DirectManipulationOwner>(this); direct_manipulation_owner_->Init(width, height); } HWND FlutterWindow::GetWindowHandle() { return window_handle_; } BOOL FlutterWindow::Win32PeekMessage(LPMSG lpMsg, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg) { return ::PeekMessage(lpMsg, window_handle_, wMsgFilterMin, wMsgFilterMax, wRemoveMsg); } uint32_t FlutterWindow::Win32MapVkToChar(uint32_t virtual_key) { return ::MapVirtualKey(virtual_key, MAPVK_VK_TO_CHAR); } UINT FlutterWindow::Win32DispatchMessage(UINT Msg, WPARAM wParam, LPARAM lParam) { return ::SendMessage(window_handle_, Msg, wParam, lParam); } std::wstring FlutterWindow::NarrowToWide(const char* source) { size_t length = strlen(source); size_t outlen = 0; std::wstring wideTitle(length, L'#'); mbstowcs_s(&outlen, &wideTitle[0], length + 1, source, length); return wideTitle; } WNDCLASS FlutterWindow::RegisterWindowClass(std::wstring& title) { window_class_name_ = title; WNDCLASS window_class{}; window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); window_class.lpszClassName = title.c_str(); window_class.style = CS_HREDRAW | CS_VREDRAW; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = GetModuleHandle(nullptr); window_class.hIcon = nullptr; window_class.hbrBackground = 0; window_class.lpszMenuName = nullptr; window_class.lpfnWndProc = WndProc; RegisterClass(&window_class); return window_class; } LRESULT CALLBACK FlutterWindow::WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { if (message == WM_NCCREATE) { auto cs = reinterpret_cast<CREATESTRUCT*>(lparam); SetWindowLongPtr(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(cs->lpCreateParams)); auto that = static_cast<FlutterWindow*>(cs->lpCreateParams); that->window_handle_ = window; that->text_input_manager_->SetWindowHandle(window); RegisterTouchWindow(window, 0); } else if (FlutterWindow* that = GetThisFromHandle(window)) { return that->HandleMessage(message, wparam, lparam); } return DefWindowProc(window, message, wparam, lparam); } LRESULT FlutterWindow::HandleMessage(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { LPARAM result_lparam = lparam; int xPos = 0, yPos = 0; UINT width = 0, height = 0; UINT button_pressed = 0; FlutterPointerDeviceKind device_kind; switch (message) { case kWmDpiChangedBeforeParent: current_dpi_ = GetDpiForHWND(window_handle_); OnDpiScale(current_dpi_); return 0; case WM_SIZE: width = LOWORD(lparam); height = HIWORD(lparam); current_width_ = width; current_height_ = height; HandleResize(width, height); OnWindowStateEvent(width == 0 && height == 0 ? WindowStateEvent::kHide : WindowStateEvent::kShow); break; case WM_PAINT: OnPaint(); break; case WM_TOUCH: { UINT num_points = LOWORD(wparam); touch_points_.resize(num_points); auto touch_input_handle = reinterpret_cast<HTOUCHINPUT>(lparam); if (GetTouchInputInfo(touch_input_handle, num_points, touch_points_.data(), sizeof(TOUCHINPUT))) { for (const auto& touch : touch_points_) { // Generate a mapped ID for the Windows-provided touch ID auto touch_id = touch_id_generator_.GetGeneratedId(touch.dwID); POINT pt = {TOUCH_COORD_TO_PIXEL(touch.x), TOUCH_COORD_TO_PIXEL(touch.y)}; ScreenToClient(window_handle_, &pt); auto x = static_cast<double>(pt.x); auto y = static_cast<double>(pt.y); if (touch.dwFlags & TOUCHEVENTF_DOWN) { OnPointerDown(x, y, kFlutterPointerDeviceKindTouch, touch_id, WM_LBUTTONDOWN); } else if (touch.dwFlags & TOUCHEVENTF_MOVE) { OnPointerMove(x, y, kFlutterPointerDeviceKindTouch, touch_id, 0); } else if (touch.dwFlags & TOUCHEVENTF_UP) { OnPointerUp(x, y, kFlutterPointerDeviceKindTouch, touch_id, WM_LBUTTONDOWN); OnPointerLeave(x, y, kFlutterPointerDeviceKindTouch, touch_id); touch_id_generator_.ReleaseNumber(touch.dwID); } } CloseTouchInputHandle(touch_input_handle); } return 0; } case WM_MOUSEMOVE: device_kind = GetFlutterPointerDeviceKind(); if (device_kind == kFlutterPointerDeviceKindMouse) { TrackMouseLeaveEvent(window_handle_); xPos = GET_X_LPARAM(lparam); yPos = GET_Y_LPARAM(lparam); mouse_x_ = static_cast<double>(xPos); mouse_y_ = static_cast<double>(yPos); int mods = 0; if (wparam & MK_CONTROL) { mods |= kControl; } if (wparam & MK_SHIFT) { mods |= kShift; } OnPointerMove(mouse_x_, mouse_y_, device_kind, kDefaultPointerDeviceId, mods); } break; case WM_MOUSELEAVE: device_kind = GetFlutterPointerDeviceKind(); if (device_kind == kFlutterPointerDeviceKindMouse) { OnPointerLeave(mouse_x_, mouse_y_, device_kind, kDefaultPointerDeviceId); } // Once the tracked event is received, the TrackMouseEvent function // resets. Set to false to make sure it's called once mouse movement is // detected again. tracking_mouse_leave_ = false; break; case WM_SETCURSOR: { UINT hit_test_result = LOWORD(lparam); if (hit_test_result == HTCLIENT) { OnSetCursor(); return TRUE; } break; } case WM_SETFOCUS: OnWindowStateEvent(WindowStateEvent::kFocus); ::CreateCaret(window_handle_, nullptr, 1, 1); break; case WM_KILLFOCUS: OnWindowStateEvent(WindowStateEvent::kUnfocus); ::DestroyCaret(); break; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: case WM_XBUTTONDOWN: device_kind = GetFlutterPointerDeviceKind(); if (device_kind != kFlutterPointerDeviceKindMouse) { break; } if (message == WM_LBUTTONDOWN) { // Capture the pointer in case the user drags outside the client area. // In this case, the "mouse leave" event is delayed until the user // releases the button. It's only activated on left click given that // it's more common for apps to handle dragging with only the left // button. SetCapture(window_handle_); } button_pressed = message; if (message == WM_XBUTTONDOWN) { button_pressed = GET_XBUTTON_WPARAM(wparam); } xPos = GET_X_LPARAM(lparam); yPos = GET_Y_LPARAM(lparam); OnPointerDown(static_cast<double>(xPos), static_cast<double>(yPos), device_kind, kDefaultPointerDeviceId, button_pressed); break; case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: case WM_XBUTTONUP: device_kind = GetFlutterPointerDeviceKind(); if (device_kind != kFlutterPointerDeviceKindMouse) { break; } if (message == WM_LBUTTONUP) { ReleaseCapture(); } button_pressed = message; if (message == WM_XBUTTONUP) { button_pressed = GET_XBUTTON_WPARAM(wparam); } xPos = GET_X_LPARAM(lparam); yPos = GET_Y_LPARAM(lparam); OnPointerUp(static_cast<double>(xPos), static_cast<double>(yPos), device_kind, kDefaultPointerDeviceId, button_pressed); break; case WM_MOUSEWHEEL: OnScroll(0.0, -(static_cast<short>(HIWORD(wparam)) / static_cast<double>(WHEEL_DELTA)), kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId); break; case WM_MOUSEHWHEEL: OnScroll((static_cast<short>(HIWORD(wparam)) / static_cast<double>(WHEEL_DELTA)), 0.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId); break; case WM_GETOBJECT: { LRESULT lresult = OnGetObject(message, wparam, lparam); if (lresult) { return lresult; } break; } case WM_TIMER: if (wparam == kDirectManipulationTimer) { direct_manipulation_owner_->Update(); return 0; } break; case DM_POINTERHITTEST: { if (direct_manipulation_owner_) { UINT contact_id = GET_POINTERID_WPARAM(wparam); POINTER_INPUT_TYPE pointer_type; if (windows_proc_table_->GetPointerType(contact_id, &pointer_type) && pointer_type == PT_TOUCHPAD) { direct_manipulation_owner_->SetContact(contact_id); } } break; } case WM_INPUTLANGCHANGE: // TODO(cbracken): pass this to TextInputManager to aid with // language-specific issues. break; case WM_IME_SETCONTEXT: OnImeSetContext(message, wparam, lparam); // Strip the ISC_SHOWUICOMPOSITIONWINDOW bit from lparam before passing it // to DefWindowProc() so that the composition window is hidden since // Flutter renders the composing string itself. result_lparam &= ~ISC_SHOWUICOMPOSITIONWINDOW; break; case WM_IME_STARTCOMPOSITION: OnImeStartComposition(message, wparam, lparam); // Suppress further processing by DefWindowProc() so that the default // system IME style isn't used, but rather the one set in the // WM_IME_SETCONTEXT handler. return TRUE; case WM_IME_COMPOSITION: OnImeComposition(message, wparam, lparam); if (lparam & GCS_RESULTSTR || lparam & GCS_COMPSTR) { // Suppress further processing by DefWindowProc() since otherwise it // will emit the result string as WM_CHAR messages on commit. Instead, // committing the composing text to the EditableText string is handled // in TextInputModel::CommitComposing, triggered by // OnImeEndComposition(). return TRUE; } break; case WM_IME_ENDCOMPOSITION: OnImeEndComposition(message, wparam, lparam); return TRUE; case WM_IME_REQUEST: OnImeRequest(message, wparam, lparam); break; case WM_UNICHAR: { // Tell third-pary app, we can support Unicode. if (wparam == UNICODE_NOCHAR) return TRUE; // DefWindowProc will send WM_CHAR for this WM_UNICHAR. break; } case WM_THEMECHANGED: OnThemeChange(); break; case WM_DEADCHAR: case WM_SYSDEADCHAR: case WM_CHAR: case WM_SYSCHAR: case WM_KEYDOWN: case WM_SYSKEYDOWN: case WM_KEYUP: case WM_SYSKEYUP: if (keyboard_manager_->HandleMessage(message, wparam, lparam)) { return 0; } break; } return Win32DefWindowProc(window_handle_, message, wparam, result_lparam); } LRESULT FlutterWindow::OnGetObject(UINT const message, WPARAM const wparam, LPARAM const lparam) { LRESULT reference_result = static_cast<LRESULT>(0L); // Only the lower 32 bits of lparam are valid when checking the object id // because it sometimes gets sign-extended incorrectly (but not always). DWORD obj_id = static_cast<DWORD>(static_cast<DWORD_PTR>(lparam)); bool is_uia_request = static_cast<DWORD>(UiaRootObjectId) == obj_id; bool is_msaa_request = static_cast<DWORD>(OBJID_CLIENT) == obj_id; if (is_uia_request || is_msaa_request) { // On Windows, we don't get a notification that the screen reader has been // enabled or disabled. There is an API to query for screen reader state, // but that state isn't set by all screen readers, including by Narrator, // the screen reader that ships with Windows: // https://docs.microsoft.com/en-us/windows/win32/winauto/screen-reader-parameter // // Instead, we enable semantics in Flutter if Windows issues queries for // Microsoft Active Accessibility (MSAA) COM objects. OnUpdateSemanticsEnabled(true); } gfx::NativeViewAccessible root_view = GetNativeViewAccessible(); // TODO(schectman): UIA is currently disabled by default. // https://github.com/flutter/flutter/issues/114547 if (root_view) { CreateAxFragmentRoot(); if (is_uia_request) { #ifdef FLUTTER_ENGINE_USE_UIA // Retrieve UIA object for the root view. Microsoft::WRL::ComPtr<IRawElementProviderSimple> root; if (SUCCEEDED( ax_fragment_root_->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&root)))) { // Return the UIA object via UiaReturnRawElementProvider(). See: // https://docs.microsoft.com/en-us/windows/win32/winauto/wm-getobject reference_result = UiaReturnRawElementProvider(window_handle_, wparam, lparam, root.Get()); } else { FML_LOG(ERROR) << "Failed to query AX fragment root."; } #endif // FLUTTER_ENGINE_USE_UIA } else if (is_msaa_request) { // Create the accessibility root if it does not already exist. // Return the IAccessible for the root view. Microsoft::WRL::ComPtr<IAccessible> root; ax_fragment_root_->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&root)); reference_result = LresultFromObject(IID_IAccessible, wparam, root.Get()); } } return reference_result; } void FlutterWindow::OnImeSetContext(UINT const message, WPARAM const wparam, LPARAM const lparam) { if (wparam != 0) { text_input_manager_->CreateImeWindow(); } } void FlutterWindow::OnImeStartComposition(UINT const message, WPARAM const wparam, LPARAM const lparam) { text_input_manager_->CreateImeWindow(); OnComposeBegin(); } void FlutterWindow::OnImeComposition(UINT const message, WPARAM const wparam, LPARAM const lparam) { // Update the IME window position. text_input_manager_->UpdateImeWindow(); if (lparam == 0) { OnComposeChange(u"", 0); OnComposeCommit(); } // Process GCS_RESULTSTR at fisrt, because Google Japanese Input and ATOK send // both GCS_RESULTSTR and GCS_COMPSTR to commit composed text and send new // composing text. if (lparam & GCS_RESULTSTR) { // Commit but don't end composing. // Read the committed composing string. long pos = text_input_manager_->GetComposingCursorPosition(); std::optional<std::u16string> text = text_input_manager_->GetResultString(); if (text) { OnComposeChange(text.value(), pos); OnComposeCommit(); } } if (lparam & GCS_COMPSTR) { // Read the in-progress composing string. long pos = text_input_manager_->GetComposingCursorPosition(); std::optional<std::u16string> text = text_input_manager_->GetComposingString(); if (text) { OnComposeChange(text.value(), pos); } } } void FlutterWindow::OnImeEndComposition(UINT const message, WPARAM const wparam, LPARAM const lparam) { text_input_manager_->DestroyImeWindow(); OnComposeEnd(); } void FlutterWindow::OnImeRequest(UINT const message, WPARAM const wparam, LPARAM const lparam) { // TODO(cbracken): Handle IMR_RECONVERTSTRING, IMR_DOCUMENTFEED, // and IMR_QUERYCHARPOSITION messages. // https://github.com/flutter/flutter/issues/74547 } void FlutterWindow::AbortImeComposing() { text_input_manager_->AbortComposing(); } void FlutterWindow::UpdateCursorRect(const Rect& rect) { text_input_manager_->UpdateCaretRect(rect); } UINT FlutterWindow::GetCurrentDPI() { return current_dpi_; } UINT FlutterWindow::GetCurrentWidth() { return current_width_; } UINT FlutterWindow::GetCurrentHeight() { return current_height_; } float FlutterWindow::GetScrollOffsetMultiplier() { return scroll_offset_multiplier_; } LRESULT FlutterWindow::Win32DefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { return ::DefWindowProc(hWnd, Msg, wParam, lParam); } void FlutterWindow::Destroy() { if (window_handle_) { text_input_manager_->SetWindowHandle(nullptr); DestroyWindow(window_handle_); window_handle_ = nullptr; } UnregisterClass(window_class_name_.c_str(), nullptr); } void FlutterWindow::CreateAxFragmentRoot() { if (ax_fragment_root_) { return; } ax_fragment_root_ = std::make_unique<ui::AXFragmentRootWin>( window_handle_, GetAxFragmentRootDelegate()); alert_delegate_ = std::make_unique<AlertPlatformNodeDelegate>(*ax_fragment_root_); ui::AXPlatformNode* alert_node = ui::AXPlatformNodeWin::Create(alert_delegate_.get()); alert_node_.reset(static_cast<ui::AXPlatformNodeWin*>(alert_node)); ax_fragment_root_->SetAlertNode(alert_node_.get()); } } // namespace flutter
engine/shell/platform/windows/flutter_window.cc/0
{ "file_path": "engine/shell/platform/windows/flutter_window.cc", "repo_id": "engine", "token_count": 14233 }
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_KEYBOARD_HANDLER_BASE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_HANDLER_BASE_H_ #include <string> namespace flutter { // Interface for classes that handles keyboard input events. // // Keyboard handlers are added to |FlutterWindowsView| in a chain. // When a key event arrives, |KeyboardHook| is called on each handler // until the first one that returns true. Then the proper text hooks // are called on each handler. class KeyboardHandlerBase { public: using KeyEventCallback = std::function<void(bool)>; virtual ~KeyboardHandlerBase() = default; // A function for hooking into keyboard input. virtual void KeyboardHook(int key, int scancode, int action, char32_t character, bool extended, bool was_down, KeyEventCallback callback) = 0; // If needed, synthesize modifier keys events by comparing the // given modifiers state to the known pressing state.. virtual void SyncModifiersIfNeeded(int modifiers_state) = 0; // Returns the keyboard pressed state. // // Returns the keyboard pressed state. The map contains one entry per // pressed keys, mapping from the logical key to the physical key. virtual std::map<uint64_t, uint64_t> GetPressedState() = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_HANDLER_BASE_H_
engine/shell/platform/windows/keyboard_handler_base.h/0
{ "file_path": "engine/shell/platform/windows/keyboard_handler_base.h", "repo_id": "engine", "token_count": 603 }
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. #include "flutter/shell/platform/windows/platform_handler.h" #include <windows.h> #include <cstring> #include <optional> #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" #include "flutter/fml/platform/win/wstring_conversion.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h" #include "flutter/shell/platform/common/json_method_codec.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" static constexpr char kChannelName[] = "flutter/platform"; static constexpr char kGetClipboardDataMethod[] = "Clipboard.getData"; static constexpr char kHasStringsClipboardMethod[] = "Clipboard.hasStrings"; static constexpr char kSetClipboardDataMethod[] = "Clipboard.setData"; static constexpr char kExitApplicationMethod[] = "System.exitApplication"; static constexpr char kRequestAppExitMethod[] = "System.requestAppExit"; static constexpr char kInitializationCompleteMethod[] = "System.initializationComplete"; static constexpr char kPlaySoundMethod[] = "SystemSound.play"; static constexpr char kExitCodeKey[] = "exitCode"; static constexpr char kExitTypeKey[] = "type"; static constexpr char kExitResponseKey[] = "response"; static constexpr char kExitResponseCancel[] = "cancel"; static constexpr char kExitResponseExit[] = "exit"; static constexpr char kTextPlainFormat[] = "text/plain"; static constexpr char kTextKey[] = "text"; static constexpr char kUnknownClipboardFormatMessage[] = "Unknown clipboard format"; static constexpr char kValueKey[] = "value"; static constexpr int kAccessDeniedErrorCode = 5; static constexpr int kErrorSuccess = 0; static constexpr char kExitRequestError[] = "ExitApplication error"; static constexpr char kInvalidExitRequestMessage[] = "Invalid application exit request"; namespace flutter { namespace { // A scoped wrapper for GlobalAlloc/GlobalFree. class ScopedGlobalMemory { public: // Allocates |bytes| bytes of global memory with the given flags. ScopedGlobalMemory(unsigned int flags, size_t bytes) { memory_ = ::GlobalAlloc(flags, bytes); if (!memory_) { FML_LOG(ERROR) << "Unable to allocate global memory: " << ::GetLastError(); } } ~ScopedGlobalMemory() { if (memory_) { if (::GlobalFree(memory_) != nullptr) { FML_LOG(ERROR) << "Failed to free global allocation: " << ::GetLastError(); } } } // Returns the memory pointer, which will be nullptr if allocation failed. void* get() { return memory_; } void* release() { void* memory = memory_; memory_ = nullptr; return memory; } private: HGLOBAL memory_; FML_DISALLOW_COPY_AND_ASSIGN(ScopedGlobalMemory); }; // A scoped wrapper for GlobalLock/GlobalUnlock. class ScopedGlobalLock { public: // Attempts to acquire a global lock on |memory| for the life of this object. ScopedGlobalLock(HGLOBAL memory) { source_ = memory; if (memory) { locked_memory_ = ::GlobalLock(memory); if (!locked_memory_) { FML_LOG(ERROR) << "Unable to acquire global lock: " << ::GetLastError(); } } } ~ScopedGlobalLock() { if (locked_memory_) { if (!::GlobalUnlock(source_)) { DWORD error = ::GetLastError(); if (error != NO_ERROR) { FML_LOG(ERROR) << "Unable to release global lock: " << ::GetLastError(); } } } } // Returns the locked memory pointer, which will be nullptr if acquiring the // lock failed. void* get() { return locked_memory_; } private: HGLOBAL source_; void* locked_memory_; FML_DISALLOW_COPY_AND_ASSIGN(ScopedGlobalLock); }; // A Clipboard wrapper that automatically closes the clipboard when it goes out // of scope. class ScopedClipboard : public ScopedClipboardInterface { public: ScopedClipboard(); virtual ~ScopedClipboard(); int Open(HWND window) override; bool HasString() override; std::variant<std::wstring, int> GetString() override; int SetString(const std::wstring string) override; private: bool opened_ = false; FML_DISALLOW_COPY_AND_ASSIGN(ScopedClipboard); }; ScopedClipboard::ScopedClipboard() {} ScopedClipboard::~ScopedClipboard() { if (opened_) { ::CloseClipboard(); } } int ScopedClipboard::Open(HWND window) { opened_ = ::OpenClipboard(window); if (!opened_) { return ::GetLastError(); } return kErrorSuccess; } bool ScopedClipboard::HasString() { // Allow either plain text format, since getting data will auto-interpolate. return ::IsClipboardFormatAvailable(CF_UNICODETEXT) || ::IsClipboardFormatAvailable(CF_TEXT); } std::variant<std::wstring, int> ScopedClipboard::GetString() { FML_DCHECK(opened_) << "Called GetString when clipboard is closed"; HANDLE data = ::GetClipboardData(CF_UNICODETEXT); if (data == nullptr) { return ::GetLastError(); } ScopedGlobalLock locked_data(data); if (!locked_data.get()) { return ::GetLastError(); } return static_cast<wchar_t*>(locked_data.get()); } int ScopedClipboard::SetString(const std::wstring string) { FML_DCHECK(opened_) << "Called GetString when clipboard is closed"; if (!::EmptyClipboard()) { return ::GetLastError(); } size_t null_terminated_byte_count = sizeof(decltype(string)::traits_type::char_type) * (string.size() + 1); ScopedGlobalMemory destination_memory(GMEM_MOVEABLE, null_terminated_byte_count); ScopedGlobalLock locked_memory(destination_memory.get()); if (!locked_memory.get()) { return ::GetLastError(); } memcpy(locked_memory.get(), string.c_str(), null_terminated_byte_count); if (!::SetClipboardData(CF_UNICODETEXT, locked_memory.get())) { return ::GetLastError(); } // The clipboard now owns the global memory. destination_memory.release(); return kErrorSuccess; } } // namespace static AppExitType StringToAppExitType(const std::string& string) { if (string.compare(PlatformHandler::kExitTypeRequired) == 0) { return AppExitType::required; } else if (string.compare(PlatformHandler::kExitTypeCancelable) == 0) { return AppExitType::cancelable; } FML_LOG(ERROR) << string << " is not recognized as a valid exit type."; return AppExitType::required; } PlatformHandler::PlatformHandler( BinaryMessenger* messenger, FlutterWindowsEngine* engine, std::optional<std::function<std::unique_ptr<ScopedClipboardInterface>()>> scoped_clipboard_provider) : channel_(std::make_unique<MethodChannel<rapidjson::Document>>( messenger, kChannelName, &JsonMethodCodec::GetInstance())), engine_(engine) { channel_->SetMethodCallHandler( [this](const MethodCall<rapidjson::Document>& call, std::unique_ptr<MethodResult<rapidjson::Document>> result) { HandleMethodCall(call, std::move(result)); }); if (scoped_clipboard_provider.has_value()) { scoped_clipboard_provider_ = scoped_clipboard_provider.value(); } else { scoped_clipboard_provider_ = []() { return std::make_unique<ScopedClipboard>(); }; } } PlatformHandler::~PlatformHandler() = default; void PlatformHandler::GetPlainText( std::unique_ptr<MethodResult<rapidjson::Document>> result, std::string_view key) { // TODO(loicsharma): Remove implicit view assumption. // https://github.com/flutter/flutter/issues/142845 const FlutterWindowsView* view = engine_->view(kImplicitViewId); if (view == nullptr) { result->Error(kClipboardError, "Clipboard is not available in Windows headless mode"); return; } std::unique_ptr<ScopedClipboardInterface> clipboard = scoped_clipboard_provider_(); int open_result = clipboard->Open(view->GetWindowHandle()); if (open_result != kErrorSuccess) { rapidjson::Document error_code; error_code.SetInt(open_result); result->Error(kClipboardError, "Unable to open clipboard", error_code); return; } if (!clipboard->HasString()) { result->Success(rapidjson::Document()); return; } std::variant<std::wstring, int> get_string_result = clipboard->GetString(); if (std::holds_alternative<int>(get_string_result)) { rapidjson::Document error_code; error_code.SetInt(std::get<int>(get_string_result)); result->Error(kClipboardError, "Unable to get clipboard data", error_code); return; } rapidjson::Document document; document.SetObject(); rapidjson::Document::AllocatorType& allocator = document.GetAllocator(); document.AddMember( rapidjson::Value(key.data(), allocator), rapidjson::Value( fml::WideStringToUtf8(std::get<std::wstring>(get_string_result)), allocator), allocator); result->Success(document); } void PlatformHandler::GetHasStrings( std::unique_ptr<MethodResult<rapidjson::Document>> result) { // TODO(loicsharma): Remove implicit view assumption. // https://github.com/flutter/flutter/issues/142845 const FlutterWindowsView* view = engine_->view(kImplicitViewId); if (view == nullptr) { result->Error(kClipboardError, "Clipboard is not available in Windows headless mode"); return; } std::unique_ptr<ScopedClipboardInterface> clipboard = scoped_clipboard_provider_(); bool hasStrings; int open_result = clipboard->Open(view->GetWindowHandle()); if (open_result != kErrorSuccess) { // Swallow errors of type ERROR_ACCESS_DENIED. These happen when the app is // not in the foreground and GetHasStrings is irrelevant. // See https://github.com/flutter/flutter/issues/95817. if (open_result != kAccessDeniedErrorCode) { rapidjson::Document error_code; error_code.SetInt(open_result); result->Error(kClipboardError, "Unable to open clipboard", error_code); return; } hasStrings = false; } else { hasStrings = clipboard->HasString(); } rapidjson::Document document; document.SetObject(); rapidjson::Document::AllocatorType& allocator = document.GetAllocator(); document.AddMember(rapidjson::Value(kValueKey, allocator), rapidjson::Value(hasStrings), allocator); result->Success(document); } void PlatformHandler::SetPlainText( const std::string& text, std::unique_ptr<MethodResult<rapidjson::Document>> result) { // TODO(loicsharma): Remove implicit view assumption. // https://github.com/flutter/flutter/issues/142845 const FlutterWindowsView* view = engine_->view(kImplicitViewId); if (view == nullptr) { result->Error(kClipboardError, "Clipboard is not available in Windows headless mode"); return; } std::unique_ptr<ScopedClipboardInterface> clipboard = scoped_clipboard_provider_(); int open_result = clipboard->Open(view->GetWindowHandle()); if (open_result != kErrorSuccess) { rapidjson::Document error_code; error_code.SetInt(open_result); result->Error(kClipboardError, "Unable to open clipboard", error_code); return; } int set_result = clipboard->SetString(fml::Utf8ToWideString(text)); if (set_result != kErrorSuccess) { rapidjson::Document error_code; error_code.SetInt(set_result); result->Error(kClipboardError, "Unable to set clipboard data", error_code); return; } result->Success(); } void PlatformHandler::SystemSoundPlay( const std::string& sound_type, std::unique_ptr<MethodResult<rapidjson::Document>> result) { if (sound_type.compare(kSoundTypeAlert) == 0) { MessageBeep(MB_OK); result->Success(); } else { result->NotImplemented(); } } void PlatformHandler::SystemExitApplication( AppExitType exit_type, UINT exit_code, std::unique_ptr<MethodResult<rapidjson::Document>> result) { rapidjson::Document result_doc; result_doc.SetObject(); if (exit_type == AppExitType::required) { QuitApplication(std::nullopt, std::nullopt, std::nullopt, exit_code); result_doc.GetObjectW().AddMember(kExitResponseKey, kExitResponseExit, result_doc.GetAllocator()); result->Success(result_doc); } else { RequestAppExit(std::nullopt, std::nullopt, std::nullopt, exit_type, exit_code); result_doc.GetObjectW().AddMember(kExitResponseKey, kExitResponseCancel, result_doc.GetAllocator()); result->Success(result_doc); } } // Indicates whether an exit request may be canceled by the framework. // These values must be kept in sync with ExitType in platform_handler.h static constexpr const char* kExitTypeNames[] = { PlatformHandler::kExitTypeRequired, PlatformHandler::kExitTypeCancelable}; void PlatformHandler::RequestAppExit(std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, AppExitType exit_type, UINT exit_code) { auto callback = std::make_unique<MethodResultFunctions<rapidjson::Document>>( [this, exit_code, hwnd, wparam, lparam](const rapidjson::Document* response) { RequestAppExitSuccess(hwnd, wparam, lparam, response, exit_code); }, nullptr, nullptr); auto args = std::make_unique<rapidjson::Document>(); args->SetObject(); args->GetObjectW().AddMember( kExitTypeKey, std::string(kExitTypeNames[static_cast<int>(exit_type)]), args->GetAllocator()); channel_->InvokeMethod(kRequestAppExitMethod, std::move(args), std::move(callback)); } void PlatformHandler::RequestAppExitSuccess(std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, const rapidjson::Document* result, UINT exit_code) { rapidjson::Value::ConstMemberIterator itr = result->FindMember(kExitResponseKey); if (itr == result->MemberEnd() || !itr->value.IsString()) { FML_LOG(ERROR) << "Application request response did not contain a valid " "response value"; return; } const std::string& exit_type = itr->value.GetString(); if (exit_type.compare(kExitResponseExit) == 0) { QuitApplication(hwnd, wparam, lparam, exit_code); } } void PlatformHandler::QuitApplication(std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, UINT exit_code) { engine_->OnQuit(hwnd, wparam, lparam, exit_code); } void PlatformHandler::HandleMethodCall( const MethodCall<rapidjson::Document>& method_call, std::unique_ptr<MethodResult<rapidjson::Document>> result) { const std::string& method = method_call.method_name(); if (method.compare(kExitApplicationMethod) == 0) { const rapidjson::Value& arguments = method_call.arguments()[0]; rapidjson::Value::ConstMemberIterator itr = arguments.FindMember(kExitTypeKey); if (itr == arguments.MemberEnd() || !itr->value.IsString()) { result->Error(kExitRequestError, kInvalidExitRequestMessage); return; } const std::string& exit_type = itr->value.GetString(); itr = arguments.FindMember(kExitCodeKey); if (itr == arguments.MemberEnd() || !itr->value.IsInt()) { result->Error(kExitRequestError, kInvalidExitRequestMessage); return; } UINT exit_code = arguments[kExitCodeKey].GetInt(); SystemExitApplication(StringToAppExitType(exit_type), exit_code, std::move(result)); } else if (method.compare(kGetClipboardDataMethod) == 0) { // Only one string argument is expected. const rapidjson::Value& format = method_call.arguments()[0]; if (strcmp(format.GetString(), kTextPlainFormat) != 0) { result->Error(kClipboardError, kUnknownClipboardFormatMessage); return; } GetPlainText(std::move(result), kTextKey); } else if (method.compare(kHasStringsClipboardMethod) == 0) { // Only one string argument is expected. const rapidjson::Value& format = method_call.arguments()[0]; if (strcmp(format.GetString(), kTextPlainFormat) != 0) { result->Error(kClipboardError, kUnknownClipboardFormatMessage); return; } GetHasStrings(std::move(result)); } else if (method.compare(kSetClipboardDataMethod) == 0) { const rapidjson::Value& document = *method_call.arguments(); rapidjson::Value::ConstMemberIterator itr = document.FindMember(kTextKey); if (itr == document.MemberEnd()) { result->Error(kClipboardError, kUnknownClipboardFormatMessage); return; } if (!itr->value.IsString()) { result->Error(kClipboardError, kUnknownClipboardFormatMessage); return; } SetPlainText(itr->value.GetString(), std::move(result)); } else if (method.compare(kPlaySoundMethod) == 0) { // Only one string argument is expected. const rapidjson::Value& sound_type = method_call.arguments()[0]; SystemSoundPlay(sound_type.GetString(), std::move(result)); } else if (method.compare(kInitializationCompleteMethod) == 0) { // Deprecated but should not cause an error. result->Success(); } else { result->NotImplemented(); } } } // namespace flutter
engine/shell/platform/windows/platform_handler.cc/0
{ "file_path": "engine/shell/platform/windows/platform_handler.cc", "repo_id": "engine", "token_count": 6645 }
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. #include <cstring> #include <cwchar> #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/system_utils.h" #include "flutter/shell/platform/windows/testing/mock_windows_proc_table.h" #include "gtest/gtest.h" namespace flutter { namespace testing { TEST(SystemUtils, GetPreferredLanguageInfo) { WindowsProcTable proc_table; std::vector<LanguageInfo> languages = GetPreferredLanguageInfo(WindowsProcTable()); // There should be at least one language. ASSERT_GE(languages.size(), 1); // The info should have a valid languge. EXPECT_GE(languages[0].language.size(), 2); } TEST(SystemUtils, GetPreferredLanguages) { MockWindowsProcTable proc_table; EXPECT_CALL(proc_table, GetThreadPreferredUILanguages) .WillRepeatedly( [](DWORD flags, PULONG count, PZZWSTR languages, PULONG size) { // Languages string ends in a double-null. static const wchar_t lang[] = L"en-US\0"; static const size_t lang_len = sizeof(lang) / sizeof(wchar_t); static const int cnt = 1; if (languages == nullptr) { *size = lang_len; *count = cnt; } else if (*size >= lang_len) { memcpy(languages, lang, lang_len * sizeof(wchar_t)); } return TRUE; }); std::vector<std::wstring> languages = GetPreferredLanguages(proc_table); // There should be at least one language. ASSERT_GE(languages.size(), 1); // The language should be non-empty. EXPECT_FALSE(languages[0].empty()); // There should not be a trailing null from the parsing step. EXPECT_EQ(languages[0].size(), wcslen(languages[0].c_str())); EXPECT_EQ(languages[0], L"en-US"); } TEST(SystemUtils, ParseLanguageNameGeneric) { LanguageInfo info = ParseLanguageName(L"en"); EXPECT_EQ(info.language, "en"); EXPECT_TRUE(info.region.empty()); EXPECT_TRUE(info.script.empty()); } TEST(SystemUtils, ParseLanguageNameWithRegion) { LanguageInfo info = ParseLanguageName(L"hu-HU"); EXPECT_EQ(info.language, "hu"); EXPECT_EQ(info.region, "HU"); EXPECT_TRUE(info.script.empty()); } TEST(SystemUtils, ParseLanguageNameWithScript) { LanguageInfo info = ParseLanguageName(L"us-Latn"); EXPECT_EQ(info.language, "us"); EXPECT_TRUE(info.region.empty()); EXPECT_EQ(info.script, "Latn"); } TEST(SystemUtils, ParseLanguageNameWithRegionAndScript) { LanguageInfo info = ParseLanguageName(L"uz-Latn-UZ"); EXPECT_EQ(info.language, "uz"); EXPECT_EQ(info.region, "UZ"); EXPECT_EQ(info.script, "Latn"); } TEST(SystemUtils, ParseLanguageNameWithSuplementalLanguage) { LanguageInfo info = ParseLanguageName(L"en-US-x-fabricam"); EXPECT_EQ(info.language, "en"); EXPECT_EQ(info.region, "US"); EXPECT_TRUE(info.script.empty()); } // Ensure that ISO 639-2/T codes are handled. TEST(SystemUtils, ParseLanguageNameWithThreeCharacterLanguage) { LanguageInfo info = ParseLanguageName(L"ale-ZZ"); EXPECT_EQ(info.language, "ale"); EXPECT_EQ(info.region, "ZZ"); EXPECT_TRUE(info.script.empty()); } TEST(SystemUtils, GetUserTimeFormat) { // The value varies based on machine; just ensure that something is returned. EXPECT_FALSE(GetUserTimeFormat().empty()); } TEST(SystemUtils, Prefer24HourTimeHandlesEmptyFormat) { EXPECT_FALSE(Prefer24HourTime(L"")); } TEST(SystemUtils, Prefer24HourTimeHandles12Hour) { EXPECT_FALSE(Prefer24HourTime(L"h:mm:ss tt")); } TEST(SystemUtils, Prefer24HourTimeHandles24Hour) { EXPECT_TRUE(Prefer24HourTime(L"HH:mm:ss")); } } // namespace testing } // namespace flutter
engine/shell/platform/windows/system_utils_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/system_utils_unittests.cc", "repo_id": "engine", "token_count": 1455 }
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_TESTING_MOCK_TEXT_INPUT_MANAGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_TEXT_INPUT_MANAGER_H_ #include <cstring> #include <optional> #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/text_input_manager.h" #include "gmock/gmock.h" namespace flutter { namespace testing { /// Mock for the |Window| base class. class MockTextInputManager : public TextInputManager { public: MockTextInputManager(); virtual ~MockTextInputManager(); MOCK_METHOD(std::optional<std::u16string>, GetComposingString, (), (const, override)); MOCK_METHOD(std::optional<std::u16string>, GetResultString, (), (const, override)); MOCK_METHOD(long, GetComposingCursorPosition, (), (const, override)); private: FML_DISALLOW_COPY_AND_ASSIGN(MockTextInputManager); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_TEXT_INPUT_MANAGER_H_
engine/shell/platform/windows/testing/mock_text_input_manager.h/0
{ "file_path": "engine/shell/platform/windows/testing/mock_text_input_manager.h", "repo_id": "engine", "token_count": 470 }
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/testing/windows_test_context.h" #include "flutter/fml/platform/win/wstring_conversion.h" namespace flutter { namespace testing { WindowsTestContext::WindowsTestContext(std::string_view assets_path) : assets_path_(fml::Utf8ToWideString(assets_path)), native_resolver_(std::make_shared<TestDartNativeResolver>()) { isolate_create_callbacks_.push_back( [weak_resolver = std::weak_ptr<TestDartNativeResolver>{native_resolver_}]() { if (auto resolver = weak_resolver.lock()) { resolver->SetNativeResolverForIsolate(); } }); } WindowsTestContext::~WindowsTestContext() = default; const std::wstring& WindowsTestContext::GetAssetsPath() const { return assets_path_; } const std::wstring& WindowsTestContext::GetIcuDataPath() const { return icu_data_path_; } const std::wstring& WindowsTestContext::GetAotLibraryPath() const { return aot_library_path_; } void WindowsTestContext::AddNativeFunction(std::string_view name, Dart_NativeFunction function) { native_resolver_->AddNativeCallback(std::string{name}, function); } fml::closure WindowsTestContext::GetRootIsolateCallback() { return [this]() { for (auto closure : this->isolate_create_callbacks_) { closure(); } }; } } // namespace testing } // namespace flutter
engine/shell/platform/windows/testing/windows_test_context.cc/0
{ "file_path": "engine/shell/platform/windows/testing/windows_test_context.cc", "repo_id": "engine", "token_count": 562 }
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. #include "windows_lifecycle_manager.h" #include <TlHelp32.h> #include <WinUser.h> #include <Windows.h> #include <tchar.h> #include "flutter/shell/platform/windows/flutter_windows_engine.h" namespace flutter { WindowsLifecycleManager::WindowsLifecycleManager(FlutterWindowsEngine* engine) : engine_(engine) {} WindowsLifecycleManager::~WindowsLifecycleManager() {} void WindowsLifecycleManager::Quit(std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, UINT exit_code) { if (!hwnd.has_value()) { ::PostQuitMessage(exit_code); } else { BASE_CHECK(wparam.has_value() && lparam.has_value()); sent_close_messages_[std::make_tuple(*hwnd, *wparam, *lparam)]++; DispatchMessage(*hwnd, WM_CLOSE, *wparam, *lparam); } } void WindowsLifecycleManager::DispatchMessage(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { PostMessage(hwnd, message, wparam, lparam); } bool WindowsLifecycleManager::HandleCloseMessage(HWND hwnd, WPARAM wparam, LPARAM lparam) { if (!process_exit_) { return false; } auto key = std::make_tuple(hwnd, wparam, lparam); auto itr = sent_close_messages_.find(key); if (itr != sent_close_messages_.end()) { if (itr->second == 1) { sent_close_messages_.erase(itr); } else { sent_close_messages_[key]--; } return false; } if (IsLastWindowOfProcess()) { engine_->RequestApplicationQuit(hwnd, wparam, lparam, AppExitType::cancelable); return true; } return false; } bool WindowsLifecycleManager::WindowProc(HWND hwnd, UINT msg, WPARAM wpar, LPARAM lpar, LRESULT* result) { switch (msg) { // When WM_CLOSE is received from the final window of an application, we // send a request to the framework to see if the app should exit. If it // is, we re-dispatch a new WM_CLOSE message. In order to allow the new // message to reach other delegates, we ignore it here. case WM_CLOSE: return HandleCloseMessage(hwnd, wpar, lpar); // DWM composition can be disabled on Windows 7. // Notify the engine as this can result in screen tearing. case WM_DWMCOMPOSITIONCHANGED: engine_->OnDwmCompositionChanged(); break; case WM_SIZE: if (wpar == SIZE_MAXIMIZED || wpar == SIZE_RESTORED) { OnWindowStateEvent(hwnd, WindowStateEvent::kShow); } else if (wpar == SIZE_MINIMIZED) { OnWindowStateEvent(hwnd, WindowStateEvent::kHide); } break; case WM_SHOWWINDOW: if (!wpar) { OnWindowStateEvent(hwnd, WindowStateEvent::kHide); } else { OnWindowStateEvent(hwnd, WindowStateEvent::kShow); } break; case WM_DESTROY: OnWindowStateEvent(hwnd, WindowStateEvent::kHide); break; } return false; } class ThreadSnapshot { public: ThreadSnapshot() { thread_snapshot_ = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); } ~ThreadSnapshot() { if (thread_snapshot_ != INVALID_HANDLE_VALUE) { ::CloseHandle(thread_snapshot_); } } std::optional<THREADENTRY32> GetFirstThread() { if (thread_snapshot_ == INVALID_HANDLE_VALUE) { FML_LOG(ERROR) << "Failed to get thread snapshot"; return std::nullopt; } THREADENTRY32 thread; thread.dwSize = sizeof(thread); if (!::Thread32First(thread_snapshot_, &thread)) { DWORD error_num = ::GetLastError(); char msg[256]; ::FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error_num, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), msg, 256, nullptr); FML_LOG(ERROR) << "Failed to get thread(" << error_num << "): " << msg; return std::nullopt; } return thread; } bool GetNextThread(THREADENTRY32& thread) { if (thread_snapshot_ == INVALID_HANDLE_VALUE) { return false; } return ::Thread32Next(thread_snapshot_, &thread); } private: HANDLE thread_snapshot_; }; static int64_t NumWindowsForThread(const THREADENTRY32& thread) { int64_t num_windows = 0; ::EnumThreadWindows( thread.th32ThreadID, [](HWND hwnd, LPARAM lparam) { int64_t* windows_ptr = reinterpret_cast<int64_t*>(lparam); if (::GetParent(hwnd) == nullptr) { (*windows_ptr)++; } return *windows_ptr <= 1 ? TRUE : FALSE; }, reinterpret_cast<LPARAM>(&num_windows)); return num_windows; } bool WindowsLifecycleManager::IsLastWindowOfProcess() { DWORD pid = ::GetCurrentProcessId(); ThreadSnapshot thread_snapshot; std::optional<THREADENTRY32> first_thread = thread_snapshot.GetFirstThread(); if (!first_thread.has_value()) { FML_LOG(ERROR) << "No first thread found"; return true; } int num_windows = 0; THREADENTRY32 thread = *first_thread; do { if (thread.th32OwnerProcessID == pid) { num_windows += NumWindowsForThread(thread); if (num_windows > 1) { return false; } } } while (thread_snapshot.GetNextThread(thread)); return num_windows <= 1; } void WindowsLifecycleManager::BeginProcessingLifecycle() { process_lifecycle_ = true; } void WindowsLifecycleManager::BeginProcessingExit() { process_exit_ = true; } void WindowsLifecycleManager::SetLifecycleState(AppLifecycleState state) { if (state_ == state) { return; } state_ = state; if (engine_ && process_lifecycle_) { const char* state_name = AppLifecycleStateToString(state); engine_->SendPlatformMessage("flutter/lifecycle", reinterpret_cast<const uint8_t*>(state_name), strlen(state_name), nullptr, nullptr); } } void WindowsLifecycleManager::OnWindowStateEvent(HWND hwnd, WindowStateEvent event) { // Synthesize an unfocus event when a focused window is hidden. if (event == WindowStateEvent::kHide && focused_windows_.find(hwnd) != focused_windows_.end()) { OnWindowStateEvent(hwnd, WindowStateEvent::kUnfocus); } std::lock_guard guard(state_update_lock_); switch (event) { case WindowStateEvent::kShow: { bool first_shown_window = visible_windows_.empty(); auto pair = visible_windows_.insert(hwnd); if (first_shown_window && pair.second && state_ == AppLifecycleState::kHidden) { SetLifecycleState(AppLifecycleState::kInactive); } break; } case WindowStateEvent::kHide: { bool present = visible_windows_.erase(hwnd); bool empty = visible_windows_.empty(); if (present && empty && (state_ == AppLifecycleState::kResumed || state_ == AppLifecycleState::kInactive)) { SetLifecycleState(AppLifecycleState::kHidden); } break; } case WindowStateEvent::kFocus: { bool first_focused_window = focused_windows_.empty(); auto pair = focused_windows_.insert(hwnd); if (first_focused_window && pair.second && state_ == AppLifecycleState::kInactive) { SetLifecycleState(AppLifecycleState::kResumed); } break; } case WindowStateEvent::kUnfocus: { if (focused_windows_.erase(hwnd) && focused_windows_.empty() && state_ == AppLifecycleState::kResumed) { SetLifecycleState(AppLifecycleState::kInactive); } break; } } } std::optional<LRESULT> WindowsLifecycleManager::ExternalWindowMessage( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { std::optional<flutter::WindowStateEvent> event = std::nullopt; // TODO (schectman): Handle WM_CLOSE messages. // https://github.com/flutter/flutter/issues/131497 switch (message) { case WM_SHOWWINDOW: event = wparam ? flutter::WindowStateEvent::kShow : flutter::WindowStateEvent::kHide; break; case WM_SIZE: switch (wparam) { case SIZE_MINIMIZED: event = flutter::WindowStateEvent::kHide; break; case SIZE_RESTORED: case SIZE_MAXIMIZED: event = flutter::WindowStateEvent::kShow; break; } break; case WM_SETFOCUS: event = flutter::WindowStateEvent::kFocus; break; case WM_KILLFOCUS: event = flutter::WindowStateEvent::kUnfocus; break; case WM_DESTROY: event = flutter::WindowStateEvent::kHide; break; case WM_CLOSE: if (HandleCloseMessage(hwnd, wparam, lparam)) { return NULL; } break; } if (event.has_value()) { OnWindowStateEvent(hwnd, *event); } return std::nullopt; } } // namespace flutter
engine/shell/platform/windows/windows_lifecycle_manager.cc/0
{ "file_path": "engine/shell/platform/windows/windows_lifecycle_manager.cc", "repo_id": "engine", "token_count": 4151 }
377
#!/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 re import shutil import subprocess import sys """Tool for starting a GDB client and server to debug a Flutter engine process on an Android device. Usage: flutter_gdb server com.example.package_name flutter_gdb client com.example.package_name The Android package must be marked as debuggable in its manifest. The "client" command will copy system libraries from the device to the host in order to provide debug symbols. If this has already been done on a previous run for a given device, then you can skip this step by passing --no-pull-libs. """ ADB_LOCAL_PATH = 'third_party/android_tools/sdk/platform-tools/adb' def _get_flutter_root(): path = os.path.dirname(os.path.abspath(__file__)) while os.path.basename(path) != 'src': path = os.path.dirname(path) return path def _get_adb_command(args, flutter_root): if args.adb is None: adb_path = os.path.join(flutter_root, ADB_LOCAL_PATH) else: adb_path = args.adb adb_command = [adb_path] if args.device is not None: adb_command.extend(['-s', args.device]) return adb_command def _find_package_pid(adb_command, package): """Find the pid of the Flutter application process.""" ps_output = subprocess.check_output(adb_command + ['shell', 'ps'], encoding='utf-8') ps_match = re.search('^\S+\s+(\d+).*\s%s' % package, ps_output, re.MULTILINE) if not ps_match: print('Unable to find pid for package %s on device' % package) return None return int(ps_match.group(1)) def _get_device_abi(adb_command): abi_output = subprocess.check_output( adb_command + ['shell', 'getprop', 'ro.product.cpu.abi'], encoding='utf-8').strip() if abi_output.startswith('arm64'): return 'arm64' if abi_output.startswith('arm'): return 'arm' return abi_output def _default_local_engine(abi): """Return the default Flutter build output directory for a given target ABI.""" if abi == 'x86': return 'android_debug_unopt_x86' elif abi == 'x86_64': return 'android_debug_unopt_x64' elif abi == 'arm64': return 'android_debug_unopt_arm64' else: return 'android_debug_unopt' class GdbClient(object): SYSTEM_LIBS_PATH = '/tmp/flutter_gdb_device_libs' def _gdb_local_path(self): GDB_LOCAL_PATH = ('third_party/android_tools/ndk/prebuilt/%s-x86_64/bin/gdb') if sys.platform.startswith('darwin'): return GDB_LOCAL_PATH % 'darwin' else: return GDB_LOCAL_PATH % 'linux' def add_subparser(self, subparsers): parser = subparsers.add_parser('client', help='run a GDB client') parser.add_argument('package', type=str) parser.add_argument('--local-engine', type=str) parser.add_argument('--gdb-port', type=int, default=8888) parser.add_argument('--no-pull-libs', action="store_false", default=True, dest="pull_libs", help="Do not copy system libraries from the device to the host") parser.add_argument('--old-sysroot', action="store_true", default=False, help='Create a sysroot tree suitable for debugging on older (pre-N) versions of Android') parser.set_defaults(func=self.run) def _copy_system_libs(self, adb_command, package, old_sysroot): """Copy libraries used by the Flutter process from the device to the host.""" package_pid = _find_package_pid(adb_command, package) if package_pid is None: return False # Find library files that are mapped into the process. proc_maps = subprocess.check_output( adb_command + ['shell', 'run-as', package, 'cat', '/proc/%d/maps' % package_pid], encoding='utf-8') proc_libs = re.findall('(/system/.*\.(?:so|oat))\s*$', proc_maps, re.MULTILINE) if old_sysroot: device_libs = set((lib, os.path.basename(lib)) for lib in proc_libs) device_libs.add(('/system/bin/linker', 'linker')) else: device_libs = set((lib, lib[1:]) for lib in proc_libs) device_libs.add(('/system/bin/linker', 'system/bin/linker')) device_libs.add(('/system/bin/app_process32', 'system/bin/app_process32')) device_libs.add(('/system/bin/app_process64', 'system/bin/app_process64')) if os.path.isdir(GdbClient.SYSTEM_LIBS_PATH): shutil.rmtree(GdbClient.SYSTEM_LIBS_PATH) dev_null = open(os.devnull, 'w') for lib, local_path in sorted(device_libs): print('Copying %s' % lib) local_path = os.path.join(GdbClient.SYSTEM_LIBS_PATH, local_path) if not os.path.exists(os.path.dirname(local_path)): os.makedirs(os.path.dirname(local_path)) subprocess.call(adb_command + ['pull', lib, local_path], stderr=dev_null) return True def run(self, args): flutter_root = _get_flutter_root() adb_command = _get_adb_command(args, flutter_root) if args.pull_libs: if not self._copy_system_libs(adb_command, args.package, args.old_sysroot): return 1 subprocess.check_call( adb_command + ['forward', 'tcp:%d' % args.gdb_port, 'tcp:%d' % args.gdb_port]) if args.local_engine is None: abi = _get_device_abi(adb_command) local_engine = _default_local_engine(abi) else: local_engine = args.local_engine debug_out_path = os.path.join(flutter_root, 'out/%s' % local_engine) if not os.path.exists(os.path.join(debug_out_path, 'libflutter.so')): print('Unable to find libflutter.so. Make sure you have completed a %s build' % local_engine) return 1 eval_commands = [] if not args.old_sysroot: eval_commands.append('set sysroot %s' % GdbClient.SYSTEM_LIBS_PATH) eval_commands.append('set solib-search-path %s:%s' % (debug_out_path, GdbClient.SYSTEM_LIBS_PATH)) eval_commands.append('target remote localhost:%d' % args.gdb_port) exec_command = [os.path.join(flutter_root, self._gdb_local_path())] for command in eval_commands: exec_command += ['--eval-command', command] os.execv(exec_command[0], exec_command) class GdbServer(object): GDB_SERVER_DEVICE_TMP_PATH = '/data/local/tmp/gdbserver' def add_subparser(self, subparsers): parser = subparsers.add_parser('server', help='run a GDB server on the device') parser.add_argument('package', type=str) parser.add_argument('--gdb-port', type=int, default=8888) parser.set_defaults(func=self.run) def run(self, args): flutter_root = _get_flutter_root() adb_command = _get_adb_command(args, flutter_root) package_pid = _find_package_pid(adb_command, args.package) if package_pid is None: return 1 abi = _get_device_abi(adb_command) gdb_server_local_path = 'third_party/android_tools/ndk/prebuilt/android-%s/gdbserver/gdbserver' % abi # Copy gdbserver to the package's data directory. subprocess.check_call(adb_command + ['push', os.path.join(flutter_root, gdb_server_local_path), GdbServer.GDB_SERVER_DEVICE_TMP_PATH]) gdb_server_device_path = '/data/data/%s/gdbserver' % args.package subprocess.check_call(adb_command + ['shell', 'run-as', args.package, 'cp', '-F', GdbServer.GDB_SERVER_DEVICE_TMP_PATH, gdb_server_device_path]) subprocess.call(adb_command + ['shell', 'run-as', args.package, 'killall', 'gdbserver']) # Run gdbserver. try: subprocess.call(adb_command + ['shell', 'run-as', args.package, gdb_server_device_path, '--attach', ':%d' % args.gdb_port, str(package_pid)]) except KeyboardInterrupt: pass def main(): parser = argparse.ArgumentParser(description='Flutter debugger tool') subparsers = parser.add_subparsers(help='sub-command help') parser.add_argument('--adb', type=str, help='path to ADB tool') parser.add_argument('--device', type=str, help='serial number of the target device') parser.set_defaults(func=lambda args: parser.print_help()) commands = [ GdbClient(), GdbServer(), ] for command in commands: command.add_subparser(subparsers) args = parser.parse_args() return args.func(args) if __name__ == '__main__': sys.exit(main())
engine/sky/tools/flutter_gdb/0
{ "file_path": "engine/sky/tools/flutter_gdb", "repo_id": "engine", "token_count": 4037 }
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_TESTING_ANDROID_NATIVE_ACTIVITY_NATIVE_ACTIVITY_H_ #define FLUTTER_TESTING_ANDROID_NATIVE_ACTIVITY_NATIVE_ACTIVITY_H_ #include <android/native_activity.h> #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief An instance of a native activity. Users of the /// `native_activity_apk` are meant to subclass this and return an /// instance of this subclass from `flutter::NativeActivityMain`. /// /// All methods are called on the Android Platform main-thread. /// Subclasses will usually re-thread calls to a background thread /// for long running tasks as these will lead to ANRs on when /// invoked on the platform thread. /// class NativeActivity { public: virtual ~NativeActivity(); //---------------------------------------------------------------------------- /// @brief Perform graceful termination of the activity. Will eventually /// lead to the other activity lifecycle callback on the way to /// termination. /// /// Can be called from any thread. /// void Terminate(); virtual void OnStart(); virtual void OnStop(); virtual void OnPause(); virtual void OnResume(); virtual std::shared_ptr<fml::Mapping> OnSaveInstanceState(); virtual void OnWindowFocusChanged(bool has_focus); virtual void OnNativeWindowCreated(ANativeWindow* window); virtual void OnNativeWindowResized(ANativeWindow* window); virtual void OnNativeWindowRedrawNeeded(ANativeWindow* window); virtual void OnNativeWindowDestroyed(ANativeWindow* window); virtual void OnInputQueueCreated(AInputQueue* queue); virtual void OnInputQueueDestroyed(AInputQueue* queue); virtual void OnConfigurationChanged(); virtual void OnLowMemory(); protected: explicit NativeActivity(ANativeActivity* activity); private: ANativeActivity* activity_ = nullptr; FML_DISALLOW_COPY_AND_ASSIGN(NativeActivity); }; std::unique_ptr<NativeActivity> NativeActivityMain( ANativeActivity* activity, std::unique_ptr<fml::Mapping> saved_state); } // namespace flutter #endif // FLUTTER_TESTING_ANDROID_NATIVE_ACTIVITY_NATIVE_ACTIVITY_H_
engine/testing/android/native_activity/native_activity.h/0
{ "file_path": "engine/testing/android/native_activity/native_activity.h", "repo_id": "engine", "token_count": 770 }
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. name: android_background_image publish_to: none environment: sdk: '>=3.2.0-0 <4.0.0' # Do not add any dependencies that require more than what is provided in # //third_party/dart/pkg, //third_party/dart/third_party/pkg, or # //third_party/pkg. In particular, package:test is not usable here. # If you do add packages here, make sure you can run `pub get --offline`, and # check the .packages and .package_config to make sure all the paths are # relative to this directory into //third_party/dart, or //third_party/pkg dependencies: sky_engine: any dependency_overrides: sky_engine: path: ../../sky/packages/sky_engine
engine/testing/android_background_image/pubspec.yaml/0
{ "file_path": "engine/testing/android_background_image/pubspec.yaml", "repo_id": "engine", "token_count": 250 }
380
// 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_CANVAS_TEST_H_ #define FLUTTER_TESTING_CANVAS_TEST_H_ #include "flutter/fml/macros.h" #include "flutter/testing/mock_canvas.h" #include "gtest/gtest.h" #include "third_party/skia/include/core/SkColorSpace.h" namespace flutter { namespace testing { // This fixture allows creating tests that make use of a mock |SkCanvas|. template <typename BaseT> class CanvasTestBase : public BaseT { public: CanvasTestBase() = default; MockCanvas& mock_canvas() { return canvas_; } sk_sp<SkColorSpace> mock_color_space() { return color_space_; } private: MockCanvas canvas_; sk_sp<SkColorSpace> color_space_ = SkColorSpace::MakeSRGB(); FML_DISALLOW_COPY_AND_ASSIGN(CanvasTestBase); }; using CanvasTest = CanvasTestBase<::testing::Test>; } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_CANVAS_TEST_H_
engine/testing/canvas_test.h/0
{ "file_path": "engine/testing/canvas_test.h", "repo_id": "engine", "token_count": 367 }
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. // ignore_for_file: avoid_relative_lib_imports import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:litetest/litetest.dart'; import '../../lib/gpu/lib/gpu.dart' as gpu; import 'impeller_enabled.dart'; void main() { // TODO(131346): Remove this once we migrate the Dart GPU API into this space. test('smoketest', () async { final int result = gpu.testProc(); expect(result, 1); final String? message = gpu.testProcWithCallback((int result) { expect(result, 1234); }); expect(message, null); final gpu.FlutterGpuTestClass a = gpu.FlutterGpuTestClass(); a.coolMethod(9847); }); test('gpu.context throws exception for incompatible embedders', () async { try { // ignore: unnecessary_statements gpu.gpuContext; // Force the context to instantiate. if (!impellerEnabled) { fail('Exception not thrown, but no Impeller context available.'); } } catch (e) { if (impellerEnabled) { fail('Exception thrown even though Impeller is enabled.'); } expect( e.toString(), contains( 'Flutter GPU requires the Impeller rendering backend to be enabled.')); } }); test('HostBuffer.emplace', () async { final gpu.HostBuffer hostBuffer = gpu.gpuContext.createHostBuffer(); final gpu.BufferView view0 = hostBuffer .emplace(Int8List.fromList(<int>[0, 1, 2, 3]).buffer.asByteData()); expect(view0.offsetInBytes, 0); expect(view0.lengthInBytes, 4); final gpu.BufferView view1 = hostBuffer .emplace(Int8List.fromList(<int>[0, 1, 2, 3]).buffer.asByteData()); expect(view1.offsetInBytes >= 4, true); expect(view1.lengthInBytes, 4); }, skip: !impellerEnabled); test('GpuContext.createDeviceBuffer', () async { final gpu.DeviceBuffer? deviceBuffer = gpu.gpuContext.createDeviceBuffer(gpu.StorageMode.hostVisible, 4); assert(deviceBuffer != null); expect(deviceBuffer!.sizeInBytes, 4); }, skip: !impellerEnabled); test('DeviceBuffer.overwrite', () async { final gpu.DeviceBuffer? deviceBuffer = gpu.gpuContext.createDeviceBuffer(gpu.StorageMode.hostVisible, 4); assert(deviceBuffer != null); final bool success = deviceBuffer! .overwrite(Int8List.fromList(<int>[0, 1, 2, 3]).buffer.asByteData()); expect(success, true); }, skip: !impellerEnabled); test('DeviceBuffer.overwrite fails when out of bounds', () async { final gpu.DeviceBuffer? deviceBuffer = gpu.gpuContext.createDeviceBuffer(gpu.StorageMode.hostVisible, 4); assert(deviceBuffer != null); final bool success = deviceBuffer!.overwrite( Int8List.fromList(<int>[0, 1, 2, 3]).buffer.asByteData(), destinationOffsetInBytes: 1); expect(success, false); }, skip: !impellerEnabled); test('DeviceBuffer.overwrite throws for negative destination offset', () async { final gpu.DeviceBuffer? deviceBuffer = gpu.gpuContext.createDeviceBuffer(gpu.StorageMode.hostVisible, 4); assert(deviceBuffer != null); try { deviceBuffer!.overwrite( Int8List.fromList(<int>[0, 1, 2, 3]).buffer.asByteData(), destinationOffsetInBytes: -1); fail('Exception not thrown for negative destination offset.'); } catch (e) { expect( e.toString(), contains('destinationOffsetInBytes must be positive')); } }, skip: !impellerEnabled); test('GpuContext.createTexture', () async { final gpu.Texture? texture = gpu.gpuContext.createTexture(gpu.StorageMode.hostVisible, 100, 100); assert(texture != null); // Check the defaults. expect( texture!.coordinateSystem, gpu.TextureCoordinateSystem.renderToTexture); expect(texture.width, 100); expect(texture.height, 100); expect(texture.storageMode, gpu.StorageMode.hostVisible); expect(texture.sampleCount, 1); expect(texture.format, gpu.PixelFormat.r8g8b8a8UNormInt); expect(texture.enableRenderTargetUsage, true); expect(texture.enableShaderReadUsage, true); expect(!texture.enableShaderWriteUsage, true); expect(texture.bytesPerTexel, 4); expect(texture.GetBaseMipLevelSizeInBytes(), 40000); }, skip: !impellerEnabled); test('Texture.overwrite', () async { final gpu.Texture? texture = gpu.gpuContext.createTexture(gpu.StorageMode.hostVisible, 2, 2); assert(texture != null); const ui.Color red = ui.Color.fromARGB(0xFF, 0xFF, 0, 0); const ui.Color green = ui.Color.fromARGB(0xFF, 0, 0xFF, 0); final bool success = texture!.overwrite(Int32List.fromList( <int>[red.value, green.value, green.value, red.value]) .buffer .asByteData()); expect(success, true); }, skip: !impellerEnabled); test('Texture.overwrite throws for wrong buffer size', () async { final gpu.Texture? texture = gpu.gpuContext.createTexture(gpu.StorageMode.hostVisible, 100, 100); assert(texture != null); const ui.Color red = ui.Color.fromARGB(0xFF, 0xFF, 0, 0); try { texture!.overwrite( Int32List.fromList(<int>[red.value, red.value, red.value, red.value]) .buffer .asByteData()); fail('Exception not thrown for wrong buffer size.'); } catch (e) { expect( e.toString(), contains( 'The length of sourceBytes (bytes: 16) must exactly match the size of the base mip level (bytes: 40000)')); } }, skip: !impellerEnabled); test('Texture.asImage returns a valid ui.Image handle', () async { final gpu.Texture? texture = gpu.gpuContext.createTexture(gpu.StorageMode.hostVisible, 100, 100); assert(texture != null); final ui.Image image = texture!.asImage(); expect(image.width, 100); expect(image.height, 100); }, skip: !impellerEnabled); test('Texture.asImage throws when not shader readable', () async { final gpu.Texture? texture = gpu.gpuContext.createTexture( gpu.StorageMode.hostVisible, 100, 100, enableShaderReadUsage: false); assert(texture != null); try { texture!.asImage(); fail('Exception not thrown when not shader readable.'); } catch (e) { expect( e.toString(), contains( 'Only shader readable Flutter GPU textures can be used as UI Images')); } }, skip: !impellerEnabled); }
engine/testing/dart/gpu_test.dart/0
{ "file_path": "engine/testing/dart/gpu_test.dart", "repo_id": "engine", "token_count": 2493 }
382
// 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('MaskFilter - NOP blur does not crash', () async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); final Paint paint = Paint() ..color = const Color(0xff00AA00) ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 0); canvas.saveLayer(const Rect.fromLTRB(-100, -100, 200, 200), paint); canvas.drawRect(const Rect.fromLTRB(0, 0, 100, 100), Paint()); canvas.restore(); final Picture picture = recorder.endRecording(); final SceneBuilder builder = SceneBuilder(); builder.addPicture(Offset.zero, picture); final Scene scene = builder.build(); await scene.toImage(100, 100); }); }
engine/testing/dart/mask_filter_test.dart/0
{ "file_path": "engine/testing/dart/mask_filter_test.dart", "repo_id": "engine", "token_count": 308 }
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:ui'; import 'package:litetest/litetest.dart'; typedef StringFunction = String Function(); typedef IntFunction = int Function(); String top() => 'top'; class Foo { const Foo(); static int getInt() => 1; double getDouble() => 1.0; } void main() { test('PluginUtilities Callback Handles', () { // Top level callback. final CallbackHandle hTop = PluginUtilities.getCallbackHandle(top)!; expect(hTop, notEquals(0)); expect(PluginUtilities.getCallbackHandle(top), hTop); final StringFunction topClosure = PluginUtilities.getCallbackFromHandle(hTop)! as StringFunction; expect(topClosure(), 'top'); // Static method callback. final CallbackHandle hGetInt = PluginUtilities.getCallbackHandle(Foo.getInt)!; expect(hGetInt, notEquals(0)); expect(PluginUtilities.getCallbackHandle(Foo.getInt), hGetInt); final IntFunction getIntClosure = PluginUtilities.getCallbackFromHandle(hGetInt)! as IntFunction; expect(getIntClosure(), 1); // Instance method callbacks cannot be looked up. const Foo foo = Foo(); expect(PluginUtilities.getCallbackHandle(foo.getDouble), isNull); // Anonymous closures cannot be looked up. final Function anon = (int a, int b) => a + b; // ignore: prefer_function_declarations_over_variables expect(PluginUtilities.getCallbackHandle(anon), isNull); }); }
engine/testing/dart/plugin_utilities_test.dart/0
{ "file_path": "engine/testing/dart/plugin_utilities_test.dart", "repo_id": "engine", "token_count": 487 }
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. #ifndef FLUTTER_TESTING_DEBUGGER_DETECTION_H_ #define FLUTTER_TESTING_DEBUGGER_DETECTION_H_ #include "flutter/fml/macros.h" namespace flutter { namespace testing { enum class DebuggerStatus { kDontKnow, kAttached, }; DebuggerStatus GetDebuggerStatus(); } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_DEBUGGER_DETECTION_H_
engine/testing/debugger_detection.h/0
{ "file_path": "engine/testing/debugger_detection.h", "repo_id": "engine", "token_count": 181 }
385
{ "images" : [ { "idiom" : "iphone", "scale" : "2x", "size" : "20x20" }, { "idiom" : "iphone", "scale" : "3x", "size" : "20x20" }, { "idiom" : "iphone", "scale" : "2x", "size" : "29x29" }, { "idiom" : "iphone", "scale" : "3x", "size" : "29x29" }, { "idiom" : "iphone", "scale" : "2x", "size" : "40x40" }, { "idiom" : "iphone", "scale" : "3x", "size" : "40x40" }, { "idiom" : "iphone", "scale" : "2x", "size" : "60x60" }, { "idiom" : "iphone", "scale" : "3x", "size" : "60x60" }, { "idiom" : "ipad", "scale" : "1x", "size" : "20x20" }, { "idiom" : "ipad", "scale" : "2x", "size" : "20x20" }, { "idiom" : "ipad", "scale" : "1x", "size" : "29x29" }, { "idiom" : "ipad", "scale" : "2x", "size" : "29x29" }, { "idiom" : "ipad", "scale" : "1x", "size" : "40x40" }, { "idiom" : "ipad", "scale" : "2x", "size" : "40x40" }, { "idiom" : "ipad", "scale" : "1x", "size" : "76x76" }, { "idiom" : "ipad", "scale" : "2x", "size" : "76x76" }, { "idiom" : "ipad", "scale" : "2x", "size" : "83.5x83.5" }, { "idiom" : "ios-marketing", "scale" : "1x", "size" : "1024x1024" } ], "info" : { "author" : "xcode", "version" : 1 } }
engine/testing/ios/IosBenchmarks/IosBenchmarks/Assets.xcassets/AppIcon.appiconset/Contents.json/0
{ "file_path": "engine/testing/ios/IosBenchmarks/IosBenchmarks/Assets.xcassets/AppIcon.appiconset/Contents.json", "repo_id": "engine", "token_count": 1023 }
386
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package dev.flutter.scenariosui; import android.content.Intent; import androidx.annotation.NonNull; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import dev.flutter.scenarios.SpawnedEngineActivity; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) @LargeTest public class SpawnEngineTests { Intent intent; @Rule @NonNull public ActivityTestRule<SpawnedEngineActivity> activityRule = new ActivityTestRule<>( SpawnedEngineActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false); @Before public void setUp() { intent = new Intent(Intent.ACTION_MAIN); } @Test public void testSpawnedEngine() throws Exception { intent.putExtra("scenario_name", "spawn_engine_works"); ScreenshotUtil.capture( activityRule.launchActivity(intent), "SpawnEngineTests_testSpawnedEngine"); } }
engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/SpawnEngineTests.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/SpawnEngineTests.java", "repo_id": "engine", "token_count": 379 }
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. import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; /// A screenshot from the Android emulator. class Screenshot { Screenshot(this.filename, this.fileContent, this.pixelCount); /// The name of the screenshot. final String filename; /// The binary content of the screenshot. final Uint8List fileContent; /// The number of pixels in the screenshot. final int pixelCount; } /// Takes the input stream and transforms it into [Screenshot]s. class ScreenshotBlobTransformer extends StreamTransformerBase<Uint8List, Screenshot> { const ScreenshotBlobTransformer(); @override Stream<Screenshot> bind(Stream<Uint8List> stream) async* { final BytesBuilder pending = BytesBuilder(); await for (final Uint8List blob in stream) { pending.add(blob); if (pending.length < 12) { continue; } // See ScreenshotUtil#writeFile in ScreenshotUtil.java for producer side. final Uint8List bytes = pending.toBytes(); final ByteData byteData = bytes.buffer.asByteData(); int off = 0; final int fnameLen = byteData.getInt32(off); off += 4; final int fcontentLen = byteData.getInt32(off); off += 4; final int pixelCount = byteData.getInt32(off); off += 4; assert(fnameLen > 0); assert(fcontentLen > 0); assert(pixelCount > 0); if (pending.length < off + fnameLen) { continue; } final String filename = utf8.decode(bytes.buffer.asUint8List(off, fnameLen)); off += fnameLen; if (pending.length < off + fcontentLen) { continue; } final Uint8List fileContent = bytes.buffer.asUint8List(off, fcontentLen); off += fcontentLen; pending.clear(); pending.add(bytes.buffer.asUint8List(off)); yield Screenshot('$filename.png', fileContent, pixelCount); } } }
engine/testing/scenario_app/bin/utils/screenshot_transformer.dart/0
{ "file_path": "engine/testing/scenario_app/bin/utils/screenshot_transformer.dart", "repo_id": "engine", "token_count": 743 }
388
// 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. #ifndef FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_APPDELEGATE_H_ #define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_APPDELEGATE_H_ #import <Flutter/Flutter.h> #import <UIKit/UIKit.h> @interface AppDelegate : FlutterAppDelegate @end #endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOS_APPDELEGATE_H_
engine/testing/scenario_app/ios/Scenarios/Scenarios/AppDelegate.h/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/AppDelegate.h", "repo_id": "engine", "token_count": 209 }
389
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>NSExtension</key> <dict> <key>NSExtensionAttributes</key> <dict> <key>NSExtensionActivationRule</key> <string>TRUEPREDICATE</string> </dict> <key>NSExtensionPrincipalClass</key> <string>ShareViewController</string> <key>NSExtensionPointIdentifier</key> <string>com.apple.share-services</string> </dict> </dict> </plist>
engine/testing/scenario_app/ios/Scenarios/ScenariosShare/Info.plist/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosShare/Info.plist", "repo_id": "engine", "token_count": 227 }
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. #ifndef FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_GOLDENTESTMANAGER_H_ #define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_GOLDENTESTMANAGER_H_ #import <Foundation/Foundation.h> #import <XCTest/XCTest.h> #import "GoldenImage.h" NS_ASSUME_NONNULL_BEGIN extern NSDictionary* launchArgsMap; const extern double kDefaultRmseThreshold; // Manages a `GoldenPlatformViewTests`. // // It creates the correct `identifer` based on the `launchArg`. // It also generates the correct GoldenImage based on the `identifier`. @interface GoldenTestManager : NSObject @property(readonly, strong, nonatomic) GoldenImage* goldenImage; @property(readonly, copy, nonatomic) NSString* identifier; @property(readonly, copy, nonatomic) NSString* launchArg; // Initilize with launchArg. // // Crahes if the launchArg is not mapped in `Appdelegate.launchArgsMap`. - (instancetype)initWithLaunchArg:(NSString*)launchArg; // Take a sceenshot of the test app and check it has the same pixels with // goldenImage inside the `GoldenTestManager`. - (void)checkGoldenForTest:(XCTestCase*)test rmesThreshold:(double)rmesThreshold; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_GOLDENTESTMANAGER_H_
engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenTestManager.h/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenTestManager.h", "repo_id": "engine", "token_count": 495 }
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. import 'channel_util.dart'; import 'scenario.dart'; /// A blank page that just sends back to the platform what the set initial /// route is. class InitialRouteReply extends Scenario { /// Creates the InitialRouteReply. InitialRouteReply(super.view); @override void onBeginFrame(Duration duration) { sendJsonMethodCall( dispatcher: view.platformDispatcher, channel: 'initial_route_test_channel', method: view.platformDispatcher.defaultRouteName, ); } }
engine/testing/scenario_app/lib/src/initial_route_reply.dart/0
{ "file_path": "engine/testing/scenario_app/lib/src/initial_route_reply.dart", "repo_id": "engine", "token_count": 199 }
392
/// Skia Gold errors thrown by intepreting process exits and [stdout]/[stderr]. final class SkiaGoldProcessError extends Error { /// Creates a new [SkiaGoldProcessError] from the provided origin. /// /// - [command] is the command that was executed. /// - [stdout] is the result of the process's standard output. /// - [stderr] is the result of the process's standard error. /// /// Optionally, [message] as context for the error. /// /// ## Example /// /// ```dart /// final io.ProcessResult result = await _runCommand(someCommand); /// if (result.exitCode != 0) { /// throw SkiaGoldProcessError( /// command: someCommand, /// stdout: result.stdout.toString(), /// stderr: result.stderr.toString(), /// message: 'Authentication failed <or whatever we were doing>', /// ); /// } /// ``` SkiaGoldProcessError({ required Iterable<String> command, required this.stdout, required this.stderr, this.message, }) : command = List<String>.unmodifiable(command); /// Optional message to include as context for the error. final String? message; /// Command that was executed. final List<String> command; /// The result of the process's standard output. final String stdout; /// The result of the process's standard error. final String stderr; @override String toString() { return <String>[ 'Error when running Skia Gold: ${command.join(' ')}', if (message != null) message!, '', 'stdout: $stdout', 'stderr: $stderr', ].join('\n'); } }
engine/testing/skia_gold_client/lib/src/errors.dart/0
{ "file_path": "engine/testing/skia_gold_client/lib/src/errors.dart", "repo_id": "engine", "token_count": 524 }
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. #ifndef FLUTTER_TESTING_TEST_TIMEOUT_LISTENER_H_ #define FLUTTER_TESTING_TEST_TIMEOUT_LISTENER_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/fml/task_runner.h" #include "flutter/fml/thread.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { class PendingTests; class TestTimeoutListener : public ::testing::EmptyTestEventListener { public: explicit TestTimeoutListener(fml::TimeDelta timeout); ~TestTimeoutListener(); private: const fml::TimeDelta timeout_; fml::Thread listener_thread_; fml::RefPtr<fml::TaskRunner> listener_thread_runner_; std::shared_ptr<PendingTests> pending_tests_; // |testing::EmptyTestEventListener| void OnTestStart(const ::testing::TestInfo& test_info) override; // |testing::EmptyTestEventListener| void OnTestEnd(const ::testing::TestInfo& test_info) override; FML_DISALLOW_COPY_AND_ASSIGN(TestTimeoutListener); }; } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_TEST_TIMEOUT_LISTENER_H_
engine/testing/test_timeout_listener.h/0
{ "file_path": "engine/testing/test_timeout_listener.h", "repo_id": "engine", "token_count": 400 }
394
// 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. #ifndef UI_ACCESSIBILITY_AX_CONSTANTS_H_ #define UI_ACCESSIBILITY_AX_CONSTANTS_H_ #include <cstdint> namespace ax { namespace mojom { // https://www.w3.org/TR/wai-aria-1.1/#aria-rowcount // https://www.w3.org/TR/wai-aria-1.1/#aria-colcount // If the total number of (rows|columns) is unknown, authors MUST set the // value of aria-(rowcount|colcount) to -1 to indicate that the value should not // be calculated by the user agent. // See: AXTableInfo const int32_t kUnknownAriaColumnOrRowCount = -1; } // namespace mojom } // namespace ax #endif // UI_ACCESSIBILITY_AX_CONSTANTS_H_
engine/third_party/accessibility/ax/ax_constants.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_constants.h", "repo_id": "engine", "token_count": 273 }
395
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_ACCESSIBILITY_AX_NODE_H_ #define UI_ACCESSIBILITY_AX_NODE_H_ #include <cstdint> #include <memory> #include <optional> #include <ostream> #include <string> #include <vector> #include "ax_build/build_config.h" #include "ax_export.h" #include "ax_node_data.h" #include "ax_tree_id.h" #include "base/logging.h" #include "gfx/geometry/rect.h" #include "gfx/transform.h" #ifdef _WIN32 // windowx.h defines GetNextSibling as a macro. #undef GetNextSibling #endif namespace ui { class AXTableInfo; // One node in an AXTree. class AX_EXPORT AXNode final { public: // Defines the type used for AXNode IDs. using AXID = int32_t; // TODO(chunhtai): I modified this to be -1 so it can work with flutter. // If a node is not yet or no longer valid, its ID should have a value of // kInvalidAXID. static constexpr AXID kInvalidAXID = -1; // Interface to the tree class that owns an AXNode. We use this instead // of letting AXNode have a pointer to its AXTree directly so that we're // forced to think twice before calling an AXTree interface that might not // be necessary. class OwnerTree { public: struct Selection { bool is_backward; AXID anchor_object_id; int anchor_offset; ax::mojom::TextAffinity anchor_affinity; AXID focus_object_id; int focus_offset; ax::mojom::TextAffinity focus_affinity; }; // See AXTree::GetAXTreeID. virtual AXTreeID GetAXTreeID() const = 0; // See AXTree::GetTableInfo. virtual AXTableInfo* GetTableInfo(const AXNode* table_node) const = 0; // See AXTree::GetFromId. virtual AXNode* GetFromId(int32_t id) const = 0; virtual std::optional<int> GetPosInSet(const AXNode& node) = 0; virtual std::optional<int> GetSetSize(const AXNode& node) = 0; virtual Selection GetUnignoredSelection() const = 0; virtual bool GetTreeUpdateInProgressState() const = 0; virtual bool HasPaginationSupport() const = 0; }; template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> class ChildIteratorBase { public: ChildIteratorBase(const NodeType* parent, NodeType* child); ChildIteratorBase(const ChildIteratorBase& it); ~ChildIteratorBase() {} bool operator==(const ChildIteratorBase& rhs) const; bool operator!=(const ChildIteratorBase& rhs) const; ChildIteratorBase& operator++(); ChildIteratorBase& operator--(); NodeType* get() const; NodeType& operator*() const; NodeType* operator->() const; protected: const NodeType* parent_; NodeType* child_; }; // The constructor requires a parent, id, and index in parent, but // the data is not required. After initialization, only index_in_parent // and unignored_index_in_parent is allowed to change, the others are // guaranteed to never change. AXNode(OwnerTree* tree, AXNode* parent, int32_t id, size_t index_in_parent, size_t unignored_index_in_parent = 0); virtual ~AXNode(); // Accessors. OwnerTree* tree() const { return tree_; } AXID id() const { return data_.id; } AXNode* parent() const { return parent_; } const AXNodeData& data() const { return data_; } const std::vector<AXNode*>& children() const { return children_; } size_t index_in_parent() const { return index_in_parent_; } // Returns ownership of |data_| to the caller; effectively clearing |data_|. AXNodeData&& TakeData(); // Walking the tree skipping ignored nodes. size_t GetUnignoredChildCount() const; AXNode* GetUnignoredChildAtIndex(size_t index) const; AXNode* GetUnignoredParent() const; // Gets the unignored selection from the accessibility tree, meaning the // selection whose endpoints are on unignored nodes. (An "ignored" node is a // node that is not exposed to platform APIs: See `IsIgnored`.) OwnerTree::Selection GetUnignoredSelection() const; size_t GetUnignoredIndexInParent() const; size_t GetIndexInParent() const; AXNode* GetFirstUnignoredChild() const; AXNode* GetLastUnignoredChild() const; AXNode* GetDeepestFirstUnignoredChild() const; AXNode* GetDeepestLastUnignoredChild() const; AXNode* GetNextUnignoredSibling() const; AXNode* GetPreviousUnignoredSibling() const; AXNode* GetNextUnignoredInTreeOrder() const; AXNode* GetPreviousUnignoredInTreeOrder() const; using UnignoredChildIterator = ChildIteratorBase<AXNode, &AXNode::GetNextUnignoredSibling, &AXNode::GetPreviousUnignoredSibling, &AXNode::GetFirstUnignoredChild, &AXNode::GetLastUnignoredChild>; UnignoredChildIterator UnignoredChildrenBegin() const; UnignoredChildIterator UnignoredChildrenEnd() const; // Walking the tree including both ignored and unignored nodes. // These methods consider only the direct children or siblings of a node. AXNode* GetFirstChild() const; AXNode* GetLastChild() const; AXNode* GetPreviousSibling() const; AXNode* GetNextSibling() const; // Returns true if the node has any of the text related roles, including // kStaticText, kInlineTextBox and kListMarker (for Legacy Layout). Does not // include any text field roles. bool IsText() const; // Returns true if the node has any line break related roles or is the child // of a node with line break related roles. bool IsLineBreak() const; // Set the node's accessibility data. This may be done during initialization // or later when the node data changes. void SetData(const AXNodeData& src); // Update this node's location. This is separate from |SetData| just because // changing only the location is common and should be more efficient than // re-copying all of the data. // // The node's location is stored as a relative bounding box, the ID of // the element it's relative to, and an optional transformation matrix. // See ax_node_data.h for details. void SetLocation(int32_t offset_container_id, const gfx::RectF& location, gfx::Transform* transform); // Set the index in parent, for example if siblings were inserted or deleted. void SetIndexInParent(size_t index_in_parent); // Update the unignored index in parent for unignored children. void UpdateUnignoredCachedValues(); // Swap the internal children vector with |children|. This instance // now owns all of the passed children. void SwapChildren(std::vector<AXNode*>* children); // This is called when the AXTree no longer includes this node in the // tree. Reference counting is used on some platforms because the // operating system may hold onto a reference to an AXNode // object even after we're through with it, so this may decrement the // reference count and clear out the object's data. void Destroy(); // Return true if this object is equal to or a descendant of |ancestor|. bool IsDescendantOf(const AXNode* ancestor) const; bool IsDescendantOfCrossingTreeBoundary(const AXNode* ancestor) const; AXNode* GetParentCrossingTreeBoundary() const; // Gets the text offsets where new lines start either from the node's data or // by computing them and caching the result. std::vector<int> GetOrComputeLineStartOffsets(); // Accessing accessibility attributes. // See |AXNodeData| for more information. bool HasBoolAttribute(ax::mojom::BoolAttribute attribute) const { return data().HasBoolAttribute(attribute); } bool GetBoolAttribute(ax::mojom::BoolAttribute attribute) const { return data().GetBoolAttribute(attribute); } bool GetBoolAttribute(ax::mojom::BoolAttribute attribute, bool* value) const { return data().GetBoolAttribute(attribute, value); } bool HasFloatAttribute(ax::mojom::FloatAttribute attribute) const { return data().HasFloatAttribute(attribute); } float GetFloatAttribute(ax::mojom::FloatAttribute attribute) const { return data().GetFloatAttribute(attribute); } bool GetFloatAttribute(ax::mojom::FloatAttribute attribute, float* value) const { return data().GetFloatAttribute(attribute, value); } bool HasIntAttribute(ax::mojom::IntAttribute attribute) const { return data().HasIntAttribute(attribute); } int GetIntAttribute(ax::mojom::IntAttribute attribute) const { return data().GetIntAttribute(attribute); } bool GetIntAttribute(ax::mojom::IntAttribute attribute, int* value) const { return data().GetIntAttribute(attribute, value); } bool HasStringAttribute(ax::mojom::StringAttribute attribute) const { return data().HasStringAttribute(attribute); } const std::string& GetStringAttribute( ax::mojom::StringAttribute attribute) const { return data().GetStringAttribute(attribute); } bool GetStringAttribute(ax::mojom::StringAttribute attribute, std::string* value) const { return data().GetStringAttribute(attribute, value); } bool GetString16Attribute(ax::mojom::StringAttribute attribute, std::u16string* value) const { return data().GetString16Attribute(attribute, value); } std::u16string GetString16Attribute( ax::mojom::StringAttribute attribute) const { return data().GetString16Attribute(attribute); } bool HasIntListAttribute(ax::mojom::IntListAttribute attribute) const { return data().HasIntListAttribute(attribute); } const std::vector<int32_t>& GetIntListAttribute( ax::mojom::IntListAttribute attribute) const { return data().GetIntListAttribute(attribute); } bool GetIntListAttribute(ax::mojom::IntListAttribute attribute, std::vector<int32_t>* value) const { return data().GetIntListAttribute(attribute, value); } bool HasStringListAttribute(ax::mojom::StringListAttribute attribute) const { return data().HasStringListAttribute(attribute); } const std::vector<std::string>& GetStringListAttribute( ax::mojom::StringListAttribute attribute) const { return data().GetStringListAttribute(attribute); } bool GetStringListAttribute(ax::mojom::StringListAttribute attribute, std::vector<std::string>* value) const { return data().GetStringListAttribute(attribute, value); } bool GetHtmlAttribute(const char* attribute, std::u16string* value) const { return data().GetHtmlAttribute(attribute, value); } bool GetHtmlAttribute(const char* attribute, std::string* value) const { return data().GetHtmlAttribute(attribute, value); } // Return the hierarchical level if supported. std::optional<int> GetHierarchicalLevel() const; // PosInSet and SetSize public methods. bool IsOrderedSetItem() const; bool IsOrderedSet() const; std::optional<int> GetPosInSet(); std::optional<int> GetSetSize(); // Helpers for GetPosInSet and GetSetSize. // Returns true if the role of ordered set matches the role of item. // Returns false otherwise. bool SetRoleMatchesItemRole(const AXNode* ordered_set) const; // Container objects that should be ignored for computing PosInSet and SetSize // for ordered sets. bool IsIgnoredContainerForOrderedSet() const; const std::string& GetInheritedStringAttribute( ax::mojom::StringAttribute attribute) const; std::u16string GetInheritedString16Attribute( ax::mojom::StringAttribute attribute) const; // Returns the text of this node and all descendant nodes; including text // found in embedded objects. // // Only text displayed on screen is included. Text from ARIA and HTML // attributes that is either not displayed on screen, or outside this node, is // not returned. std::string GetInnerText() const; // Return a string representing the language code. // // This will consider the language declared in the DOM, and may eventually // attempt to automatically detect the language from the text. // // This language code will be BCP 47. // // Returns empty string if no appropriate language was found. std::string GetLanguage() const; // Helper functions for tables, table rows, and table cells. // Most of these functions construct and cache an AXTableInfo behind // the scenes to infer many properties of tables. // // These interfaces use attributes provided by the source of the // AX tree where possible, but fills in missing details and ignores // specified attributes when they're bad or inconsistent. That way // you're guaranteed to get a valid, consistent table when using these // interfaces. // // Table-like nodes (including grids). All indices are 0-based except // ARIA indices are all 1-based. In other words, the top-left corner // of the table is row 0, column 0, cell index 0 - but that same cell // has a minimum ARIA row index of 1 and column index of 1. // // The below methods return std::nullopt if the AXNode they are called on is // not inside a table. bool IsTable() const; std::optional<int> GetTableColCount() const; std::optional<int> GetTableRowCount() const; std::optional<int> GetTableAriaColCount() const; std::optional<int> GetTableAriaRowCount() const; std::optional<int> GetTableCellCount() const; std::optional<bool> GetTableHasColumnOrRowHeaderNode() const; AXNode* GetTableCaption() const; AXNode* GetTableCellFromIndex(int index) const; AXNode* GetTableCellFromCoords(int row_index, int col_index) const; // Get all the column header node ids of the table. std::vector<AXNode::AXID> GetTableColHeaderNodeIds() const; // Get the column header node ids associated with |col_index|. std::vector<AXNode::AXID> GetTableColHeaderNodeIds(int col_index) const; // Get the row header node ids associated with |row_index|. std::vector<AXNode::AXID> GetTableRowHeaderNodeIds(int row_index) const; std::vector<AXNode::AXID> GetTableUniqueCellIds() const; // Extra computed nodes for the accessibility tree for macOS: // one column node for each table column, followed by one // table header container node, or nullptr if not applicable. const std::vector<AXNode*>* GetExtraMacNodes() const; // Table row-like nodes. bool IsTableRow() const; std::optional<int> GetTableRowRowIndex() const; // Get the node ids that represent rows in a table. std::vector<AXNode::AXID> GetTableRowNodeIds() const; #if defined(OS_APPLE) // Table column-like nodes. These nodes are only present on macOS. bool IsTableColumn() const; std::optional<int> GetTableColColIndex() const; #endif // defined(OS_APPLE) // Table cell-like nodes. bool IsTableCellOrHeader() const; std::optional<int> GetTableCellIndex() const; std::optional<int> GetTableCellColIndex() const; std::optional<int> GetTableCellRowIndex() const; std::optional<int> GetTableCellColSpan() const; std::optional<int> GetTableCellRowSpan() const; std::optional<int> GetTableCellAriaColIndex() const; std::optional<int> GetTableCellAriaRowIndex() const; std::vector<AXNode::AXID> GetTableCellColHeaderNodeIds() const; std::vector<AXNode::AXID> GetTableCellRowHeaderNodeIds() const; void GetTableCellColHeaders(std::vector<AXNode*>* col_headers) const; void GetTableCellRowHeaders(std::vector<AXNode*>* row_headers) const; // Helper methods to check if a cell is an ARIA-1.1+ 'cell' or 'gridcell' bool IsCellOrHeaderOfARIATable() const; bool IsCellOrHeaderOfARIAGrid() const; // Returns true if node is a group and is a direct descendant of a set-like // element. bool IsEmbeddedGroup() const; // Returns true if node has ignored state or ignored role. bool IsIgnored() const; // Returns true if an ancestor of this node (not including itself) is a // leaf node, meaning that this node is not actually exposed to any // platform's accessibility layer. bool IsChildOfLeaf() const; // Returns true if this is a leaf node, meaning all its // children should not be exposed to any platform's native accessibility // layer. // // The definition of a leaf includes nodes with children that are exclusively // an internal renderer implementation, such as the children of an HTML native // text field, as well as nodes with presentational children according to the // ARIA and HTML5 Specs. Also returns true if all of the node's descendants // are ignored. // // A leaf node should never have children that are focusable or // that might send notifications. bool IsLeaf() const; // Returns true if this node is a list marker or if it's a descendant // of a list marker node. Returns false otherwise. bool IsInListMarker() const; // Returns true if this node is a collapsed popup button that is parent to a // menu list popup. bool IsCollapsedMenuListPopUpButton() const; // Returns the popup button ancestor of this current node if any. The popup // button needs to be the parent of a menu list popup and needs to be // collapsed. AXNode* GetCollapsedMenuListPopUpButtonAncestor() const; // Returns the text field ancestor of this current node if any. AXNode* GetTextFieldAncestor() const; // Finds and returns a pointer to ordered set containing node. AXNode* GetOrderedSet() const; // If this node is exposed to the platform's accessibility layer, returns this // node. Otherwise, returns the lowest ancestor that is exposed to the // platform. (See `IsLeaf` and `IsIgnored` for information on what is // exposed to platform APIs.) AXNode* GetLowestPlatformAncestor() const; private: // Computes the text offset where each line starts by traversing all child // leaf nodes. void ComputeLineStartOffsets(std::vector<int>* line_offsets, int* start_offset) const; AXTableInfo* GetAncestorTableInfo() const; void IdVectorToNodeVector(const std::vector<int32_t>& ids, std::vector<AXNode*>* nodes) const; int UpdateUnignoredCachedValuesRecursive(int startIndex); AXNode* ComputeLastUnignoredChildRecursive() const; AXNode* ComputeFirstUnignoredChildRecursive() const; OwnerTree* const tree_; // Owns this. size_t index_in_parent_; size_t unignored_index_in_parent_; size_t unignored_child_count_ = 0; AXNode* const parent_; std::vector<AXNode*> children_; AXNodeData data_; }; AX_EXPORT std::ostream& operator<<(std::ostream& stream, const AXNode& node); template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>::ChildIteratorBase(const NodeType* parent, NodeType* child) : parent_(parent), child_(child) {} template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>::ChildIteratorBase(const ChildIteratorBase& it) : parent_(it.parent_), child_(it.child_) {} template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> bool AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>::operator==(const ChildIteratorBase& rhs) const { return parent_ == rhs.parent_ && child_ == rhs.child_; } template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> bool AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>::operator!=(const ChildIteratorBase& rhs) const { return parent_ != rhs.parent_ || child_ != rhs.child_; } template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>& AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>::operator++() { // |child_ = nullptr| denotes the iterator's past-the-end condition. When we // increment the iterator past the end, we remain at the past-the-end iterator // condition. if (child_ && parent_) { if (child_ == (parent_->*LastChild)()) child_ = nullptr; else child_ = (child_->*NextSibling)(); } return *this; } template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>& AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>::operator--() { if (parent_) { // If the iterator is past the end, |child_=nullptr|, decrement the iterator // gives us the last iterator element. if (!child_) child_ = (parent_->*LastChild)(); // Decrement the iterator gives us the previous element, except when the // iterator is at the beginning; in which case, decrementing the iterator // remains at the beginning. else if (child_ != (parent_->*FirstChild)()) child_ = (child_->*PreviousSibling)(); } return *this; } template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> NodeType* AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>::get() const { BASE_DCHECK(child_); return child_; } template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> NodeType& AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>::operator*() const { BASE_DCHECK(child_); return *child_; } template <typename NodeType, NodeType* (NodeType::*NextSibling)() const, NodeType* (NodeType::*PreviousSibling)() const, NodeType* (NodeType::*FirstChild)() const, NodeType* (NodeType::*LastChild)() const> NodeType* AXNode::ChildIteratorBase<NodeType, NextSibling, PreviousSibling, FirstChild, LastChild>::operator->() const { BASE_DCHECK(child_); return child_; } } // namespace ui #endif // UI_ACCESSIBILITY_AX_NODE_H_
engine/third_party/accessibility/ax/ax_node.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_node.h", "repo_id": "engine", "token_count": 9226 }
396
// 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_ROLE_PROPERTIES_H_ #define UI_ACCESSIBILITY_AX_ROLE_PROPERTIES_H_ #include "ax_base_export.h" #include "ax_enums.h" namespace ui { // This file contains various helper functions that determine whether a // specific accessibility role meets certain criteria. // // Please keep these functions in alphabetic order. // Returns true for object roles that have the attribute "Children // Presentational: True" as defined in the ARIA Specification. // https://www.w3.org/TR/wai-aria-1.1/#childrenArePresentational. AX_BASE_EXPORT bool HasPresentationalChildren(const ax::mojom::Role role); // Returns true if the given role is an alert or alert-dialog type. AX_BASE_EXPORT bool IsAlert(const ax::mojom::Role role); // Returns true if the provided role belongs to a native or an ARIA button. AX_BASE_EXPORT bool IsButton(const ax::mojom::Role role); // Returns true if the provided role belongs to an object on which a click // handler is commonly attached, or to an object that carries out an action when // clicked, such as activating itself, opening a dialog or closing a menu. // // A button and a checkbox fall in the first category, whilst a color well and a // list menu option in the second. Note that a text field, or a similar element, // also carries out an action when clicked. It focuses itself, so the action // verb is "activate". Not all roles that inherently support a click handler or // that can potentially be focused are included, because in that case even a div // could be made clickable or focusable. // // The reason for the existence of this function is that certain screen readers, // such as Jaws, might need to report such objects as clickable to their users, // so that users will know that they could activate them if they so choose. AX_BASE_EXPORT bool IsClickable(const ax::mojom::Role role); // Returns true if the provided role belongs to a cell or a table header. AX_BASE_EXPORT bool IsCellOrTableHeader(const ax::mojom::Role role); // Returns true if the provided role belongs to a container with selectable // children. AX_BASE_EXPORT bool IsContainerWithSelectableChildren( const ax::mojom::Role role); // Returns true if the provided role is a control. AX_BASE_EXPORT bool IsControl(const ax::mojom::Role role); // Returns true if the provided role is a control on the Android platform. AX_BASE_EXPORT bool IsControlOnAndroid(const ax::mojom::Role role, bool isFocusable); // Returns true if the provided role belongs to a document. AX_BASE_EXPORT bool IsDocument(const ax::mojom::Role role); // Returns true if the provided role represents a dialog. AX_BASE_EXPORT bool IsDialog(const ax::mojom::Role role); // Returns true if the provided role is a form. AX_BASE_EXPORT bool IsForm(const ax::mojom::Role role); // Returns true if crossing into or out of the provided role should count as // crossing a format boundary. AX_BASE_EXPORT bool IsFormatBoundary(const ax::mojom::Role role); // Returns true if the provided role belongs to a heading. AX_BASE_EXPORT bool IsHeading(const ax::mojom::Role role); // Returns true if the provided role belongs to a heading or a table header. AX_BASE_EXPORT bool IsHeadingOrTableHeader(const ax::mojom::Role role); // Returns true if the provided role belongs to an iframe. AX_BASE_EXPORT bool IsIframe(const ax::mojom::Role role); // Returns true if the provided role belongs to an image, graphic, canvas, etc. AX_BASE_EXPORT bool IsImage(const ax::mojom::Role role); // Returns true if the provided role is for any kind of image or video. AX_BASE_EXPORT bool IsImageOrVideo(const ax::mojom::Role role); // Returns true if the provided role is item-like, specifically if it can hold // pos_in_set and set_size values. AX_BASE_EXPORT bool IsItemLike(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Landmark abstract role. AX_BASE_EXPORT bool IsLandmark(const ax::mojom::Role role); // Returns true if the provided role belongs to a link. AX_BASE_EXPORT bool IsLink(const ax::mojom::Role role); // Returns true if the provided role belongs to a list. AX_BASE_EXPORT bool IsList(const ax::mojom::Role role); // Returns true if the provided role belongs to a list item. AX_BASE_EXPORT bool IsListItem(const ax::mojom::Role role); // Returns true if the provided role belongs to a menu item, including menu item // checkbox and menu item radio buttons. AX_BASE_EXPORT bool IsMenuItem(ax::mojom::Role role); // Returns true if the provided role belongs to a menu or related control. AX_BASE_EXPORT bool IsMenuRelated(const ax::mojom::Role role); // Returns true if the provided role is presentational in nature, i.e. a node // whose implicit native role semantics will not be mapped to the accessibility // API. AX_BASE_EXPORT bool IsPresentational(const ax::mojom::Role role); // Returns true if the provided role belongs to a radio. AX_BASE_EXPORT bool IsRadio(const ax::mojom::Role role); // Returns true if the provided role supports a range-based value, such as a // slider. AX_BASE_EXPORT bool IsRangeValueSupported(const ax::mojom::Role role); // Returns true if this object supports readonly. // // Note: This returns false for table cells and headers, it is up to the // caller to make sure that they are included IFF they are within an // ARIA-1.1+ role='grid' or 'treegrid', and not role='table'. AX_BASE_EXPORT bool IsReadOnlySupported(const ax::mojom::Role role); // Returns true if the provided role belongs to a widget that can contain a // table or grid row. AX_BASE_EXPORT bool IsRowContainer(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Section abstract role. AX_BASE_EXPORT bool IsSection(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Sectionhead role. AX_BASE_EXPORT bool IsSectionhead(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Select abstract role. AX_BASE_EXPORT bool IsSelect(const ax::mojom::Role role); // Returns true if the provided role is ordered-set like, specifically if it // can hold set_size values. AX_BASE_EXPORT bool IsSetLike(const ax::mojom::Role role); // Returns true if the provided role belongs to a non-interactive list. AX_BASE_EXPORT bool IsStaticList(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Structure abstract role. AX_BASE_EXPORT bool IsStructure(const ax::mojom::Role role); // Returns true if the provided role belongs to a table or grid column, and the // table is not used for layout purposes. AX_BASE_EXPORT bool IsTableColumn(ax::mojom::Role role); // Returns true if the provided role belongs to a table header. AX_BASE_EXPORT bool IsTableHeader(ax::mojom::Role role); // Returns true if the provided role belongs to a table, a grid or a treegrid. AX_BASE_EXPORT bool IsTableLike(const ax::mojom::Role role); // Returns true if the provided role belongs to a table or grid row, and the // table is not used for layout purposes. AX_BASE_EXPORT bool IsTableRow(ax::mojom::Role role); // Returns true if the provided role is text-related, e.g., static text, line // break, or inline text box. AX_BASE_EXPORT bool IsText(ax::mojom::Role role); // Returns true if the role supports expand/collapse. AX_BASE_EXPORT bool SupportsExpandCollapse(const ax::mojom::Role role); // Returns true if the role supports hierarchical level. AX_BASE_EXPORT bool SupportsHierarchicalLevel(const ax::mojom::Role role); // Returns true if the provided role can have an orientation. AX_BASE_EXPORT bool SupportsOrientation(const ax::mojom::Role role); // Returns true if the provided role supports aria-selected state. AX_BASE_EXPORT bool SupportsSelected(const ax::mojom::Role role); // Returns true if the provided role supports toggle. AX_BASE_EXPORT bool SupportsToggle(const ax::mojom::Role role); // Returns true if the node should be read only by default AX_BASE_EXPORT bool ShouldHaveReadonlyStateByDefault( const ax::mojom::Role role); } // namespace ui #endif // UI_ACCESSIBILITY_AX_ROLE_PROPERTIES_H_
engine/third_party/accessibility/ax/ax_role_properties.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_role_properties.h", "repo_id": "engine", "token_count": 2478 }
397
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ax_platform_node_delegate_utils_win.h" #include "ax/ax_node_data.h" #include "ax/ax_role_properties.h" #include "ax/platform/ax_platform_node.h" #include "ax/platform/ax_platform_node_delegate.h" namespace ui { bool IsValuePatternSupported(AXPlatformNodeDelegate* delegate) { // https://docs.microsoft.com/en-us/windows/desktop/winauto/uiauto-implementingvalue // The Value control pattern is used to support controls that have an // intrinsic value not spanning a range and that can be represented as // a string. // // IValueProvider must be implemented by controls such as the color picker // selection control [...] // https://www.w3.org/TR/html-aam-1.0/ // The HTML AAM maps "href [a; area]" to UIA Value.Value return delegate->GetData().IsRangeValueSupported() || IsReadOnlySupported(delegate->GetData().role) || IsLink(delegate->GetData().role) || delegate->GetData().role == ax::mojom::Role::kColorWell || delegate->IsCellOrHeaderOfARIAGrid(); } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_platform_node_delegate_utils_win.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_delegate_utils_win.cc", "repo_id": "engine", "token_count": 402 }
398
// // 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_unittest.h" #include <oleacc.h> #include <wrl/client.h> #include <memory> #include "ax_fragment_root_win.h" #include "ax_platform_node_win.h" #include "base/auto_reset.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "test_ax_node_wrapper.h" #include "third_party/accessibility/ax/ax_enums.h" #include "third_party/accessibility/ax/ax_node_data.h" #include "third_party/accessibility/base/win/atl_module.h" #include "third_party/accessibility/base/win/scoped_bstr.h" #include "third_party/accessibility/base/win/scoped_safearray.h" #include "third_party/accessibility/base/win/scoped_variant.h" using base::win::ScopedBstr; using base::win::ScopedVariant; using Microsoft::WRL::ComPtr; namespace ui { const std::u16string AXPlatformNodeWinTest::kEmbeddedCharacterAsString = { ui::AXPlatformNodeBase::kEmbeddedCharacter}; namespace { // Most IAccessible functions require a VARIANT set to CHILDID_SELF as // the first argument. ScopedVariant SELF(CHILDID_SELF); } // namespace // Helper macros for UIAutomation HRESULT expectations #define EXPECT_UIA_ELEMENTNOTAVAILABLE(expr) \ EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), (expr)) #define EXPECT_UIA_INVALIDOPERATION(expr) \ EXPECT_EQ(static_cast<HRESULT>(UIA_E_INVALIDOPERATION), (expr)) #define EXPECT_UIA_ELEMENTNOTENABLED(expr) \ EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTENABLED), (expr)) #define EXPECT_UIA_NOTSUPPORTED(expr) \ EXPECT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), (expr)) #define ASSERT_UIA_ELEMENTNOTAVAILABLE(expr) \ ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), (expr)) #define ASSERT_UIA_INVALIDOPERATION(expr) \ ASSERT_EQ(static_cast<HRESULT>(UIA_E_INVALIDOPERATION), (expr)) #define ASSERT_UIA_ELEMENTNOTENABLED(expr) \ ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTENABLED), (expr)) #define ASSERT_UIA_NOTSUPPORTED(expr) \ ASSERT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), (expr)) // Helper macros for testing UIAutomation property values and maintain // correct stack tracing and failure causality. // // WARNING: These aren't intended to be generic EXPECT_BSTR_EQ macros // as the logic is specific to extracting and comparing UIA property // values. #define EXPECT_UIA_EMPTY(node, property_id) \ { \ ScopedVariant actual; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(property_id, actual.Receive())); \ EXPECT_EQ(VT_EMPTY, actual.type()); \ } #define EXPECT_UIA_VALUE_EQ(node, property_id, expectedVariant) \ { \ ScopedVariant actual; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(property_id, actual.Receive())); \ EXPECT_EQ(0, actual.Compare(expectedVariant)); \ } #define EXPECT_UIA_BSTR_EQ(node, property_id, expected) \ { \ ScopedVariant expectedVariant(expected); \ ASSERT_EQ(VT_BSTR, expectedVariant.type()); \ ASSERT_NE(nullptr, expectedVariant.ptr()->bstrVal); \ ScopedVariant actual; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(property_id, actual.Receive())); \ ASSERT_EQ(VT_BSTR, actual.type()); \ ASSERT_NE(nullptr, actual.ptr()->bstrVal); \ EXPECT_STREQ(expectedVariant.ptr()->bstrVal, actual.ptr()->bstrVal); \ } #define EXPECT_UIA_BOOL_EQ(node, property_id, expected) \ { \ ScopedVariant expectedVariant(expected); \ ASSERT_EQ(VT_BOOL, expectedVariant.type()); \ ScopedVariant actual; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(property_id, actual.Receive())); \ EXPECT_EQ(expectedVariant.ptr()->boolVal, actual.ptr()->boolVal); \ } #define EXPECT_UIA_DOUBLE_ARRAY_EQ(node, array_property_id, \ expected_property_values) \ { \ ScopedVariant array; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(array_property_id, array.Receive())); \ ASSERT_EQ(VT_ARRAY | VT_R8, array.type()); \ ASSERT_EQ(1u, SafeArrayGetDim(array.ptr()->parray)); \ LONG array_lower_bound; \ ASSERT_HRESULT_SUCCEEDED( \ SafeArrayGetLBound(array.ptr()->parray, 1, &array_lower_bound)); \ LONG array_upper_bound; \ ASSERT_HRESULT_SUCCEEDED( \ SafeArrayGetUBound(array.ptr()->parray, 1, &array_upper_bound)); \ double* array_data; \ ASSERT_HRESULT_SUCCEEDED(::SafeArrayAccessData( \ array.ptr()->parray, reinterpret_cast<void**>(&array_data))); \ size_t count = array_upper_bound - array_lower_bound + 1; \ ASSERT_EQ(expected_property_values.size(), count); \ for (size_t i = 0; i < count; ++i) { \ EXPECT_EQ(array_data[i], expected_property_values[i]); \ } \ ASSERT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(array.ptr()->parray)); \ } #define EXPECT_UIA_INT_EQ(node, property_id, expected) \ { \ ScopedVariant expectedVariant(expected); \ ASSERT_EQ(VT_I4, expectedVariant.type()); \ ScopedVariant actual; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(property_id, actual.Receive())); \ EXPECT_EQ(expectedVariant.ptr()->intVal, actual.ptr()->intVal); \ } #define EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(array, element_test_property_id, \ expected_property_values) \ { \ ASSERT_EQ(1u, SafeArrayGetDim(array)); \ LONG array_lower_bound; \ ASSERT_HRESULT_SUCCEEDED( \ SafeArrayGetLBound(array, 1, &array_lower_bound)); \ LONG array_upper_bound; \ ASSERT_HRESULT_SUCCEEDED( \ SafeArrayGetUBound(array, 1, &array_upper_bound)); \ IUnknown** array_data; \ ASSERT_HRESULT_SUCCEEDED( \ ::SafeArrayAccessData(array, reinterpret_cast<void**>(&array_data))); \ size_t count = array_upper_bound - array_lower_bound + 1; \ ASSERT_EQ(expected_property_values.size(), count); \ for (size_t i = 0; i < count; ++i) { \ ComPtr<IRawElementProviderSimple> element; \ ASSERT_HRESULT_SUCCEEDED( \ array_data[i]->QueryInterface(IID_PPV_ARGS(&element))); \ EXPECT_UIA_BSTR_EQ(element, element_test_property_id, \ expected_property_values[i].c_str()); \ } \ ASSERT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(array)); \ } #define EXPECT_UIA_PROPERTY_ELEMENT_ARRAY_BSTR_EQ(node, array_property_id, \ element_test_property_id, \ expected_property_values) \ { \ ScopedVariant array; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(array_property_id, array.Receive())); \ ASSERT_EQ(VT_ARRAY | VT_UNKNOWN, array.type()); \ EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(array.ptr()->parray, \ element_test_property_id, \ expected_property_values); \ } #define EXPECT_UIA_PROPERTY_UNORDERED_ELEMENT_ARRAY_BSTR_EQ( \ node, array_property_id, element_test_property_id, \ expected_property_values) \ { \ ScopedVariant array; \ ASSERT_HRESULT_SUCCEEDED( \ node->GetPropertyValue(array_property_id, array.Receive())); \ ASSERT_EQ(VT_ARRAY | VT_UNKNOWN, array.type()); \ ASSERT_EQ(1u, SafeArrayGetDim(array.ptr()->parray)); \ LONG array_lower_bound; \ ASSERT_HRESULT_SUCCEEDED( \ SafeArrayGetLBound(array.ptr()->parray, 1, &array_lower_bound)); \ LONG array_upper_bound; \ ASSERT_HRESULT_SUCCEEDED( \ SafeArrayGetUBound(array.ptr()->parray, 1, &array_upper_bound)); \ IUnknown** array_data; \ ASSERT_HRESULT_SUCCEEDED(::SafeArrayAccessData( \ array.ptr()->parray, reinterpret_cast<void**>(&array_data))); \ size_t count = array_upper_bound - array_lower_bound + 1; \ ASSERT_EQ(expected_property_values.size(), count); \ std::vector<std::wstring> property_values; \ for (size_t i = 0; i < count; ++i) { \ ComPtr<IRawElementProviderSimple> element; \ ASSERT_HRESULT_SUCCEEDED( \ array_data[i]->QueryInterface(IID_PPV_ARGS(&element))); \ ScopedVariant actual; \ ASSERT_HRESULT_SUCCEEDED(element->GetPropertyValue( \ element_test_property_id, actual.Receive())); \ ASSERT_EQ(VT_BSTR, actual.type()); \ ASSERT_NE(nullptr, actual.ptr()->bstrVal); \ property_values.push_back(std::wstring( \ V_BSTR(actual.ptr()), SysStringLen(V_BSTR(actual.ptr())))); \ } \ ASSERT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(array.ptr()->parray)); \ EXPECT_THAT(property_values, \ testing::UnorderedElementsAreArray(expected_property_values)); \ } MockIRawElementProviderSimple::MockIRawElementProviderSimple() = default; MockIRawElementProviderSimple::~MockIRawElementProviderSimple() = default; HRESULT MockIRawElementProviderSimple::CreateMockIRawElementProviderSimple( IRawElementProviderSimple** provider) { CComObject<MockIRawElementProviderSimple>* raw_element_provider = nullptr; HRESULT hr = CComObject<MockIRawElementProviderSimple>::CreateInstance( &raw_element_provider); if (SUCCEEDED(hr)) { *provider = raw_element_provider; } return hr; } // // IRawElementProviderSimple methods. // IFACEMETHODIMP MockIRawElementProviderSimple::GetPatternProvider( PATTERNID pattern_id, IUnknown** result) { return E_NOTIMPL; } IFACEMETHODIMP MockIRawElementProviderSimple::GetPropertyValue( PROPERTYID property_id, VARIANT* result) { return E_NOTIMPL; } IFACEMETHODIMP MockIRawElementProviderSimple::get_ProviderOptions(enum ProviderOptions* ret) { return E_NOTIMPL; } IFACEMETHODIMP MockIRawElementProviderSimple::get_HostRawElementProvider( IRawElementProviderSimple** provider) { return E_NOTIMPL; } AXPlatformNodeWinTest::AXPlatformNodeWinTest() { // scoped_feature_list_.InitAndEnableFeature(features::kIChromeAccessible); } AXPlatformNodeWinTest::~AXPlatformNodeWinTest() {} void AXPlatformNodeWinTest::SetUp() { win::CreateATLModuleIfNeeded(); } void AXPlatformNodeWinTest::TearDown() { // Destroy the tree and make sure we're not leaking any objects. ax_fragment_root_.reset(nullptr); DestroyTree(); TestAXNodeWrapper::SetGlobalIsWebContent(false); TestAXNodeWrapper::ClearHitTestResults(); ASSERT_EQ(0U, AXPlatformNodeBase::GetInstanceCountForTesting()); } AXPlatformNode* AXPlatformNodeWinTest::AXPlatformNodeFromNode(AXNode* node) { const TestAXNodeWrapper* wrapper = TestAXNodeWrapper::GetOrCreate(GetTree(), node); return wrapper ? wrapper->ax_platform_node() : nullptr; } template <typename T> ComPtr<T> AXPlatformNodeWinTest::QueryInterfaceFromNodeId(AXNode::AXID id) { return QueryInterfaceFromNode<T>(GetNodeFromTree(id)); } template <typename T> ComPtr<T> AXPlatformNodeWinTest::QueryInterfaceFromNode(AXNode* node) { AXPlatformNode* ax_platform_node = AXPlatformNodeFromNode(node); if (!ax_platform_node) return ComPtr<T>(); ComPtr<T> result; EXPECT_HRESULT_SUCCEEDED( ax_platform_node->GetNativeViewAccessible()->QueryInterface(__uuidof(T), &result)); return result; } ComPtr<IRawElementProviderSimple> AXPlatformNodeWinTest::GetRootIRawElementProviderSimple() { return QueryInterfaceFromNode<IRawElementProviderSimple>(GetRootAsAXNode()); } ComPtr<IRawElementProviderSimple> AXPlatformNodeWinTest::GetIRawElementProviderSimpleFromChildIndex( int child_index) { if (!GetRootAsAXNode() || child_index < 0 || static_cast<size_t>(child_index) >= GetRootAsAXNode()->children().size()) { return ComPtr<IRawElementProviderSimple>(); } return QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[static_cast<size_t>(child_index)]); } Microsoft::WRL::ComPtr<IRawElementProviderSimple> AXPlatformNodeWinTest::GetIRawElementProviderSimpleFromTree( const ui::AXTreeID tree_id, const AXNode::AXID node_id) { return QueryInterfaceFromNode<IRawElementProviderSimple>( GetNodeFromTree(tree_id, node_id)); } ComPtr<IRawElementProviderFragment> AXPlatformNodeWinTest::GetRootIRawElementProviderFragment() { return QueryInterfaceFromNode<IRawElementProviderFragment>(GetRootAsAXNode()); } Microsoft::WRL::ComPtr<IRawElementProviderFragment> AXPlatformNodeWinTest::IRawElementProviderFragmentFromNode(AXNode* node) { AXPlatformNode* platform_node = AXPlatformNodeFromNode(node); gfx::NativeViewAccessible native_view = platform_node->GetNativeViewAccessible(); ComPtr<IUnknown> unknown_node = native_view; ComPtr<IRawElementProviderFragment> fragment_node; unknown_node.As(&fragment_node); return fragment_node; } ComPtr<IAccessible> AXPlatformNodeWinTest::IAccessibleFromNode(AXNode* node) { return QueryInterfaceFromNode<IAccessible>(node); } ComPtr<IAccessible> AXPlatformNodeWinTest::GetRootIAccessible() { return IAccessibleFromNode(GetRootAsAXNode()); } void AXPlatformNodeWinTest::CheckVariantHasName(const ScopedVariant& variant, const wchar_t* expected_name) { ASSERT_NE(nullptr, variant.ptr()); ComPtr<IAccessible> accessible; ASSERT_HRESULT_SUCCEEDED( V_DISPATCH(variant.ptr())->QueryInterface(IID_PPV_ARGS(&accessible))); ScopedBstr name; EXPECT_EQ(S_OK, accessible->get_accName(SELF, name.Receive())); EXPECT_STREQ(expected_name, name.Get()); } void AXPlatformNodeWinTest::InitFragmentRoot() { test_fragment_root_delegate_ = std::make_unique<TestFragmentRootDelegate>(); ax_fragment_root_.reset(InitNodeAsFragmentRoot( GetRootAsAXNode(), test_fragment_root_delegate_.get())); } AXFragmentRootWin* AXPlatformNodeWinTest::InitNodeAsFragmentRoot( AXNode* node, TestFragmentRootDelegate* delegate) { delegate->child_ = AXPlatformNodeFromNode(node)->GetNativeViewAccessible(); if (node->parent()) delegate->parent_ = AXPlatformNodeFromNode(node->parent())->GetNativeViewAccessible(); return new AXFragmentRootWin(gfx::kMockAcceleratedWidget, delegate); } ComPtr<IRawElementProviderFragmentRoot> AXPlatformNodeWinTest::GetFragmentRoot() { ComPtr<IRawElementProviderFragmentRoot> fragment_root_provider; ax_fragment_root_->GetNativeViewAccessible()->QueryInterface( IID_PPV_ARGS(&fragment_root_provider)); return fragment_root_provider; } AXPlatformNodeWinTest::PatternSet AXPlatformNodeWinTest::GetSupportedPatternsFromNodeId(AXNode::AXID id) { ComPtr<IRawElementProviderSimple> raw_element_provider_simple = QueryInterfaceFromNodeId<IRawElementProviderSimple>(id); PatternSet supported_patterns; static const std::vector<LONG> all_supported_patterns_ = { UIA_TextChildPatternId, UIA_TextEditPatternId, UIA_TextPatternId, UIA_WindowPatternId, UIA_InvokePatternId, UIA_ExpandCollapsePatternId, UIA_GridPatternId, UIA_GridItemPatternId, UIA_RangeValuePatternId, UIA_ScrollPatternId, UIA_ScrollItemPatternId, UIA_TablePatternId, UIA_TableItemPatternId, UIA_SelectionItemPatternId, UIA_SelectionPatternId, UIA_TogglePatternId, UIA_ValuePatternId, }; for (LONG property_id : all_supported_patterns_) { ComPtr<IUnknown> provider; if (SUCCEEDED(raw_element_provider_simple->GetPatternProvider(property_id, &provider)) && provider) { supported_patterns.insert(property_id); } } return supported_patterns; } TestFragmentRootDelegate::TestFragmentRootDelegate() = default; TestFragmentRootDelegate::~TestFragmentRootDelegate() = default; gfx::NativeViewAccessible TestFragmentRootDelegate::GetChildOfAXFragmentRoot() { return child_; } gfx::NativeViewAccessible TestFragmentRootDelegate::GetParentOfAXFragmentRoot() { return parent_; } bool TestFragmentRootDelegate::IsAXFragmentRootAControlElement() { return is_control_element_; } TEST_F(AXPlatformNodeWinTest, IAccessibleDetachedObject) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.SetName("Name"); Init(root); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ScopedBstr name; EXPECT_EQ(S_OK, root_obj->get_accName(SELF, name.Receive())); EXPECT_STREQ(L"Name", name.Get()); // Create an empty tree. SetTree(std::make_unique<AXTree>()); ScopedBstr name2; EXPECT_EQ(E_FAIL, root_obj->get_accName(SELF, name2.Receive())); } TEST_F(AXPlatformNodeWinTest, IAccessibleHitTest) { AXNodeData root; root.id = 1; root.relative_bounds.bounds = gfx::RectF(0, 0, 40, 40); AXNodeData node1; node1.id = 2; node1.role = ax::mojom::Role::kGenericContainer; node1.relative_bounds.bounds = gfx::RectF(0, 0, 10, 10); node1.SetName("Name1"); root.child_ids.push_back(node1.id); AXNodeData node2; node2.id = 3; node2.role = ax::mojom::Role::kGenericContainer; node2.relative_bounds.bounds = gfx::RectF(20, 20, 20, 20); node2.SetName("Name2"); root.child_ids.push_back(node2.id); Init(root, node1, node2); ComPtr<IAccessible> root_obj(GetRootIAccessible()); // This is way outside of the root node. ScopedVariant obj_1; EXPECT_EQ(S_FALSE, root_obj->accHitTest(50, 50, obj_1.Receive())); EXPECT_EQ(VT_EMPTY, obj_1.type()); // This is directly on node 1. EXPECT_EQ(S_OK, root_obj->accHitTest(5, 5, obj_1.Receive())); ASSERT_NE(nullptr, obj_1.ptr()); CheckVariantHasName(obj_1, L"Name1"); // This is directly on node 2 with a scale factor of 1.5. ScopedVariant obj_2; std::unique_ptr<base::AutoReset<float>> scale_factor_reset = TestAXNodeWrapper::SetScaleFactor(1.5); EXPECT_EQ(S_OK, root_obj->accHitTest(38, 38, obj_2.Receive())); ASSERT_NE(nullptr, obj_2.ptr()); CheckVariantHasName(obj_2, L"Name2"); } TEST_F(AXPlatformNodeWinTest, IAccessibleHitTestDoesNotLoopForever) { AXNodeData root; root.id = 1; root.relative_bounds.bounds = gfx::RectF(0, 0, 40, 40); AXNodeData node1; node1.id = 2; node1.role = ax::mojom::Role::kGenericContainer; node1.relative_bounds.bounds = gfx::RectF(0, 0, 10, 10); node1.SetName("Name1"); root.child_ids.push_back(node1.id); Init(root, node1); // Set up the endless loop. TestAXNodeWrapper::SetHitTestResult(1, 2); TestAXNodeWrapper::SetHitTestResult(2, 1); // Hit testing on the root returns the child. Hit testing on the // child returns the root, but that should be rejected rather than // looping endlessly. ComPtr<IAccessible> root_obj(GetRootIAccessible()); ScopedVariant obj_1; EXPECT_EQ(S_OK, root_obj->accHitTest(5, 5, obj_1.Receive())); ASSERT_NE(nullptr, obj_1.ptr()); CheckVariantHasName(obj_1, L"Name1"); } TEST_F(AXPlatformNodeWinTest, IAccessibleName) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.SetName("Name"); Init(root); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ScopedBstr name; EXPECT_EQ(S_OK, root_obj->get_accName(SELF, name.Receive())); EXPECT_STREQ(L"Name", name.Get()); EXPECT_EQ(E_INVALIDARG, root_obj->get_accName(SELF, nullptr)); ScopedVariant bad_id(999); ScopedBstr name2; EXPECT_EQ(E_INVALIDARG, root_obj->get_accName(bad_id, name2.Receive())); } TEST_F(AXPlatformNodeWinTest, IAccessibleDescription) { AXNodeData root; root.id = 1; root.AddStringAttribute(ax::mojom::StringAttribute::kDescription, "Description"); Init(root); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ScopedBstr description; EXPECT_EQ(S_OK, root_obj->get_accDescription(SELF, description.Receive())); EXPECT_STREQ(L"Description", description.Get()); EXPECT_EQ(E_INVALIDARG, root_obj->get_accDescription(SELF, nullptr)); ScopedVariant bad_id(999); ScopedBstr d2; EXPECT_EQ(E_INVALIDARG, root_obj->get_accDescription(bad_id, d2.Receive())); } TEST_F(AXPlatformNodeWinTest, IAccessibleAccValue) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTextField; root.AddStringAttribute(ax::mojom::StringAttribute::kValue, "Value"); Init(root); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ScopedBstr value; EXPECT_EQ(S_OK, root_obj->get_accValue(SELF, value.Receive())); EXPECT_STREQ(L"Value", value.Get()); EXPECT_EQ(E_INVALIDARG, root_obj->get_accValue(SELF, nullptr)); ScopedVariant bad_id(999); ScopedBstr v2; EXPECT_EQ(E_INVALIDARG, root_obj->get_accValue(bad_id, v2.Receive())); } TEST_F(AXPlatformNodeWinTest, IAccessibleShortcut) { AXNodeData root; root.id = 1; root.AddStringAttribute(ax::mojom::StringAttribute::kKeyShortcuts, "Shortcut"); Init(root); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ScopedBstr shortcut; EXPECT_EQ(S_OK, root_obj->get_accKeyboardShortcut(SELF, shortcut.Receive())); EXPECT_STREQ(L"Shortcut", shortcut.Get()); EXPECT_EQ(E_INVALIDARG, root_obj->get_accKeyboardShortcut(SELF, nullptr)); ScopedVariant bad_id(999); ScopedBstr k2; EXPECT_EQ(E_INVALIDARG, root_obj->get_accKeyboardShortcut(bad_id, k2.Receive())); } TEST_F(AXPlatformNodeWinTest, IAccessibleSelectionListBoxOptionNothingSelected) { AXNodeData list; list.id = 1; list.role = ax::mojom::Role::kListBox; AXNodeData list_item_1; list_item_1.id = 2; list_item_1.role = ax::mojom::Role::kListBoxOption; list_item_1.SetName("Name1"); AXNodeData list_item_2; list_item_2.id = 3; list_item_2.role = ax::mojom::Role::kListBoxOption; list_item_2.SetName("Name2"); list.child_ids.push_back(list_item_1.id); list.child_ids.push_back(list_item_2.id); Init(list, list_item_1, list_item_2); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ASSERT_NE(nullptr, root_obj.Get()); ScopedVariant selection; EXPECT_EQ(S_OK, root_obj->get_accSelection(selection.Receive())); EXPECT_EQ(VT_EMPTY, selection.type()); } TEST_F(AXPlatformNodeWinTest, IAccessibleSelectionListBoxOptionOneSelected) { AXNodeData list; list.id = 1; list.role = ax::mojom::Role::kListBox; AXNodeData list_item_1; list_item_1.id = 2; list_item_1.role = ax::mojom::Role::kListBoxOption; list_item_1.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); list_item_1.SetName("Name1"); AXNodeData list_item_2; list_item_2.id = 3; list_item_2.role = ax::mojom::Role::kListBoxOption; list_item_2.SetName("Name2"); list.child_ids.push_back(list_item_1.id); list.child_ids.push_back(list_item_2.id); Init(list, list_item_1, list_item_2); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ASSERT_NE(nullptr, root_obj.Get()); ScopedVariant selection; EXPECT_EQ(S_OK, root_obj->get_accSelection(selection.Receive())); EXPECT_EQ(VT_DISPATCH, selection.type()); CheckVariantHasName(selection, L"Name1"); } TEST_F(AXPlatformNodeWinTest, IAccessibleSelectionListBoxOptionMultipleSelected) { AXNodeData list; list.id = 1; list.role = ax::mojom::Role::kListBox; AXNodeData list_item_1; list_item_1.id = 2; list_item_1.role = ax::mojom::Role::kListBoxOption; list_item_1.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); list_item_1.SetName("Name1"); AXNodeData list_item_2; list_item_2.id = 3; list_item_2.role = ax::mojom::Role::kListBoxOption; list_item_2.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); list_item_2.SetName("Name2"); AXNodeData list_item_3; list_item_3.id = 4; list_item_3.role = ax::mojom::Role::kListBoxOption; list_item_3.SetName("Name3"); list.child_ids.push_back(list_item_1.id); list.child_ids.push_back(list_item_2.id); list.child_ids.push_back(list_item_3.id); Init(list, list_item_1, list_item_2, list_item_3); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ASSERT_NE(nullptr, root_obj.Get()); ScopedVariant selection; EXPECT_EQ(S_OK, root_obj->get_accSelection(selection.Receive())); EXPECT_EQ(VT_UNKNOWN, selection.type()); ASSERT_NE(nullptr, selection.ptr()); // Loop through the selections and make sure we have the right ones. ComPtr<IEnumVARIANT> accessibles; ASSERT_HRESULT_SUCCEEDED( V_UNKNOWN(selection.ptr())->QueryInterface(IID_PPV_ARGS(&accessibles))); ULONG retrieved_count; // Check out the first selected item. { ScopedVariant item; HRESULT hr = accessibles->Next(1, item.Receive(), &retrieved_count); EXPECT_EQ(S_OK, hr); ComPtr<IAccessible> accessible; ASSERT_HRESULT_SUCCEEDED( V_DISPATCH(item.ptr())->QueryInterface(IID_PPV_ARGS(&accessible))); ScopedBstr name; EXPECT_EQ(S_OK, accessible->get_accName(SELF, name.Receive())); EXPECT_STREQ(L"Name1", name.Get()); } // And the second selected element. { ScopedVariant item; HRESULT hr = accessibles->Next(1, item.Receive(), &retrieved_count); EXPECT_EQ(S_OK, hr); ComPtr<IAccessible> accessible; ASSERT_HRESULT_SUCCEEDED( V_DISPATCH(item.ptr())->QueryInterface(IID_PPV_ARGS(&accessible))); ScopedBstr name; EXPECT_EQ(S_OK, accessible->get_accName(SELF, name.Receive())); EXPECT_STREQ(L"Name2", name.Get()); } // There shouldn't be any more selected. { ScopedVariant item; HRESULT hr = accessibles->Next(1, item.Receive(), &retrieved_count); EXPECT_EQ(S_FALSE, hr); } } TEST_F(AXPlatformNodeWinTest, IAccessibleSelectionTableNothingSelected) { Init(Build3X3Table()); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ASSERT_NE(nullptr, root_obj.Get()); ScopedVariant selection; EXPECT_EQ(S_OK, root_obj->get_accSelection(selection.Receive())); EXPECT_EQ(VT_EMPTY, selection.type()); } TEST_F(AXPlatformNodeWinTest, IAccessibleSelectionTableRowOneSelected) { AXTreeUpdate update = Build3X3Table(); // 5 == table_row_1 update.nodes[5].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); Init(update); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ASSERT_NE(nullptr, root_obj.Get()); ScopedVariant selection; EXPECT_EQ(S_OK, root_obj->get_accSelection(selection.Receive())); EXPECT_EQ(VT_DISPATCH, selection.type()); ASSERT_NE(nullptr, selection.ptr()); ComPtr<IAccessible> row; ASSERT_HRESULT_SUCCEEDED( V_DISPATCH(selection.ptr())->QueryInterface(IID_PPV_ARGS(&row))); ScopedVariant role; EXPECT_HRESULT_SUCCEEDED(row->get_accRole(SELF, role.Receive())); EXPECT_EQ(ROLE_SYSTEM_ROW, V_I4(role.ptr())); } TEST_F(AXPlatformNodeWinTest, IAccessibleSelectionTableRowMultipleSelected) { AXTreeUpdate update = Build3X3Table(); // 5 == table_row_1 // 9 == table_row_2 update.nodes[5].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); update.nodes[9].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); Init(update); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ASSERT_NE(nullptr, root_obj.Get()); ScopedVariant selection; EXPECT_EQ(S_OK, root_obj->get_accSelection(selection.Receive())); EXPECT_EQ(VT_UNKNOWN, selection.type()); ASSERT_NE(nullptr, selection.ptr()); // Loop through the selections and make sure we have the right ones. ComPtr<IEnumVARIANT> accessibles; ASSERT_HRESULT_SUCCEEDED( V_UNKNOWN(selection.ptr())->QueryInterface(IID_PPV_ARGS(&accessibles))); ULONG retrieved_count; // Check out the first selected row. { ScopedVariant item; HRESULT hr = accessibles->Next(1, item.Receive(), &retrieved_count); EXPECT_EQ(S_OK, hr); ComPtr<IAccessible> accessible; ASSERT_HRESULT_SUCCEEDED( V_DISPATCH(item.ptr())->QueryInterface(IID_PPV_ARGS(&accessible))); ScopedVariant role; EXPECT_HRESULT_SUCCEEDED(accessible->get_accRole(SELF, role.Receive())); EXPECT_EQ(ROLE_SYSTEM_ROW, V_I4(role.ptr())); } // And the second selected element. { ScopedVariant item; HRESULT hr = accessibles->Next(1, item.Receive(), &retrieved_count); EXPECT_EQ(S_OK, hr); ComPtr<IAccessible> accessible; ASSERT_HRESULT_SUCCEEDED( V_DISPATCH(item.ptr())->QueryInterface(IID_PPV_ARGS(&accessible))); ScopedVariant role; EXPECT_HRESULT_SUCCEEDED(accessible->get_accRole(SELF, role.Receive())); EXPECT_EQ(ROLE_SYSTEM_ROW, V_I4(role.ptr())); } // There shouldn't be any more selected. { ScopedVariant item; HRESULT hr = accessibles->Next(1, item.Receive(), &retrieved_count); EXPECT_EQ(S_FALSE, hr); } } TEST_F(AXPlatformNodeWinTest, IAccessibleSelectionTableCellOneSelected) { AXTreeUpdate update = Build3X3Table(); // 7 == table_cell_1 update.nodes[7].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); Init(update); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ASSERT_NE(nullptr, root_obj.Get()); ComPtr<IDispatch> row2; ASSERT_HRESULT_SUCCEEDED(root_obj->get_accChild(ScopedVariant(2), &row2)); ComPtr<IAccessible> row2_accessible; ASSERT_HRESULT_SUCCEEDED(row2.As(&row2_accessible)); ScopedVariant selection; EXPECT_EQ(S_OK, row2_accessible->get_accSelection(selection.Receive())); EXPECT_EQ(VT_DISPATCH, selection.type()); ASSERT_NE(nullptr, selection.ptr()); ComPtr<IAccessible> cell; ASSERT_HRESULT_SUCCEEDED( V_DISPATCH(selection.ptr())->QueryInterface(IID_PPV_ARGS(&cell))); ScopedVariant role; EXPECT_HRESULT_SUCCEEDED(cell->get_accRole(SELF, role.Receive())); EXPECT_EQ(ROLE_SYSTEM_CELL, V_I4(role.ptr())); ScopedBstr name; EXPECT_EQ(S_OK, cell->get_accName(SELF, name.Receive())); EXPECT_STREQ(L"1", name.Get()); } TEST_F(AXPlatformNodeWinTest, IAccessibleSelectionTableCellMultipleSelected) { AXTreeUpdate update = Build3X3Table(); // 11 == table_cell_3 // 12 == table_cell_4 update.nodes[11].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); update.nodes[12].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); Init(update); ComPtr<IAccessible> root_obj(GetRootIAccessible()); ASSERT_NE(nullptr, root_obj.Get()); ComPtr<IDispatch> row3; ASSERT_HRESULT_SUCCEEDED(root_obj->get_accChild(ScopedVariant(3), &row3)); ComPtr<IAccessible> row3_accessible; ASSERT_HRESULT_SUCCEEDED(row3.As(&row3_accessible)); ScopedVariant selection; EXPECT_EQ(S_OK, row3_accessible->get_accSelection(selection.Receive())); EXPECT_EQ(VT_UNKNOWN, selection.type()); ASSERT_NE(nullptr, selection.ptr()); // Loop through the selections and make sure we have the right ones. ComPtr<IEnumVARIANT> accessibles; ASSERT_HRESULT_SUCCEEDED( V_UNKNOWN(selection.ptr())->QueryInterface(IID_PPV_ARGS(&accessibles))); ULONG retrieved_count; // Check out the first selected cell. { ScopedVariant item; HRESULT hr = accessibles->Next(1, item.Receive(), &retrieved_count); EXPECT_EQ(S_OK, hr); ComPtr<IAccessible> accessible; ASSERT_HRESULT_SUCCEEDED( V_DISPATCH(item.ptr())->QueryInterface(IID_PPV_ARGS(&accessible))); ScopedBstr name; EXPECT_EQ(S_OK, accessible->get_accName(SELF, name.Receive())); EXPECT_STREQ(L"3", name.Get()); } // And the second selected cell. { ScopedVariant item; HRESULT hr = accessibles->Next(1, item.Receive(), &retrieved_count); EXPECT_EQ(S_OK, hr); ComPtr<IAccessible> accessible; ASSERT_HRESULT_SUCCEEDED( V_DISPATCH(item.ptr())->QueryInterface(IID_PPV_ARGS(&accessible))); ScopedBstr name; EXPECT_EQ(S_OK, accessible->get_accName(SELF, name.Receive())); EXPECT_STREQ(L"4", name.Get()); } // There shouldn't be any more selected. { ScopedVariant item; HRESULT hr = accessibles->Next(1, item.Receive(), &retrieved_count); EXPECT_EQ(S_FALSE, hr); } } TEST_F(AXPlatformNodeWinTest, IAccessibleRole) { AXNodeData root; root.id = 1; root.child_ids.push_back(2); AXNodeData child; child.id = 2; Init(root, child); AXNode* child_node = GetRootAsAXNode()->children()[0]; ComPtr<IAccessible> child_iaccessible(IAccessibleFromNode(child_node)); ScopedVariant role; child.role = ax::mojom::Role::kAlert; child_node->SetData(child); EXPECT_EQ(S_OK, child_iaccessible->get_accRole(SELF, role.Receive())); EXPECT_EQ(ROLE_SYSTEM_ALERT, V_I4(role.ptr())); child.role = ax::mojom::Role::kButton; child_node->SetData(child); EXPECT_EQ(S_OK, child_iaccessible->get_accRole(SELF, role.Receive())); EXPECT_EQ(ROLE_SYSTEM_PUSHBUTTON, V_I4(role.ptr())); child.role = ax::mojom::Role::kPopUpButton; child_node->SetData(child); EXPECT_EQ(S_OK, child_iaccessible->get_accRole(SELF, role.Receive())); EXPECT_EQ(ROLE_SYSTEM_BUTTONMENU, V_I4(role.ptr())); EXPECT_EQ(E_INVALIDARG, child_iaccessible->get_accRole(SELF, nullptr)); ScopedVariant bad_id(999); EXPECT_EQ(E_INVALIDARG, child_iaccessible->get_accRole(bad_id, role.Receive())); } TEST_F(AXPlatformNodeWinTest, IAccessibleLocation) { AXNodeData root; root.id = 1; root.relative_bounds.bounds = gfx::RectF(10, 40, 800, 600); Init(root); TestAXNodeWrapper::SetGlobalCoordinateOffset(gfx::Vector2d(100, 200)); LONG x_left, y_top, width, height; EXPECT_EQ(S_OK, GetRootIAccessible()->accLocation(&x_left, &y_top, &width, &height, SELF)); EXPECT_EQ(110, x_left); EXPECT_EQ(240, y_top); EXPECT_EQ(800, width); EXPECT_EQ(600, height); EXPECT_EQ(E_INVALIDARG, GetRootIAccessible()->accLocation( nullptr, &y_top, &width, &height, SELF)); EXPECT_EQ(E_INVALIDARG, GetRootIAccessible()->accLocation( &x_left, nullptr, &width, &height, SELF)); EXPECT_EQ(E_INVALIDARG, GetRootIAccessible()->accLocation( &x_left, &y_top, nullptr, &height, SELF)); EXPECT_EQ(E_INVALIDARG, GetRootIAccessible()->accLocation( &x_left, &y_top, &width, nullptr, SELF)); ScopedVariant bad_id(999); EXPECT_EQ(E_INVALIDARG, GetRootIAccessible()->accLocation( &x_left, &y_top, &width, &height, bad_id)); // Un-set the global offset so that it doesn't affect subsequent tests. TestAXNodeWrapper::SetGlobalCoordinateOffset(gfx::Vector2d(0, 0)); } TEST_F(AXPlatformNodeWinTest, IAccessibleChildAndParent) { AXNodeData root; root.id = 1; root.child_ids.push_back(2); root.child_ids.push_back(3); AXNodeData button; button.role = ax::mojom::Role::kButton; button.id = 2; AXNodeData checkbox; checkbox.role = ax::mojom::Role::kCheckBox; checkbox.id = 3; Init(root, button, checkbox); AXNode* button_node = GetRootAsAXNode()->children()[0]; AXNode* checkbox_node = GetRootAsAXNode()->children()[1]; ComPtr<IAccessible> root_iaccessible(GetRootIAccessible()); ComPtr<IAccessible> button_iaccessible(IAccessibleFromNode(button_node)); ComPtr<IAccessible> checkbox_iaccessible(IAccessibleFromNode(checkbox_node)); LONG child_count; EXPECT_EQ(S_OK, root_iaccessible->get_accChildCount(&child_count)); EXPECT_EQ(2L, child_count); EXPECT_EQ(S_OK, button_iaccessible->get_accChildCount(&child_count)); EXPECT_EQ(0L, child_count); EXPECT_EQ(S_OK, checkbox_iaccessible->get_accChildCount(&child_count)); EXPECT_EQ(0L, child_count); { ComPtr<IDispatch> result; EXPECT_EQ(S_OK, root_iaccessible->get_accChild(SELF, &result)); EXPECT_EQ(result.Get(), root_iaccessible.Get()); } { ComPtr<IDispatch> result; ScopedVariant child1(1); EXPECT_EQ(S_OK, root_iaccessible->get_accChild(child1, &result)); EXPECT_EQ(result.Get(), button_iaccessible.Get()); } { ComPtr<IDispatch> result; ScopedVariant child2(2); EXPECT_EQ(S_OK, root_iaccessible->get_accChild(child2, &result)); EXPECT_EQ(result.Get(), checkbox_iaccessible.Get()); } { // Asking for child id 3 should fail. ComPtr<IDispatch> result; ScopedVariant child3(3); EXPECT_EQ(E_INVALIDARG, root_iaccessible->get_accChild(child3, &result)); } // Now check parents. { ComPtr<IDispatch> result; EXPECT_EQ(S_OK, button_iaccessible->get_accParent(&result)); EXPECT_EQ(result.Get(), root_iaccessible.Get()); } { ComPtr<IDispatch> result; EXPECT_EQ(S_OK, checkbox_iaccessible->get_accParent(&result)); EXPECT_EQ(result.Get(), root_iaccessible.Get()); } { ComPtr<IDispatch> result; EXPECT_EQ(S_FALSE, root_iaccessible->get_accParent(&result)); } } TEST_F(AXPlatformNodeWinTest, AccNavigate) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kStaticText; root.child_ids.push_back(2); AXNodeData child2; child2.id = 3; child2.role = ax::mojom::Role::kStaticText; root.child_ids.push_back(3); Init(root, child1, child2); ComPtr<IAccessible> ia_root(GetRootIAccessible()); ComPtr<IDispatch> disp_root; ASSERT_HRESULT_SUCCEEDED(ia_root.As(&disp_root)); ScopedVariant var_root(disp_root.Get()); ComPtr<IAccessible> ia_child1( IAccessibleFromNode(GetRootAsAXNode()->children()[0])); ComPtr<IDispatch> disp_child1; ASSERT_HRESULT_SUCCEEDED(ia_child1.As(&disp_child1)); ScopedVariant var_child1(disp_child1.Get()); ComPtr<IAccessible> ia_child2( IAccessibleFromNode(GetRootAsAXNode()->children()[1])); ComPtr<IDispatch> disp_child2; ASSERT_HRESULT_SUCCEEDED(ia_child2.As(&disp_child2)); ScopedVariant var_child2(disp_child2.Get()); ScopedVariant end; // Invalid arguments. EXPECT_EQ( E_INVALIDARG, ia_root->accNavigate(NAVDIR_NEXT, ScopedVariant::kEmptyVariant, nullptr)); EXPECT_EQ(E_INVALIDARG, ia_child1->accNavigate(NAVDIR_NEXT, ScopedVariant::kEmptyVariant, end.AsInput())); EXPECT_EQ(VT_EMPTY, end.type()); // Navigating to first/last child should only be from self. EXPECT_EQ(E_INVALIDARG, ia_root->accNavigate(NAVDIR_FIRSTCHILD, var_root, end.AsInput())); EXPECT_EQ(VT_EMPTY, end.type()); EXPECT_EQ(E_INVALIDARG, ia_root->accNavigate(NAVDIR_LASTCHILD, var_root, end.AsInput())); EXPECT_EQ(VT_EMPTY, end.type()); // Spatial directions are not supported. EXPECT_EQ(E_NOTIMPL, ia_child1->accNavigate(NAVDIR_UP, SELF, end.AsInput())); EXPECT_EQ(E_NOTIMPL, ia_root->accNavigate(NAVDIR_DOWN, SELF, end.AsInput())); EXPECT_EQ(E_NOTIMPL, ia_child1->accNavigate(NAVDIR_RIGHT, SELF, end.AsInput())); EXPECT_EQ(E_NOTIMPL, ia_child2->accNavigate(NAVDIR_LEFT, SELF, end.AsInput())); EXPECT_EQ(VT_EMPTY, end.type()); // Logical directions should be supported. EXPECT_EQ(S_OK, ia_root->accNavigate(NAVDIR_FIRSTCHILD, SELF, end.AsInput())); EXPECT_EQ(VT_DISPATCH, end.type()); EXPECT_EQ(V_DISPATCH(var_child1.ptr()), V_DISPATCH(end.ptr())); EXPECT_EQ(S_OK, ia_root->accNavigate(NAVDIR_LASTCHILD, SELF, end.AsInput())); EXPECT_EQ(VT_DISPATCH, end.type()); EXPECT_EQ(V_DISPATCH(var_child2.ptr()), V_DISPATCH(end.ptr())); EXPECT_EQ(S_OK, ia_child1->accNavigate(NAVDIR_NEXT, SELF, end.AsInput())); EXPECT_EQ(VT_DISPATCH, end.type()); EXPECT_EQ(V_DISPATCH(var_child2.ptr()), V_DISPATCH(end.ptr())); EXPECT_EQ(S_OK, ia_child2->accNavigate(NAVDIR_PREVIOUS, SELF, end.AsInput())); EXPECT_EQ(VT_DISPATCH, end.type()); EXPECT_EQ(V_DISPATCH(var_child1.ptr()), V_DISPATCH(end.ptr())); // Child indices can also be passed by variant. // Indices are one-based. EXPECT_EQ(S_OK, ia_root->accNavigate(NAVDIR_NEXT, ScopedVariant(1), end.AsInput())); EXPECT_EQ(VT_DISPATCH, end.type()); EXPECT_EQ(V_DISPATCH(var_child2.ptr()), V_DISPATCH(end.ptr())); EXPECT_EQ(S_OK, ia_root->accNavigate(NAVDIR_PREVIOUS, ScopedVariant(2), end.AsInput())); EXPECT_EQ(VT_DISPATCH, end.type()); EXPECT_EQ(V_DISPATCH(var_child1.ptr()), V_DISPATCH(end.ptr())); // Test out-of-bounds. EXPECT_EQ(S_FALSE, ia_child1->accNavigate(NAVDIR_PREVIOUS, SELF, end.AsInput())); EXPECT_EQ(VT_EMPTY, end.type()); EXPECT_EQ(S_FALSE, ia_child2->accNavigate(NAVDIR_NEXT, SELF, end.AsInput())); EXPECT_EQ(VT_EMPTY, end.type()); EXPECT_EQ(S_FALSE, ia_root->accNavigate(NAVDIR_PREVIOUS, ScopedVariant(1), end.AsInput())); EXPECT_EQ(VT_EMPTY, end.type()); EXPECT_EQ(S_FALSE, ia_root->accNavigate(NAVDIR_NEXT, ScopedVariant(2), end.AsInput())); EXPECT_EQ(VT_EMPTY, end.type()); } TEST_F(AXPlatformNodeWinTest, AnnotatedImageName) { std::vector<const wchar_t*> expected_names; AXTreeUpdate tree; tree.root_id = 1; tree.nodes.resize(11); tree.nodes[0].id = 1; tree.nodes[0].child_ids = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // If the status is EligibleForAnnotation and there's no existing label, // the name should be the discoverability string. tree.nodes[1].id = 2; tree.nodes[1].role = ax::mojom::Role::kImage; tree.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, "Annotation"); tree.nodes[1].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation); expected_names.push_back( L"To get missing image descriptions, open the context menu."); // If the status is EligibleForAnnotation, the discoverability string // should be appended to the existing name. tree.nodes[2].id = 3; tree.nodes[2].role = ax::mojom::Role::kImage; tree.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, "Annotation"); tree.nodes[2].SetName("ExistingLabel"); tree.nodes[2].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation); expected_names.push_back( L"ExistingLabel. To get missing image descriptions, open the context " L"menu."); // If the status is SilentlyEligibleForAnnotation, the discoverability string // should not be appended to the existing name. tree.nodes[3].id = 4; tree.nodes[3].role = ax::mojom::Role::kImage; tree.nodes[3].AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, "Annotation"); tree.nodes[3].SetName("ExistingLabel"); tree.nodes[3].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation); expected_names.push_back(L"ExistingLabel"); // If the status is IneligibleForAnnotation, nothing should be appended. tree.nodes[4].id = 5; tree.nodes[4].role = ax::mojom::Role::kImage; tree.nodes[4].AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, "Annotation"); tree.nodes[4].SetName("ExistingLabel"); tree.nodes[4].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation); expected_names.push_back(L"ExistingLabel"); // If the status is AnnotationPending, pending text should be appended // to the name. tree.nodes[5].id = 6; tree.nodes[5].role = ax::mojom::Role::kImage; tree.nodes[5].AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, "Annotation"); tree.nodes[5].SetName("ExistingLabel"); tree.nodes[5].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kAnnotationPending); expected_names.push_back(L"ExistingLabel. Getting description..."); // If the status is AnnotationSucceeded, and there's no annotation, // nothing should be appended. (Ideally this shouldn't happen.) tree.nodes[6].id = 7; tree.nodes[6].role = ax::mojom::Role::kImage; tree.nodes[6].SetName("ExistingLabel"); tree.nodes[6].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded); expected_names.push_back(L"ExistingLabel"); // If the status is AnnotationSucceeded, the annotation should be appended // to the existing label. tree.nodes[7].id = 8; tree.nodes[7].role = ax::mojom::Role::kImage; tree.nodes[7].AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, "Annotation"); tree.nodes[7].SetName("ExistingLabel"); tree.nodes[7].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded); expected_names.push_back(L"ExistingLabel. Annotation"); // If the status is AnnotationEmpty, failure text should be added to the // name. tree.nodes[8].id = 9; tree.nodes[8].role = ax::mojom::Role::kImage; tree.nodes[8].AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, "Annotation"); tree.nodes[8].SetName("ExistingLabel"); tree.nodes[8].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kAnnotationEmpty); expected_names.push_back(L"ExistingLabel. No description available."); // If the status is AnnotationAdult, appropriate text should be appended // to the name. tree.nodes[9].id = 10; tree.nodes[9].role = ax::mojom::Role::kImage; tree.nodes[9].AddStringAttribute(ax::mojom::StringAttribute::kImageAnnotation, "Annotation"); tree.nodes[9].SetName("ExistingLabel"); tree.nodes[9].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kAnnotationAdult); expected_names.push_back( L"ExistingLabel. Appears to contain adult content. No description " L"available."); // If the status is AnnotationProcessFailed, failure text should be added // to the name. tree.nodes[10].id = 11; tree.nodes[10].role = ax::mojom::Role::kImage; tree.nodes[10].AddStringAttribute( ax::mojom::StringAttribute::kImageAnnotation, "Annotation"); tree.nodes[10].SetName("ExistingLabel"); tree.nodes[10].SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed); expected_names.push_back(L"ExistingLabel. No description available."); // We should have one expected name per child of the root. ASSERT_EQ(expected_names.size(), tree.nodes[0].child_ids.size()); int child_count = static_cast<int>(expected_names.size()); Init(tree); ComPtr<IAccessible> root_obj(GetRootIAccessible()); for (int child_index = 0; child_index < child_count; child_index++) { ComPtr<IDispatch> child_dispatch; ASSERT_HRESULT_SUCCEEDED(root_obj->get_accChild( ScopedVariant(child_index + 1), &child_dispatch)); ComPtr<IAccessible> child; ASSERT_HRESULT_SUCCEEDED(child_dispatch.As(&child)); ScopedBstr name; EXPECT_EQ(S_OK, child->get_accName(SELF, name.Receive())); EXPECT_STREQ(expected_names[child_index], name.Get()); } } TEST_F(AXPlatformNodeWinTest, IGridProviderGetRowCount) { Init(BuildAriaColumnAndRowCountGrids()); // Empty Grid ComPtr<IGridProvider> grid1_provider = QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode()->children()[0]); // Grid with a cell that defines aria-rowindex (4) and aria-colindex (5) ComPtr<IGridProvider> grid2_provider = QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode()->children()[1]); // Grid that specifies aria-rowcount (2) and aria-colcount (3) ComPtr<IGridProvider> grid3_provider = QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode()->children()[2]); // Grid that specifies aria-rowcount and aria-colcount are both (-1) ComPtr<IGridProvider> grid4_provider = QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode()->children()[3]); int row_count; EXPECT_HRESULT_SUCCEEDED(grid1_provider->get_RowCount(&row_count)); EXPECT_EQ(row_count, 0); EXPECT_HRESULT_SUCCEEDED(grid2_provider->get_RowCount(&row_count)); EXPECT_EQ(row_count, 4); EXPECT_HRESULT_SUCCEEDED(grid3_provider->get_RowCount(&row_count)); EXPECT_EQ(row_count, 2); EXPECT_EQ(E_UNEXPECTED, grid4_provider->get_RowCount(&row_count)); } TEST_F(AXPlatformNodeWinTest, IGridProviderGetColumnCount) { Init(BuildAriaColumnAndRowCountGrids()); // Empty Grid ComPtr<IGridProvider> grid1_provider = QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode()->children()[0]); // Grid with a cell that defines aria-rowindex (4) and aria-colindex (5) ComPtr<IGridProvider> grid2_provider = QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode()->children()[1]); // Grid that specifies aria-rowcount (2) and aria-colcount (3) ComPtr<IGridProvider> grid3_provider = QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode()->children()[2]); // Grid that specifies aria-rowcount and aria-colcount are both (-1) ComPtr<IGridProvider> grid4_provider = QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode()->children()[3]); int column_count; EXPECT_HRESULT_SUCCEEDED(grid1_provider->get_ColumnCount(&column_count)); EXPECT_EQ(column_count, 0); EXPECT_HRESULT_SUCCEEDED(grid2_provider->get_ColumnCount(&column_count)); EXPECT_EQ(column_count, 5); EXPECT_HRESULT_SUCCEEDED(grid3_provider->get_ColumnCount(&column_count)); EXPECT_EQ(column_count, 3); EXPECT_EQ(E_UNEXPECTED, grid4_provider->get_ColumnCount(&column_count)); } TEST_F(AXPlatformNodeWinTest, IGridProviderGetItem) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kGrid; root.AddIntAttribute(ax::mojom::IntAttribute::kAriaRowCount, 1); root.AddIntAttribute(ax::mojom::IntAttribute::kAriaColumnCount, 1); AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; root.child_ids.push_back(row1.id); AXNodeData cell1; cell1.id = 3; cell1.role = ax::mojom::Role::kCell; row1.child_ids.push_back(cell1.id); Init(root, row1, cell1); ComPtr<IGridProvider> root_igridprovider( QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode())); ComPtr<IRawElementProviderSimple> cell1_irawelementprovidersimple( QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[0]->children()[0])); IRawElementProviderSimple* grid_item = nullptr; EXPECT_HRESULT_SUCCEEDED(root_igridprovider->GetItem(0, 0, &grid_item)); EXPECT_NE(nullptr, grid_item); EXPECT_EQ(cell1_irawelementprovidersimple.Get(), grid_item); } TEST_F(AXPlatformNodeWinTest, ITableProviderGetColumnHeaders) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTable; AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; root.child_ids.push_back(row1.id); AXNodeData column_header; column_header.id = 3; column_header.role = ax::mojom::Role::kColumnHeader; column_header.SetName(u"column_header"); row1.child_ids.push_back(column_header.id); AXNodeData row_header; row_header.id = 4; row_header.role = ax::mojom::Role::kRowHeader; row_header.SetName(u"row_header"); row1.child_ids.push_back(row_header.id); Init(root, row1, column_header, row_header); ComPtr<ITableProvider> root_itableprovider( QueryInterfaceFromNode<ITableProvider>(GetRootAsAXNode())); base::win::ScopedSafearray safearray; EXPECT_HRESULT_SUCCEEDED( root_itableprovider->GetColumnHeaders(safearray.Receive())); EXPECT_NE(nullptr, safearray.Get()); std::vector<std::wstring> expected_names = {L"column_header"}; EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(safearray.Get(), UIA_NamePropertyId, expected_names); // Remove column_header's native event target and verify it's no longer // returned. TestAXNodeWrapper* column_header_wrapper = TestAXNodeWrapper::GetOrCreate( GetTree(), GetRootAsAXNode()->children()[0]->children()[0]); column_header_wrapper->ResetNativeEventTarget(); safearray.Release(); EXPECT_HRESULT_SUCCEEDED( root_itableprovider->GetColumnHeaders(safearray.Receive())); EXPECT_EQ(nullptr, safearray.Get()); } TEST_F(AXPlatformNodeWinTest, ITableProviderGetColumnHeadersMultipleHeaders) { // Build a table like this: // header_r1c1 | header_r1c2 | header_r1c3 // cell_r2c1 | cell_r2c2 | cell_r2c3 // cell_r3c1 | header_r3c2 | // <table> // <tr aria-label="row1"> // <th>header_r1c1</th> // <th>header_r1c2</th> // <th>header_r1c3</th> // </tr> // <tr aria-label="row2"> // <td>cell_r2c1</td> // <td>cell_r2c2</td> // <td>cell_r2c3</td> // </tr> // <tr aria-label="row3"> // <td>cell_r3c1</td> // <th>header_r3c2</th> // </tr> // </table> AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTable; AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; root.child_ids.push_back(row1.id); AXNodeData row2; row2.id = 3; row2.role = ax::mojom::Role::kRow; root.child_ids.push_back(row2.id); AXNodeData row3; row3.id = 4; row3.role = ax::mojom::Role::kRow; root.child_ids.push_back(row3.id); // <tr aria-label="row1"> // <th>header_r1c1</th> <th>header_r1c2</th> <th>header_r1c3</th> // </tr> AXNodeData header_r1c1; header_r1c1.id = 5; header_r1c1.role = ax::mojom::Role::kColumnHeader; header_r1c1.SetName(u"header_r1c1"); row1.child_ids.push_back(header_r1c1.id); AXNodeData header_r1c2; header_r1c2.id = 6; header_r1c2.role = ax::mojom::Role::kColumnHeader; header_r1c2.SetName(u"header_r1c2"); row1.child_ids.push_back(header_r1c2.id); AXNodeData header_r1c3; header_r1c3.id = 7; header_r1c3.role = ax::mojom::Role::kColumnHeader; header_r1c3.SetName(u"header_r1c3"); row1.child_ids.push_back(header_r1c3.id); // <tr aria-label="row2"> // <td>cell_r2c1</td> <td>cell_r2c2</td> <td>cell_r2c3</td> // </tr> AXNodeData cell_r2c1; cell_r2c1.id = 8; cell_r2c1.role = ax::mojom::Role::kCell; cell_r2c1.SetName(u"cell_r2c1"); row2.child_ids.push_back(cell_r2c1.id); AXNodeData cell_r2c2; cell_r2c2.id = 9; cell_r2c2.role = ax::mojom::Role::kCell; cell_r2c2.SetName(u"cell_r2c2"); row2.child_ids.push_back(cell_r2c2.id); AXNodeData cell_r2c3; cell_r2c3.id = 10; cell_r2c3.role = ax::mojom::Role::kCell; cell_r2c3.SetName(u"cell_r2c3"); row2.child_ids.push_back(cell_r2c3.id); // <tr aria-label="row3"> // <td>cell_r3c1</td> <th>header_r3c2</th> // </tr> AXNodeData cell_r3c1; cell_r3c1.id = 11; cell_r3c1.role = ax::mojom::Role::kCell; cell_r3c1.SetName(u"cell_r3c1"); row3.child_ids.push_back(cell_r3c1.id); AXNodeData header_r3c2; header_r3c2.id = 12; header_r3c2.role = ax::mojom::Role::kColumnHeader; header_r3c2.SetName(u"header_r3c2"); row3.child_ids.push_back(header_r3c2.id); Init(root, row1, row2, row3, header_r1c1, header_r1c2, header_r1c3, cell_r2c1, cell_r2c2, cell_r2c3, cell_r3c1, header_r3c2); ComPtr<ITableProvider> root_itableprovider( QueryInterfaceFromNode<ITableProvider>(GetRootAsAXNode())); base::win::ScopedSafearray safearray; EXPECT_HRESULT_SUCCEEDED( root_itableprovider->GetColumnHeaders(safearray.Receive())); EXPECT_NE(nullptr, safearray.Get()); // Validate that we retrieve all column headers of the table and in the order // below. std::vector<std::wstring> expected_names = {L"header_r1c1", L"header_r1c2", L"header_r3c2", L"header_r1c3"}; EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(safearray.Get(), UIA_NamePropertyId, expected_names); } TEST_F(AXPlatformNodeWinTest, ITableProviderGetRowHeaders) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTable; AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; root.child_ids.push_back(row1.id); AXNodeData column_header; column_header.id = 3; column_header.role = ax::mojom::Role::kColumnHeader; column_header.SetName(u"column_header"); row1.child_ids.push_back(column_header.id); AXNodeData row_header; row_header.id = 4; row_header.role = ax::mojom::Role::kRowHeader; row_header.SetName(u"row_header"); row1.child_ids.push_back(row_header.id); Init(root, row1, column_header, row_header); ComPtr<ITableProvider> root_itableprovider( QueryInterfaceFromNode<ITableProvider>(GetRootAsAXNode())); base::win::ScopedSafearray safearray; EXPECT_HRESULT_SUCCEEDED( root_itableprovider->GetRowHeaders(safearray.Receive())); EXPECT_NE(nullptr, safearray.Get()); std::vector<std::wstring> expected_names = {L"row_header"}; EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(safearray.Get(), UIA_NamePropertyId, expected_names); // Remove row_header's native event target and verify it's no longer returned. TestAXNodeWrapper* row_header_wrapper = TestAXNodeWrapper::GetOrCreate( GetTree(), GetRootAsAXNode()->children()[0]->children()[1]); row_header_wrapper->ResetNativeEventTarget(); safearray.Release(); EXPECT_HRESULT_SUCCEEDED( root_itableprovider->GetRowHeaders(safearray.Receive())); EXPECT_EQ(nullptr, safearray.Get()); } TEST_F(AXPlatformNodeWinTest, ITableProviderGetRowOrColumnMajor) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTable; Init(root); ComPtr<ITableProvider> root_itableprovider( QueryInterfaceFromNode<ITableProvider>(GetRootAsAXNode())); RowOrColumnMajor row_or_column_major; EXPECT_HRESULT_SUCCEEDED( root_itableprovider->get_RowOrColumnMajor(&row_or_column_major)); EXPECT_EQ(row_or_column_major, RowOrColumnMajor_RowMajor); } TEST_F(AXPlatformNodeWinTest, ITableItemProviderGetColumnHeaderItems) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTable; AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; root.child_ids.push_back(row1.id); AXNodeData column_header_1; column_header_1.id = 3; column_header_1.role = ax::mojom::Role::kColumnHeader; column_header_1.SetName(u"column_header_1"); row1.child_ids.push_back(column_header_1.id); AXNodeData column_header_2; column_header_2.id = 4; column_header_2.role = ax::mojom::Role::kColumnHeader; column_header_2.SetName(u"column_header_2"); row1.child_ids.push_back(column_header_2.id); AXNodeData row2; row2.id = 5; row2.role = ax::mojom::Role::kRow; root.child_ids.push_back(row2.id); AXNodeData cell; cell.id = 6; cell.role = ax::mojom::Role::kCell; row2.child_ids.push_back(cell.id); Init(root, row1, column_header_1, column_header_2, row2, cell); TestAXNodeWrapper* root_wrapper = TestAXNodeWrapper::GetOrCreate(GetTree(), GetRootAsAXNode()); root_wrapper->BuildAllWrappers(GetTree(), GetRootAsAXNode()); ComPtr<ITableItemProvider> cell_itableitemprovider( QueryInterfaceFromNode<ITableItemProvider>( GetRootAsAXNode()->children()[1]->children()[0])); base::win::ScopedSafearray safearray; EXPECT_HRESULT_SUCCEEDED( cell_itableitemprovider->GetColumnHeaderItems(safearray.Receive())); EXPECT_NE(nullptr, safearray.Get()); std::vector<std::wstring> expected_names = {L"column_header_1"}; EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(safearray.Get(), UIA_NamePropertyId, expected_names); // Remove column_header_1's native event target and verify it's no longer // returned. TestAXNodeWrapper* column_header_wrapper = TestAXNodeWrapper::GetOrCreate( GetTree(), GetRootAsAXNode()->children()[0]->children()[0]); column_header_wrapper->ResetNativeEventTarget(); safearray.Release(); EXPECT_HRESULT_SUCCEEDED( cell_itableitemprovider->GetColumnHeaderItems(safearray.Receive())); EXPECT_EQ(nullptr, safearray.Get()); } TEST_F(AXPlatformNodeWinTest, ITableItemProviderGetRowHeaderItems) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTable; AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; root.child_ids.push_back(row1.id); AXNodeData row_header_1; row_header_1.id = 3; row_header_1.role = ax::mojom::Role::kRowHeader; row_header_1.SetName(u"row_header_1"); row1.child_ids.push_back(row_header_1.id); AXNodeData cell; cell.id = 4; cell.role = ax::mojom::Role::kCell; row1.child_ids.push_back(cell.id); AXNodeData row2; row2.id = 5; row2.role = ax::mojom::Role::kRow; root.child_ids.push_back(row2.id); AXNodeData row_header_2; row_header_2.id = 6; row_header_2.role = ax::mojom::Role::kRowHeader; row_header_2.SetName(u"row_header_2"); row2.child_ids.push_back(row_header_2.id); Init(root, row1, row_header_1, cell, row2, row_header_2); TestAXNodeWrapper* root_wrapper = TestAXNodeWrapper::GetOrCreate(GetTree(), GetRootAsAXNode()); root_wrapper->BuildAllWrappers(GetTree(), GetRootAsAXNode()); ComPtr<ITableItemProvider> cell_itableitemprovider( QueryInterfaceFromNode<ITableItemProvider>( GetRootAsAXNode()->children()[0]->children()[1])); base::win::ScopedSafearray safearray; EXPECT_HRESULT_SUCCEEDED( cell_itableitemprovider->GetRowHeaderItems(safearray.Receive())); EXPECT_NE(nullptr, safearray.Get()); std::vector<std::wstring> expected_names = {L"row_header_1"}; EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(safearray.Get(), UIA_NamePropertyId, expected_names); // Remove row_header_1's native event target and verify it's no longer // returned. TestAXNodeWrapper* row_header_wrapper = TestAXNodeWrapper::GetOrCreate( GetTree(), GetRootAsAXNode()->children()[0]->children()[0]); row_header_wrapper->ResetNativeEventTarget(); safearray.Release(); EXPECT_HRESULT_SUCCEEDED( cell_itableitemprovider->GetRowHeaderItems(safearray.Receive())); EXPECT_EQ(nullptr, safearray.Get()); } TEST_F(AXPlatformNodeWinTest, UIAGetPropertySimple) { AXNodeData root; root.role = ax::mojom::Role::kList; root.SetName("fake name"); root.AddStringAttribute(ax::mojom::StringAttribute::kAccessKey, "Ctrl+Q"); root.AddStringAttribute(ax::mojom::StringAttribute::kLanguage, "en-us"); root.AddStringAttribute(ax::mojom::StringAttribute::kKeyShortcuts, "Alt+F4"); root.AddStringAttribute(ax::mojom::StringAttribute::kDescription, "fake description"); root.AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 2); root.AddIntAttribute(ax::mojom::IntAttribute::kInvalidState, 1); root.id = 1; AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kListItem; child1.AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 1); child1.SetName("child1"); root.child_ids.push_back(child1.id); Init(root, child1); ComPtr<IRawElementProviderSimple> root_node = GetRootIRawElementProviderSimple(); ScopedVariant uia_id; EXPECT_UIA_BSTR_EQ(root_node, UIA_AccessKeyPropertyId, L"Ctrl+Q"); EXPECT_UIA_BSTR_EQ(root_node, UIA_AcceleratorKeyPropertyId, L"Alt+F4"); ASSERT_HRESULT_SUCCEEDED(root_node->GetPropertyValue( UIA_AutomationIdPropertyId, uia_id.Receive())); EXPECT_UIA_BSTR_EQ(root_node, UIA_AutomationIdPropertyId, uia_id.ptr()->bstrVal); EXPECT_UIA_BSTR_EQ(root_node, UIA_FullDescriptionPropertyId, L"fake description"); EXPECT_UIA_BSTR_EQ(root_node, UIA_AriaRolePropertyId, L"list"); EXPECT_UIA_BSTR_EQ(root_node, UIA_AriaPropertiesPropertyId, L"readonly=true;expanded=false;multiline=false;" L"multiselectable=false;required=false;setsize=2"); constexpr int en_us_lcid = 1033; EXPECT_UIA_INT_EQ(root_node, UIA_CulturePropertyId, en_us_lcid); EXPECT_UIA_BSTR_EQ(root_node, UIA_NamePropertyId, L"fake name"); EXPECT_UIA_INT_EQ(root_node, UIA_ControlTypePropertyId, int{UIA_ListControlTypeId}); EXPECT_UIA_INT_EQ(root_node, UIA_OrientationPropertyId, int{OrientationType_None}); EXPECT_UIA_INT_EQ(root_node, UIA_SizeOfSetPropertyId, 2); EXPECT_UIA_INT_EQ(root_node, UIA_ToggleToggleStatePropertyId, int{ToggleState_Off}); EXPECT_UIA_BOOL_EQ(root_node, UIA_IsPasswordPropertyId, false); EXPECT_UIA_BOOL_EQ(root_node, UIA_IsEnabledPropertyId, true); EXPECT_UIA_BOOL_EQ(root_node, UIA_HasKeyboardFocusPropertyId, false); EXPECT_UIA_BOOL_EQ(root_node, UIA_IsRequiredForFormPropertyId, false); EXPECT_UIA_BOOL_EQ(root_node, UIA_IsDataValidForFormPropertyId, true); EXPECT_UIA_BOOL_EQ(root_node, UIA_IsKeyboardFocusablePropertyId, false); EXPECT_UIA_BOOL_EQ(root_node, UIA_IsOffscreenPropertyId, false); ComPtr<IRawElementProviderSimple> child_node1 = QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[0]); EXPECT_UIA_INT_EQ(child_node1, UIA_PositionInSetPropertyId, 1); } TEST_F(AXPlatformNodeWinTest, UIAGetPropertyValueClickablePoint) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kButton; root.relative_bounds.bounds = gfx::RectF(20, 30, 100, 200); Init(root); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetRootIRawElementProviderSimple(); // The clickable point of a rectangle {20, 30, 100, 200} is the rectangle's // center, with coordinates {x: 70, y: 130}. std::vector<double> expected_values = {70, 130}; EXPECT_UIA_DOUBLE_ARRAY_EQ(raw_element_provider_simple, UIA_ClickablePointPropertyId, expected_values); } TEST_F(AXPlatformNodeWinTest, UIAGetPropertyValueIsDialog) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.child_ids = {2, 3}; AXNodeData alert_dialog; alert_dialog.id = 2; alert_dialog.role = ax::mojom::Role::kAlertDialog; AXNodeData dialog; dialog.id = 3; dialog.role = ax::mojom::Role::kDialog; Init(root, alert_dialog, dialog); EXPECT_UIA_BOOL_EQ(GetRootIRawElementProviderSimple(), UIA_IsDialogPropertyId, false); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromChildIndex(0), UIA_IsDialogPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromChildIndex(1), UIA_IsDialogPropertyId, true); } TEST_F(AXPlatformNodeWinTest, UIAGetPropertyValueIsControlElementIgnoredInvisible) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.child_ids = {2, 3, 4, 5, 6, 7, 8}; AXNodeData normal_button; normal_button.id = 2; normal_button.role = ax::mojom::Role::kButton; AXNodeData ignored_button; ignored_button.id = 3; ignored_button.role = ax::mojom::Role::kButton; ignored_button.AddState(ax::mojom::State::kIgnored); AXNodeData invisible_button; invisible_button.id = 4; invisible_button.role = ax::mojom::Role::kButton; invisible_button.AddState(ax::mojom::State::kInvisible); AXNodeData invisible_focusable_button; invisible_focusable_button.id = 5; invisible_focusable_button.role = ax::mojom::Role::kButton; invisible_focusable_button.AddState(ax::mojom::State::kInvisible); invisible_focusable_button.AddState(ax::mojom::State::kFocusable); AXNodeData focusable_generic_container; focusable_generic_container.id = 6; focusable_generic_container.role = ax::mojom::Role::kGenericContainer; focusable_generic_container.AddState(ax::mojom::State::kFocusable); AXNodeData ignored_focusable_generic_container; ignored_focusable_generic_container.id = 7; ignored_focusable_generic_container.role = ax::mojom::Role::kGenericContainer; ignored_focusable_generic_container.AddState(ax::mojom::State::kIgnored); focusable_generic_container.AddState(ax::mojom::State::kFocusable); AXNodeData invisible_focusable_generic_container; invisible_focusable_generic_container.id = 8; invisible_focusable_generic_container.role = ax::mojom::Role::kGenericContainer; invisible_focusable_generic_container.AddState(ax::mojom::State::kInvisible); invisible_focusable_generic_container.AddState(ax::mojom::State::kFocusable); Init(root, normal_button, ignored_button, invisible_button, invisible_focusable_button, focusable_generic_container, ignored_focusable_generic_container, invisible_focusable_generic_container); // Turn on web content mode for the AXTree. TestAXNodeWrapper::SetGlobalIsWebContent(true); // Normal button (id=2), no invisible or ignored state set. Should be a // control element. EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromChildIndex(0), UIA_IsControlElementPropertyId, true); // Button with ignored state (id=3). Should not be a control element. EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromChildIndex(1), UIA_IsControlElementPropertyId, false); // Button with invisible state (id=4). Should not be a control element. EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromChildIndex(2), UIA_IsControlElementPropertyId, false); // Button with invisible state, but focusable (id=5). Should not be a control // element. EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromChildIndex(3), UIA_IsControlElementPropertyId, false); // Generic container, focusable (id=6). Should be a control // element. EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromChildIndex(4), UIA_IsControlElementPropertyId, true); // Generic container, ignored but focusable (id=7). Should not be a control // element. EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromChildIndex(5), UIA_IsControlElementPropertyId, false); // Generic container, invisible and ignored, but focusable (id=8). Should not // be a control element. EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromChildIndex(6), UIA_IsControlElementPropertyId, false); } TEST_F(AXPlatformNodeWinTest, UIAGetControllerForPropertyId) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.child_ids = {2, 3, 4}; AXNodeData tab; tab.id = 2; tab.role = ax::mojom::Role::kTab; tab.SetName("tab"); std::vector<AXNode::AXID> controller_ids = {3, 4}; tab.AddIntListAttribute(ax::mojom::IntListAttribute::kControlsIds, controller_ids); AXNodeData panel1; panel1.id = 3; panel1.role = ax::mojom::Role::kTabPanel; panel1.SetName("panel1"); AXNodeData panel2; panel2.id = 4; panel2.role = ax::mojom::Role::kTabPanel; panel2.SetName("panel2"); Init(root, tab, panel1, panel2); TestAXNodeWrapper* root_wrapper = TestAXNodeWrapper::GetOrCreate(GetTree(), GetRootAsAXNode()); root_wrapper->BuildAllWrappers(GetTree(), GetRootAsAXNode()); ComPtr<IRawElementProviderSimple> tab_node = QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[0]); std::vector<std::wstring> expected_names_1 = {L"panel1", L"panel2"}; EXPECT_UIA_PROPERTY_ELEMENT_ARRAY_BSTR_EQ( tab_node, UIA_ControllerForPropertyId, UIA_NamePropertyId, expected_names_1); // Remove panel1's native event target and verify it's no longer returned. TestAXNodeWrapper* panel1_wrapper = TestAXNodeWrapper::GetOrCreate( GetTree(), GetRootAsAXNode()->children()[1]); panel1_wrapper->ResetNativeEventTarget(); std::vector<std::wstring> expected_names_2 = {L"panel2"}; EXPECT_UIA_PROPERTY_ELEMENT_ARRAY_BSTR_EQ( tab_node, UIA_ControllerForPropertyId, UIA_NamePropertyId, expected_names_2); } TEST_F(AXPlatformNodeWinTest, UIAGetDescribedByPropertyId) { AXNodeData root; std::vector<AXNode::AXID> describedby_ids = {2, 3, 4}; root.AddIntListAttribute(ax::mojom::IntListAttribute::kDescribedbyIds, describedby_ids); root.id = 1; root.role = ax::mojom::Role::kMarquee; root.SetName("root"); AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kStaticText; child1.SetName("child1"); root.child_ids.push_back(child1.id); AXNodeData child2; child2.id = 3; child2.role = ax::mojom::Role::kStaticText; child2.SetName("child2"); root.child_ids.push_back(child2.id); Init(root, child1, child2); ComPtr<IRawElementProviderSimple> root_node = GetRootIRawElementProviderSimple(); std::vector<std::wstring> expected_names = {L"child1", L"child2"}; EXPECT_UIA_PROPERTY_ELEMENT_ARRAY_BSTR_EQ( root_node, UIA_DescribedByPropertyId, UIA_NamePropertyId, expected_names); } TEST_F(AXPlatformNodeWinTest, UIAItemStatusPropertyId) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTable; AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; row1.AddIntAttribute(ax::mojom::IntAttribute::kSortDirection, static_cast<int>(ax::mojom::SortDirection::kAscending)); root.child_ids.push_back(row1.id); AXNodeData header1; header1.id = 3; header1.role = ax::mojom::Role::kRowHeader; header1.AddIntAttribute( ax::mojom::IntAttribute::kSortDirection, static_cast<int>(ax::mojom::SortDirection::kAscending)); row1.child_ids.push_back(header1.id); AXNodeData header2; header2.id = 4; header2.role = ax::mojom::Role::kColumnHeader; header2.AddIntAttribute( ax::mojom::IntAttribute::kSortDirection, static_cast<int>(ax::mojom::SortDirection::kDescending)); row1.child_ids.push_back(header2.id); AXNodeData header3; header3.id = 5; header3.role = ax::mojom::Role::kColumnHeader; header3.AddIntAttribute(ax::mojom::IntAttribute::kSortDirection, static_cast<int>(ax::mojom::SortDirection::kOther)); row1.child_ids.push_back(header3.id); AXNodeData header4; header4.id = 6; header4.role = ax::mojom::Role::kColumnHeader; header4.AddIntAttribute( ax::mojom::IntAttribute::kSortDirection, static_cast<int>(ax::mojom::SortDirection::kUnsorted)); row1.child_ids.push_back(header4.id); Init(root, row1, header1, header2, header3, header4); auto* row_node = GetRootAsAXNode()->children()[0]; EXPECT_UIA_BSTR_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( row_node->children()[0]), UIA_ItemStatusPropertyId, L"ascending"); EXPECT_UIA_BSTR_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( row_node->children()[1]), UIA_ItemStatusPropertyId, L"descending"); EXPECT_UIA_BSTR_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( row_node->children()[2]), UIA_ItemStatusPropertyId, L"other"); EXPECT_UIA_VALUE_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( row_node->children()[3]), UIA_ItemStatusPropertyId, ScopedVariant::kEmptyVariant); EXPECT_UIA_VALUE_EQ( QueryInterfaceFromNode<IRawElementProviderSimple>(row_node), UIA_ItemStatusPropertyId, ScopedVariant::kEmptyVariant); } TEST_F(AXPlatformNodeWinTest, UIAGetFlowsToPropertyId) { AXNodeData root; std::vector<AXNode::AXID> flowto_ids = {2, 3, 4}; root.AddIntListAttribute(ax::mojom::IntListAttribute::kFlowtoIds, flowto_ids); root.id = 1; root.role = ax::mojom::Role::kMarquee; root.SetName("root"); AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kStaticText; child1.SetName("child1"); root.child_ids.push_back(child1.id); AXNodeData child2; child2.id = 3; child2.role = ax::mojom::Role::kStaticText; child2.SetName("child2"); root.child_ids.push_back(child2.id); Init(root, child1, child2); ComPtr<IRawElementProviderSimple> root_node = GetRootIRawElementProviderSimple(); std::vector<std::wstring> expected_names = {L"child1", L"child2"}; EXPECT_UIA_PROPERTY_ELEMENT_ARRAY_BSTR_EQ(root_node, UIA_FlowsToPropertyId, UIA_NamePropertyId, expected_names); } TEST_F(AXPlatformNodeWinTest, UIAGetPropertyValueFlowsFromNone) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.SetName("root"); Init(root); ComPtr<IRawElementProviderSimple> root_node = GetRootIRawElementProviderSimple(); ScopedVariant property_value; EXPECT_HRESULT_SUCCEEDED(root_node->GetPropertyValue( UIA_FlowsFromPropertyId, property_value.Receive())); EXPECT_EQ(VT_ARRAY | VT_UNKNOWN, property_value.type()); EXPECT_EQ(nullptr, V_ARRAY(property_value.ptr())); } TEST_F(AXPlatformNodeWinTest, UIAGetPropertyValueFlowsFromSingle) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.SetName("root"); root.AddIntListAttribute(ax::mojom::IntListAttribute::kFlowtoIds, {2}); AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kGenericContainer; child1.SetName("child1"); root.child_ids.push_back(child1.id); Init(root, child1); ASSERT_NE(nullptr, TestAXNodeWrapper::GetOrCreate(GetTree(), GetRootAsAXNode())); ComPtr<IRawElementProviderSimple> child_node1 = QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[0]); std::vector<std::wstring> expected_names = {L"root"}; EXPECT_UIA_PROPERTY_ELEMENT_ARRAY_BSTR_EQ( child_node1, UIA_FlowsFromPropertyId, UIA_NamePropertyId, expected_names); } TEST_F(AXPlatformNodeWinTest, UIAGetPropertyValueFlowsFromMultiple) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.SetName("root"); root.AddIntListAttribute(ax::mojom::IntListAttribute::kFlowtoIds, {2, 3}); AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kGenericContainer; child1.SetName("child1"); child1.AddIntListAttribute(ax::mojom::IntListAttribute::kFlowtoIds, {3}); root.child_ids.push_back(child1.id); AXNodeData child2; child2.id = 3; child2.role = ax::mojom::Role::kGenericContainer; child2.SetName("child2"); root.child_ids.push_back(child2.id); Init(root, child1, child2); ASSERT_NE(nullptr, TestAXNodeWrapper::GetOrCreate(GetTree(), GetRootAsAXNode())); ASSERT_NE(nullptr, TestAXNodeWrapper::GetOrCreate( GetTree(), GetRootAsAXNode()->children()[0])); ComPtr<IRawElementProviderSimple> child_node2 = QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[1]); std::vector<std::wstring> expected_names_1 = {L"root", L"child1"}; EXPECT_UIA_PROPERTY_UNORDERED_ELEMENT_ARRAY_BSTR_EQ( child_node2, UIA_FlowsFromPropertyId, UIA_NamePropertyId, expected_names_1); // Remove child1's native event target and verify it's no longer returned. TestAXNodeWrapper* child1_wrapper = TestAXNodeWrapper::GetOrCreate( GetTree(), GetRootAsAXNode()->children()[0]); child1_wrapper->ResetNativeEventTarget(); std::vector<std::wstring> expected_names_2 = {L"root"}; EXPECT_UIA_PROPERTY_UNORDERED_ELEMENT_ARRAY_BSTR_EQ( child_node2, UIA_FlowsFromPropertyId, UIA_NamePropertyId, expected_names_2); } TEST_F(AXPlatformNodeWinTest, UIAGetPropertyValueFrameworkId) { AXNodeData root_ax_node_data; root_ax_node_data.id = 1; root_ax_node_data.role = ax::mojom::Role::kRootWebArea; Init(root_ax_node_data); ComPtr<IRawElementProviderSimple> root_raw_element_provider_simple = GetRootIRawElementProviderSimple(); EXPECT_UIA_BSTR_EQ(root_raw_element_provider_simple, UIA_FrameworkIdPropertyId, L"Chrome"); } TEST_F(AXPlatformNodeWinTest, GetPropertyValue_LabeledByTest) { // ++1 root // ++++2 kGenericContainer LabeledBy 3 // ++++++3 kStaticText "Hello" // ++++4 kGenericContainer LabeledBy 5 // ++++++5 kGenericContainer // ++++++++6 kStaticText "3.14" // ++++7 kAlert LabeledBy 6 AXNodeData root_1; AXNodeData gc_2; AXNodeData static_text_3; AXNodeData gc_4; AXNodeData gc_5; AXNodeData static_text_6; AXNodeData alert_7; root_1.id = 1; gc_2.id = 2; static_text_3.id = 3; gc_4.id = 4; gc_5.id = 5; static_text_6.id = 6; alert_7.id = 7; root_1.role = ax::mojom::Role::kRootWebArea; root_1.child_ids = {gc_2.id, gc_4.id, alert_7.id}; gc_2.role = ax::mojom::Role::kGenericContainer; gc_2.AddIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds, {static_text_3.id}); gc_2.child_ids = {static_text_3.id}; static_text_3.role = ax::mojom::Role::kStaticText; static_text_3.SetName("Hello"); gc_4.role = ax::mojom::Role::kGenericContainer; gc_4.AddIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds, {gc_5.id}); gc_4.child_ids = {gc_5.id}; gc_5.role = ax::mojom::Role::kGenericContainer; gc_5.child_ids = {static_text_6.id}; static_text_6.role = ax::mojom::Role::kStaticText; static_text_6.SetName("3.14"); alert_7.role = ax::mojom::Role::kAlert; alert_7.AddIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds, {static_text_6.id}); Init(root_1, gc_2, static_text_3, gc_4, gc_5, static_text_6, alert_7); AXNode* root_node = GetRootAsAXNode(); AXNode* gc_2_node = root_node->children()[0]; AXNode* static_text_3_node = gc_2_node->children()[0]; AXNode* gc_4_node = root_node->children()[1]; AXNode* static_text_6_node = gc_4_node->children()[0]->children()[0]; AXNode* alert_7_node = root_node->children()[2]; // Case 1: |gc_2| is labeled by |static_text_3|. ComPtr<IRawElementProviderSimple> gc_2_provider = GetIRawElementProviderSimpleFromTree(gc_2_node->tree()->GetAXTreeID(), gc_2_node->id()); ScopedVariant property_value; EXPECT_EQ(S_OK, gc_2_provider->GetPropertyValue(UIA_LabeledByPropertyId, property_value.Receive())); ASSERT_EQ(property_value.type(), VT_UNKNOWN); ComPtr<IRawElementProviderSimple> static_text_3_provider; EXPECT_EQ(S_OK, property_value.ptr()->punkVal->QueryInterface( IID_PPV_ARGS(&static_text_3_provider))); EXPECT_UIA_BSTR_EQ(static_text_3_provider, UIA_NamePropertyId, L"Hello"); // Case 2: |gc_4| is labeled by |gc_5| and should return the first static text // child of that node, which is |static_text_6|. ComPtr<IRawElementProviderSimple> gc_4_provider = GetIRawElementProviderSimpleFromTree(gc_4_node->tree()->GetAXTreeID(), gc_4_node->id()); property_value.Reset(); EXPECT_EQ(S_OK, gc_4_provider->GetPropertyValue(UIA_LabeledByPropertyId, property_value.Receive())); ASSERT_EQ(property_value.type(), VT_UNKNOWN); ComPtr<IRawElementProviderSimple> static_text_6_provider; EXPECT_EQ(S_OK, property_value.ptr()->punkVal->QueryInterface( IID_PPV_ARGS(&static_text_6_provider))); EXPECT_UIA_BSTR_EQ(static_text_6_provider, UIA_NamePropertyId, L"3.14"); // Case 3: Some UIA control types always expect an empty value for this // property. The role kAlert corresponds to UIA_TextControlTypeId, which // always expects an empty value. |alert_7| is marked as labeled by // |static_text_6|, but shouldn't expose it to the UIA_LabeledByPropertyId. ComPtr<IRawElementProviderSimple> alert_7_provider = GetIRawElementProviderSimpleFromTree(alert_7_node->tree()->GetAXTreeID(), alert_7_node->id()); property_value.Reset(); EXPECT_EQ(S_OK, alert_7_provider->GetPropertyValue(UIA_LabeledByPropertyId, property_value.Receive())); ASSERT_EQ(property_value.type(), VT_EMPTY); // Remove the referenced nodes' native event targets and verify it's no longer // returned. // Case 1. TestAXNodeWrapper* static_text_3_node_wrapper = TestAXNodeWrapper::GetOrCreate(GetTree(), static_text_3_node); static_text_3_node_wrapper->ResetNativeEventTarget(); property_value.Reset(); EXPECT_EQ(S_OK, gc_2_provider->GetPropertyValue(UIA_LabeledByPropertyId, property_value.Receive())); EXPECT_EQ(property_value.type(), VT_EMPTY); // Case 2. TestAXNodeWrapper* static_text_6_node_wrapper = TestAXNodeWrapper::GetOrCreate(GetTree(), static_text_6_node); static_text_6_node_wrapper->ResetNativeEventTarget(); property_value.Reset(); EXPECT_EQ(S_OK, gc_4_provider->GetPropertyValue(UIA_LabeledByPropertyId, property_value.Receive())); EXPECT_EQ(property_value.type(), VT_EMPTY); } TEST_F(AXPlatformNodeWinTest, GetPropertyValue_HelpText) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; // Test Placeholder StringAttribute is exposed AXNodeData input1; input1.id = 2; input1.role = ax::mojom::Role::kTextField; input1.SetName("name-from-title"); input1.AddIntAttribute(ax::mojom::IntAttribute::kNameFrom, static_cast<int>(ax::mojom::NameFrom::kTitle)); input1.AddStringAttribute(ax::mojom::StringAttribute::kPlaceholder, "placeholder"); root.child_ids.push_back(input1.id); // Test NameFrom Title is exposed AXNodeData input2; input2.id = 3; input2.role = ax::mojom::Role::kTextField; input2.SetName("name-from-title"); input2.AddIntAttribute(ax::mojom::IntAttribute::kNameFrom, static_cast<int>(ax::mojom::NameFrom::kTitle)); root.child_ids.push_back(input2.id); // Test NameFrom Placeholder is exposed AXNodeData input3; input3.id = 4; input3.role = ax::mojom::Role::kTextField; input3.SetName("name-from-placeholder"); input3.AddIntAttribute(ax::mojom::IntAttribute::kNameFrom, static_cast<int>(ax::mojom::NameFrom::kPlaceholder)); root.child_ids.push_back(input3.id); // Test Title StringAttribute is exposed AXNodeData input4; input4.id = 5; input4.role = ax::mojom::Role::kTextField; input4.SetName("name-from-attribute"); input4.AddIntAttribute(ax::mojom::IntAttribute::kNameFrom, static_cast<int>(ax::mojom::NameFrom::kAttribute)); input4.AddStringAttribute(ax::mojom::StringAttribute::kTooltip, "tooltip"); root.child_ids.push_back(input4.id); // Test NameFrom (other), without explicit // Title / Placeholder StringAttribute is not exposed AXNodeData input5; input5.id = 6; input5.role = ax::mojom::Role::kTextField; input5.SetName("name-from-attribute"); input5.AddIntAttribute(ax::mojom::IntAttribute::kNameFrom, static_cast<int>(ax::mojom::NameFrom::kAttribute)); root.child_ids.push_back(input5.id); Init(root, input1, input2, input3, input4, input5); auto* root_node = GetRootAsAXNode(); EXPECT_UIA_BSTR_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( root_node->children()[0]), UIA_HelpTextPropertyId, L"placeholder"); EXPECT_UIA_BSTR_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( root_node->children()[1]), UIA_HelpTextPropertyId, L"name-from-title"); EXPECT_UIA_BSTR_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( root_node->children()[2]), UIA_HelpTextPropertyId, L"name-from-placeholder"); EXPECT_UIA_BSTR_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( root_node->children()[3]), UIA_HelpTextPropertyId, L"tooltip"); EXPECT_UIA_VALUE_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( root_node->children()[4]), UIA_HelpTextPropertyId, ScopedVariant::kEmptyVariant); } TEST_F(AXPlatformNodeWinTest, GetPropertyValue_LocalizedControlType) { AXNodeData root; root.role = ax::mojom::Role::kUnknown; root.id = 1; root.AddStringAttribute(ax::mojom::StringAttribute::kRoleDescription, "root role description"); AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kSearchBox; child1.AddStringAttribute(ax::mojom::StringAttribute::kRoleDescription, "child1 role description"); root.child_ids.push_back(2); AXNodeData child2; child2.id = 3; child2.role = ax::mojom::Role::kSearchBox; root.child_ids.push_back(3); Init(root, child1, child2); ComPtr<IRawElementProviderSimple> root_node = GetRootIRawElementProviderSimple(); EXPECT_UIA_BSTR_EQ(root_node, UIA_LocalizedControlTypePropertyId, L"root role description"); EXPECT_UIA_BSTR_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[0]), UIA_LocalizedControlTypePropertyId, L"child1 role description"); EXPECT_UIA_BSTR_EQ(QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[1]), UIA_LocalizedControlTypePropertyId, L"search box"); } TEST_F(AXPlatformNodeWinTest, GetPropertyValue_IsControlElement) { AXTreeUpdate update; ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID(); update.tree_data.tree_id = tree_id; update.has_tree_data = true; update.root_id = 1; update.nodes.resize(17); update.nodes[0].id = 1; update.nodes[0].role = ax::mojom::Role::kRootWebArea; update.nodes[0].child_ids = {2, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}; update.nodes[1].id = 2; update.nodes[1].role = ax::mojom::Role::kButton; update.nodes[1].child_ids = {3}; update.nodes[2].id = 3; update.nodes[2].role = ax::mojom::Role::kStaticText; update.nodes[2].SetName("some text"); update.nodes[3].id = 4; update.nodes[3].role = ax::mojom::Role::kGenericContainer; update.nodes[3].child_ids = {5}; update.nodes[4].id = 5; update.nodes[4].role = ax::mojom::Role::kStaticText; update.nodes[4].SetName("more text"); update.nodes[5].id = 6; update.nodes[5].role = ax::mojom::Role::kTable; update.nodes[6].id = 7; update.nodes[6].role = ax::mojom::Role::kList; update.nodes[7].id = 8; update.nodes[7].role = ax::mojom::Role::kForm; update.nodes[8].id = 9; update.nodes[8].role = ax::mojom::Role::kImage; update.nodes[9].id = 10; update.nodes[9].role = ax::mojom::Role::kImage; update.nodes[9].SetNameExplicitlyEmpty(); update.nodes[10].id = 11; update.nodes[10].role = ax::mojom::Role::kArticle; update.nodes[11].id = 12; update.nodes[11].role = ax::mojom::Role::kGenericContainer; update.nodes[11].AddBoolAttribute(ax::mojom::BoolAttribute::kHasAriaAttribute, true); update.nodes[12].id = 13; update.nodes[12].role = ax::mojom::Role::kGenericContainer; update.nodes[12].AddBoolAttribute(ax::mojom::BoolAttribute::kEditableRoot, true); update.nodes[13].id = 14; update.nodes[13].role = ax::mojom::Role::kGenericContainer; update.nodes[13].SetName("name"); update.nodes[14].id = 15; update.nodes[14].role = ax::mojom::Role::kGenericContainer; update.nodes[14].SetDescription("description"); update.nodes[15].id = 16; update.nodes[15].role = ax::mojom::Role::kGenericContainer; update.nodes[15].AddState(ax::mojom::State::kFocusable); update.nodes[16].id = 17; update.nodes[16].role = ax::mojom::Role::kForm; update.nodes[16].SetName("name"); Init(update); TestAXNodeWrapper::SetGlobalIsWebContent(true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 2), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 3), UIA_IsControlElementPropertyId, false); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 4), UIA_IsControlElementPropertyId, false); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 5), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 6), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 7), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 8), UIA_IsControlElementPropertyId, false); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 9), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 10), UIA_IsControlElementPropertyId, false); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 11), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 12), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 13), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 14), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 15), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 16), UIA_IsControlElementPropertyId, true); EXPECT_UIA_BOOL_EQ(GetIRawElementProviderSimpleFromTree(tree_id, 17), UIA_IsControlElementPropertyId, true); } TEST_F(AXPlatformNodeWinTest, UIAGetProviderOptions) { AXNodeData root_data; root_data.id = 1; Init(root_data); ComPtr<IRawElementProviderSimple> root_node = GetRootIRawElementProviderSimple(); ProviderOptions provider_options = static_cast<ProviderOptions>(0); EXPECT_HRESULT_SUCCEEDED(root_node->get_ProviderOptions(&provider_options)); EXPECT_EQ(ProviderOptions_ServerSideProvider | ProviderOptions_UseComThreading | ProviderOptions_RefuseNonClientSupport | ProviderOptions_HasNativeIAccessible, provider_options); } TEST_F(AXPlatformNodeWinTest, UIAGetHostRawElementProvider) { AXNodeData root_data; root_data.id = 1; Init(root_data); ComPtr<IRawElementProviderSimple> root_node = GetRootIRawElementProviderSimple(); ComPtr<IRawElementProviderSimple> host_provider; EXPECT_HRESULT_SUCCEEDED( root_node->get_HostRawElementProvider(&host_provider)); EXPECT_EQ(nullptr, host_provider.Get()); } TEST_F(AXPlatformNodeWinTest, UIAGetBoundingRectangle) { AXNodeData root_data; root_data.id = 1; root_data.relative_bounds.bounds = gfx::RectF(10, 20, 30, 50); Init(root_data); ComPtr<IRawElementProviderFragment> root_node = GetRootIRawElementProviderFragment(); UiaRect bounding_rectangle; EXPECT_HRESULT_SUCCEEDED( root_node->get_BoundingRectangle(&bounding_rectangle)); EXPECT_EQ(10, bounding_rectangle.left); EXPECT_EQ(20, bounding_rectangle.top); EXPECT_EQ(30, bounding_rectangle.width); EXPECT_EQ(50, bounding_rectangle.height); } TEST_F(AXPlatformNodeWinTest, UIAGetFragmentRoot) { // This test needs to be run on a child node since AXPlatformRootNodeWin // overrides the method. AXNodeData root_data; root_data.id = 1; AXNodeData element1_data; element1_data.id = 2; root_data.child_ids.push_back(element1_data.id); Init(root_data, element1_data); InitFragmentRoot(); AXNode* root_node = GetRootAsAXNode(); AXNode* element1_node = root_node->children()[0]; ComPtr<IRawElementProviderFragment> element1_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element1_node); ComPtr<IRawElementProviderFragmentRoot> expected_fragment_root = GetFragmentRoot(); ComPtr<IRawElementProviderFragmentRoot> actual_fragment_root; EXPECT_HRESULT_SUCCEEDED( element1_provider->get_FragmentRoot(&actual_fragment_root)); EXPECT_EQ(expected_fragment_root.Get(), actual_fragment_root.Get()); // Test the case where the fragment root has gone away. ax_fragment_root_.reset(); actual_fragment_root.Reset(); EXPECT_UIA_ELEMENTNOTAVAILABLE( element1_provider->get_FragmentRoot(&actual_fragment_root)); // Test the case where the widget has gone away. TestAXNodeWrapper* element1_wrapper = TestAXNodeWrapper::GetOrCreate(GetTree(), element1_node); element1_wrapper->ResetNativeEventTarget(); EXPECT_UIA_ELEMENTNOTAVAILABLE( element1_provider->get_FragmentRoot(&actual_fragment_root)); } TEST_F(AXPlatformNodeWinTest, UIAGetEmbeddedFragmentRoots) { AXNodeData root_data; root_data.id = 1; Init(root_data); ComPtr<IRawElementProviderFragment> root_provider = GetRootIRawElementProviderFragment(); base::win::ScopedSafearray embedded_fragment_roots; EXPECT_HRESULT_SUCCEEDED(root_provider->GetEmbeddedFragmentRoots( embedded_fragment_roots.Receive())); EXPECT_EQ(nullptr, embedded_fragment_roots.Get()); } TEST_F(AXPlatformNodeWinTest, UIAGetRuntimeId) { AXNodeData root_data; root_data.id = 1; Init(root_data); ComPtr<IRawElementProviderFragment> root_provider = GetRootIRawElementProviderFragment(); base::win::ScopedSafearray runtime_id; EXPECT_HRESULT_SUCCEEDED(root_provider->GetRuntimeId(runtime_id.Receive())); LONG array_lower_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetLBound(runtime_id.Get(), 1, &array_lower_bound)); EXPECT_EQ(0, array_lower_bound); LONG array_upper_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetUBound(runtime_id.Get(), 1, &array_upper_bound)); EXPECT_EQ(1, array_upper_bound); int* array_data; EXPECT_HRESULT_SUCCEEDED(::SafeArrayAccessData( runtime_id.Get(), reinterpret_cast<void**>(&array_data))); EXPECT_EQ(UiaAppendRuntimeId, array_data[0]); EXPECT_NE(-1, array_data[1]); EXPECT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(runtime_id.Get())); } TEST_F(AXPlatformNodeWinTest, UIAIWindowProviderGetIsModalUnset) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; Init(root); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetRootIRawElementProviderSimple(); ComPtr<IWindowProvider> window_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_WindowPatternId, &window_provider)); ASSERT_EQ(nullptr, window_provider.Get()); } TEST_F(AXPlatformNodeWinTest, UIAIWindowProviderGetIsModalFalse) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.AddBoolAttribute(ax::mojom::BoolAttribute::kModal, false); Init(root); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetRootIRawElementProviderSimple(); ComPtr<IWindowProvider> window_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_WindowPatternId, &window_provider)); ASSERT_NE(nullptr, window_provider.Get()); BOOL is_modal; EXPECT_HRESULT_SUCCEEDED(window_provider->get_IsModal(&is_modal)); ASSERT_FALSE(is_modal); } TEST_F(AXPlatformNodeWinTest, UIAIWindowProviderGetIsModalTrue) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.AddBoolAttribute(ax::mojom::BoolAttribute::kModal, true); Init(root); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetRootIRawElementProviderSimple(); ComPtr<IWindowProvider> window_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_WindowPatternId, &window_provider)); ASSERT_NE(nullptr, window_provider.Get()); BOOL is_modal; EXPECT_HRESULT_SUCCEEDED(window_provider->get_IsModal(&is_modal)); ASSERT_TRUE(is_modal); } TEST_F(AXPlatformNodeWinTest, UIAIWindowProviderInvalidArgument) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.AddBoolAttribute(ax::mojom::BoolAttribute::kModal, true); Init(root); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetRootIRawElementProviderSimple(); ComPtr<IWindowProvider> window_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_WindowPatternId, &window_provider)); ASSERT_NE(nullptr, window_provider.Get()); ASSERT_EQ(E_INVALIDARG, window_provider->WaitForInputIdle(0, nullptr)); ASSERT_EQ(E_INVALIDARG, window_provider->get_CanMaximize(nullptr)); ASSERT_EQ(E_INVALIDARG, window_provider->get_CanMinimize(nullptr)); ASSERT_EQ(E_INVALIDARG, window_provider->get_IsModal(nullptr)); ASSERT_EQ(E_INVALIDARG, window_provider->get_WindowVisualState(nullptr)); ASSERT_EQ(E_INVALIDARG, window_provider->get_WindowInteractionState(nullptr)); ASSERT_EQ(E_INVALIDARG, window_provider->get_IsTopmost(nullptr)); } TEST_F(AXPlatformNodeWinTest, UIAIWindowProviderNotSupported) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; root.AddBoolAttribute(ax::mojom::BoolAttribute::kModal, true); Init(root); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetRootIRawElementProviderSimple(); ComPtr<IWindowProvider> window_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_WindowPatternId, &window_provider)); ASSERT_NE(nullptr, window_provider.Get()); BOOL bool_result; WindowVisualState window_visual_state_result; WindowInteractionState window_interaction_state_result; ASSERT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), window_provider->SetVisualState( WindowVisualState::WindowVisualState_Normal)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), window_provider->Close()); ASSERT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), window_provider->WaitForInputIdle(0, &bool_result)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), window_provider->get_CanMaximize(&bool_result)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), window_provider->get_CanMinimize(&bool_result)); ASSERT_EQ( static_cast<HRESULT>(UIA_E_NOTSUPPORTED), window_provider->get_WindowVisualState(&window_visual_state_result)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), window_provider->get_WindowInteractionState( &window_interaction_state_result)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), window_provider->get_IsTopmost(&bool_result)); } TEST_F(AXPlatformNodeWinTest, UIANavigate) { AXNodeData root_data; root_data.id = 1; AXNodeData element1_data; element1_data.id = 2; root_data.child_ids.push_back(element1_data.id); AXNodeData element2_data; element2_data.id = 3; root_data.child_ids.push_back(element2_data.id); AXNodeData element3_data; element3_data.id = 4; element1_data.child_ids.push_back(element3_data.id); Init(root_data, element1_data, element2_data, element3_data); AXNode* root_node = GetRootAsAXNode(); AXNode* element1_node = root_node->children()[0]; AXNode* element2_node = root_node->children()[1]; AXNode* element3_node = element1_node->children()[0]; auto TestNavigate = [this](AXNode* element_node, AXNode* parent, AXNode* next_sibling, AXNode* prev_sibling, AXNode* first_child, AXNode* last_child) { ComPtr<IRawElementProviderFragment> element_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(element_node); auto TestNavigateSingle = [&](NavigateDirection direction, AXNode* expected_node) { ComPtr<IRawElementProviderFragment> expected_provider = QueryInterfaceFromNode<IRawElementProviderFragment>(expected_node); ComPtr<IRawElementProviderFragment> navigated_to_fragment; EXPECT_HRESULT_SUCCEEDED( element_provider->Navigate(direction, &navigated_to_fragment)); EXPECT_EQ(expected_provider.Get(), navigated_to_fragment.Get()); }; TestNavigateSingle(NavigateDirection_Parent, parent); TestNavigateSingle(NavigateDirection_NextSibling, next_sibling); TestNavigateSingle(NavigateDirection_PreviousSibling, prev_sibling); TestNavigateSingle(NavigateDirection_FirstChild, first_child); TestNavigateSingle(NavigateDirection_LastChild, last_child); }; TestNavigate(root_node, nullptr, // Parent nullptr, // NextSibling nullptr, // PreviousSibling element1_node, // FirstChild element2_node); // LastChild TestNavigate(element1_node, root_node, element2_node, nullptr, element3_node, element3_node); TestNavigate(element2_node, root_node, nullptr, element1_node, nullptr, nullptr); TestNavigate(element3_node, element1_node, nullptr, nullptr, nullptr, nullptr); } TEST_F(AXPlatformNodeWinTest, ISelectionProviderCanSelectMultipleDefault) { Init(BuildListBox(/*option_1_is_selected*/ false, /*option_2_is_selected*/ false, /*option_3_is_selected*/ false, {})); ComPtr<ISelectionProvider> selection_provider( QueryInterfaceFromNode<ISelectionProvider>(GetRootAsAXNode())); BOOL multiple = TRUE; EXPECT_HRESULT_SUCCEEDED( selection_provider->get_CanSelectMultiple(&multiple)); EXPECT_FALSE(multiple); } TEST_F(AXPlatformNodeWinTest, ISelectionProviderCanSelectMultipleTrue) { const std::vector<ax::mojom::State> state = { ax::mojom::State::kMultiselectable, ax::mojom::State::kFocusable}; Init(BuildListBox(/*option_1_is_selected*/ false, /*option_2_is_selected*/ false, /*option_3_is_selected*/ false, /*additional_state*/ state)); ComPtr<ISelectionProvider> selection_provider( QueryInterfaceFromNode<ISelectionProvider>(GetRootAsAXNode())); BOOL multiple = FALSE; EXPECT_HRESULT_SUCCEEDED( selection_provider->get_CanSelectMultiple(&multiple)); EXPECT_TRUE(multiple); } TEST_F(AXPlatformNodeWinTest, ISelectionProviderIsSelectionRequiredDefault) { Init(BuildListBox(/*option_1_is_selected*/ false, /*option_2_is_selected*/ false, /*option_3_is_selected*/ false, /*additional_state*/ {})); ComPtr<ISelectionProvider> selection_provider( QueryInterfaceFromNode<ISelectionProvider>(GetRootAsAXNode())); BOOL selection_required = TRUE; EXPECT_HRESULT_SUCCEEDED( selection_provider->get_IsSelectionRequired(&selection_required)); EXPECT_FALSE(selection_required); } TEST_F(AXPlatformNodeWinTest, ISelectionProviderIsSelectionRequiredTrue) { Init(BuildListBox(/*option_1_is_selected*/ false, /*option_2_is_selected*/ false, /*option_3_is_selected*/ false, /*additional_state*/ {ax::mojom::State::kRequired})); ComPtr<ISelectionProvider> selection_provider( QueryInterfaceFromNode<ISelectionProvider>(GetRootAsAXNode())); BOOL selection_required = FALSE; EXPECT_HRESULT_SUCCEEDED( selection_provider->get_IsSelectionRequired(&selection_required)); EXPECT_TRUE(selection_required); } TEST_F(AXPlatformNodeWinTest, ISelectionProviderGetSelectionNoneSelected) { Init(BuildListBox(/*option_1_is_selected*/ false, /*option_2_is_selected*/ false, /*option_3_is_selected*/ false, /*additional_state*/ {ax::mojom::State::kFocusable})); ComPtr<ISelectionProvider> selection_provider( QueryInterfaceFromNode<ISelectionProvider>(GetRootAsAXNode())); base::win::ScopedSafearray selected_items; EXPECT_HRESULT_SUCCEEDED( selection_provider->GetSelection(selected_items.Receive())); EXPECT_NE(nullptr, selected_items.Get()); LONG array_lower_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetLBound(selected_items.Get(), 1, &array_lower_bound)); EXPECT_EQ(0, array_lower_bound); LONG array_upper_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetUBound(selected_items.Get(), 1, &array_upper_bound)); EXPECT_EQ(-1, array_upper_bound); } TEST_F(AXPlatformNodeWinTest, ISelectionProviderGetSelectionSingleItemSelected) { Init(BuildListBox(/*option_1_is_selected*/ false, /*option_2_is_selected*/ true, /*option_3_is_selected*/ false, /*additional_state*/ {ax::mojom::State::kFocusable})); ComPtr<ISelectionProvider> selection_provider( QueryInterfaceFromNode<ISelectionProvider>(GetRootAsAXNode())); ComPtr<IRawElementProviderSimple> option2_provider( QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[1])); base::win::ScopedSafearray selected_items; EXPECT_HRESULT_SUCCEEDED( selection_provider->GetSelection(selected_items.Receive())); EXPECT_NE(nullptr, selected_items.Get()); LONG array_lower_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetLBound(selected_items.Get(), 1, &array_lower_bound)); EXPECT_EQ(0, array_lower_bound); LONG array_upper_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetUBound(selected_items.Get(), 1, &array_upper_bound)); EXPECT_EQ(0, array_upper_bound); IRawElementProviderSimple** array_data; EXPECT_HRESULT_SUCCEEDED(::SafeArrayAccessData( selected_items.Get(), reinterpret_cast<void**>(&array_data))); EXPECT_EQ(option2_provider.Get(), array_data[0]); EXPECT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(selected_items.Get())); } TEST_F(AXPlatformNodeWinTest, ISelectionProviderGetSelectionMultipleItemsSelected) { const std::vector<ax::mojom::State> state = { ax::mojom::State::kMultiselectable, ax::mojom::State::kFocusable}; Init(BuildListBox(/*option_1_is_selected*/ true, /*option_2_is_selected*/ true, /*option_3_is_selected*/ true, /*additional_state*/ state)); ComPtr<ISelectionProvider> selection_provider( QueryInterfaceFromNode<ISelectionProvider>(GetRootAsAXNode())); ComPtr<IRawElementProviderSimple> option1_provider( QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[0])); ComPtr<IRawElementProviderSimple> option2_provider( QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[1])); ComPtr<IRawElementProviderSimple> option3_provider( QueryInterfaceFromNode<IRawElementProviderSimple>( GetRootAsAXNode()->children()[2])); base::win::ScopedSafearray selected_items; EXPECT_HRESULT_SUCCEEDED( selection_provider->GetSelection(selected_items.Receive())); EXPECT_NE(nullptr, selected_items.Get()); LONG array_lower_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetLBound(selected_items.Get(), 1, &array_lower_bound)); EXPECT_EQ(0, array_lower_bound); LONG array_upper_bound; EXPECT_HRESULT_SUCCEEDED( ::SafeArrayGetUBound(selected_items.Get(), 1, &array_upper_bound)); EXPECT_EQ(2, array_upper_bound); IRawElementProviderSimple** array_data; EXPECT_HRESULT_SUCCEEDED(::SafeArrayAccessData( selected_items.Get(), reinterpret_cast<void**>(&array_data))); EXPECT_EQ(option1_provider.Get(), array_data[0]); EXPECT_EQ(option2_provider.Get(), array_data[1]); EXPECT_EQ(option3_provider.Get(), array_data[2]); EXPECT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(selected_items.Get())); } TEST_F(AXPlatformNodeWinTest, ComputeUIAControlType) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; AXNodeData child1; AXNode::AXID child1_id = 2; child1.id = child1_id; child1.role = ax::mojom::Role::kTable; root.child_ids.push_back(child1_id); AXNodeData child2; AXNode::AXID child2_id = 3; child2.id = child2_id; child2.role = ax::mojom::Role::kLayoutTable; root.child_ids.push_back(child2_id); AXNodeData child3; AXNode::AXID child3_id = 4; child3.id = child3_id; child3.role = ax::mojom::Role::kTextField; root.child_ids.push_back(child3_id); AXNodeData child4; AXNode::AXID child4_id = 5; child4.id = child4_id; child4.role = ax::mojom::Role::kSearchBox; root.child_ids.push_back(child4_id); Init(root, child1, child2, child3, child4); EXPECT_UIA_INT_EQ( QueryInterfaceFromNodeId<IRawElementProviderSimple>(child1_id), UIA_ControlTypePropertyId, int{UIA_TableControlTypeId}); EXPECT_UIA_INT_EQ( QueryInterfaceFromNodeId<IRawElementProviderSimple>(child2_id), UIA_ControlTypePropertyId, int{UIA_TableControlTypeId}); EXPECT_UIA_INT_EQ( QueryInterfaceFromNodeId<IRawElementProviderSimple>(child3_id), UIA_ControlTypePropertyId, int{UIA_EditControlTypeId}); EXPECT_UIA_INT_EQ( QueryInterfaceFromNodeId<IRawElementProviderSimple>(child4_id), UIA_ControlTypePropertyId, int{UIA_EditControlTypeId}); } TEST_F(AXPlatformNodeWinTest, UIALandmarkType) { auto TestLandmarkType = [this](ax::mojom::Role node_role, std::optional<LONG> expected_landmark_type, const std::string& node_name = {}) { AXNodeData root_data; root_data.id = 1; root_data.role = node_role; if (!node_name.empty()) root_data.SetName(node_name); Init(root_data); ComPtr<IRawElementProviderSimple> root_provider = GetRootIRawElementProviderSimple(); if (expected_landmark_type) { EXPECT_UIA_INT_EQ(root_provider, UIA_LandmarkTypePropertyId, expected_landmark_type.value()); } else { EXPECT_UIA_EMPTY(root_provider, UIA_LandmarkTypePropertyId); } }; TestLandmarkType(ax::mojom::Role::kBanner, UIA_CustomLandmarkTypeId); TestLandmarkType(ax::mojom::Role::kComplementary, UIA_CustomLandmarkTypeId); TestLandmarkType(ax::mojom::Role::kContentInfo, UIA_CustomLandmarkTypeId); TestLandmarkType(ax::mojom::Role::kFooter, UIA_CustomLandmarkTypeId); TestLandmarkType(ax::mojom::Role::kMain, UIA_MainLandmarkTypeId); TestLandmarkType(ax::mojom::Role::kNavigation, UIA_NavigationLandmarkTypeId); TestLandmarkType(ax::mojom::Role::kSearch, UIA_SearchLandmarkTypeId); // Only named forms should be exposed as landmarks. TestLandmarkType(ax::mojom::Role::kForm, {}); TestLandmarkType(ax::mojom::Role::kForm, UIA_FormLandmarkTypeId, "name"); // Only named regions should be exposed as landmarks. TestLandmarkType(ax::mojom::Role::kRegion, {}); TestLandmarkType(ax::mojom::Role::kRegion, UIA_CustomLandmarkTypeId, "name"); TestLandmarkType(ax::mojom::Role::kGroup, {}); TestLandmarkType(ax::mojom::Role::kHeading, {}); TestLandmarkType(ax::mojom::Role::kList, {}); TestLandmarkType(ax::mojom::Role::kTable, {}); } TEST_F(AXPlatformNodeWinTest, UIALocalizedLandmarkType) { auto TestLocalizedLandmarkType = [this](ax::mojom::Role node_role, const std::wstring& expected_localized_landmark, const std::string& node_name = {}) { AXNodeData root_data; root_data.id = 1; root_data.role = node_role; if (!node_name.empty()) root_data.SetName(node_name); Init(root_data); ComPtr<IRawElementProviderSimple> root_provider = GetRootIRawElementProviderSimple(); if (expected_localized_landmark.empty()) { EXPECT_UIA_EMPTY(root_provider, UIA_LocalizedLandmarkTypePropertyId); } else { EXPECT_UIA_BSTR_EQ(root_provider, UIA_LocalizedLandmarkTypePropertyId, expected_localized_landmark.c_str()); } }; TestLocalizedLandmarkType(ax::mojom::Role::kBanner, L"banner"); TestLocalizedLandmarkType(ax::mojom::Role::kComplementary, L"complementary"); TestLocalizedLandmarkType(ax::mojom::Role::kContentInfo, L"content information"); TestLocalizedLandmarkType(ax::mojom::Role::kFooter, L"content information"); // Only named regions should be exposed as landmarks. TestLocalizedLandmarkType(ax::mojom::Role::kRegion, {}); TestLocalizedLandmarkType(ax::mojom::Role::kRegion, L"region", "name"); TestLocalizedLandmarkType(ax::mojom::Role::kForm, {}); TestLocalizedLandmarkType(ax::mojom::Role::kGroup, {}); TestLocalizedLandmarkType(ax::mojom::Role::kHeading, {}); TestLocalizedLandmarkType(ax::mojom::Role::kList, {}); TestLocalizedLandmarkType(ax::mojom::Role::kMain, {}); TestLocalizedLandmarkType(ax::mojom::Role::kNavigation, {}); TestLocalizedLandmarkType(ax::mojom::Role::kSearch, {}); TestLocalizedLandmarkType(ax::mojom::Role::kTable, {}); } TEST_F(AXPlatformNodeWinTest, IRawElementProviderSimple2ShowContextMenu) { AXNodeData root_data; root_data.id = 1; AXNodeData element1_data; element1_data.id = 2; root_data.child_ids.push_back(element1_data.id); AXNodeData element2_data; element2_data.id = 3; root_data.child_ids.push_back(element2_data.id); Init(root_data, element1_data, element2_data); AXNode* root_node = GetRootAsAXNode(); AXNode* element1_node = root_node->children()[0]; AXNode* element2_node = root_node->children()[1]; ComPtr<IRawElementProviderSimple2> root_provider = QueryInterfaceFromNode<IRawElementProviderSimple2>(root_node); ComPtr<IRawElementProviderSimple2> element1_provider = QueryInterfaceFromNode<IRawElementProviderSimple2>(element1_node); ComPtr<IRawElementProviderSimple2> element2_provider = QueryInterfaceFromNode<IRawElementProviderSimple2>(element2_node); EXPECT_HRESULT_SUCCEEDED(element1_provider->ShowContextMenu()); EXPECT_EQ(element1_node, TestAXNodeWrapper::GetNodeFromLastShowContextMenu()); EXPECT_HRESULT_SUCCEEDED(element2_provider->ShowContextMenu()); EXPECT_EQ(element2_node, TestAXNodeWrapper::GetNodeFromLastShowContextMenu()); EXPECT_HRESULT_SUCCEEDED(root_provider->ShowContextMenu()); EXPECT_EQ(root_node, TestAXNodeWrapper::GetNodeFromLastShowContextMenu()); } TEST_F(AXPlatformNodeWinTest, UIAErrorHandling) { AXNodeData root; root.id = 1; Init(root); ComPtr<IRawElementProviderSimple> simple_provider = GetRootIRawElementProviderSimple(); ComPtr<IRawElementProviderSimple2> simple2_provider = QueryInterfaceFromNode<IRawElementProviderSimple2>(GetRootAsAXNode()); ComPtr<IRawElementProviderFragment> fragment_provider = GetRootIRawElementProviderFragment(); ComPtr<IGridItemProvider> grid_item_provider = QueryInterfaceFromNode<IGridItemProvider>(GetRootAsAXNode()); ComPtr<IGridProvider> grid_provider = QueryInterfaceFromNode<IGridProvider>(GetRootAsAXNode()); ComPtr<IScrollItemProvider> scroll_item_provider = QueryInterfaceFromNode<IScrollItemProvider>(GetRootAsAXNode()); ComPtr<IScrollProvider> scroll_provider = QueryInterfaceFromNode<IScrollProvider>(GetRootAsAXNode()); ComPtr<ISelectionItemProvider> selection_item_provider = QueryInterfaceFromNode<ISelectionItemProvider>(GetRootAsAXNode()); ComPtr<ISelectionProvider> selection_provider = QueryInterfaceFromNode<ISelectionProvider>(GetRootAsAXNode()); ComPtr<ITableItemProvider> table_item_provider = QueryInterfaceFromNode<ITableItemProvider>(GetRootAsAXNode()); ComPtr<ITableProvider> table_provider = QueryInterfaceFromNode<ITableProvider>(GetRootAsAXNode()); ComPtr<IExpandCollapseProvider> expand_collapse_provider = QueryInterfaceFromNode<IExpandCollapseProvider>(GetRootAsAXNode()); ComPtr<IToggleProvider> toggle_provider = QueryInterfaceFromNode<IToggleProvider>(GetRootAsAXNode()); ComPtr<IValueProvider> value_provider = QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()); ComPtr<IRangeValueProvider> range_value_provider = QueryInterfaceFromNode<IRangeValueProvider>(GetRootAsAXNode()); ComPtr<IWindowProvider> window_provider = QueryInterfaceFromNode<IWindowProvider>(GetRootAsAXNode()); // Create an empty tree. SetTree(std::make_unique<AXTree>()); // IGridItemProvider int int_result = 0; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), grid_item_provider->get_Column(&int_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), grid_item_provider->get_ColumnSpan(&int_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), grid_item_provider->get_Row(&int_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), grid_item_provider->get_RowSpan(&int_result)); // IExpandCollapseProvider ExpandCollapseState expand_collapse_state; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), expand_collapse_provider->Collapse()); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), expand_collapse_provider->Expand()); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), expand_collapse_provider->get_ExpandCollapseState( &expand_collapse_state)); // IGridProvider ComPtr<IRawElementProviderSimple> temp_simple_provider; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), grid_provider->GetItem(0, 0, &temp_simple_provider)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), grid_provider->get_RowCount(&int_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), grid_provider->get_ColumnCount(&int_result)); // IScrollItemProvider EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), scroll_item_provider->ScrollIntoView()); // IScrollProvider BOOL bool_result = TRUE; double double_result = 3.14; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), scroll_provider->SetScrollPercent(0, 0)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), scroll_provider->get_HorizontallyScrollable(&bool_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), scroll_provider->get_HorizontalScrollPercent(&double_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), scroll_provider->get_HorizontalViewSize(&double_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), scroll_provider->get_VerticallyScrollable(&bool_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), scroll_provider->get_VerticalScrollPercent(&double_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), scroll_provider->get_VerticalViewSize(&double_result)); // ISelectionItemProvider EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), selection_item_provider->AddToSelection()); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), selection_item_provider->RemoveFromSelection()); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), selection_item_provider->Select()); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), selection_item_provider->get_IsSelected(&bool_result)); EXPECT_EQ( static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), selection_item_provider->get_SelectionContainer(&temp_simple_provider)); // ISelectionProvider base::win::ScopedSafearray array_result; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), selection_provider->GetSelection(array_result.Receive())); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), selection_provider->get_CanSelectMultiple(&bool_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), selection_provider->get_IsSelectionRequired(&bool_result)); // ITableItemProvider RowOrColumnMajor row_or_column_major_result; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), table_item_provider->GetColumnHeaderItems(array_result.Receive())); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), table_item_provider->GetRowHeaderItems(array_result.Receive())); // ITableProvider EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), table_provider->GetColumnHeaders(array_result.Receive())); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), table_provider->GetRowHeaders(array_result.Receive())); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), table_provider->get_RowOrColumnMajor(&row_or_column_major_result)); // IRawElementProviderSimple ScopedVariant variant; ComPtr<IUnknown> unknown; ComPtr<IRawElementProviderSimple> host_provider; ProviderOptions options; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), simple_provider->GetPatternProvider(UIA_WindowPatternId, &unknown)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), simple_provider->GetPropertyValue(UIA_FrameworkIdPropertyId, variant.Receive())); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), simple_provider->get_ProviderOptions(&options)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), simple_provider->get_HostRawElementProvider(&host_provider)); // IRawElementProviderSimple2 EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), simple2_provider->ShowContextMenu()); // IRawElementProviderFragment ComPtr<IRawElementProviderFragment> navigated_to_fragment; base::win::ScopedSafearray safearray; UiaRect bounding_rectangle; ComPtr<IRawElementProviderFragmentRoot> fragment_root; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->Navigate(NavigateDirection_Parent, &navigated_to_fragment)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->GetRuntimeId(safearray.Receive())); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->get_BoundingRectangle(&bounding_rectangle)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->GetEmbeddedFragmentRoots(safearray.Receive())); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->get_FragmentRoot(&fragment_root)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), fragment_provider->SetFocus()); // IValueProvider ScopedBstr bstr_value; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), value_provider->SetValue(L"3.14")); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), value_provider->get_Value(bstr_value.Receive())); // IRangeValueProvider EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), range_value_provider->SetValue(double_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), range_value_provider->get_LargeChange(&double_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), range_value_provider->get_Maximum(&double_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), range_value_provider->get_Minimum(&double_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), range_value_provider->get_SmallChange(&double_result)); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), range_value_provider->get_Value(&double_result)); // IToggleProvider ToggleState toggle_state; EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), toggle_provider->Toggle()); EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), toggle_provider->get_ToggleState(&toggle_state)); // IWindowProvider ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), window_provider->SetVisualState( WindowVisualState::WindowVisualState_Normal)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), window_provider->Close()); ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), window_provider->WaitForInputIdle(0, nullptr)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), window_provider->get_CanMaximize(nullptr)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), window_provider->get_CanMinimize(nullptr)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), window_provider->get_IsModal(nullptr)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), window_provider->get_WindowVisualState(nullptr)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), window_provider->get_WindowInteractionState(nullptr)); ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), window_provider->get_IsTopmost(nullptr)); } TEST_F(AXPlatformNodeWinTest, GetPatternProviderSupportedPatterns) { constexpr AXNode::AXID root_id = 1; constexpr AXNode::AXID text_field_with_combo_box_id = 2; constexpr AXNode::AXID meter_id = 3; constexpr AXNode::AXID group_with_scroll_id = 4; constexpr AXNode::AXID checkbox_id = 5; constexpr AXNode::AXID link_id = 6; constexpr AXNode::AXID table_without_header_id = 7; constexpr AXNode::AXID table_without_header_cell_id = 8; constexpr AXNode::AXID table_with_header_id = 9; constexpr AXNode::AXID table_with_header_row_1_id = 10; constexpr AXNode::AXID table_with_header_column_header_id = 11; constexpr AXNode::AXID table_with_header_row_2_id = 12; constexpr AXNode::AXID table_with_header_cell_id = 13; constexpr AXNode::AXID grid_without_header_id = 14; constexpr AXNode::AXID grid_without_header_cell_id = 15; constexpr AXNode::AXID grid_with_header_id = 16; constexpr AXNode::AXID grid_with_header_row_1_id = 17; constexpr AXNode::AXID grid_with_header_column_header_id = 18; constexpr AXNode::AXID grid_with_header_row_2_id = 19; constexpr AXNode::AXID grid_with_header_cell_id = 20; AXTreeUpdate update; update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); update.has_tree_data = true; update.root_id = root_id; update.nodes.resize(20); update.nodes[0].id = root_id; update.nodes[0].role = ax::mojom::Role::kRootWebArea; update.nodes[0].child_ids = {text_field_with_combo_box_id, meter_id, group_with_scroll_id, checkbox_id, link_id, table_without_header_id, table_with_header_id, grid_without_header_id, grid_with_header_id}; update.nodes[1].id = text_field_with_combo_box_id; update.nodes[1].role = ax::mojom::Role::kTextFieldWithComboBox; update.nodes[2].id = meter_id; update.nodes[2].role = ax::mojom::Role::kMeter; update.nodes[3].id = group_with_scroll_id; update.nodes[3].role = ax::mojom::Role::kGroup; update.nodes[3].AddIntAttribute(ax::mojom::IntAttribute::kScrollXMin, 10); update.nodes[3].AddIntAttribute(ax::mojom::IntAttribute::kScrollXMax, 10); update.nodes[3].AddIntAttribute(ax::mojom::IntAttribute::kScrollX, 10); update.nodes[4].id = checkbox_id; update.nodes[4].role = ax::mojom::Role::kCheckBox; update.nodes[5].id = link_id; update.nodes[5].role = ax::mojom::Role::kLink; update.nodes[6].id = table_without_header_id; update.nodes[6].role = ax::mojom::Role::kTable; update.nodes[6].child_ids = {table_without_header_cell_id}; update.nodes[7].id = table_without_header_cell_id; update.nodes[7].role = ax::mojom::Role::kCell; update.nodes[8].id = table_with_header_id; update.nodes[8].role = ax::mojom::Role::kTable; update.nodes[8].child_ids = {table_with_header_row_1_id, table_with_header_row_2_id}; update.nodes[9].id = table_with_header_row_1_id; update.nodes[9].role = ax::mojom::Role::kRow; update.nodes[9].child_ids = {table_with_header_column_header_id}; update.nodes[10].id = table_with_header_column_header_id; update.nodes[10].role = ax::mojom::Role::kColumnHeader; update.nodes[11].id = table_with_header_row_2_id; update.nodes[11].role = ax::mojom::Role::kRow; update.nodes[11].child_ids = {table_with_header_cell_id}; update.nodes[12].id = table_with_header_cell_id; update.nodes[12].role = ax::mojom::Role::kCell; update.nodes[13].id = grid_without_header_id; update.nodes[13].role = ax::mojom::Role::kGrid; update.nodes[13].child_ids = {grid_without_header_cell_id}; update.nodes[14].id = grid_without_header_cell_id; update.nodes[14].role = ax::mojom::Role::kCell; update.nodes[14].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false); update.nodes[15].id = grid_with_header_id; update.nodes[15].role = ax::mojom::Role::kGrid; update.nodes[15].child_ids = {grid_with_header_row_1_id, grid_with_header_row_2_id}; update.nodes[16].id = grid_with_header_row_1_id; update.nodes[16].role = ax::mojom::Role::kRow; update.nodes[16].child_ids = {grid_with_header_column_header_id}; update.nodes[17].id = grid_with_header_column_header_id; update.nodes[17].role = ax::mojom::Role::kColumnHeader; update.nodes[17].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false); update.nodes[18].id = grid_with_header_row_2_id; update.nodes[18].role = ax::mojom::Role::kRow; update.nodes[18].child_ids = {grid_with_header_cell_id}; update.nodes[19].id = grid_with_header_cell_id; update.nodes[19].role = ax::mojom::Role::kCell; update.nodes[19].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false); Init(update); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_TextPatternId, UIA_TextEditPatternId}), GetSupportedPatternsFromNodeId(root_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ValuePatternId, UIA_ExpandCollapsePatternId, UIA_TextPatternId, UIA_TextEditPatternId}), GetSupportedPatternsFromNodeId(text_field_with_combo_box_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ValuePatternId, UIA_RangeValuePatternId}), GetSupportedPatternsFromNodeId(meter_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ScrollPatternId}), GetSupportedPatternsFromNodeId(group_with_scroll_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ValuePatternId, UIA_TogglePatternId}), GetSupportedPatternsFromNodeId(checkbox_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ValuePatternId, UIA_InvokePatternId}), GetSupportedPatternsFromNodeId(link_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_GridPatternId}), GetSupportedPatternsFromNodeId(table_without_header_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_GridItemPatternId}), GetSupportedPatternsFromNodeId(table_without_header_cell_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_GridPatternId, UIA_TablePatternId}), GetSupportedPatternsFromNodeId(table_with_header_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_GridItemPatternId, UIA_TableItemPatternId}), GetSupportedPatternsFromNodeId(table_with_header_column_header_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_GridItemPatternId, UIA_TableItemPatternId}), GetSupportedPatternsFromNodeId(table_with_header_cell_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ValuePatternId, UIA_SelectionPatternId, UIA_GridPatternId}), GetSupportedPatternsFromNodeId(grid_without_header_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ValuePatternId, UIA_SelectionItemPatternId, UIA_GridItemPatternId}), GetSupportedPatternsFromNodeId(grid_without_header_cell_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ValuePatternId, UIA_SelectionPatternId, UIA_GridPatternId, UIA_TablePatternId}), GetSupportedPatternsFromNodeId(grid_with_header_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ValuePatternId, UIA_GridItemPatternId, UIA_TableItemPatternId, UIA_SelectionItemPatternId}), GetSupportedPatternsFromNodeId(grid_with_header_column_header_id)); EXPECT_EQ(PatternSet({UIA_ScrollItemPatternId, UIA_ValuePatternId, UIA_GridItemPatternId, UIA_TableItemPatternId, UIA_SelectionItemPatternId}), GetSupportedPatternsFromNodeId(grid_with_header_cell_id)); } TEST_F(AXPlatformNodeWinTest, GetPatternProviderExpandCollapsePattern) { ui::AXNodeData root; root.id = 1; ui::AXNodeData list_box; ui::AXNodeData list_item; ui::AXNodeData menu_item; ui::AXNodeData menu_list_option; ui::AXNodeData tree_item; ui::AXNodeData combo_box_grouping; ui::AXNodeData combo_box_menu_button; ui::AXNodeData disclosure_triangle; ui::AXNodeData text_field_with_combo_box; list_box.id = 2; list_item.id = 3; menu_item.id = 4; menu_list_option.id = 5; tree_item.id = 6; combo_box_grouping.id = 7; combo_box_menu_button.id = 8; disclosure_triangle.id = 9; text_field_with_combo_box.id = 10; root.child_ids.push_back(list_box.id); root.child_ids.push_back(list_item.id); root.child_ids.push_back(menu_item.id); root.child_ids.push_back(menu_list_option.id); root.child_ids.push_back(tree_item.id); root.child_ids.push_back(combo_box_grouping.id); root.child_ids.push_back(combo_box_menu_button.id); root.child_ids.push_back(disclosure_triangle.id); root.child_ids.push_back(text_field_with_combo_box.id); // list_box HasPopup set to false, does not support expand collapse. list_box.role = ax::mojom::Role::kListBoxOption; list_box.SetHasPopup(ax::mojom::HasPopup::kFalse); // list_item HasPopup set to true, supports expand collapse. list_item.role = ax::mojom::Role::kListItem; list_item.SetHasPopup(ax::mojom::HasPopup::kTrue); // menu_item has expanded state and supports expand collapse. menu_item.role = ax::mojom::Role::kMenuItem; menu_item.AddState(ax::mojom::State::kExpanded); // menu_list_option has collapsed state and supports expand collapse. menu_list_option.role = ax::mojom::Role::kMenuListOption; menu_list_option.AddState(ax::mojom::State::kCollapsed); // These roles by default supports expand collapse. tree_item.role = ax::mojom::Role::kTreeItem; combo_box_grouping.role = ax::mojom::Role::kComboBoxGrouping; combo_box_menu_button.role = ax::mojom::Role::kComboBoxMenuButton; disclosure_triangle.role = ax::mojom::Role::kDisclosureTriangle; text_field_with_combo_box.role = ax::mojom::Role::kTextFieldWithComboBox; Init(root, list_box, list_item, menu_item, menu_list_option, tree_item, combo_box_grouping, combo_box_menu_button, disclosure_triangle, text_field_with_combo_box); // list_box HasPopup set to false, does not support expand collapse. ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(0); ComPtr<IExpandCollapseProvider> expandcollapse_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); EXPECT_EQ(nullptr, expandcollapse_provider.Get()); // list_item HasPopup set to true, supports expand collapse. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(1); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); EXPECT_NE(nullptr, expandcollapse_provider.Get()); // menu_item has expanded state and supports expand collapse. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(2); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); EXPECT_NE(nullptr, expandcollapse_provider.Get()); // menu_list_option has collapsed state and supports expand collapse. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(3); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); EXPECT_NE(nullptr, expandcollapse_provider.Get()); // tree_item by default supports expand collapse. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(4); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); EXPECT_NE(nullptr, expandcollapse_provider.Get()); // combo_box_grouping by default supports expand collapse. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(5); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); EXPECT_NE(nullptr, expandcollapse_provider.Get()); // combo_box_menu_button by default supports expand collapse. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(6); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); EXPECT_NE(nullptr, expandcollapse_provider.Get()); // disclosure_triangle by default supports expand collapse. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(7); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); EXPECT_NE(nullptr, expandcollapse_provider.Get()); // text_field_with_combo_box by default supports expand collapse. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(8); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); EXPECT_NE(nullptr, expandcollapse_provider.Get()); } TEST_F(AXPlatformNodeWinTest, GetPatternProviderInvokePattern) { ui::AXNodeData root; root.id = 1; ui::AXNodeData link; ui::AXNodeData generic_container; ui::AXNodeData combo_box_grouping; ui::AXNodeData check_box; link.id = 2; generic_container.id = 3; combo_box_grouping.id = 4; check_box.id = 5; root.child_ids.push_back(link.id); root.child_ids.push_back(generic_container.id); root.child_ids.push_back(combo_box_grouping.id); root.child_ids.push_back(check_box.id); // Role link is clickable and neither supports expand collapse nor supports // toggle. It should support invoke pattern. link.role = ax::mojom::Role::kLink; // Role generic container is not clickable. It should not support invoke // pattern. generic_container.role = ax::mojom::Role::kGenericContainer; // Role combo box grouping supports expand collapse. It should not support // invoke pattern. combo_box_grouping.role = ax::mojom::Role::kComboBoxGrouping; // Role check box supports toggle. It should not support invoke pattern. check_box.role = ax::mojom::Role::kCheckBox; Init(root, link, generic_container, combo_box_grouping, check_box); // Role link is clickable and neither supports expand collapse nor supports // toggle. It should support invoke pattern. ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(0); ComPtr<IInvokeProvider> invoke_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_InvokePatternId, &invoke_provider)); EXPECT_NE(nullptr, invoke_provider.Get()); // Role generic container is not clickable. It should not support invoke // pattern. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(1); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_InvokePatternId, &invoke_provider)); EXPECT_EQ(nullptr, invoke_provider.Get()); // Role combo box grouping supports expand collapse. It should not support // invoke pattern. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(2); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_InvokePatternId, &invoke_provider)); EXPECT_EQ(nullptr, invoke_provider.Get()); // Role check box supports toggle. It should not support invoke pattern. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(3); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_InvokePatternId, &invoke_provider)); EXPECT_EQ(nullptr, invoke_provider.Get()); } TEST_F(AXPlatformNodeWinTest, IExpandCollapsePatternProviderAction) { ui::AXNodeData root; root.id = 1; ui::AXNodeData combo_box_grouping_has_popup; ui::AXNodeData combo_box_grouping_expanded; ui::AXNodeData combo_box_grouping_collapsed; ui::AXNodeData combo_box_grouping_disabled; ui::AXNodeData button_has_popup_menu; ui::AXNodeData button_has_popup_menu_pressed; ui::AXNodeData button_has_popup_true; ui::AXNodeData generic_container_has_popup_menu; combo_box_grouping_has_popup.id = 2; combo_box_grouping_expanded.id = 3; combo_box_grouping_collapsed.id = 4; combo_box_grouping_disabled.id = 5; button_has_popup_menu.id = 6; button_has_popup_menu_pressed.id = 7; button_has_popup_true.id = 8; generic_container_has_popup_menu.id = 9; root.child_ids = { combo_box_grouping_has_popup.id, combo_box_grouping_expanded.id, combo_box_grouping_collapsed.id, combo_box_grouping_disabled.id, button_has_popup_menu.id, button_has_popup_menu_pressed.id, button_has_popup_true.id, generic_container_has_popup_menu.id}; // combo_box_grouping HasPopup set to true, can collapse, can expand. // state is ExpandCollapseState_LeafNode. combo_box_grouping_has_popup.role = ax::mojom::Role::kComboBoxGrouping; combo_box_grouping_has_popup.SetHasPopup(ax::mojom::HasPopup::kTrue); // combo_box_grouping Expanded set, can collapse, cannot expand. // state is ExpandCollapseState_Expanded. combo_box_grouping_expanded.role = ax::mojom::Role::kComboBoxGrouping; combo_box_grouping_expanded.AddState(ax::mojom::State::kExpanded); // combo_box_grouping Collapsed set, can expand, cannot collapse. // state is ExpandCollapseState_Collapsed. combo_box_grouping_collapsed.role = ax::mojom::Role::kComboBoxGrouping; combo_box_grouping_collapsed.AddState(ax::mojom::State::kCollapsed); // combo_box_grouping is disabled, can neither expand nor collapse. // state is ExpandCollapseState_LeafNode. combo_box_grouping_disabled.role = ax::mojom::Role::kComboBoxGrouping; combo_box_grouping_disabled.SetRestriction(ax::mojom::Restriction::kDisabled); // button_has_popup_menu HasPopup set to kMenu and is not STATE_PRESSED. // state is ExpandCollapseState_Collapsed. button_has_popup_menu.role = ax::mojom::Role::kButton; button_has_popup_menu.SetHasPopup(ax::mojom::HasPopup::kMenu); // button_has_popup_menu_pressed HasPopup set to kMenu and is STATE_PRESSED. // state is ExpandCollapseState_Expanded. button_has_popup_menu_pressed.role = ax::mojom::Role::kButton; button_has_popup_menu_pressed.SetHasPopup(ax::mojom::HasPopup::kMenu); button_has_popup_menu_pressed.SetCheckedState(ax::mojom::CheckedState::kTrue); // button_has_popup_true HasPopup set to true but is not a menu. // state is ExpandCollapseState_LeafNode. button_has_popup_true.role = ax::mojom::Role::kButton; button_has_popup_true.SetHasPopup(ax::mojom::HasPopup::kTrue); // generic_container_has_popup_menu HasPopup set to menu but with no expand // state set. // state is ExpandCollapseState_LeafNode. generic_container_has_popup_menu.role = ax::mojom::Role::kGenericContainer; generic_container_has_popup_menu.SetHasPopup(ax::mojom::HasPopup::kMenu); Init(root, combo_box_grouping_has_popup, combo_box_grouping_disabled, combo_box_grouping_expanded, combo_box_grouping_collapsed, combo_box_grouping_disabled, button_has_popup_menu, button_has_popup_menu_pressed, button_has_popup_true, generic_container_has_popup_menu); // combo_box_grouping HasPopup set to true, can collapse, can expand. // state is ExpandCollapseState_LeafNode. ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(0); ComPtr<IExpandCollapseProvider> expandcollapse_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); ASSERT_NE(nullptr, expandcollapse_provider.Get()); EXPECT_HRESULT_SUCCEEDED(expandcollapse_provider->Collapse()); EXPECT_HRESULT_SUCCEEDED(expandcollapse_provider->Expand()); ExpandCollapseState state; EXPECT_HRESULT_SUCCEEDED( expandcollapse_provider->get_ExpandCollapseState(&state)); EXPECT_EQ(ExpandCollapseState_LeafNode, state); // combo_box_grouping Expanded set, can collapse, cannot expand. // state is ExpandCollapseState_Expanded. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(1); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); ASSERT_NE(nullptr, expandcollapse_provider.Get()); EXPECT_HRESULT_SUCCEEDED(expandcollapse_provider->Collapse()); EXPECT_HRESULT_FAILED(expandcollapse_provider->Expand()); EXPECT_HRESULT_SUCCEEDED( expandcollapse_provider->get_ExpandCollapseState(&state)); EXPECT_EQ(ExpandCollapseState_Expanded, state); // combo_box_grouping Collapsed set, can expand, cannot collapse. // state is ExpandCollapseState_Collapsed. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(2); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); ASSERT_NE(nullptr, expandcollapse_provider.Get()); EXPECT_HRESULT_FAILED(expandcollapse_provider->Collapse()); EXPECT_HRESULT_SUCCEEDED(expandcollapse_provider->Expand()); EXPECT_HRESULT_SUCCEEDED( expandcollapse_provider->get_ExpandCollapseState(&state)); EXPECT_EQ(ExpandCollapseState_Collapsed, state); // combo_box_grouping is disabled, can neither expand nor collapse. // state is ExpandCollapseState_LeafNode. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(3); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); ASSERT_NE(nullptr, expandcollapse_provider.Get()); EXPECT_HRESULT_FAILED(expandcollapse_provider->Collapse()); EXPECT_HRESULT_FAILED(expandcollapse_provider->Expand()); EXPECT_HRESULT_SUCCEEDED( expandcollapse_provider->get_ExpandCollapseState(&state)); EXPECT_EQ(ExpandCollapseState_LeafNode, state); // button_has_popup_menu HasPopup set to kMenu and is not STATE_PRESSED. // state is ExpandCollapseState_Collapsed. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(4); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); ASSERT_NE(nullptr, expandcollapse_provider.Get()); EXPECT_HRESULT_SUCCEEDED( expandcollapse_provider->get_ExpandCollapseState(&state)); EXPECT_EQ(ExpandCollapseState_Collapsed, state); // button_has_popup_menu_pressed HasPopup set to kMenu and is STATE_PRESSED. // state is ExpandCollapseState_Expanded. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(5); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); ASSERT_NE(nullptr, expandcollapse_provider.Get()); EXPECT_HRESULT_SUCCEEDED( expandcollapse_provider->get_ExpandCollapseState(&state)); EXPECT_EQ(ExpandCollapseState_Expanded, state); // button_has_popup_true HasPopup set to true but is not a menu. // state is ExpandCollapseState_LeafNode. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(6); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); ASSERT_NE(nullptr, expandcollapse_provider.Get()); EXPECT_HRESULT_SUCCEEDED( expandcollapse_provider->get_ExpandCollapseState(&state)); EXPECT_EQ(ExpandCollapseState_LeafNode, state); // generic_container_has_popup_menu HasPopup set to menu but with no expand // state set. // state is ExpandCollapseState_LeafNode. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(7); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_ExpandCollapsePatternId, &expandcollapse_provider)); ASSERT_NE(nullptr, expandcollapse_provider.Get()); EXPECT_HRESULT_SUCCEEDED( expandcollapse_provider->get_ExpandCollapseState(&state)); EXPECT_EQ(ExpandCollapseState_LeafNode, state); } TEST_F(AXPlatformNodeWinTest, IInvokeProviderInvoke) { ui::AXNodeData root; root.id = 1; ui::AXNodeData button; ui::AXNodeData button_disabled; button.id = 2; button_disabled.id = 3; root.child_ids.push_back(button.id); root.child_ids.push_back(button_disabled.id); // generic button can be invoked. button.role = ax::mojom::Role::kButton; // disabled button, cannot be invoked. button_disabled.role = ax::mojom::Role::kButton; button_disabled.SetRestriction(ax::mojom::Restriction::kDisabled); Init(root, button, button_disabled); AXNode* button_node = GetRootAsAXNode()->children()[0]; // generic button can be invoked. ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(0); ComPtr<IInvokeProvider> invoke_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_InvokePatternId, &invoke_provider)); EXPECT_NE(nullptr, invoke_provider.Get()); EXPECT_HRESULT_SUCCEEDED(invoke_provider->Invoke()); EXPECT_EQ(button_node, TestAXNodeWrapper::GetNodeFromLastDefaultAction()); // disabled button, cannot be invoked. raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(1); EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_InvokePatternId, &invoke_provider)); EXPECT_NE(nullptr, invoke_provider.Get()); EXPECT_UIA_ELEMENTNOTENABLED(invoke_provider->Invoke()); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderNotSupported) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kNone; Init(root); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetRootIRawElementProviderSimple(); ComPtr<ISelectionItemProvider> selection_item_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_SelectionItemPatternId, &selection_item_provider)); ASSERT_EQ(nullptr, selection_item_provider.Get()); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderDisabled) { AXNodeData root; root.id = 1; root.AddIntAttribute(ax::mojom::IntAttribute::kRestriction, static_cast<int>(ax::mojom::Restriction::kDisabled)); root.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); root.role = ax::mojom::Role::kTab; Init(root); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetRootIRawElementProviderSimple(); ComPtr<ISelectionItemProvider> selection_item_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_SelectionItemPatternId, &selection_item_provider)); ASSERT_NE(nullptr, selection_item_provider.Get()); BOOL selected; EXPECT_UIA_ELEMENTNOTENABLED(selection_item_provider->AddToSelection()); EXPECT_UIA_ELEMENTNOTENABLED(selection_item_provider->RemoveFromSelection()); EXPECT_UIA_ELEMENTNOTENABLED(selection_item_provider->Select()); EXPECT_HRESULT_SUCCEEDED(selection_item_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderNotSelectable) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTab; Init(root); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetRootIRawElementProviderSimple(); ComPtr<ISelectionItemProvider> selection_item_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_SelectionItemPatternId, &selection_item_provider)); ASSERT_EQ(nullptr, selection_item_provider.Get()); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderSimple) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kListBox; AXNodeData option1; option1.id = 2; option1.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false); option1.role = ax::mojom::Role::kListBoxOption; root.child_ids.push_back(option1.id); Init(root, option1); ComPtr<IRawElementProviderSimple> raw_element_provider_simple = GetIRawElementProviderSimpleFromChildIndex(0); ComPtr<ISelectionItemProvider> option1_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_SelectionItemPatternId, &option1_provider)); ASSERT_NE(nullptr, option1_provider.Get()); BOOL selected; // Note: TestAXNodeWrapper::AccessibilityPerformAction will // flip kSelected for kListBoxOption when the kDoDefault action is fired. // Initial State EXPECT_HRESULT_SUCCEEDED(option1_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); // AddToSelection should fire event when not selected EXPECT_HRESULT_SUCCEEDED(option1_provider->AddToSelection()); EXPECT_HRESULT_SUCCEEDED(option1_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // AddToSelection should not fire event when selected EXPECT_HRESULT_SUCCEEDED(option1_provider->AddToSelection()); EXPECT_HRESULT_SUCCEEDED(option1_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // RemoveFromSelection should fire event when selected EXPECT_HRESULT_SUCCEEDED(option1_provider->RemoveFromSelection()); EXPECT_HRESULT_SUCCEEDED(option1_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); // RemoveFromSelection should not fire event when not selected EXPECT_HRESULT_SUCCEEDED(option1_provider->RemoveFromSelection()); EXPECT_HRESULT_SUCCEEDED(option1_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); // Select should fire event when not selected EXPECT_HRESULT_SUCCEEDED(option1_provider->Select()); EXPECT_HRESULT_SUCCEEDED(option1_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // Select should not fire event when selected EXPECT_HRESULT_SUCCEEDED(option1_provider->Select()); EXPECT_HRESULT_SUCCEEDED(option1_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderRadioButton) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRadioGroup; // CheckedState::kNone AXNodeData option1; option1.id = 2; option1.AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int>(ax::mojom::CheckedState::kNone)); option1.role = ax::mojom::Role::kRadioButton; root.child_ids.push_back(option1.id); // CheckedState::kFalse AXNodeData option2; option2.id = 3; option2.AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int>(ax::mojom::CheckedState::kFalse)); option2.role = ax::mojom::Role::kRadioButton; root.child_ids.push_back(option2.id); // CheckedState::kTrue AXNodeData option3; option3.id = 4; option3.AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int>(ax::mojom::CheckedState::kTrue)); option3.role = ax::mojom::Role::kRadioButton; root.child_ids.push_back(option3.id); // CheckedState::kMixed AXNodeData option4; option4.id = 5; option4.AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int>(ax::mojom::CheckedState::kMixed)); option4.role = ax::mojom::Role::kRadioButton; root.child_ids.push_back(option4.id); Init(root, option1, option2, option3, option4); BOOL selected; // Option 1, CheckedState::kNone, ISelectionItemProvider is not supported. ComPtr<ISelectionItemProvider> option1_provider; EXPECT_HRESULT_SUCCEEDED( GetIRawElementProviderSimpleFromChildIndex(0)->GetPatternProvider( UIA_SelectionItemPatternId, &option1_provider)); ASSERT_EQ(nullptr, option1_provider.Get()); // Option 2, CheckedState::kFalse. ComPtr<ISelectionItemProvider> option2_provider; EXPECT_HRESULT_SUCCEEDED( GetIRawElementProviderSimpleFromChildIndex(1)->GetPatternProvider( UIA_SelectionItemPatternId, &option2_provider)); ASSERT_NE(nullptr, option2_provider.Get()); EXPECT_HRESULT_SUCCEEDED(option2_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); EXPECT_HRESULT_SUCCEEDED(option2_provider->Select()); EXPECT_HRESULT_SUCCEEDED(option2_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // Option 3, CheckedState::kTrue. ComPtr<ISelectionItemProvider> option3_provider; EXPECT_HRESULT_SUCCEEDED( GetIRawElementProviderSimpleFromChildIndex(2)->GetPatternProvider( UIA_SelectionItemPatternId, &option3_provider)); ASSERT_NE(nullptr, option3_provider.Get()); EXPECT_HRESULT_SUCCEEDED(option3_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); EXPECT_HRESULT_SUCCEEDED(option3_provider->RemoveFromSelection()); EXPECT_HRESULT_SUCCEEDED(option3_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); EXPECT_HRESULT_SUCCEEDED(option3_provider->AddToSelection()); EXPECT_HRESULT_SUCCEEDED(option3_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // Option 4, CheckedState::kMixed, ISelectionItemProvider is not supported. ComPtr<ISelectionItemProvider> option4_provider; EXPECT_HRESULT_SUCCEEDED( GetIRawElementProviderSimpleFromChildIndex(3)->GetPatternProvider( UIA_SelectionItemPatternId, &option4_provider)); ASSERT_EQ(nullptr, option4_provider.Get()); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderMenuItemRadio) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kMenu; // CheckedState::kNone AXNodeData option1; option1.id = 2; option1.AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int>(ax::mojom::CheckedState::kNone)); option1.role = ax::mojom::Role::kMenuItemRadio; root.child_ids.push_back(option1.id); // CheckedState::kFalse AXNodeData option2; option2.id = 3; option2.AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int>(ax::mojom::CheckedState::kFalse)); option2.role = ax::mojom::Role::kMenuItemRadio; root.child_ids.push_back(option2.id); // CheckedState::kTrue AXNodeData option3; option3.id = 4; option3.AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int>(ax::mojom::CheckedState::kTrue)); option3.role = ax::mojom::Role::kMenuItemRadio; root.child_ids.push_back(option3.id); // CheckedState::kMixed AXNodeData option4; option4.id = 5; option4.AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int>(ax::mojom::CheckedState::kMixed)); option4.role = ax::mojom::Role::kMenuItemRadio; root.child_ids.push_back(option4.id); Init(root, option1, option2, option3, option4); BOOL selected; // Option 1, CheckedState::kNone, ISelectionItemProvider is not supported. ComPtr<ISelectionItemProvider> option1_provider; EXPECT_HRESULT_SUCCEEDED( GetIRawElementProviderSimpleFromChildIndex(0)->GetPatternProvider( UIA_SelectionItemPatternId, &option1_provider)); ASSERT_EQ(nullptr, option1_provider.Get()); // Option 2, CheckedState::kFalse. ComPtr<ISelectionItemProvider> option2_provider; EXPECT_HRESULT_SUCCEEDED( GetIRawElementProviderSimpleFromChildIndex(1)->GetPatternProvider( UIA_SelectionItemPatternId, &option2_provider)); ASSERT_NE(nullptr, option2_provider.Get()); EXPECT_HRESULT_SUCCEEDED(option2_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); EXPECT_HRESULT_SUCCEEDED(option2_provider->Select()); EXPECT_HRESULT_SUCCEEDED(option2_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // Option 3, CheckedState::kTrue. ComPtr<ISelectionItemProvider> option3_provider; EXPECT_HRESULT_SUCCEEDED( GetIRawElementProviderSimpleFromChildIndex(2)->GetPatternProvider( UIA_SelectionItemPatternId, &option3_provider)); ASSERT_NE(nullptr, option3_provider.Get()); EXPECT_HRESULT_SUCCEEDED(option3_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); EXPECT_HRESULT_SUCCEEDED(option3_provider->RemoveFromSelection()); EXPECT_HRESULT_SUCCEEDED(option3_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); EXPECT_HRESULT_SUCCEEDED(option3_provider->AddToSelection()); EXPECT_HRESULT_SUCCEEDED(option3_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // Option 4, CheckedState::kMixed, ISelectionItemProvider is not supported. ComPtr<ISelectionItemProvider> option4_provider; EXPECT_HRESULT_SUCCEEDED( GetIRawElementProviderSimpleFromChildIndex(3)->GetPatternProvider( UIA_SelectionItemPatternId, &option4_provider)); ASSERT_EQ(nullptr, option4_provider.Get()); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderTable) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTable; AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; root.child_ids.push_back(row1.id); AXNodeData cell1; cell1.id = 3; cell1.role = ax::mojom::Role::kCell; cell1.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false); row1.child_ids.push_back(cell1.id); Init(root, row1, cell1); ComPtr<ISelectionItemProvider> selection_item_provider; EXPECT_HRESULT_SUCCEEDED( GetIRawElementProviderSimpleFromChildIndex(0)->GetPatternProvider( UIA_SelectionItemPatternId, &selection_item_provider)); ASSERT_EQ(nullptr, selection_item_provider.Get()); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderGrid) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kGrid; AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; root.child_ids.push_back(row1.id); AXNodeData cell1; cell1.id = 3; cell1.role = ax::mojom::Role::kCell; cell1.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false); row1.child_ids.push_back(cell1.id); Init(root, row1, cell1); const auto* row = GetRootAsAXNode()->children()[0]; ComPtr<IRawElementProviderSimple> raw_element_provider_simple = QueryInterfaceFromNode<IRawElementProviderSimple>(row->children()[0]); ComPtr<ISelectionItemProvider> selection_item_provider; EXPECT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider( UIA_SelectionItemPatternId, &selection_item_provider)); ASSERT_NE(nullptr, selection_item_provider.Get()); BOOL selected; // Note: TestAXNodeWrapper::AccessibilityPerformAction will // flip kSelected for kCell when the kDoDefault action is fired. // Initial State EXPECT_HRESULT_SUCCEEDED(selection_item_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); // AddToSelection should fire event when not selected EXPECT_HRESULT_SUCCEEDED(selection_item_provider->AddToSelection()); EXPECT_HRESULT_SUCCEEDED(selection_item_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // AddToSelection should not fire event when selected EXPECT_HRESULT_SUCCEEDED(selection_item_provider->AddToSelection()); EXPECT_HRESULT_SUCCEEDED(selection_item_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // RemoveFromSelection should fire event when selected EXPECT_HRESULT_SUCCEEDED(selection_item_provider->RemoveFromSelection()); EXPECT_HRESULT_SUCCEEDED(selection_item_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); // RemoveFromSelection should not fire event when not selected EXPECT_HRESULT_SUCCEEDED(selection_item_provider->RemoveFromSelection()); EXPECT_HRESULT_SUCCEEDED(selection_item_provider->get_IsSelected(&selected)); EXPECT_FALSE(selected); // Select should fire event when not selected EXPECT_HRESULT_SUCCEEDED(selection_item_provider->Select()); EXPECT_HRESULT_SUCCEEDED(selection_item_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); // Select should not fire event when selected EXPECT_HRESULT_SUCCEEDED(selection_item_provider->Select()); EXPECT_HRESULT_SUCCEEDED(selection_item_provider->get_IsSelected(&selected)); EXPECT_TRUE(selected); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderGetSelectionContainer) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kGrid; AXNodeData row1; row1.id = 2; row1.role = ax::mojom::Role::kRow; root.child_ids.push_back(row1.id); AXNodeData cell1; cell1.id = 3; cell1.role = ax::mojom::Role::kCell; cell1.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false); row1.child_ids.push_back(cell1.id); Init(root, row1, cell1); ComPtr<IRawElementProviderSimple> container_provider = GetRootIRawElementProviderSimple(); const auto* row = GetRootAsAXNode()->children()[0]; ComPtr<ISelectionItemProvider> item_provider = QueryInterfaceFromNode<ISelectionItemProvider>(row->children()[0]); ComPtr<IRawElementProviderSimple> container; EXPECT_HRESULT_SUCCEEDED(item_provider->get_SelectionContainer(&container)); EXPECT_NE(nullptr, container); EXPECT_EQ(container, container_provider); } TEST_F(AXPlatformNodeWinTest, ISelectionItemProviderSelectFollowFocus) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kTabList; AXNodeData tab1; tab1.id = 2; tab1.role = ax::mojom::Role::kTab; tab1.AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false); tab1.SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kClick); root.child_ids.push_back(tab1.id); Init(root, tab1); auto* tab1_node = GetRootAsAXNode()->children()[0]; ComPtr<IRawElementProviderSimple> tab1_raw_element_provider_simple = QueryInterfaceFromNode<IRawElementProviderSimple>(tab1_node); ASSERT_NE(nullptr, tab1_raw_element_provider_simple.Get()); ComPtr<IRawElementProviderFragment> tab1_raw_element_provider_fragment = IRawElementProviderFragmentFromNode(tab1_node); ASSERT_NE(nullptr, tab1_raw_element_provider_fragment.Get()); ComPtr<ISelectionItemProvider> tab1_selection_item_provider; EXPECT_HRESULT_SUCCEEDED(tab1_raw_element_provider_simple->GetPatternProvider( UIA_SelectionItemPatternId, &tab1_selection_item_provider)); ASSERT_NE(nullptr, tab1_selection_item_provider.Get()); BOOL is_selected; // Before setting focus to "tab1", validate that "tab1" has selected=false. tab1_selection_item_provider->get_IsSelected(&is_selected); EXPECT_FALSE(is_selected); // Setting focus on "tab1" will result in selected=true. tab1_raw_element_provider_fragment->SetFocus(); tab1_selection_item_provider->get_IsSelected(&is_selected); EXPECT_TRUE(is_selected); // Verify that we can still trigger action::kDoDefault through Select(). EXPECT_HRESULT_SUCCEEDED(tab1_selection_item_provider->Select()); tab1_selection_item_provider->get_IsSelected(&is_selected); EXPECT_TRUE(is_selected); EXPECT_EQ(tab1_node, TestAXNodeWrapper::GetNodeFromLastDefaultAction()); // Verify that after Select(), "tab1" is still selected. tab1_selection_item_provider->get_IsSelected(&is_selected); EXPECT_TRUE(is_selected); // Since last Select() performed |action::kDoDefault|, which set // |kSelectedFromFocus| to false. Calling Select() again will not perform // |action::kDoDefault| again. TestAXNodeWrapper::SetNodeFromLastDefaultAction(nullptr); EXPECT_HRESULT_SUCCEEDED(tab1_selection_item_provider->Select()); tab1_selection_item_provider->get_IsSelected(&is_selected); EXPECT_TRUE(is_selected); // Verify that after Select(),|action::kDoDefault| was not triggered on // "tab1". EXPECT_EQ(nullptr, TestAXNodeWrapper::GetNodeFromLastDefaultAction()); } TEST_F(AXPlatformNodeWinTest, IValueProvider_GetValue) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kProgressIndicator; child1.AddFloatAttribute(ax::mojom::FloatAttribute::kValueForRange, 3.0f); root.child_ids.push_back(child1.id); AXNodeData child2; child2.id = 3; child2.role = ax::mojom::Role::kTextField; child2.AddState(ax::mojom::State::kEditable); child2.AddStringAttribute(ax::mojom::StringAttribute::kValue, "test"); root.child_ids.push_back(child2.id); AXNodeData child3; child3.id = 4; child3.role = ax::mojom::Role::kTextField; child3.AddStringAttribute(ax::mojom::StringAttribute::kValue, "test"); child3.AddIntAttribute(ax::mojom::IntAttribute::kRestriction, static_cast<int>(ax::mojom::Restriction::kReadOnly)); root.child_ids.push_back(child3.id); Init(root, child1, child2, child3); ScopedBstr bstr_value; EXPECT_HRESULT_SUCCEEDED( QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[0]) ->get_Value(bstr_value.Receive())); EXPECT_STREQ(L"3", bstr_value.Get()); bstr_value.Reset(); EXPECT_HRESULT_SUCCEEDED( QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[1]) ->get_Value(bstr_value.Receive())); EXPECT_STREQ(L"test", bstr_value.Get()); bstr_value.Reset(); EXPECT_HRESULT_SUCCEEDED( QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[2]) ->get_Value(bstr_value.Receive())); EXPECT_STREQ(L"test", bstr_value.Get()); bstr_value.Reset(); } TEST_F(AXPlatformNodeWinTest, IValueProvider_SetValue) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kProgressIndicator; child1.AddFloatAttribute(ax::mojom::FloatAttribute::kValueForRange, 3.0f); root.child_ids.push_back(child1.id); AXNodeData child2; child2.id = 3; child2.role = ax::mojom::Role::kTextField; child2.AddStringAttribute(ax::mojom::StringAttribute::kValue, "test"); root.child_ids.push_back(child2.id); AXNodeData child3; child3.id = 4; child3.role = ax::mojom::Role::kTextField; child3.AddStringAttribute(ax::mojom::StringAttribute::kValue, "test"); child3.AddIntAttribute(ax::mojom::IntAttribute::kRestriction, static_cast<int>(ax::mojom::Restriction::kReadOnly)); root.child_ids.push_back(child3.id); Init(root, child1, child2, child3); ComPtr<IValueProvider> root_provider = QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()); ComPtr<IValueProvider> provider1 = QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[0]); ComPtr<IValueProvider> provider2 = QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[1]); ComPtr<IValueProvider> provider3 = QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[2]); ScopedBstr bstr_value; // Note: TestAXNodeWrapper::AccessibilityPerformAction will // modify the value when the kSetValue action is fired. EXPECT_UIA_ELEMENTNOTENABLED(provider1->SetValue(L"2")); EXPECT_HRESULT_SUCCEEDED(provider1->get_Value(bstr_value.Receive())); EXPECT_STREQ(L"3", bstr_value.Get()); bstr_value.Reset(); EXPECT_HRESULT_SUCCEEDED(provider2->SetValue(L"changed")); EXPECT_HRESULT_SUCCEEDED(provider2->get_Value(bstr_value.Receive())); EXPECT_STREQ(L"changed", bstr_value.Get()); bstr_value.Reset(); EXPECT_UIA_ELEMENTNOTENABLED(provider3->SetValue(L"changed")); EXPECT_HRESULT_SUCCEEDED(provider3->get_Value(bstr_value.Receive())); EXPECT_STREQ(L"test", bstr_value.Get()); bstr_value.Reset(); } TEST_F(AXPlatformNodeWinTest, IValueProvider_IsReadOnly) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kRootWebArea; AXNodeData child1; child1.id = 2; child1.role = ax::mojom::Role::kTextField; child1.AddState(ax::mojom::State::kEditable); root.child_ids.push_back(child1.id); AXNodeData child2; child2.id = 3; child2.role = ax::mojom::Role::kTextField; child2.AddIntAttribute(ax::mojom::IntAttribute::kRestriction, static_cast<int>(ax::mojom::Restriction::kReadOnly)); root.child_ids.push_back(child2.id); AXNodeData child3; child3.id = 4; child3.role = ax::mojom::Role::kTextField; child3.AddIntAttribute(ax::mojom::IntAttribute::kRestriction, static_cast<int>(ax::mojom::Restriction::kDisabled)); root.child_ids.push_back(child3.id); AXNodeData child4; child4.id = 5; child4.role = ax::mojom::Role::kLink; root.child_ids.push_back(child4.id); Init(root, child1, child2, child3, child4); BOOL is_readonly = false; EXPECT_HRESULT_SUCCEEDED( QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[0]) ->get_IsReadOnly(&is_readonly)); EXPECT_FALSE(is_readonly); EXPECT_HRESULT_SUCCEEDED( QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[1]) ->get_IsReadOnly(&is_readonly)); EXPECT_TRUE(is_readonly); EXPECT_HRESULT_SUCCEEDED( QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[2]) ->get_IsReadOnly(&is_readonly)); EXPECT_TRUE(is_readonly); EXPECT_HRESULT_SUCCEEDED( QueryInterfaceFromNode<IValueProvider>(GetRootAsAXNode()->children()[3]) ->get_IsReadOnly(&is_readonly)); EXPECT_TRUE(is_readonly); } TEST_F(AXPlatformNodeWinTest, IScrollProviderSetScrollPercent) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kGenericContainer; root.AddIntAttribute(ax::mojom::IntAttribute::kScrollX, 0); root.AddIntAttribute(ax::mojom::IntAttribute::kScrollXMin, 0); root.AddIntAttribute(ax::mojom::IntAttribute::kScrollXMax, 100); root.AddIntAttribute(ax::mojom::IntAttribute::kScrollY, 60); root.AddIntAttribute(ax::mojom::IntAttribute::kScrollYMin, 10); root.AddIntAttribute(ax::mojom::IntAttribute::kScrollYMax, 60); Init(root); ComPtr<IScrollProvider> scroll_provider = QueryInterfaceFromNode<IScrollProvider>(GetRootAsAXNode()); double x_scroll_percent; double y_scroll_percent; // Set x scroll percent: 0%, y scroll percent: 0%. // Expected x scroll percent: 0%, y scroll percent: 0%. EXPECT_HRESULT_SUCCEEDED(scroll_provider->SetScrollPercent(0, 0)); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_HorizontalScrollPercent(&x_scroll_percent)); EXPECT_EQ(x_scroll_percent, 0); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_VerticalScrollPercent(&y_scroll_percent)); EXPECT_EQ(y_scroll_percent, 0); // Set x scroll percent: 100%, y scroll percent: 100%. // Expected x scroll percent: 100%, y scroll percent: 100%. EXPECT_HRESULT_SUCCEEDED(scroll_provider->SetScrollPercent(100, 100)); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_HorizontalScrollPercent(&x_scroll_percent)); EXPECT_EQ(x_scroll_percent, 100); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_VerticalScrollPercent(&y_scroll_percent)); EXPECT_EQ(y_scroll_percent, 100); // Set x scroll percent: 500%, y scroll percent: 600%. // Expected x scroll percent: 100%, y scroll percent: 100%. EXPECT_HRESULT_SUCCEEDED(scroll_provider->SetScrollPercent(500, 600)); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_HorizontalScrollPercent(&x_scroll_percent)); EXPECT_EQ(x_scroll_percent, 100); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_VerticalScrollPercent(&y_scroll_percent)); EXPECT_EQ(y_scroll_percent, 100); // Set x scroll percent: -100%, y scroll percent: -200%. // Expected x scroll percent: 0%, y scroll percent: 0%. EXPECT_HRESULT_SUCCEEDED(scroll_provider->SetScrollPercent(-100, -200)); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_HorizontalScrollPercent(&x_scroll_percent)); EXPECT_EQ(x_scroll_percent, 0); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_VerticalScrollPercent(&y_scroll_percent)); EXPECT_EQ(y_scroll_percent, 0); // Set x scroll percent: 12%, y scroll percent: 34%. // Expected x scroll percent: 12%, y scroll percent: 34%. EXPECT_HRESULT_SUCCEEDED(scroll_provider->SetScrollPercent(12, 34)); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_HorizontalScrollPercent(&x_scroll_percent)); EXPECT_EQ(x_scroll_percent, 12); EXPECT_HRESULT_SUCCEEDED( scroll_provider->get_VerticalScrollPercent(&y_scroll_percent)); EXPECT_EQ(y_scroll_percent, 34); } TEST_F(AXPlatformNodeWinTest, MojoEventToUIAPropertyTest) { AXNodeData root; root.id = 1; root.role = ax::mojom::Role::kCheckBox; root.AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int>(ax::mojom::CheckedState::kMixed)); Init(root); ComPtr<AXPlatformNodeWin> platform_node = QueryInterfaceFromNode<AXPlatformNodeWin>(GetRootAsAXNode()); EXPECT_EQ( platform_node->MojoEventToUIAProperty(ax::mojom::Event::kValueChanged), UIA_ToggleToggleStatePropertyId); } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_platform_node_win_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_win_unittest.cc", "repo_id": "engine", "token_count": 77539 }
399
// 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_tree_manager.h" #include "ax_node.h" #include "ax_tree_data.h" #include "ax_tree_manager_map.h" namespace ui { TestAXTreeManager::TestAXTreeManager() = default; TestAXTreeManager::TestAXTreeManager(std::unique_ptr<AXTree> tree) : tree_(std::move(tree)) { AXTreeManagerMap::GetInstance().AddTreeManager(GetTreeID(), this); } TestAXTreeManager::~TestAXTreeManager() { if (tree_) AXTreeManagerMap::GetInstance().RemoveTreeManager(GetTreeID()); } void TestAXTreeManager::DestroyTree() { if (!tree_) return; AXTreeManagerMap::GetInstance().RemoveTreeManager(GetTreeID()); tree_.reset(); } AXTree* TestAXTreeManager::GetTree() const { if (!tree_) { BASE_LOG() << "Did you forget to call SetTree?"; BASE_UNREACHABLE(); } return tree_.get(); } void TestAXTreeManager::SetTree(std::unique_ptr<AXTree> tree) { if (tree_) AXTreeManagerMap::GetInstance().RemoveTreeManager(GetTreeID()); tree_ = std::move(tree); AXTreeManagerMap::GetInstance().AddTreeManager(GetTreeID(), this); } AXNode* TestAXTreeManager::GetNodeFromTree(const AXTreeID tree_id, const AXNode::AXID node_id) const { return (tree_ && GetTreeID() == tree_id) ? tree_->GetFromId(node_id) : nullptr; } AXNode* TestAXTreeManager::GetNodeFromTree(const AXNode::AXID node_id) const { return tree_ ? tree_->GetFromId(node_id) : nullptr; } AXTreeID TestAXTreeManager::GetTreeID() const { return tree_ ? tree_->data().tree_id : AXTreeIDUnknown(); } AXTreeID TestAXTreeManager::GetParentTreeID() const { return AXTreeIDUnknown(); } AXNode* TestAXTreeManager::GetRootAsAXNode() const { return tree_ ? tree_->root() : nullptr; } AXNode* TestAXTreeManager::GetParentNodeFromParentTreeAsAXNode() const { return nullptr; } } // namespace ui
engine/third_party/accessibility/ax/test_ax_tree_manager.cc/0
{ "file_path": "engine/third_party/accessibility/ax/test_ax_tree_manager.cc", "repo_id": "engine", "token_count": 787 }
400
# `base/numerics` This directory contains a dependency-free, header-only library of templates providing well-defined semantics for safely and performantly handling a variety of numeric operations, including most common arithmetic operations and conversions. The public API is broken out into the following header files: * `checked_math.h` contains the `CheckedNumeric` template class and helper functions for performing arithmetic and conversion operations that detect errors and boundary conditions (e.g. overflow, truncation, etc.). * `clamped_math.h` contains the `ClampedNumeric` template class and helper functions for performing fast, clamped (i.e. [non-sticky](#notsticky) saturating) arithmetic operations and conversions. * `safe_conversions.h` contains the `StrictNumeric` template class and a collection of custom casting templates and helper functions for safely converting between a range of numeric types. * `safe_math.h` includes all of the previously mentioned headers. *** aside **Note:** The `Numeric` template types implicitly convert from C numeric types and `Numeric` templates that are convertable to an underlying C numeric type. The conversion priority for `Numeric` type coercions is: * `StrictNumeric` coerces to `ClampedNumeric` and `CheckedNumeric` * `ClampedNumeric` coerces to `CheckedNumeric` *** [TOC] ## Common patterns and use-cases The following covers the preferred style for the most common uses of this library. Please don't cargo-cult from anywhere else. 😉 ### Performing checked arithmetic type conversions The `checked_cast` template converts between arbitrary arithmetic types, and is used for cases where a conversion failure should result in program termination: ```cpp // Crash if signed_value is out of range for buff_size. size_t buff_size = checked_cast<size_t>(signed_value); ``` ### Performing saturated (clamped) arithmetic type conversions The `saturated_cast` template converts between arbitrary arithmetic types, and is used in cases where an out-of-bounds source value should be saturated to the corresponding maximum or minimum of the destination type: ```cpp // Cast to a smaller type, saturating as needed. int8_t eight_bit_value = saturated_cast<int8_t>(int_value); // Convert from float with saturation to INT_MAX, INT_MIN, or 0 for NaN. int int_value = saturated_cast<int>(floating_point_value); ``` `ClampCeil`, `ClampFloor`, and `ClampRound` provide similar functionality to the versions in `std::`, but saturate and return an integral type. An optional template parameter specifies the desired destination type (`int` if unspecified). These should be used for most floating-to-integral conversions. ```cpp // Basically saturated_cast<int>(std::round(floating_point_value)). int int_value = ClampRound(floating_point_value); // A destination type can be explicitly specified. uint8_t byte_value = ClampFloor<uint8_t>(floating_point_value); ``` ### Enforcing arithmetic type conversions at compile-time The `strict_cast` emits code that is identical to `static_cast`. However, provides static checks that will cause a compilation failure if the destination type cannot represent the full range of the source type: ```cpp // Throw a compiler error if byte_value is changed to an out-of-range-type. int int_value = strict_cast<int>(byte_value); ``` You can also enforce these compile-time restrictions on function parameters by using the `StrictNumeric` template: ```cpp // Throw a compiler error if the size argument cannot be represented by a // size_t (e.g. passing an int will fail to compile). bool AllocateBuffer(void** buffer, StrictCast<size_t> size); ``` ### Comparing values between arbitrary arithmetic types Both the `StrictNumeric` and `ClampedNumeric` types provide well defined comparisons between arbitrary arithmetic types. This allows you to perform comparisons that are not legal or would trigger compiler warnings or errors under the normal arithmetic promotion rules: ```cpp bool foo(unsigned value, int upper_bound) { // Converting to StrictNumeric allows this comparison to work correctly. if (MakeStrictNum(value) >= upper_bound) return false; ``` *** note **Warning:** Do not perform manual conversions using the comparison operators. Instead, use the cast templates described in the previous sections, or the constexpr template functions `IsValueInRangeForNumericType` and `IsTypeInRangeForNumericType`, as these templates properly handle the full range of corner cases and employ various optimizations. *** ### Calculating a buffer size (checked arithmetic) When making exact calculations—such as for buffer lengths—it's often necessary to know when those calculations trigger an overflow, undefined behavior, or other boundary conditions. The `CheckedNumeric` template does this by storing a bit determining whether or not some arithmetic operation has occurred that would put the variable in an "invalid" state. Attempting to extract the value from a variable in an invalid state will trigger a check/trap condition, that by default will result in process termination. Here's an example of a buffer calculation using a `CheckedNumeric` type (note: the AssignIfValid method will trigger a compile error if the result is ignored). ```cpp // Calculate the buffer size and detect if an overflow occurs. size_t size; if (!CheckAdd(kHeaderSize, CheckMul(count, kItemSize)).AssignIfValid(&size)) { // Handle an overflow error... } ``` ### Calculating clamped coordinates (non-sticky saturating arithmetic) Certain classes of calculations—such as coordinate calculations—require well-defined semantics that always produce a valid result on boundary conditions. The `ClampedNumeric` template addresses this by providing performant, non-sticky saturating arithmetic operations. Here's an example of using a `ClampedNumeric` to calculate an operation insetting a rectangle. ```cpp // Use clamped arithmetic since inset calculations might overflow. void Rect::Inset(int left, int top, int right, int bottom) { origin_ += Vector2d(left, top); set_width(ClampSub(width(), ClampAdd(left, right))); set_height(ClampSub(height(), ClampAdd(top, bottom))); } ``` *** note <a name="notsticky"></a> The `ClampedNumeric` type is not "sticky", which means the saturation is not retained across individual operations. As such, one arithmetic operation may result in a saturated value, while the next operation may then "desaturate" the value. Here's an example: ```cpp ClampedNumeric<int> value = INT_MAX; ++value; // value is still INT_MAX, due to saturation. --value; // value is now (INT_MAX - 1), because saturation is not sticky. ``` *** ## Conversion functions and StrictNumeric<> in safe_conversions.h This header includes a collection of helper `constexpr` templates for safely performing a range of conversions, assignments, and tests. ### Safe casting templates * `as_signed()` - Returns the supplied integral value as a signed type of the same width. * `as_unsigned()` - Returns the supplied integral value as an unsigned type of the same width. * `checked_cast<>()` - Analogous to `static_cast<>` for numeric types, except that by default it will trigger a crash on an out-of-bounds conversion (e.g. overflow, underflow, NaN to integral) or a compile error if the conversion error can be detected at compile time. The crash handler can be overridden to perform a behavior other than crashing. * `saturated_cast<>()` - Analogous to `static_cast` for numeric types, except that it returns a saturated result when the specified numeric conversion would otherwise overflow or underflow. An NaN source returns 0 by default, but can be overridden to return a different result. * `strict_cast<>()` - Analogous to `static_cast` for numeric types, except this causes a compile failure if the destination type is not large enough to contain any value in the source type. It performs no runtime checking and thus introduces no runtime overhead. ### Other helper and conversion functions * `ClampCeil<>()` - A convenience function that computes the ceil of its floating- point arg, then saturates to the destination type (template parameter, defaults to `int`). * `ClampFloor<>()` - A convenience function that computes the floor of its floating-point arg, then saturates to the destination type (template parameter, defaults to `int`). * `IsTypeInRangeForNumericType<>()` - A convenience function that evaluates entirely at compile-time and returns true if the destination type (first template parameter) can represent the full range of the source type (second template parameter). * `IsValueInRangeForNumericType<>()` - A convenience function that returns true if the type supplied as the template parameter can represent the value passed as an argument to the function. * `IsValueNegative()` - A convenience function that will accept any arithmetic type as an argument and will return whether the value is less than zero. Unsigned types always return false. * `ClampRound<>()` - A convenience function that rounds its floating-point arg, then saturates to the destination type (template parameter, defaults to `int`). * `SafeUnsignedAbs()` - Returns the absolute value of the supplied integer parameter as an unsigned result (thus avoiding an overflow if the value is the signed, two's complement minimum). ### StrictNumeric<> `StrictNumeric<>` is a wrapper type that performs assignments and copies via the `strict_cast` template, and can perform valid arithmetic comparisons across any range of arithmetic types. `StrictNumeric` is the return type for values extracted from a `CheckedNumeric` class instance. The raw numeric value is extracted via `static_cast` to the underlying type or any type with sufficient range to represent the underlying type. * `MakeStrictNum()` - Creates a new `StrictNumeric` from the underlying type of the supplied arithmetic or StrictNumeric type. * `SizeT` - Alias for `StrictNumeric<size_t>`. ## CheckedNumeric<> in checked_math.h `CheckedNumeric<>` implements all the logic and operators for detecting integer boundary conditions such as overflow, underflow, and invalid conversions. The `CheckedNumeric` type implicitly converts from floating point and integer data types, and contains overloads for basic arithmetic operations (i.e.: `+`, `-`, `*`, `/` for all types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers). However, *the [variadic template functions ](#CheckedNumeric_in-checked_math_h-Non_member-helper-functions) are the preferred API,* as they remove type ambiguities and help prevent a number of common errors. The variadic functions can also be more performant, as they eliminate redundant expressions that are unavoidable with the with the operator overloads. (Ideally the compiler should optimize those away, but better to avoid them in the first place.) Type promotions are a slightly modified version of the [standard C/C++ numeric promotions ](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions) with the two differences being that *there is no default promotion to int* and *bitwise logical operations always return an unsigned of the wider type.* ### Example ``` #include "base/numerics/checked_math.h" ... CheckedNumeric<uint32_t> variable = 0; variable++; variable--; if (variable.ValueOrDie() == 0) // Fine, |variable| still within valid range. variable--; variable++; if (variable.ValueOrDie() == 0) // Breakpoint or configured CheckHandler // Does not happen as variable underflowed. ``` ### Members The unary negation, increment, and decrement operators are supported, along with the following unary arithmetic methods, which return a new `CheckedNumeric` as a result of the operation: * `Abs()` - Absolute value. * `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type (valid for only integral types). * `Max()` - Returns whichever is greater of the current instance or argument. The underlying return type is whichever has the greatest magnitude. * `Min()` - Returns whichever is lowest of the current instance or argument. The underlying return type is whichever has can represent the lowest number in the smallest width (e.g. int8_t over unsigned, int over int8_t, and float over int). The following are for converting `CheckedNumeric` instances: * `type` - The underlying numeric type. * `AssignIfValid()` - Assigns the underlying value to the supplied destination pointer if the value is currently valid and within the range supported by the destination type. Returns true on success. * `Cast<>()` - Instance method returning a `CheckedNumeric` derived from casting the current instance to a `CheckedNumeric` of the supplied destination type. *** aside The following member functions return a `StrictNumeric`, which is valid for comparison and assignment operations, but will trigger a compile failure on attempts to assign to a type of insufficient range. The underlying value can be extracted by an explicit `static_cast` to the underlying type or any type with sufficient range to represent the underlying type. *** * `IsValid()` - Returns true if the underlying numeric value is valid (i.e. has not wrapped or saturated and is not the result of an invalid conversion). * `ValueOrDie()` - Returns the underlying value. If the state is not valid this call will trigger a crash by default (but may be overridden by supplying an alternate handler to the template). * `ValueOrDefault()` - Returns the current value, or the supplied default if the state is not valid (but will not crash). **Comparison operators are explicitly not provided** for `CheckedNumeric` types because they could result in a crash if the type is not in a valid state. Patterns like the following should be used instead: ```cpp // Either input or padding (or both) may be arbitrary sizes. size_t buff_size; if (!CheckAdd(input, padding, kHeaderLength).AssignIfValid(&buff_size) || buff_size >= kMaxBuffer) { // Handle an error... } else { // Do stuff on success... } ``` ### Non-member helper functions The following variadic convenience functions, which accept standard arithmetic or `CheckedNumeric` types, perform arithmetic operations, and return a `CheckedNumeric` result. The supported functions are: * `CheckAdd()` - Addition. * `CheckSub()` - Subtraction. * `CheckMul()` - Multiplication. * `CheckDiv()` - Division. * `CheckMod()` - Modulus (integer only). * `CheckLsh()` - Left integer shift (integer only). * `CheckRsh()` - Right integer shift (integer only). * `CheckAnd()` - Bitwise AND (integer only with unsigned result). * `CheckOr()` - Bitwise OR (integer only with unsigned result). * `CheckXor()` - Bitwise XOR (integer only with unsigned result). * `CheckMax()` - Maximum of supplied arguments. * `CheckMin()` - Minimum of supplied arguments. The following wrapper functions can be used to avoid the template disambiguator syntax when converting a destination type. * `IsValidForType<>()` in place of: `a.template IsValid<>()` * `ValueOrDieForType<>()` in place of: `a.template ValueOrDie<>()` * `ValueOrDefaultForType<>()` in place of: `a.template ValueOrDefault<>()` The following general utility methods is are useful for converting from arithmetic types to `CheckedNumeric` types: * `MakeCheckedNum()` - Creates a new `CheckedNumeric` from the underlying type of the supplied arithmetic or directly convertible type. ## ClampedNumeric<> in clamped_math.h `ClampedNumeric<>` implements all the logic and operators for clamped (non-sticky saturating) arithmetic operations and conversions. The `ClampedNumeric` type implicitly converts back and forth between floating point and integer data types, saturating on assignment as appropriate. It contains overloads for basic arithmetic operations (i.e.: `+`, `-`, `*`, `/` for all types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers) along with comparison operators for arithmetic types of any size. However, *the [variadic template functions ](#ClampedNumeric_in-clamped_math_h-Non_member-helper-functions) are the preferred API,* as they remove type ambiguities and help prevent a number of common errors. The variadic functions can also be more performant, as they eliminate redundant expressions that are unavoidable with the operator overloads. (Ideally the compiler should optimize those away, but better to avoid them in the first place.) Type promotions are a slightly modified version of the [standard C/C++ numeric promotions ](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions) with the two differences being that *there is no default promotion to int* and *bitwise logical operations always return an unsigned of the wider type.* *** aside Most arithmetic operations saturate normally, to the numeric limit in the direction of the sign. The potentially unusual cases are: * **Division:** Division by zero returns the saturated limit in the direction of sign of the dividend (first argument). The one exception is 0/0, which returns zero (although logically is NaN). * **Modulus:** Division by zero returns the dividend (first argument). * **Left shift:** Non-zero values saturate in the direction of the signed limit (max/min), even for shifts larger than the bit width. 0 shifted any amount results in 0. * **Right shift:** Negative values saturate to -1. Positive or 0 saturates to 0. (Effectively just an unbounded arithmetic-right-shift.) * **Bitwise operations:** No saturation; bit pattern is identical to non-saturated bitwise operations. *** ### Members The unary negation, increment, and decrement operators are supported, along with the following unary arithmetic methods, which return a new `ClampedNumeric` as a result of the operation: * `Abs()` - Absolute value. * `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type (valid for only integral types). * `Max()` - Returns whichever is greater of the current instance or argument. The underlying return type is whichever has the greatest magnitude. * `Min()` - Returns whichever is lowest of the current instance or argument. The underlying return type is whichever has can represent the lowest number in the smallest width (e.g. int8_t over unsigned, int over int8_t, and float over int). The following are for converting `ClampedNumeric` instances: * `type` - The underlying numeric type. * `RawValue()` - Returns the raw value as the underlying arithmetic type. This is useful when e.g. assigning to an auto type or passing as a deduced template parameter. * `Cast<>()` - Instance method returning a `ClampedNumeric` derived from casting the current instance to a `ClampedNumeric` of the supplied destination type. ### Non-member helper functions The following variadic convenience functions, which accept standard arithmetic or `ClampedNumeric` types, perform arithmetic operations, and return a `ClampedNumeric` result. The supported functions are: * `ClampAdd()` - Addition. * `ClampSub()` - Subtraction. * `ClampMul()` - Multiplication. * `ClampDiv()` - Division. * `ClampMod()` - Modulus (integer only). * `ClampLsh()` - Left integer shift (integer only). * `ClampRsh()` - Right integer shift (integer only). * `ClampAnd()` - Bitwise AND (integer only with unsigned result). * `ClampOr()` - Bitwise OR (integer only with unsigned result). * `ClampXor()` - Bitwise XOR (integer only with unsigned result). * `ClampMax()` - Maximum of supplied arguments. * `ClampMin()` - Minimum of supplied arguments. The following is a general utility method that is useful for converting to a `ClampedNumeric` type: * `MakeClampedNum()` - Creates a new `ClampedNumeric` from the underlying type of the supplied arithmetic or directly convertible type.
engine/third_party/accessibility/base/numerics/README.md/0
{ "file_path": "engine/third_party/accessibility/base/numerics/README.md", "repo_id": "engine", "token_count": 5463 }
401
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "simple_token.h" #include <ostream> #include <random> namespace base { constexpr size_t kRandomTokenLength = 10; SimpleToken::SimpleToken(const std::string& token) : token_(token) {} // static SimpleToken SimpleToken::Create() { const char charset[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; const size_t max_index = (sizeof(charset) - 1); std::string str; for (size_t i = 0; i < kRandomTokenLength; i++) { str.push_back(charset[rand() % max_index]); } return SimpleToken(str); } std::ostream& operator<<(std::ostream& out, const SimpleToken& token) { return out << "(" << token.ToString() << ")"; } std::optional<base::SimpleToken> ValueToSimpleToken(std::string str) { return std::make_optional<base::SimpleToken>(str); } std::string SimpleTokenToValue(const SimpleToken& token) { return token.ToString(); } size_t SimpleTokenHash(const SimpleToken& SimpleToken) { return std::hash<std::string>()(SimpleToken.ToString()); } } // namespace base
engine/third_party/accessibility/base/simple_token.cc/0
{ "file_path": "engine/third_party/accessibility/base/simple_token.cc", "repo_id": "engine", "token_count": 424 }
402
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/win/scoped_bstr.h" #include <cstdint> #include "base/logging.h" #include "base/numerics/safe_conversions.h" namespace base { namespace win { namespace { BSTR AllocBstrOrDie(std::wstring_view non_bstr) { BSTR result = ::SysAllocStringLen(non_bstr.data(), checked_cast<UINT>(non_bstr.length())); if (!result) std::abort(); return result; } BSTR AllocBstrBytesOrDie(size_t bytes) { BSTR result = ::SysAllocStringByteLen(nullptr, checked_cast<UINT>(bytes)); if (!result) std::abort(); return result; } } // namespace ScopedBstr::ScopedBstr(std::wstring_view non_bstr) : bstr_(AllocBstrOrDie(non_bstr)) {} ScopedBstr::~ScopedBstr() { static_assert(sizeof(ScopedBstr) == sizeof(BSTR), "ScopedBstrSize"); ::SysFreeString(bstr_); } void ScopedBstr::Reset(BSTR bstr) { if (bstr != bstr_) { // SysFreeString handles null properly. ::SysFreeString(bstr_); bstr_ = bstr; } } BSTR ScopedBstr::Release() { BSTR bstr = bstr_; bstr_ = nullptr; return bstr; } void ScopedBstr::Swap(ScopedBstr& bstr2) { BSTR tmp = bstr_; bstr_ = bstr2.bstr_; bstr2.bstr_ = tmp; } BSTR* ScopedBstr::Receive() { BASE_DCHECK(!bstr_) << "BSTR leak."; return &bstr_; } BSTR ScopedBstr::Allocate(std::wstring_view str) { Reset(AllocBstrOrDie(str)); return bstr_; } BSTR ScopedBstr::AllocateBytes(size_t bytes) { Reset(AllocBstrBytesOrDie(bytes)); return bstr_; } void ScopedBstr::SetByteLen(size_t bytes) { BASE_DCHECK(bstr_); uint32_t* data = reinterpret_cast<uint32_t*>(bstr_); data[-1] = checked_cast<uint32_t>(bytes); } size_t ScopedBstr::Length() const { return ::SysStringLen(bstr_); } size_t ScopedBstr::ByteLength() const { return ::SysStringByteLen(bstr_); } } // namespace win } // namespace base
engine/third_party/accessibility/base/win/scoped_bstr.cc/0
{ "file_path": "engine/third_party/accessibility/base/win/scoped_bstr.cc", "repo_id": "engine", "token_count": 844 }
403
// 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 "insets_f.h" #include "base/string_utils.h" namespace gfx { std::string InsetsF::ToString() const { // Print members in the same order of the constructor parameters. return base::StringPrintf("%f,%f,%f,%f", top(), left(), bottom(), right()); } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/insets_f.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/insets_f.cc", "repo_id": "engine", "token_count": 143 }
404
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstddef> #include <limits> #include "ax_build/build_config.h" #include "gfx/test/gfx_util.h" #include "gtest/gtest.h" #include "rect.h" #include "rect_conversions.h" #if defined(OS_WIN) #include <windows.h> #endif namespace gfx { template <typename T, size_t N> constexpr size_t size(const T (&array)[N]) noexcept { return N; } TEST(RectTest, Contains) { static const struct ContainsCase { int rect_x; int rect_y; int rect_width; int rect_height; int point_x; int point_y; bool contained; } contains_cases[] = { {0, 0, 10, 10, 0, 0, true}, {0, 0, 10, 10, 5, 5, true}, {0, 0, 10, 10, 9, 9, true}, {0, 0, 10, 10, 5, 10, false}, {0, 0, 10, 10, 10, 5, false}, {0, 0, 10, 10, -1, -1, false}, {0, 0, 10, 10, 50, 50, false}, #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) {0, 0, -10, -10, 0, 0, false}, #endif }; for (size_t i = 0; i < size(contains_cases); ++i) { const ContainsCase& value = contains_cases[i]; Rect rect(value.rect_x, value.rect_y, value.rect_width, value.rect_height); EXPECT_EQ(value.contained, rect.Contains(value.point_x, value.point_y)); } } TEST(RectTest, Intersects) { static const struct { int x1; // rect 1 int y1; int w1; int h1; int x2; // rect 2 int y2; int w2; int h2; bool intersects; } tests[] = {{0, 0, 0, 0, 0, 0, 0, 0, false}, {0, 0, 0, 0, -10, -10, 20, 20, false}, {-10, 0, 0, 20, 0, -10, 20, 0, false}, {0, 0, 10, 10, 0, 0, 10, 10, true}, {0, 0, 10, 10, 10, 10, 10, 10, false}, {10, 10, 10, 10, 0, 0, 10, 10, false}, {10, 10, 10, 10, 5, 5, 10, 10, true}, {10, 10, 10, 10, 15, 15, 10, 10, true}, {10, 10, 10, 10, 20, 15, 10, 10, false}, {10, 10, 10, 10, 21, 15, 10, 10, false}}; for (size_t i = 0; i < size(tests); ++i) { Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); EXPECT_EQ(tests[i].intersects, r1.Intersects(r2)); EXPECT_EQ(tests[i].intersects, r2.Intersects(r1)); } } TEST(RectTest, Intersect) { static const struct { int x1; // rect 1 int y1; int w1; int h1; int x2; // rect 2 int y2; int w2; int h2; int x3; // rect 3: the union of rects 1 and 2 int y3; int w3; int h3; } tests[] = {{0, 0, 0, 0, // zeros 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 4, 4, // equal 0, 0, 4, 4, 0, 0, 4, 4}, {0, 0, 4, 4, // neighboring 4, 4, 4, 4, 0, 0, 0, 0}, {0, 0, 4, 4, // overlapping corners 2, 2, 4, 4, 2, 2, 2, 2}, {0, 0, 4, 4, // T junction 3, 1, 4, 2, 3, 1, 1, 2}, {3, 0, 2, 2, // gap 0, 0, 2, 2, 0, 0, 0, 0}}; for (size_t i = 0; i < size(tests); ++i) { Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); Rect r3(tests[i].x3, tests[i].y3, tests[i].w3, tests[i].h3); Rect ir = IntersectRects(r1, r2); EXPECT_EQ(r3.x(), ir.x()); EXPECT_EQ(r3.y(), ir.y()); EXPECT_EQ(r3.width(), ir.width()); EXPECT_EQ(r3.height(), ir.height()); } } TEST(RectTest, Union) { static const struct Test { int x1; // rect 1 int y1; int w1; int h1; int x2; // rect 2 int y2; int w2; int h2; int x3; // rect 3: the union of rects 1 and 2 int y3; int w3; int h3; } tests[] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 4, 4, 0, 0, 4, 4, 0, 0, 4, 4}, {0, 0, 4, 4, 4, 4, 4, 4, 0, 0, 8, 8}, {0, 0, 4, 4, 0, 5, 4, 4, 0, 0, 4, 9}, {0, 0, 2, 2, 3, 3, 2, 2, 0, 0, 5, 5}, {3, 3, 2, 2, // reverse r1 and r2 from previous test 0, 0, 2, 2, 0, 0, 5, 5}, {0, 0, 0, 0, // union with empty rect 2, 2, 2, 2, 2, 2, 2, 2}}; for (size_t i = 0; i < size(tests); ++i) { Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); Rect r3(tests[i].x3, tests[i].y3, tests[i].w3, tests[i].h3); Rect u = UnionRects(r1, r2); EXPECT_EQ(r3.x(), u.x()); EXPECT_EQ(r3.y(), u.y()); EXPECT_EQ(r3.width(), u.width()); EXPECT_EQ(r3.height(), u.height()); } } TEST(RectTest, Equals) { ASSERT_TRUE(Rect(0, 0, 0, 0) == Rect(0, 0, 0, 0)); ASSERT_TRUE(Rect(1, 2, 3, 4) == Rect(1, 2, 3, 4)); ASSERT_FALSE(Rect(0, 0, 0, 0) == Rect(0, 0, 0, 1)); ASSERT_FALSE(Rect(0, 0, 0, 0) == Rect(0, 0, 1, 0)); ASSERT_FALSE(Rect(0, 0, 0, 0) == Rect(0, 1, 0, 0)); ASSERT_FALSE(Rect(0, 0, 0, 0) == Rect(1, 0, 0, 0)); } TEST(RectTest, AdjustToFit) { static const struct Test { int x1; // source int y1; int w1; int h1; int x2; // target int y2; int w2; int h2; int x3; // rect 3: results of invoking AdjustToFit int y3; int w3; int h3; } tests[] = {{0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2}, {2, 2, 3, 3, 0, 0, 4, 4, 1, 1, 3, 3}, {-1, -1, 5, 5, 0, 0, 4, 4, 0, 0, 4, 4}, {2, 2, 4, 4, 0, 0, 3, 3, 0, 0, 3, 3}, {2, 2, 1, 1, 0, 0, 3, 3, 2, 2, 1, 1}}; for (size_t i = 0; i < size(tests); ++i) { Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); Rect r3(tests[i].x3, tests[i].y3, tests[i].w3, tests[i].h3); Rect u = r1; u.AdjustToFit(r2); EXPECT_EQ(r3.x(), u.x()); EXPECT_EQ(r3.y(), u.y()); EXPECT_EQ(r3.width(), u.width()); EXPECT_EQ(r3.height(), u.height()); } } TEST(RectTest, Subtract) { Rect result; // Matching result = Rect(10, 10, 20, 20); result.Subtract(Rect(10, 10, 20, 20)); EXPECT_EQ(Rect(0, 0, 0, 0), result); // Contains result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 5, 30, 30)); EXPECT_EQ(Rect(0, 0, 0, 0), result); // No intersection result = Rect(10, 10, 20, 20); result.Subtract(Rect(30, 30, 30, 30)); EXPECT_EQ(Rect(10, 10, 20, 20), result); // Not a complete intersection in either direction result = Rect(10, 10, 20, 20); result.Subtract(Rect(15, 15, 20, 20)); EXPECT_EQ(Rect(10, 10, 20, 20), result); // Complete intersection in the x-direction, top edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(10, 15, 20, 20)); EXPECT_EQ(Rect(10, 10, 20, 5), result); // Complete intersection in the x-direction, top edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 15, 30, 20)); EXPECT_EQ(Rect(10, 10, 20, 5), result); // Complete intersection in the x-direction, bottom edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 5, 30, 20)); EXPECT_EQ(Rect(10, 25, 20, 5), result); // Complete intersection in the x-direction, none of the edges is fully // covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 15, 30, 1)); EXPECT_EQ(Rect(10, 10, 20, 20), result); // Complete intersection in the y-direction, left edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(10, 10, 10, 30)); EXPECT_EQ(Rect(20, 10, 10, 20), result); // Complete intersection in the y-direction, left edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(5, 5, 20, 30)); EXPECT_EQ(Rect(25, 10, 5, 20), result); // Complete intersection in the y-direction, right edge is fully covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(20, 5, 20, 30)); EXPECT_EQ(Rect(10, 10, 10, 20), result); // Complete intersection in the y-direction, none of the edges is fully // covered. result = Rect(10, 10, 20, 20); result.Subtract(Rect(15, 5, 1, 30)); EXPECT_EQ(Rect(10, 10, 20, 20), result); } TEST(RectTest, IsEmpty) { EXPECT_TRUE(Rect(0, 0, 0, 0).IsEmpty()); EXPECT_TRUE(Rect(0, 0, 0, 0).size().IsEmpty()); EXPECT_TRUE(Rect(0, 0, 10, 0).IsEmpty()); EXPECT_TRUE(Rect(0, 0, 10, 0).size().IsEmpty()); EXPECT_TRUE(Rect(0, 0, 0, 10).IsEmpty()); EXPECT_TRUE(Rect(0, 0, 0, 10).size().IsEmpty()); EXPECT_FALSE(Rect(0, 0, 10, 10).IsEmpty()); EXPECT_FALSE(Rect(0, 0, 10, 10).size().IsEmpty()); } TEST(RectTest, SplitVertically) { Rect left_half, right_half; // Splitting when origin is (0, 0). Rect(0, 0, 20, 20).SplitVertically(&left_half, &right_half); EXPECT_TRUE(left_half == Rect(0, 0, 10, 20)); EXPECT_TRUE(right_half == Rect(10, 0, 10, 20)); // Splitting when origin is arbitrary. Rect(10, 10, 20, 10).SplitVertically(&left_half, &right_half); EXPECT_TRUE(left_half == Rect(10, 10, 10, 10)); EXPECT_TRUE(right_half == Rect(20, 10, 10, 10)); // Splitting a rectangle of zero width. Rect(10, 10, 0, 10).SplitVertically(&left_half, &right_half); EXPECT_TRUE(left_half == Rect(10, 10, 0, 10)); EXPECT_TRUE(right_half == Rect(10, 10, 0, 10)); // Splitting a rectangle of odd width. Rect(10, 10, 5, 10).SplitVertically(&left_half, &right_half); EXPECT_TRUE(left_half == Rect(10, 10, 2, 10)); EXPECT_TRUE(right_half == Rect(12, 10, 3, 10)); } TEST(RectTest, CenterPoint) { Point center; // When origin is (0, 0). center = Rect(0, 0, 20, 20).CenterPoint(); EXPECT_TRUE(center == Point(10, 10)); // When origin is even. center = Rect(10, 10, 20, 20).CenterPoint(); EXPECT_TRUE(center == Point(20, 20)); // When origin is odd. center = Rect(11, 11, 20, 20).CenterPoint(); EXPECT_TRUE(center == Point(21, 21)); // When 0 width or height. center = Rect(10, 10, 0, 20).CenterPoint(); EXPECT_TRUE(center == Point(10, 20)); center = Rect(10, 10, 20, 0).CenterPoint(); EXPECT_TRUE(center == Point(20, 10)); // When an odd size. center = Rect(10, 10, 21, 21).CenterPoint(); EXPECT_TRUE(center == Point(20, 20)); // When an odd size and position. center = Rect(11, 11, 21, 21).CenterPoint(); EXPECT_TRUE(center == Point(21, 21)); } TEST(RectTest, CenterPointF) { PointF center; // When origin is (0, 0). center = RectF(0, 0, 20, 20).CenterPoint(); EXPECT_TRUE(center == PointF(10, 10)); // When origin is even. center = RectF(10, 10, 20, 20).CenterPoint(); EXPECT_TRUE(center == PointF(20, 20)); // When origin is odd. center = RectF(11, 11, 20, 20).CenterPoint(); EXPECT_TRUE(center == PointF(21, 21)); // When 0 width or height. center = RectF(10, 10, 0, 20).CenterPoint(); EXPECT_TRUE(center == PointF(10, 20)); center = RectF(10, 10, 20, 0).CenterPoint(); EXPECT_TRUE(center == PointF(20, 10)); // When an odd size. center = RectF(10, 10, 21, 21).CenterPoint(); EXPECT_TRUE(center == PointF(20.5f, 20.5f)); // When an odd size and position. center = RectF(11, 11, 21, 21).CenterPoint(); EXPECT_TRUE(center == PointF(21.5f, 21.5f)); } TEST(RectTest, SharesEdgeWith) { Rect r(2, 3, 4, 5); // Must be non-overlapping EXPECT_FALSE(r.SharesEdgeWith(r)); Rect just_above(2, 1, 4, 2); Rect just_below(2, 8, 4, 2); Rect just_left(0, 3, 2, 5); Rect just_right(6, 3, 2, 5); EXPECT_TRUE(r.SharesEdgeWith(just_above)); EXPECT_TRUE(r.SharesEdgeWith(just_below)); EXPECT_TRUE(r.SharesEdgeWith(just_left)); EXPECT_TRUE(r.SharesEdgeWith(just_right)); // Wrong placement Rect same_height_no_edge(0, 0, 1, 5); Rect same_width_no_edge(0, 0, 4, 1); EXPECT_FALSE(r.SharesEdgeWith(same_height_no_edge)); EXPECT_FALSE(r.SharesEdgeWith(same_width_no_edge)); Rect just_above_no_edge(2, 1, 5, 2); // too wide Rect just_below_no_edge(2, 8, 3, 2); // too narrow Rect just_left_no_edge(0, 3, 2, 6); // too tall Rect just_right_no_edge(6, 3, 2, 4); // too short EXPECT_FALSE(r.SharesEdgeWith(just_above_no_edge)); EXPECT_FALSE(r.SharesEdgeWith(just_below_no_edge)); EXPECT_FALSE(r.SharesEdgeWith(just_left_no_edge)); EXPECT_FALSE(r.SharesEdgeWith(just_right_no_edge)); } // Similar to EXPECT_FLOAT_EQ, but lets NaN equal NaN #define EXPECT_FLOAT_AND_NAN_EQ(a, b) \ { \ if (a == a || b == b) { \ EXPECT_FLOAT_EQ(a, b); \ } \ } TEST(RectTest, ScaleRect) { static const struct Test { int x1; // source int y1; int w1; int h1; float scale; float x2; // target float y2; float w2; float h2; } tests[] = { {3, 3, 3, 3, 1.5f, 4.5f, 4.5f, 4.5f, 4.5f}, {3, 3, 3, 3, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, {3, 3, 3, 3, std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN()}, {3, 3, 3, 3, std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max()}}; for (size_t i = 0; i < size(tests); ++i) { RectF r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); RectF r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); RectF scaled = ScaleRect(r1, tests[i].scale); EXPECT_FLOAT_AND_NAN_EQ(r2.x(), scaled.x()); EXPECT_FLOAT_AND_NAN_EQ(r2.y(), scaled.y()); EXPECT_FLOAT_AND_NAN_EQ(r2.width(), scaled.width()); EXPECT_FLOAT_AND_NAN_EQ(r2.height(), scaled.height()); } } TEST(RectTest, ToEnclosedRect) { static const int max_int = std::numeric_limits<int>::max(); static const int min_int = std::numeric_limits<int>::min(); static const float max_float = std::numeric_limits<float>::max(); static const float max_int_f = static_cast<float>(max_int); static const float min_int_f = static_cast<float>(min_int); static const struct Test { struct { float x; float y; float width; float height; } in; struct { int x; int y; int width; int height; } expected; } tests[] = { {{0.0f, 0.0f, 0.0f, 0.0f}, {0, 0, 0, 0}}, {{-1.5f, -1.5f, 3.0f, 3.0f}, {-1, -1, 2, 2}}, {{-1.5f, -1.5f, 3.5f, 3.5f}, {-1, -1, 3, 3}}, {{max_float, max_float, 2.0f, 2.0f}, {max_int, max_int, 0, 0}}, {{0.0f, 0.0f, max_float, max_float}, {0, 0, max_int, max_int}}, {{20000.5f, 20000.5f, 0.5f, 0.5f}, {20001, 20001, 0, 0}}, {{max_int_f, max_int_f, max_int_f, max_int_f}, {max_int, max_int, 0, 0}}, {{1.9999f, 2.0002f, 5.9998f, 6.0001f}, {2, 3, 5, 5}}, {{1.9999f, 2.0001f, 6.0002f, 5.9998f}, {2, 3, 6, 4}}, {{1.9998f, 2.0002f, 6.0001f, 5.9999f}, {2, 3, 5, 5}}}; for (size_t i = 0; i < size(tests); ++i) { RectF source(tests[i].in.x, tests[i].in.y, tests[i].in.width, tests[i].in.height); Rect enclosed = ToEnclosedRect(source); EXPECT_EQ(tests[i].expected.x, enclosed.x()); EXPECT_EQ(tests[i].expected.y, enclosed.y()); EXPECT_EQ(tests[i].expected.width, enclosed.width()); EXPECT_EQ(tests[i].expected.height, enclosed.height()); } { RectF source(min_int_f, min_int_f, max_int_f * 3.f, max_int_f * 3.f); Rect enclosed = ToEnclosedRect(source); // That rect can't be represented, but it should be big. EXPECT_EQ(max_int, enclosed.width()); EXPECT_EQ(max_int, enclosed.height()); // It should include some axis near the global origin. EXPECT_GT(1, enclosed.x()); EXPECT_GT(1, enclosed.y()); // And it should not cause computation issues for itself. EXPECT_LT(0, enclosed.right()); EXPECT_LT(0, enclosed.bottom()); } } TEST(RectTest, ToEnclosingRect) { static const int max_int = std::numeric_limits<int>::max(); static const int min_int = std::numeric_limits<int>::min(); static const float max_float = std::numeric_limits<float>::max(); static const float epsilon_float = std::numeric_limits<float>::epsilon(); static const float max_int_f = static_cast<float>(max_int); static const float min_int_f = static_cast<float>(min_int); static const struct Test { struct { float x; float y; float width; float height; } in; struct { int x; int y; int width; int height; } expected; } tests[] = { {{0.0f, 0.0f, 0.0f, 0.0f}, {0, 0, 0, 0}}, {{5.5f, 5.5f, 0.0f, 0.0f}, {5, 5, 0, 0}}, {{3.5f, 2.5f, epsilon_float, -0.0f}, {3, 2, 0, 0}}, {{3.5f, 2.5f, 0.f, 0.001f}, {3, 2, 0, 1}}, {{-1.5f, -1.5f, 3.0f, 3.0f}, {-2, -2, 4, 4}}, {{-1.5f, -1.5f, 3.5f, 3.5f}, {-2, -2, 4, 4}}, {{max_float, max_float, 2.0f, 2.0f}, {max_int, max_int, 0, 0}}, {{0.0f, 0.0f, max_float, max_float}, {0, 0, max_int, max_int}}, {{20000.5f, 20000.5f, 0.5f, 0.5f}, {20000, 20000, 1, 1}}, {{max_int_f, max_int_f, max_int_f, max_int_f}, {max_int, max_int, 0, 0}}, {{-0.5f, -0.5f, 22777712.f, 1.f}, {-1, -1, 22777713, 2}}, {{1.9999f, 2.0002f, 5.9998f, 6.0001f}, {1, 2, 7, 7}}, {{1.9999f, 2.0001f, 6.0002f, 5.9998f}, {1, 2, 8, 6}}, {{1.9998f, 2.0002f, 6.0001f, 5.9999f}, {1, 2, 7, 7}}}; for (size_t i = 0; i < size(tests); ++i) { RectF source(tests[i].in.x, tests[i].in.y, tests[i].in.width, tests[i].in.height); Rect enclosing = ToEnclosingRect(source); EXPECT_EQ(tests[i].expected.x, enclosing.x()); EXPECT_EQ(tests[i].expected.y, enclosing.y()); EXPECT_EQ(tests[i].expected.width, enclosing.width()); EXPECT_EQ(tests[i].expected.height, enclosing.height()); } { RectF source(min_int_f, min_int_f, max_int_f * 3.f, max_int_f * 3.f); Rect enclosing = ToEnclosingRect(source); // That rect can't be represented, but it should be big. EXPECT_EQ(max_int, enclosing.width()); EXPECT_EQ(max_int, enclosing.height()); // It should include some axis near the global origin. EXPECT_GT(1, enclosing.x()); EXPECT_GT(1, enclosing.y()); // And it should cause computation issues for itself. EXPECT_LT(0, enclosing.right()); EXPECT_LT(0, enclosing.bottom()); } } TEST(RectTest, ToEnclosingRectIgnoringError) { static const int max_int = std::numeric_limits<int>::max(); static const float max_float = std::numeric_limits<float>::max(); static const float epsilon_float = std::numeric_limits<float>::epsilon(); static const float max_int_f = static_cast<float>(max_int); static const float error = 0.001f; static const struct Test { struct { float x; float y; float width; float height; } in; struct { int x; int y; int width; int height; } expected; } tests[] = { {{0.0f, 0.0f, 0.0f, 0.0f}, {0, 0, 0, 0}}, {{5.5f, 5.5f, 0.0f, 0.0f}, {5, 5, 0, 0}}, {{3.5f, 2.5f, epsilon_float, -0.0f}, {3, 2, 0, 0}}, {{3.5f, 2.5f, 0.f, 0.001f}, {3, 2, 0, 1}}, {{-1.5f, -1.5f, 3.0f, 3.0f}, {-2, -2, 4, 4}}, {{-1.5f, -1.5f, 3.5f, 3.5f}, {-2, -2, 4, 4}}, {{max_float, max_float, 2.0f, 2.0f}, {max_int, max_int, 0, 0}}, {{0.0f, 0.0f, max_float, max_float}, {0, 0, max_int, max_int}}, {{20000.5f, 20000.5f, 0.5f, 0.5f}, {20000, 20000, 1, 1}}, {{max_int_f, max_int_f, max_int_f, max_int_f}, {max_int, max_int, 0, 0}}, {{-0.5f, -0.5f, 22777712.f, 1.f}, {-1, -1, 22777713, 2}}, {{1.9999f, 2.0002f, 5.9998f, 6.0001f}, {2, 2, 6, 6}}, {{1.9999f, 2.0001f, 6.0002f, 5.9998f}, {2, 2, 6, 6}}, {{1.9998f, 2.0002f, 6.0001f, 5.9999f}, {2, 2, 6, 6}}}; for (size_t i = 0; i < size(tests); ++i) { RectF source(tests[i].in.x, tests[i].in.y, tests[i].in.width, tests[i].in.height); Rect enclosing = ToEnclosingRectIgnoringError(source, error); EXPECT_EQ(tests[i].expected.x, enclosing.x()); EXPECT_EQ(tests[i].expected.y, enclosing.y()); EXPECT_EQ(tests[i].expected.width, enclosing.width()); EXPECT_EQ(tests[i].expected.height, enclosing.height()); } } TEST(RectTest, ToNearestRect) { Rect rect; EXPECT_EQ(rect, ToNearestRect(RectF(rect))); rect = Rect(-1, -1, 3, 3); EXPECT_EQ(rect, ToNearestRect(RectF(rect))); RectF rectf(-1.00001f, -0.999999f, 3.0000001f, 2.999999f); EXPECT_EQ(rect, ToNearestRect(rectf)); } TEST(RectTest, ToFlooredRect) { static const struct Test { float x1; // source float y1; float w1; float h1; int x2; // target int y2; int w2; int h2; } tests[] = { {0.0f, 0.0f, 0.0f, 0.0f, 0, 0, 0, 0}, {-1.5f, -1.5f, 3.0f, 3.0f, -2, -2, 3, 3}, {-1.5f, -1.5f, 3.5f, 3.5f, -2, -2, 3, 3}, {20000.5f, 20000.5f, 0.5f, 0.5f, 20000, 20000, 0, 0}, }; for (size_t i = 0; i < size(tests); ++i) { RectF r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1); Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2); Rect floored = ToFlooredRectDeprecated(r1); EXPECT_FLOAT_EQ(r2.x(), floored.x()); EXPECT_FLOAT_EQ(r2.y(), floored.y()); EXPECT_FLOAT_EQ(r2.width(), floored.width()); EXPECT_FLOAT_EQ(r2.height(), floored.height()); } } TEST(RectTest, ScaleToEnclosedRect) { static const struct Test { Rect input_rect; float input_scale; Rect expected_rect; } tests[] = {{ Rect(), 5.f, Rect(), }, { Rect(1, 1, 1, 1), 5.f, Rect(5, 5, 5, 5), }, { Rect(-1, -1, 0, 0), 5.f, Rect(-5, -5, 0, 0), }, { Rect(1, -1, 0, 1), 5.f, Rect(5, -5, 0, 5), }, { Rect(-1, 1, 1, 0), 5.f, Rect(-5, 5, 5, 0), }, { Rect(1, 2, 3, 4), 1.5f, Rect(2, 3, 4, 6), }, { Rect(-1, -2, 0, 0), 1.5f, Rect(-1, -3, 0, 0), }}; for (size_t i = 0; i < size(tests); ++i) { Rect result = ScaleToEnclosedRect(tests[i].input_rect, tests[i].input_scale); EXPECT_EQ(tests[i].expected_rect, result); } } TEST(RectTest, ScaleToEnclosingRect) { static const struct Test { Rect input_rect; float input_scale; Rect expected_rect; } tests[] = {{ Rect(), 5.f, Rect(), }, { Rect(1, 1, 1, 1), 5.f, Rect(5, 5, 5, 5), }, { Rect(-1, -1, 0, 0), 5.f, Rect(-5, -5, 0, 0), }, { Rect(1, -1, 0, 1), 5.f, Rect(5, -5, 0, 5), }, { Rect(-1, 1, 1, 0), 5.f, Rect(-5, 5, 5, 0), }, { Rect(1, 2, 3, 4), 1.5f, Rect(1, 3, 5, 6), }, { Rect(-1, -2, 0, 0), 1.5f, Rect(-2, -3, 0, 0), }}; for (size_t i = 0; i < size(tests); ++i) { Rect result = ScaleToEnclosingRect(tests[i].input_rect, tests[i].input_scale); EXPECT_EQ(tests[i].expected_rect, result); Rect result_safe = ScaleToEnclosingRectSafe(tests[i].input_rect, tests[i].input_scale); EXPECT_EQ(tests[i].expected_rect, result_safe); } } #if defined(OS_WIN) TEST(RectTest, ConstructAndAssign) { const RECT rect_1 = {0, 0, 10, 10}; const RECT rect_2 = {0, 0, -10, -10}; Rect test1(rect_1); Rect test2(rect_2); } #endif TEST(RectTest, ToRectF) { // Check that explicit conversion from integer to float compiles. Rect a(10, 20, 30, 40); RectF b(10, 20, 30, 40); RectF c = RectF(a); EXPECT_EQ(b, c); } TEST(RectTest, BoundingRect) { struct { Point a; Point b; Rect expected; } int_tests[] = { // If point B dominates A, then A should be the origin. {Point(4, 6), Point(4, 6), Rect(4, 6, 0, 0)}, {Point(4, 6), Point(8, 6), Rect(4, 6, 4, 0)}, {Point(4, 6), Point(4, 9), Rect(4, 6, 0, 3)}, {Point(4, 6), Point(8, 9), Rect(4, 6, 4, 3)}, // If point A dominates B, then B should be the origin. {Point(4, 6), Point(4, 6), Rect(4, 6, 0, 0)}, {Point(8, 6), Point(4, 6), Rect(4, 6, 4, 0)}, {Point(4, 9), Point(4, 6), Rect(4, 6, 0, 3)}, {Point(8, 9), Point(4, 6), Rect(4, 6, 4, 3)}, // If neither point dominates, then the origin is a combination of the // two. {Point(4, 6), Point(6, 4), Rect(4, 4, 2, 2)}, {Point(-4, -6), Point(-6, -4), Rect(-6, -6, 2, 2)}, {Point(-4, 6), Point(6, -4), Rect(-4, -4, 10, 10)}, }; for (size_t i = 0; i < size(int_tests); ++i) { Rect actual = BoundingRect(int_tests[i].a, int_tests[i].b); EXPECT_EQ(int_tests[i].expected, actual); } struct { PointF a; PointF b; RectF expected; } float_tests[] = { // If point B dominates A, then A should be the origin. {PointF(4.2f, 6.8f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 0, 0)}, {PointF(4.2f, 6.8f), PointF(8.5f, 6.8f), RectF(4.2f, 6.8f, 4.3f, 0)}, {PointF(4.2f, 6.8f), PointF(4.2f, 9.3f), RectF(4.2f, 6.8f, 0, 2.5f)}, {PointF(4.2f, 6.8f), PointF(8.5f, 9.3f), RectF(4.2f, 6.8f, 4.3f, 2.5f)}, // If point A dominates B, then B should be the origin. {PointF(4.2f, 6.8f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 0, 0)}, {PointF(8.5f, 6.8f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 4.3f, 0)}, {PointF(4.2f, 9.3f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 0, 2.5f)}, {PointF(8.5f, 9.3f), PointF(4.2f, 6.8f), RectF(4.2f, 6.8f, 4.3f, 2.5f)}, // If neither point dominates, then the origin is a combination of the // two. {PointF(4.2f, 6.8f), PointF(6.8f, 4.2f), RectF(4.2f, 4.2f, 2.6f, 2.6f)}, {PointF(-4.2f, -6.8f), PointF(-6.8f, -4.2f), RectF(-6.8f, -6.8f, 2.6f, 2.6f)}, {PointF(-4.2f, 6.8f), PointF(6.8f, -4.2f), RectF(-4.2f, -4.2f, 11.0f, 11.0f)}}; for (size_t i = 0; i < size(float_tests); ++i) { RectF actual = BoundingRect(float_tests[i].a, float_tests[i].b); EXPECT_RECTF_EQ(float_tests[i].expected, actual); } } TEST(RectTest, IsExpressibleAsRect) { EXPECT_TRUE(RectF().IsExpressibleAsRect()); float min = static_cast<float>(std::numeric_limits<int>::min()); float max = static_cast<float>(std::numeric_limits<int>::max()); float infinity = std::numeric_limits<float>::infinity(); EXPECT_TRUE( RectF(min + 200, min + 200, max - 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE( RectF(min - 200, min + 200, max + 200, max + 200).IsExpressibleAsRect()); EXPECT_FALSE( RectF(min + 200, min - 200, max + 200, max + 200).IsExpressibleAsRect()); EXPECT_FALSE( RectF(min + 200, min + 200, max + 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE( RectF(min + 200, min + 200, max - 200, max + 200).IsExpressibleAsRect()); EXPECT_TRUE(RectF(0, 0, max - 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(200, 0, max + 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 200, max - 200, max + 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 0, max + 200, max - 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 0, max - 200, max + 200).IsExpressibleAsRect()); EXPECT_FALSE(RectF(infinity, 0, 1, 1).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, infinity, 1, 1).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 0, infinity, 1).IsExpressibleAsRect()); EXPECT_FALSE(RectF(0, 0, 1, infinity).IsExpressibleAsRect()); } TEST(RectTest, Offset) { Rect i(1, 2, 3, 4); EXPECT_EQ(Rect(2, 1, 3, 4), (i + Vector2d(1, -1))); EXPECT_EQ(Rect(2, 1, 3, 4), (Vector2d(1, -1) + i)); i += Vector2d(1, -1); EXPECT_EQ(Rect(2, 1, 3, 4), i); EXPECT_EQ(Rect(1, 2, 3, 4), (i - Vector2d(1, -1))); i -= Vector2d(1, -1); EXPECT_EQ(Rect(1, 2, 3, 4), i); RectF f(1.1f, 2.2f, 3.3f, 4.4f); EXPECT_EQ(RectF(2.2f, 1.1f, 3.3f, 4.4f), (f + Vector2dF(1.1f, -1.1f))); EXPECT_EQ(RectF(2.2f, 1.1f, 3.3f, 4.4f), (Vector2dF(1.1f, -1.1f) + f)); f += Vector2dF(1.1f, -1.1f); EXPECT_EQ(RectF(2.2f, 1.1f, 3.3f, 4.4f), f); EXPECT_EQ(RectF(1.1f, 2.2f, 3.3f, 4.4f), (f - Vector2dF(1.1f, -1.1f))); f -= Vector2dF(1.1f, -1.1f); EXPECT_EQ(RectF(1.1f, 2.2f, 3.3f, 4.4f), f); } TEST(RectTest, Corners) { Rect i(1, 2, 3, 4); RectF f(1.1f, 2.1f, 3.1f, 4.1f); EXPECT_EQ(Point(1, 2), i.origin()); EXPECT_EQ(Point(4, 2), i.top_right()); EXPECT_EQ(Point(1, 6), i.bottom_left()); EXPECT_EQ(Point(4, 6), i.bottom_right()); EXPECT_EQ(PointF(1.1f, 2.1f), f.origin()); EXPECT_EQ(PointF(4.2f, 2.1f), f.top_right()); EXPECT_EQ(PointF(1.1f, 6.2f), f.bottom_left()); EXPECT_EQ(PointF(4.2f, 6.2f), f.bottom_right()); } TEST(RectTest, Centers) { Rect i(10, 20, 30, 40); EXPECT_EQ(Point(10, 40), i.left_center()); EXPECT_EQ(Point(25, 20), i.top_center()); EXPECT_EQ(Point(40, 40), i.right_center()); EXPECT_EQ(Point(25, 60), i.bottom_center()); RectF f(10.1f, 20.2f, 30.3f, 40.4f); EXPECT_EQ(PointF(10.1f, 40.4f), f.left_center()); EXPECT_EQ(PointF(25.25f, 20.2f), f.top_center()); EXPECT_EQ(PointF(40.4f, 40.4f), f.right_center()); EXPECT_EQ(25.25f, f.bottom_center().x()); EXPECT_NEAR(60.6f, f.bottom_center().y(), 0.001f); } TEST(RectTest, Transpose) { Rect i(10, 20, 30, 40); i.Transpose(); EXPECT_EQ(Rect(20, 10, 40, 30), i); RectF f(10.1f, 20.2f, 30.3f, 40.4f); f.Transpose(); EXPECT_EQ(RectF(20.2f, 10.1f, 40.4f, 30.3f), f); } TEST(RectTest, ManhattanDistanceToPoint) { Rect i(1, 2, 3, 4); EXPECT_EQ(0, i.ManhattanDistanceToPoint(Point(1, 2))); EXPECT_EQ(0, i.ManhattanDistanceToPoint(Point(4, 6))); EXPECT_EQ(0, i.ManhattanDistanceToPoint(Point(2, 4))); EXPECT_EQ(3, i.ManhattanDistanceToPoint(Point(0, 0))); EXPECT_EQ(2, i.ManhattanDistanceToPoint(Point(2, 0))); EXPECT_EQ(3, i.ManhattanDistanceToPoint(Point(5, 0))); EXPECT_EQ(1, i.ManhattanDistanceToPoint(Point(5, 4))); EXPECT_EQ(3, i.ManhattanDistanceToPoint(Point(5, 8))); EXPECT_EQ(2, i.ManhattanDistanceToPoint(Point(3, 8))); EXPECT_EQ(2, i.ManhattanDistanceToPoint(Point(0, 7))); EXPECT_EQ(1, i.ManhattanDistanceToPoint(Point(0, 3))); RectF f(1.1f, 2.1f, 3.1f, 4.1f); EXPECT_FLOAT_EQ(0.f, f.ManhattanDistanceToPoint(PointF(1.1f, 2.1f))); EXPECT_FLOAT_EQ(0.f, f.ManhattanDistanceToPoint(PointF(4.2f, 6.f))); EXPECT_FLOAT_EQ(0.f, f.ManhattanDistanceToPoint(PointF(2.f, 4.f))); EXPECT_FLOAT_EQ(3.2f, f.ManhattanDistanceToPoint(PointF(0.f, 0.f))); EXPECT_FLOAT_EQ(2.1f, f.ManhattanDistanceToPoint(PointF(2.f, 0.f))); EXPECT_FLOAT_EQ(2.9f, f.ManhattanDistanceToPoint(PointF(5.f, 0.f))); EXPECT_FLOAT_EQ(.8f, f.ManhattanDistanceToPoint(PointF(5.f, 4.f))); EXPECT_FLOAT_EQ(2.6f, f.ManhattanDistanceToPoint(PointF(5.f, 8.f))); EXPECT_FLOAT_EQ(1.8f, f.ManhattanDistanceToPoint(PointF(3.f, 8.f))); EXPECT_FLOAT_EQ(1.9f, f.ManhattanDistanceToPoint(PointF(0.f, 7.f))); EXPECT_FLOAT_EQ(1.1f, f.ManhattanDistanceToPoint(PointF(0.f, 3.f))); } TEST(RectTest, ManhattanInternalDistance) { Rect i(0, 0, 400, 400); EXPECT_EQ(0, i.ManhattanInternalDistance(gfx::Rect(-1, 0, 2, 1))); EXPECT_EQ(1, i.ManhattanInternalDistance(gfx::Rect(400, 0, 1, 400))); EXPECT_EQ(2, i.ManhattanInternalDistance(gfx::Rect(-100, -100, 100, 100))); EXPECT_EQ(2, i.ManhattanInternalDistance(gfx::Rect(-101, 100, 100, 100))); EXPECT_EQ(4, i.ManhattanInternalDistance(gfx::Rect(-101, -101, 100, 100))); EXPECT_EQ(435, i.ManhattanInternalDistance(gfx::Rect(630, 603, 100, 100))); RectF f(0.0f, 0.0f, 400.0f, 400.0f); static const float kEpsilon = std::numeric_limits<float>::epsilon(); EXPECT_FLOAT_EQ( 0.0f, f.ManhattanInternalDistance(gfx::RectF(-1.0f, 0.0f, 2.0f, 1.0f))); EXPECT_FLOAT_EQ(kEpsilon, f.ManhattanInternalDistance( gfx::RectF(400.0f, 0.0f, 1.0f, 400.0f))); EXPECT_FLOAT_EQ(2.0f * kEpsilon, f.ManhattanInternalDistance(gfx::RectF( -100.0f, -100.0f, 100.0f, 100.0f))); EXPECT_FLOAT_EQ(1.0f + kEpsilon, f.ManhattanInternalDistance(gfx::RectF( -101.0f, 100.0f, 100.0f, 100.0f))); EXPECT_FLOAT_EQ(2.0f + 2.0f * kEpsilon, f.ManhattanInternalDistance( gfx::RectF(-101.0f, -101.0f, 100.0f, 100.0f))); EXPECT_FLOAT_EQ( 433.0f + 2.0f * kEpsilon, f.ManhattanInternalDistance(gfx::RectF(630.0f, 603.0f, 100.0f, 100.0f))); EXPECT_FLOAT_EQ( 0.0f, f.ManhattanInternalDistance(gfx::RectF(-1.0f, 0.0f, 1.1f, 1.0f))); EXPECT_FLOAT_EQ(0.1f + kEpsilon, f.ManhattanInternalDistance( gfx::RectF(-1.5f, 0.0f, 1.4f, 1.0f))); EXPECT_FLOAT_EQ(kEpsilon, f.ManhattanInternalDistance( gfx::RectF(-1.5f, 0.0f, 1.5f, 1.0f))); } TEST(RectTest, IntegerOverflow) { int limit = std::numeric_limits<int>::max(); int min_limit = std::numeric_limits<int>::min(); int expected = 10; int large_number = limit - expected; Rect height_overflow(0, large_number, 100, 100); EXPECT_EQ(large_number, height_overflow.y()); EXPECT_EQ(expected, height_overflow.height()); Rect width_overflow(large_number, 0, 100, 100); EXPECT_EQ(large_number, width_overflow.x()); EXPECT_EQ(expected, width_overflow.width()); Rect size_height_overflow(Point(0, large_number), Size(100, 100)); EXPECT_EQ(large_number, size_height_overflow.y()); EXPECT_EQ(expected, size_height_overflow.height()); Rect size_width_overflow(Point(large_number, 0), Size(100, 100)); EXPECT_EQ(large_number, size_width_overflow.x()); EXPECT_EQ(expected, size_width_overflow.width()); Rect set_height_overflow(0, large_number, 100, 5); EXPECT_EQ(5, set_height_overflow.height()); set_height_overflow.set_height(100); EXPECT_EQ(expected, set_height_overflow.height()); Rect set_y_overflow(100, 100, 100, 100); EXPECT_EQ(100, set_y_overflow.height()); set_y_overflow.set_y(large_number); EXPECT_EQ(expected, set_y_overflow.height()); Rect set_width_overflow(large_number, 0, 5, 100); EXPECT_EQ(5, set_width_overflow.width()); set_width_overflow.set_width(100); EXPECT_EQ(expected, set_width_overflow.width()); Rect set_x_overflow(100, 100, 100, 100); EXPECT_EQ(100, set_x_overflow.width()); set_x_overflow.set_x(large_number); EXPECT_EQ(expected, set_x_overflow.width()); Point large_offset(large_number, large_number); Size size(100, 100); Size expected_size(10, 10); Rect set_origin_overflow(100, 100, 100, 100); EXPECT_EQ(size, set_origin_overflow.size()); set_origin_overflow.set_origin(large_offset); EXPECT_EQ(large_offset, set_origin_overflow.origin()); EXPECT_EQ(expected_size, set_origin_overflow.size()); Rect set_size_overflow(large_number, large_number, 5, 5); EXPECT_EQ(Size(5, 5), set_size_overflow.size()); set_size_overflow.set_size(size); EXPECT_EQ(large_offset, set_size_overflow.origin()); EXPECT_EQ(expected_size, set_size_overflow.size()); Rect set_rect_overflow; set_rect_overflow.SetRect(large_number, large_number, 100, 100); EXPECT_EQ(large_offset, set_rect_overflow.origin()); EXPECT_EQ(expected_size, set_rect_overflow.size()); // Insetting an empty rect, but the total inset (left + right) could overflow. Rect inset_overflow; inset_overflow.Inset(large_number, large_number, 100, 100); EXPECT_EQ(large_offset, inset_overflow.origin()); EXPECT_EQ(gfx::Size(), inset_overflow.size()); // Insetting where the total inset (width - left - right) could overflow. // Also, this insetting by the min limit in all directions cannot // represent width() without overflow, so that will also clamp. Rect inset_overflow2; inset_overflow2.Inset(min_limit, min_limit, min_limit, min_limit); EXPECT_EQ(inset_overflow2, gfx::Rect(min_limit, min_limit, limit, limit)); // Insetting where the width shouldn't change, but if the insets operations // clamped in the wrong order, e.g. ((width - left) - right) vs (width - (left // + right)) then this will not work properly. This is the proper order, // as if left + right overflows, the width cannot be decreased by more than // max int anyway. Additionally, if left + right underflows, it cannot be // increased by more then max int. Rect inset_overflow3(0, 0, limit, limit); inset_overflow3.Inset(-100, -100, 100, 100); EXPECT_EQ(inset_overflow3, gfx::Rect(-100, -100, limit, limit)); Rect inset_overflow4(-1000, -1000, limit, limit); inset_overflow4.Inset(100, 100, -100, -100); EXPECT_EQ(inset_overflow4, gfx::Rect(-900, -900, limit, limit)); Rect offset_overflow(0, 0, 100, 100); offset_overflow.Offset(large_number, large_number); EXPECT_EQ(large_offset, offset_overflow.origin()); EXPECT_EQ(expected_size, offset_overflow.size()); Rect operator_overflow(0, 0, 100, 100); operator_overflow += Vector2d(large_number, large_number); EXPECT_EQ(large_offset, operator_overflow.origin()); EXPECT_EQ(expected_size, operator_overflow.size()); Rect origin_maxint(limit, limit, limit, limit); EXPECT_EQ(origin_maxint, Rect(gfx::Point(limit, limit), gfx::Size())); // Expect a rect at the origin and a rect whose right/bottom is maxint // create a rect that extends from 0..maxint in both extents. { Rect origin_small(0, 0, 100, 100); Rect big_clamped(50, 50, limit, limit); EXPECT_EQ(big_clamped.right(), limit); Rect unioned = UnionRects(origin_small, big_clamped); Rect rect_limit(0, 0, limit, limit); EXPECT_EQ(unioned, rect_limit); } // Expect a rect that would overflow width (but not right) to be clamped // and to have maxint extents after unioning. { Rect small(-500, -400, 100, 100); Rect big(-400, -500, limit, limit); // Technically, this should be limit + 100 width, but will clamp to maxint. EXPECT_EQ(UnionRects(small, big), Rect(-500, -500, limit, limit)); } // Expect a rect that would overflow right *and* width to be clamped. { Rect clamped(500, 500, limit, limit); Rect positive_origin(100, 100, 500, 500); // Ideally, this should be (100, 100, limit + 400, limit + 400). // However, width overflows and would be clamped to limit, but right // overflows too and so will be clamped to limit - 100. Rect expected(100, 100, limit - 100, limit - 100); EXPECT_EQ(UnionRects(clamped, positive_origin), expected); } // Unioning a left=minint rect with a right=maxint rect. // We can't represent both ends of the spectrum in the same rect. // Make sure we keep the most useful area. { int part_limit = min_limit / 3; Rect left_minint(min_limit, min_limit, 1, 1); Rect right_maxint(limit - 1, limit - 1, limit, limit); Rect expected(part_limit, part_limit, 2 * part_limit, 2 * part_limit); Rect result = UnionRects(left_minint, right_maxint); // The result should be maximally big. EXPECT_EQ(limit, result.height()); EXPECT_EQ(limit, result.width()); // The result should include the area near the origin. EXPECT_GT(-part_limit, result.x()); EXPECT_LT(part_limit, result.right()); EXPECT_GT(-part_limit, result.y()); EXPECT_LT(part_limit, result.bottom()); // More succinctly, but harder to read in the results. EXPECT_TRUE(UnionRects(left_minint, right_maxint).Contains(expected)); } } TEST(RectTest, ScaleToEnclosingRectSafe) { const int max_int = std::numeric_limits<int>::max(); const int min_int = std::numeric_limits<int>::min(); const float max_float = std::numeric_limits<float>::max(); Rect xy_underflow(-100000, -123456, 10, 20); EXPECT_EQ(ScaleToEnclosingRectSafe(xy_underflow, 100000, 100000), Rect(min_int, min_int, 1000000, 2000000)); // A location overflow means that width/right and bottom/top also // overflow so need to be clamped. Rect xy_overflow(100000, 123456, 10, 20); EXPECT_EQ(ScaleToEnclosingRectSafe(xy_overflow, 100000, 100000), Rect(max_int, max_int, 0, 0)); // In practice all rects are clamped to 0 width / 0 height so // negative sizes don't matter, but try this for the sake of testing. Rect size_underflow(-1, -2, 100000, 100000); EXPECT_EQ(ScaleToEnclosingRectSafe(size_underflow, -100000, -100000), Rect(100000, 200000, 0, 0)); Rect size_overflow(-1, -2, 123456, 234567); EXPECT_EQ(ScaleToEnclosingRectSafe(size_overflow, 100000, 100000), Rect(-100000, -200000, max_int, max_int)); // Verify width/right gets clamped properly too if x/y positive. Rect size_overflow2(1, 2, 123456, 234567); EXPECT_EQ(ScaleToEnclosingRectSafe(size_overflow2, 100000, 100000), Rect(100000, 200000, max_int - 100000, max_int - 200000)); Rect max_rect(max_int, max_int, max_int, max_int); EXPECT_EQ(ScaleToEnclosingRectSafe(max_rect, max_float, max_float), Rect(max_int, max_int, 0, 0)); Rect min_rect(min_int, min_int, max_int, max_int); // Min rect can't be scaled up any further in any dimension. EXPECT_EQ(ScaleToEnclosingRectSafe(min_rect, 2, 3.5), min_rect); EXPECT_EQ(ScaleToEnclosingRectSafe(min_rect, max_float, max_float), min_rect); // Min rect scaled by min is an empty rect at (max, max) EXPECT_EQ(ScaleToEnclosingRectSafe(min_rect, min_int, min_int), max_rect); } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/rect_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/rect_unittest.cc", "repo_id": "engine", "token_count": 20207 }
405
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ACCESSIBILITY_GFX_MAC_COORDINATE_CONVERSION_H_ #define ACCESSIBILITY_GFX_MAC_COORDINATE_CONVERSION_H_ #import <Foundation/Foundation.h> #include "gfx/gfx_export.h" namespace gfx { class Point; class Rect; // Convert a gfx::Rect specified with the origin at the top left of the primary // display into AppKit secreen coordinates (origin at the bottom left). GFX_EXPORT NSRect ScreenRectToNSRect(const Rect& rect); // Convert an AppKit NSRect with origin in the bottom left of the primary // display into a gfx::Rect with origin at the top left of the primary display. GFX_EXPORT Rect ScreenRectFromNSRect(const NSRect& point); // Convert a gfx::Point specified with the origin at the top left of the primary // display into AppKit screen coordinates (origin at the bottom left). GFX_EXPORT NSPoint ScreenPointToNSPoint(const Point& point); // Convert an AppKit NSPoint with origin in the bottom left of the primary // display into a gfx::Point with origin at the top left of the primary display. GFX_EXPORT Point ScreenPointFromNSPoint(const NSPoint& point); } // namespace gfx #endif // ACCESSIBILITY_GFX_MAC_COORDINATE_CONVERSION_H_
engine/third_party/accessibility/gfx/mac/coordinate_conversion.h/0
{ "file_path": "engine/third_party/accessibility/gfx/mac/coordinate_conversion.h", "repo_id": "engine", "token_count": 393 }
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 TONIC_COMMON_MACROS_H_ #define TONIC_COMMON_MACROS_H_ #include <cassert> #include <cstdio> #include <cstdlib> #include "tonic/common/log.h" #define TONIC_DISALLOW_COPY(TypeName) TypeName(const TypeName&) = delete; #define TONIC_DISALLOW_ASSIGN(TypeName) \ void operator=(const TypeName&) = delete; #define TONIC_DISALLOW_COPY_AND_ASSIGN(TypeName) \ TONIC_DISALLOW_COPY(TypeName) \ TONIC_DISALLOW_ASSIGN(TypeName) #define TONIC_CHECK(condition) \ { \ if (!(condition)) { \ tonic::Log("assertion failed " #condition); \ abort(); \ } \ } #ifndef NDEBUG #define TONIC_DCHECK TONIC_CHECK #else // NDEBUG #define TONIC_DCHECK (void) #endif // NDEBUG #endif // TONIC_COMMON_MACROS_H_
engine/third_party/tonic/common/macros.h/0
{ "file_path": "engine/third_party/tonic/common/macros.h", "repo_id": "engine", "token_count": 554 }
407
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIB_TONIC_DART_MICROTASK_QUEUE_H_ #define LIB_TONIC_DART_MICROTASK_QUEUE_H_ #include <vector> #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/dart_persistent_value.h" #include "tonic/logging/dart_error.h" namespace tonic { class DartMicrotaskQueue { public: DartMicrotaskQueue(); ~DartMicrotaskQueue(); static void StartForCurrentThread(); static DartMicrotaskQueue* GetForCurrentThread(); void ScheduleMicrotask(Dart_Handle callback); void RunMicrotasks(); void Destroy(); bool HasMicrotasks() const { return !queue_.empty(); } DartErrorHandleType GetLastError(); private: typedef std::vector<DartPersistentValue> MicrotaskQueue; DartErrorHandleType last_error_; MicrotaskQueue queue_; }; } // namespace tonic #endif // LIB_TONIC_DART_MICROTASK_QUEUE_H_
engine/third_party/tonic/dart_microtask_queue.h/0
{ "file_path": "engine/third_party/tonic/dart_microtask_queue.h", "repo_id": "engine", "token_count": 339 }
408
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tonic/logging/dart_error.h" #include <atomic> #include "tonic/common/macros.h" #include "tonic/converter/dart_converter.h" namespace tonic { namespace DartError { const char kInvalidArgument[] = "Invalid argument."; } // namespace DartError namespace { void DefaultLogUnhandledException(Dart_Handle, Dart_Handle) {} std::atomic<DartError::UnhandledExceptionReporter> log_unhandled_exception = DefaultLogUnhandledException; void ReportUnhandledException(Dart_Handle exception_handle, Dart_Handle stack_trace_handle) { log_unhandled_exception.load()(exception_handle, stack_trace_handle); } } // namespace void SetUnhandledExceptionReporter( DartError::UnhandledExceptionReporter reporter) { log_unhandled_exception.store(reporter); } bool CheckAndHandleError(Dart_Handle handle) { // Specifically handle UnhandledExceptionErrors first. These exclude fatal // errors that are shutting down the vm and compilation errors in source code. if (Dart_IsUnhandledExceptionError(handle)) { Dart_Handle exception_handle = Dart_ErrorGetException(handle); Dart_Handle stack_trace_handle = Dart_ErrorGetStackTrace(handle); ReportUnhandledException(exception_handle, stack_trace_handle); return true; } else if (Dart_IsFatalError(handle)) { // An UnwindError designed to shutdown isolates. This is thrown by // Isolate.exit. This is ordinary API usage, not actually an error, so // silently shut down the isolate. The actual isolate shutdown happens in // DartMessageHandler::UnhandledError. return true; } else if (Dart_IsError(handle)) { tonic::Log("Dart Error: %s", Dart_GetError(handle)); return true; } else { return false; } } DartErrorHandleType GetErrorHandleType(Dart_Handle handle) { if (Dart_IsCompilationError(handle)) { return kCompilationErrorType; } else if (Dart_IsApiError(handle)) { return kApiErrorType; } else if (Dart_IsError(handle)) { return kUnknownErrorType; } else { return kNoError; } } int GetErrorExitCode(Dart_Handle handle) { if (Dart_IsCompilationError(handle)) { return 254; // dart::bin::kCompilationErrorExitCode } else if (Dart_IsApiError(handle)) { return 253; // dart::bin::kApiErrorExitCode } else if (Dart_IsError(handle)) { return 255; // dart::bin::kErrorExitCode } else { return 0; } } } // namespace tonic
engine/third_party/tonic/logging/dart_error.cc/0
{ "file_path": "engine/third_party/tonic/logging/dart_error.cc", "repo_id": "engine", "token_count": 868 }
409
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIB_TONIC_TYPED_DATA_DART_BYTE_DATA_H_ #define LIB_TONIC_TYPED_DATA_DART_BYTE_DATA_H_ #include <vector> #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/converter/dart_converter.h" namespace tonic { class DartByteData { public: static const size_t kExternalSizeThreshold; static Dart_Handle Create(const void* data, size_t length); explicit DartByteData(Dart_Handle list); DartByteData(DartByteData&& other); DartByteData(); ~DartByteData(); const void* data() const { return data_; } void* data() { return data_; } size_t length_in_bytes() const { return length_in_bytes_; } Dart_Handle dart_handle() const { return dart_handle_; } std::vector<char> Copy() const; void Release() const; explicit operator bool() const { return data_ != nullptr; } private: mutable void* data_; intptr_t length_in_bytes_; Dart_Handle dart_handle_; DartByteData(const DartByteData& other) = delete; DartByteData(const void* data, size_t length); }; template <> struct DartConverter<DartByteData> { using FfiType = Dart_Handle; static void SetReturnValue(Dart_NativeArguments args, DartByteData val); static DartByteData FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception); static DartByteData FromFfi(FfiType val) { return DartByteData(val); } static FfiType ToFfi(DartByteData val) { return val.dart_handle(); } }; } // namespace tonic #endif // LIB_TONIC_TYPED_DATA_DART_BYTE_DATA_H_
engine/third_party/tonic/typed_data/dart_byte_data.h/0
{ "file_path": "engine/third_party/tonic/typed_data/dart_byte_data.h", "repo_id": "engine", "token_count": 636 }
410
/* * 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_skia.h" #include <algorithm> #include <numeric> #include "display_list/dl_paint.h" #include "fml/logging.h" #include "impeller/typographer/backends/skia/text_frame_skia.h" #include "include/core/SkMatrix.h" namespace txt { namespace skt = skia::textlayout; using PaintID = skt::ParagraphPainter::PaintID; using namespace flutter; namespace { // Convert SkFontStyle::Weight values (ranging from 100-900) to txt::FontWeight // values (ranging from 0-8). txt::FontWeight GetTxtFontWeight(int font_weight) { int txt_weight = (font_weight - 100) / 100; txt_weight = std::clamp(txt_weight, static_cast<int>(txt::FontWeight::w100), static_cast<int>(txt::FontWeight::w900)); return static_cast<txt::FontWeight>(txt_weight); } txt::FontStyle GetTxtFontStyle(SkFontStyle::Slant font_slant) { return font_slant == SkFontStyle::Slant::kUpright_Slant ? txt::FontStyle::normal : txt::FontStyle::italic; } class DisplayListParagraphPainter : public skt::ParagraphPainter { public: //---------------------------------------------------------------------------- /// @brief Creates a |skt::ParagraphPainter| that draws to DisplayList. /// /// @param builder The display list builder. /// @param[in] dl_paints The paints referenced by ID in the `drawX` methods. /// @param[in] draw_path_effect If true, draw path effects directly by /// drawing multiple lines instead of providing // a path effect to the paint. /// /// @note Impeller does not (and will not) support path effects, but the /// Skia backend does. That means that if we want to draw dashed /// and dotted lines, we need to draw them directly using the /// `drawLine` API instead of using a path effect. /// /// See https://github.com/flutter/flutter/issues/126673. It /// probably makes sense to eventually make this a compile-time /// decision (i.e. with `#ifdef`) instead of a runtime option. DisplayListParagraphPainter(DisplayListBuilder* builder, const std::vector<DlPaint>& dl_paints, bool impeller_enabled) : builder_(builder), dl_paints_(dl_paints), impeller_enabled_(impeller_enabled) {} void drawTextBlob(const sk_sp<SkTextBlob>& blob, SkScalar x, SkScalar y, const SkPaintOrID& paint) override { if (!blob) { return; } size_t paint_id = std::get<PaintID>(paint); FML_DCHECK(paint_id < dl_paints_.size()); #ifdef IMPELLER_SUPPORTS_RENDERING if (impeller_enabled_) { if (ShouldRenderAsPath(dl_paints_[paint_id])) { auto path = skia::textlayout::Paragraph::GetPath(blob.get()); auto transformed = path.makeTransform(SkMatrix::Translate( x + blob->bounds().left(), y + blob->bounds().top())); builder_->DrawPath(transformed, dl_paints_[paint_id]); return; } builder_->DrawTextFrame(impeller::MakeTextFrameFromTextBlobSkia(blob), x, y, dl_paints_[paint_id]); return; } #endif // IMPELLER_SUPPORTS_RENDERING builder_->DrawTextBlob(blob, x, y, dl_paints_[paint_id]); } void drawTextShadow(const sk_sp<SkTextBlob>& blob, SkScalar x, SkScalar y, SkColor color, SkScalar blur_sigma) override { if (!blob) { return; } DlPaint paint; paint.setColor(DlColor(color)); if (blur_sigma > 0.0) { DlBlurMaskFilter filter(DlBlurStyle::kNormal, blur_sigma, false); paint.setMaskFilter(&filter); } if (impeller_enabled_) { builder_->DrawTextFrame(impeller::MakeTextFrameFromTextBlobSkia(blob), x, y, paint); return; } builder_->DrawTextBlob(blob, x, y, paint); } void drawRect(const SkRect& rect, const SkPaintOrID& paint) override { size_t paint_id = std::get<PaintID>(paint); FML_DCHECK(paint_id < dl_paints_.size()); builder_->DrawRect(rect, dl_paints_[paint_id]); } void drawFilledRect(const SkRect& rect, const DecorationStyle& decor_style) override { DlPaint paint = toDlPaint(decor_style, DlDrawStyle::kFill); builder_->DrawRect(rect, paint); } void drawPath(const SkPath& path, const DecorationStyle& decor_style) override { builder_->DrawPath(path, toDlPaint(decor_style)); } void drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1, const DecorationStyle& decor_style) override { // We only support horizontal lines. FML_DCHECK(y0 == y1); // This function is called for both solid and dashed lines. If we're drawing // a dashed line, and we're using the Impeller backend, then we need to draw // the line directly using the `drawLine` API instead of using a path effect // (because Impeller does not support path effects). auto dash_path_effect = decor_style.getDashPathEffect(); #ifdef IMPELLER_SUPPORTS_RENDERING if (impeller_enabled_ && dash_path_effect) { auto path = dashedLine(x0, x1, y0, *dash_path_effect); builder_->DrawPath(path, toDlPaint(decor_style)); return; } #endif // IMPELLER_SUPPORTS_RENDERING auto paint = toDlPaint(decor_style); if (dash_path_effect) { setPathEffect(paint, *dash_path_effect); } builder_->DrawLine(SkPoint::Make(x0, y0), SkPoint::Make(x1, y1), paint); } void clipRect(const SkRect& rect) override { builder_->ClipRect(rect, DlCanvas::ClipOp::kIntersect, false); } void translate(SkScalar dx, SkScalar dy) override { builder_->Translate(dx, dy); } void save() override { builder_->Save(); } void restore() override { builder_->Restore(); } private: SkPath dashedLine(SkScalar x0, SkScalar x1, SkScalar y0, const DashPathEffect& dash_path_effect) { auto dx = 0.0; auto path = SkPath(); auto on = true; auto length = x1 - x0; while (dx < length) { if (on) { // Draw the on part of the dash. path.moveTo(x0 + dx, y0); dx += dash_path_effect.fOnLength; path.lineTo(x0 + dx, y0); } else { // Skip the off part of the dash. dx += dash_path_effect.fOffLength; } on = !on; } path.close(); return path; } bool ShouldRenderAsPath(const DlPaint& paint) const { FML_DCHECK(impeller_enabled_); // Text with non-trivial color sources or stroke paint mode should be // rendered as a path when running on Impeller for correctness. These // filters rely on having the glyph coverage, whereas regular text is // drawn as rectangular texture samples. return ((paint.getColorSource() && !paint.getColorSource()->asColor()) || paint.getDrawStyle() != DlDrawStyle::kFill); } DlPaint toDlPaint(const DecorationStyle& decor_style, DlDrawStyle draw_style = DlDrawStyle::kStroke) { DlPaint paint; paint.setDrawStyle(draw_style); paint.setAntiAlias(true); paint.setColor(DlColor(decor_style.getColor())); paint.setStrokeWidth(decor_style.getStrokeWidth()); return paint; } void setPathEffect(DlPaint& paint, const DashPathEffect& dash_path_effect) { // Impeller does not support path effects, so we should never be setting. FML_DCHECK(!impeller_enabled_); std::array<SkScalar, 2> intervals{dash_path_effect.fOnLength, dash_path_effect.fOffLength}; auto effect = DlDashPathEffect::Make(intervals.data(), intervals.size(), 0); paint.setPathEffect(effect); } DisplayListBuilder* builder_; const std::vector<DlPaint>& dl_paints_; const bool impeller_enabled_; }; } // anonymous namespace ParagraphSkia::ParagraphSkia(std::unique_ptr<skt::Paragraph> paragraph, std::vector<flutter::DlPaint>&& dl_paints, bool impeller_enabled) : paragraph_(std::move(paragraph)), dl_paints_(dl_paints), impeller_enabled_(impeller_enabled) {} double ParagraphSkia::GetMaxWidth() { return SkScalarToDouble(paragraph_->getMaxWidth()); } double ParagraphSkia::GetHeight() { return SkScalarToDouble(paragraph_->getHeight()); } double ParagraphSkia::GetLongestLine() { return SkScalarToDouble(paragraph_->getLongestLine()); } std::vector<LineMetrics>& ParagraphSkia::GetLineMetrics() { if (!line_metrics_) { std::vector<skt::LineMetrics> metrics; paragraph_->getLineMetrics(metrics); line_metrics_.emplace(); line_metrics_styles_.reserve( std::accumulate(metrics.begin(), metrics.end(), 0, [](const int a, const skt::LineMetrics& b) { return a + b.fLineMetrics.size(); })); for (const skt::LineMetrics& skm : metrics) { LineMetrics& txtm = line_metrics_->emplace_back( skm.fStartIndex, skm.fEndIndex, skm.fEndExcludingWhitespaces, skm.fEndIncludingNewline, skm.fHardBreak); txtm.ascent = skm.fAscent; txtm.descent = skm.fDescent; txtm.unscaled_ascent = skm.fUnscaledAscent; txtm.height = skm.fHeight; txtm.width = skm.fWidth; txtm.left = skm.fLeft; txtm.baseline = skm.fBaseline; txtm.line_number = skm.fLineNumber; for (const auto& sk_iter : skm.fLineMetrics) { const skt::StyleMetrics& sk_style_metrics = sk_iter.second; line_metrics_styles_.push_back(SkiaToTxt(*sk_style_metrics.text_style)); txtm.run_metrics.emplace( std::piecewise_construct, std::forward_as_tuple(sk_iter.first), std::forward_as_tuple(&line_metrics_styles_.back(), sk_style_metrics.font_metrics)); } } } return line_metrics_.value(); } bool ParagraphSkia::GetLineMetricsAt(int lineNumber, skt::LineMetrics* lineMetrics) const { return paragraph_->getLineMetricsAt(lineNumber, lineMetrics); }; double ParagraphSkia::GetMinIntrinsicWidth() { return SkScalarToDouble(paragraph_->getMinIntrinsicWidth()); } double ParagraphSkia::GetMaxIntrinsicWidth() { return SkScalarToDouble(paragraph_->getMaxIntrinsicWidth()); } double ParagraphSkia::GetAlphabeticBaseline() { return SkScalarToDouble(paragraph_->getAlphabeticBaseline()); } double ParagraphSkia::GetIdeographicBaseline() { return SkScalarToDouble(paragraph_->getIdeographicBaseline()); } bool ParagraphSkia::DidExceedMaxLines() { return paragraph_->didExceedMaxLines(); } void ParagraphSkia::Layout(double width) { line_metrics_.reset(); line_metrics_styles_.clear(); paragraph_->layout(width); } bool ParagraphSkia::Paint(DisplayListBuilder* builder, double x, double y) { DisplayListParagraphPainter painter(builder, dl_paints_, impeller_enabled_); paragraph_->paint(&painter, x, y); return true; } std::vector<Paragraph::TextBox> ParagraphSkia::GetRectsForRange( size_t start, size_t end, RectHeightStyle rect_height_style, RectWidthStyle rect_width_style) { std::vector<skt::TextBox> skia_boxes = paragraph_->getRectsForRange( start, end, static_cast<skt::RectHeightStyle>(rect_height_style), static_cast<skt::RectWidthStyle>(rect_width_style)); std::vector<Paragraph::TextBox> boxes; for (const skt::TextBox& skia_box : skia_boxes) { boxes.emplace_back(skia_box.rect, static_cast<TextDirection>(skia_box.direction)); } return boxes; } std::vector<Paragraph::TextBox> ParagraphSkia::GetRectsForPlaceholders() { std::vector<skt::TextBox> skia_boxes = paragraph_->getRectsForPlaceholders(); std::vector<Paragraph::TextBox> boxes; for (const skt::TextBox& skia_box : skia_boxes) { boxes.emplace_back(skia_box.rect, static_cast<TextDirection>(skia_box.direction)); } return boxes; } Paragraph::PositionWithAffinity ParagraphSkia::GetGlyphPositionAtCoordinate( double dx, double dy) { skt::PositionWithAffinity skia_pos = paragraph_->getGlyphPositionAtCoordinate(dx, dy); return ParagraphSkia::PositionWithAffinity( skia_pos.position, static_cast<Affinity>(skia_pos.affinity)); } bool ParagraphSkia::GetGlyphInfoAt( unsigned offset, skia::textlayout::Paragraph::GlyphInfo* glyphInfo) const { return paragraph_->getGlyphInfoAtUTF16Offset(offset, glyphInfo); } bool ParagraphSkia::GetClosestGlyphInfoAtCoordinate( double dx, double dy, skia::textlayout::Paragraph::GlyphInfo* glyphInfo) const { return paragraph_->getClosestUTF16GlyphInfoAt(dx, dy, glyphInfo); }; Paragraph::Range<size_t> ParagraphSkia::GetWordBoundary(size_t offset) { skt::SkRange<size_t> range = paragraph_->getWordBoundary(offset); return Paragraph::Range<size_t>(range.start, range.end); } size_t ParagraphSkia::GetNumberOfLines() const { return paragraph_->lineNumber(); } int ParagraphSkia::GetLineNumberAt(size_t codeUnitIndex) const { return paragraph_->getLineNumberAtUTF16Offset(codeUnitIndex); } TextStyle ParagraphSkia::SkiaToTxt(const skt::TextStyle& skia) { TextStyle txt; txt.color = skia.getColor(); txt.decoration = static_cast<TextDecoration>(skia.getDecorationType()); txt.decoration_color = skia.getDecorationColor(); txt.decoration_style = static_cast<TextDecorationStyle>(skia.getDecorationStyle()); txt.decoration_thickness_multiplier = SkScalarToDouble(skia.getDecorationThicknessMultiplier()); txt.font_weight = GetTxtFontWeight(skia.getFontStyle().weight()); txt.font_style = GetTxtFontStyle(skia.getFontStyle().slant()); txt.text_baseline = static_cast<TextBaseline>(skia.getTextBaseline()); for (const SkString& font_family : skia.getFontFamilies()) { txt.font_families.emplace_back(font_family.c_str()); } txt.font_size = SkScalarToDouble(skia.getFontSize()); txt.letter_spacing = SkScalarToDouble(skia.getLetterSpacing()); txt.word_spacing = SkScalarToDouble(skia.getWordSpacing()); txt.height = SkScalarToDouble(skia.getHeight()); txt.locale = skia.getLocale().c_str(); if (skia.hasBackground()) { PaintID background_id = std::get<PaintID>(skia.getBackgroundPaintOrID()); txt.background = dl_paints_[background_id]; } if (skia.hasForeground()) { PaintID foreground_id = std::get<PaintID>(skia.getForegroundPaintOrID()); txt.foreground = dl_paints_[foreground_id]; } txt.text_shadows.clear(); for (const skt::TextShadow& skia_shadow : skia.getShadows()) { txt::TextShadow shadow; shadow.offset = skia_shadow.fOffset; shadow.blur_sigma = skia_shadow.fBlurSigma; shadow.color = skia_shadow.fColor; txt.text_shadows.emplace_back(shadow); } return txt; } } // namespace txt
engine/third_party/txt/src/skia/paragraph_skia.cc/0
{ "file_path": "engine/third_party/txt/src/skia/paragraph_skia.cc", "repo_id": "engine", "token_count": 6506 }
411
<?xml version="1.0" encoding="UTF-8"?> <issues format="6" by="lint 8.1.0 [10406996] " type="baseline" client="" dependencies="true" name="" variant="all" version="8.1.0 [10406996] "> <issue id="HardcodedDebugMode" message="Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one" errorLine1=" &lt;application android:label=&quot;Flutter Shell&quot; android:name=&quot;FlutterApplication&quot; android:debuggable=&quot;true&quot;>" errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="../../../flutter/shell/platform/android/AndroidManifest.xml" line="13" column="82"/> </issue> <issue id="ClickableViewAccessibility" message="Custom view `FlutterView` overrides `onTouchEvent` but not `performClick`" errorLine1=" public boolean onTouchEvent(MotionEvent event) {" errorLine2=" ~~~~~~~~~~~~"> <location file="../../../flutter/shell/platform/android/io/flutter/view/FlutterView.java" line="445" column="18"/> </issue> <issue id="ClickableViewAccessibility" message="Custom view `FlutterView` overrides `onTouchEvent` but not `performClick`" errorLine1=" public boolean onTouchEvent(@NonNull MotionEvent event) {" errorLine2=" ~~~~~~~~~~~~"> <location file="../../../flutter/shell/platform/android/io/flutter/embedding/android/FlutterView.java" line="928" column="18"/> </issue> </issues>
engine/tools/android_lint/baseline.xml/0
{ "file_path": "engine/tools/android_lint/baseline.xml", "repo_id": "engine", "token_count": 772 }
412
{ "configVersion": 2, "packages": [ { "name": "const_finder_fixtures", "rootUri": "../lib/", "languageVersion": "2.17" }, { "name": "const_finder_fixtures_package", "rootUri": "../pkg/", "languageVersion": "2.17" } ] }
engine/tools/const_finder/test/fixtures/.dart_tool/package_config.json/0
{ "file_path": "engine/tools/const_finder/test/fixtures/.dart_tool/package_config.json", "repo_id": "engine", "token_count": 197 }
413
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' show Directory; import 'dart:math'; import 'package:path/path.dart' as p; import '../dart_utils.dart'; import '../environment.dart'; import '../logger.dart'; import '../proc_utils.dart'; import '../worker_pool.dart'; import 'command.dart'; import 'flags.dart'; /// The different kind of linters we support. enum Linter { /// Dart linter dart, /// Java linter java, /// C/C++ linter c, /// Python linter python } class _LinterDescription { _LinterDescription(this.linter, this.cwd, this.command); final Linter linter; final Directory cwd; final List<String> command; } /// The root 'lint' command. final class LintCommand extends CommandBase { /// Constructs the 'lint' command. LintCommand({ required super.environment, }) { final String engineFlutterPath = environment.engine.flutterDir.path; _linters[Linter.dart] = _LinterDescription( Linter.dart, environment.engine.flutterDir, <String>[ p.join(engineFlutterPath, 'ci', 'analyze.sh'), findDartBinDirectory(environment) ]); _linters[Linter.java] = _LinterDescription(Linter.java, environment.engine.flutterDir, <String>[ findDartBinary(environment), '--disable-dart-dev', p.join(engineFlutterPath, 'tools', 'android_lint', 'bin', 'main.dart'), ]); _linters[Linter.c] = _LinterDescription( Linter.c, environment.engine.flutterDir, <String>[p.join(engineFlutterPath, 'ci', 'clang_tidy.sh')]); _linters[Linter.python] = _LinterDescription( Linter.python, environment.engine.flutterDir, <String>[p.join(engineFlutterPath, 'ci', 'pylint.sh')]); argParser.addFlag( quietFlag, abbr: 'q', help: 'Prints minimal output', ); } final Map<Linter, _LinterDescription> _linters = <Linter, _LinterDescription>{}; @override String get name => 'lint'; @override String get description => 'Lint the engine repository.'; @override Future<int> run() async { // TODO(loic-sharma): Relax this restriction. if (environment.platform.isWindows) { environment.logger .fatal('lint command is not supported on Windows (for now).'); return 1; } final WorkerPool wp = WorkerPool(environment, ProcessTaskProgressReporter(environment)); final Set<ProcessTask> tasks = <ProcessTask>{}; for (final MapEntry<Linter, _LinterDescription> entry in _linters.entries) { tasks.add(ProcessTask( entry.key.name, environment, entry.value.cwd, entry.value.command)); } final bool r = await wp.run(tasks); final bool quiet = argResults![quietFlag] as bool; if (!quiet) { environment.logger.status('\nDumping failure logs\n'); for (final ProcessTask pt in tasks) { final ProcessArtifacts pa = pt.processArtifacts; if (pa.exitCode == 0) { continue; } environment.logger.status('Linter ${pt.name} found issues:'); environment.logger.status('${pa.stdout}\n'); environment.logger.status('${pa.stderr}\n'); } } return r ? 0 : 1; } } /// A WorkerPoolProgressReporter designed to work with ProcessTasks. class ProcessTaskProgressReporter implements WorkerPoolProgressReporter { /// Construct a new reporter. ProcessTaskProgressReporter(this._environment); final Environment _environment; Spinner? _spinner; bool _finished = false; int _longestName = 0; @override void onRun(Set<WorkerTask> tasks) { for (final WorkerTask task in tasks) { _longestName = max(_longestName, task.name.length); } } @override void onFinish() { _finished = true; _updateSpinner(<ProcessTask>[]); } List<ProcessTask> _makeProcessTaskList(WorkerPool pool) { final List<ProcessTask> runningTasks = <ProcessTask>[]; for (final WorkerTask task in pool.running) { if (task is! ProcessTask) { continue; } runningTasks.add(task); } return runningTasks; } @override void onTaskStart(WorkerPool pool, WorkerTask task) { final List<ProcessTask> running = _makeProcessTaskList(pool); _updateSpinner(running); } @override void onTaskDone(WorkerPool pool, WorkerTask task, [Object? err]) { final List<ProcessTask> running = _makeProcessTaskList(pool); task as ProcessTask; final ProcessArtifacts pa = task.processArtifacts; final String dt = _formatDurationShort(task.runTime); if (pa.exitCode != 0) { final String paPath = task.processArtifactsPath; _environment.logger.clearLine(); _environment.logger.status( 'FAIL: ${task.name.padLeft(_longestName)} after $dt [details in $paPath]'); } else { _environment.logger.clearLine(); _environment.logger .status('OKAY: ${task.name.padLeft(_longestName)} after $dt'); } _updateSpinner(running); } void _updateSpinner(List<ProcessTask> tasks) { if (_spinner != null) { _spinner!.finish(); _spinner = null; } if (_finished) { return; } _environment.logger.clearLine(); String runStatus = '['; for (final ProcessTask pt in tasks) { if (runStatus != '[') { runStatus += ' '; } runStatus += pt.name; } if (tasks.isNotEmpty) { runStatus += '...'; } runStatus += '] '; _environment.logger.status('Linting $runStatus', newline: false); _spinner = _environment.logger.startSpinner(); } } String _formatDurationShort(Duration dur) { int micros = dur.inMicroseconds; String r = ''; if (micros >= Duration.microsecondsPerMinute) { final int minutes = micros ~/ Duration.microsecondsPerMinute; micros -= minutes * Duration.microsecondsPerMinute; r += '${minutes}m'; } if (micros >= Duration.microsecondsPerSecond) { final int seconds = micros ~/ Duration.microsecondsPerSecond; micros -= seconds * Duration.microsecondsPerSecond; if (r.isNotEmpty) { r += '.'; } r += '${seconds}s'; } if (micros >= Duration.microsecondsPerMillisecond) { final int millis = micros ~/ Duration.microsecondsPerMillisecond; micros -= millis * Duration.microsecondsPerMillisecond; if (r.isNotEmpty) { r += '.'; } r += '${millis}ms'; } return r; }
engine/tools/engine_tool/lib/src/commands/lint_command.dart/0
{ "file_path": "engine/tools/engine_tool/lib/src/commands/lint_command.dart", "repo_id": "engine", "token_count": 2474 }
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. 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/commands/flags.dart'; import 'package:engine_tool/src/environment.dart'; import 'package:engine_tool/src/logger.dart'; import 'package:litetest/litetest.dart'; import 'package:logging/logging.dart' as log; import 'package:platform/platform.dart'; import 'package:process_fakes/process_fakes.dart'; import 'package:process_runner/process_runner.dart'; void main() { final Engine engine; try { engine = Engine.findWithin(); } catch (e) { io.stderr.writeln(e); io.exitCode = 1; return; } Environment linuxEnv(Logger logger, FakeProcessManager processManager) { return Environment( abi: ffi.Abi.linuxX64, engine: engine, platform: FakePlatform( resolvedExecutable: '/dart', operatingSystem: Platform.linux, ), processRunner: ProcessRunner( processManager: processManager, ), logger: logger, ); } List<String> stringsFromLogs(List<log.LogRecord> logs) { return logs.map((log.LogRecord r) => r.message).toList(); } test('--fix is passed to ci/bin/format.dart by default', () async { final Logger logger = Logger.test(); final FakeProcessManager manager = _formatProcessManager( expectedFlags: <String>['--fix'], ); final Environment env = linuxEnv(logger, manager); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: <String, BuilderConfig>{}, ); final int result = await runner.run(<String>[ 'format', ]); expect(result, equals(0)); }); test('--fix is not passed to ci/bin/format.dart with --dry-run', () async { final Logger logger = Logger.test(); final FakeProcessManager manager = _formatProcessManager( expectedFlags: <String>[], ); final Environment env = linuxEnv(logger, manager); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: <String, BuilderConfig>{}, ); final int result = await runner.run(<String>[ 'format', '--$dryRunFlag', ]); expect(result, equals(0)); }); test('exit code is non-zero when ci/bin/format.dart exit code was non zero', () async { final Logger logger = Logger.test(); final FakeProcessManager manager = _formatProcessManager( expectedFlags: <String>['--fix'], exitCode: 1, ); final Environment env = linuxEnv(logger, manager); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: <String, BuilderConfig>{}, ); final int result = await runner.run(<String>[ 'format', ]); expect(result, equals(1)); }); test('--all-files is passed to ci/bin/format.dart correctly', () async { final Logger logger = Logger.test(); final FakeProcessManager manager = _formatProcessManager( expectedFlags: <String>['--fix', '--all-files'], ); final Environment env = linuxEnv(logger, manager); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: <String, BuilderConfig>{}, ); final int result = await runner.run(<String>[ 'format', '--$allFlag', ]); expect(result, equals(0)); }); test('--verbose is passed to ci/bin/format.dart correctly', () async { final Logger logger = Logger.test(); final FakeProcessManager manager = _formatProcessManager( expectedFlags: <String>['--fix', '--verbose'], ); final Environment env = linuxEnv(logger, manager); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: <String, BuilderConfig>{}, ); final int result = await runner.run(<String>[ 'format', '--$verboseFlag', ]); expect(result, equals(0)); }); test('--quiet suppresses non-error output', () async { final Logger logger = Logger.test(); final FakeProcessManager manager = _formatProcessManager( expectedFlags: <String>['--fix'], stdout: <String>['many', 'lines', 'of', 'output'].join('\n'), stderr: 'error\n', ); final Environment env = linuxEnv(logger, manager); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: <String, BuilderConfig>{}, ); final int result = await runner.run(<String>[ 'format', '--$quietFlag', ]); expect(result, equals(0)); expect(stringsFromLogs(logger.testLogs), equals(<String>['error\n'])); }); test('Diffs are suppressed by default', () async { final Logger logger = Logger.test(); final FakeProcessManager manager = _formatProcessManager( expectedFlags: <String>['--fix'], stdout: <String>[ 'To fix, run `et format` or:', 'many', 'lines', 'of', 'output', 'DONE', ].join('\n'), ); final Environment env = linuxEnv(logger, manager); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: <String, BuilderConfig>{}, ); final int result = await runner.run(<String>[ 'format', ]); expect(result, equals(0)); expect(stringsFromLogs(logger.testLogs), isEmpty); }); test('--dry-run disables --fix and prints diffs', () async { final Logger logger = Logger.test(); final FakeProcessManager manager = _formatProcessManager( expectedFlags: <String>[], stdout: <String>[ 'To fix, run `et format` or:', 'many', 'lines', 'of', 'output', 'DONE', ].join('\n'), ); final Environment env = linuxEnv(logger, manager); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: <String, BuilderConfig>{}, ); final int result = await runner.run(<String>[ 'format', '--$dryRunFlag', ]); expect(result, equals(0)); expect( stringsFromLogs(logger.testLogs), equals(<String>[ 'To fix, run `et format` or:\n', 'many\n', 'lines\n', 'of\n', 'output\n', 'DONE\n', ])); }); test('progress lines are followed by a carriage return', () async { final Logger logger = Logger.test(); const String progressLine = 'diff Jobs: 46% done, 1528/3301 completed, ' '7 in progress, 1753 pending, 13 failed.'; final FakeProcessManager manager = _formatProcessManager( expectedFlags: <String>['--fix'], stdout: progressLine, ); final Environment env = linuxEnv(logger, manager); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: <String, BuilderConfig>{}, ); final int result = await runner.run(<String>[ 'format', ]); expect(result, equals(0)); expect( stringsFromLogs(logger.testLogs), equals(<String>['$progressLine\r'])); }); } FakeProcessManager _formatProcessManager({ required List<String> expectedFlags, int exitCode = 0, String stdout = '', String stderr = '', bool Function(Object?, {String? workingDirectory})? canRun, bool failUnknown = true, }) { final io.ProcessResult success = io.ProcessResult(1, 0, '', ''); final FakeProcess formatProcess = FakeProcess( exitCode: exitCode, stdout: stdout, stderr: stderr, ); return FakeProcessManager( canRun: canRun ?? (Object? exe, {String? workingDirectory}) => true, onRun: (List<String> cmd) => switch (cmd) { _ => failUnknown ? io.ProcessResult(1, 1, '', '') : success, }, onStart: (List<String> cmd) => switch (cmd) { [final String exe, final String fmt, ...final List<String> rest] when exe.endsWith('dart') && fmt.endsWith('ci/bin/format.dart') && rest.length == expectedFlags.length && expectedFlags.every(rest.contains) => formatProcess, _ => failUnknown ? FakeProcess(exitCode: 1) : FakeProcess(), }, ); }
engine/tools/engine_tool/test/format_command_test.dart/0
{ "file_path": "engine/tools/engine_tool/test/format_command_test.dart", "repo_id": "engine", "token_count": 3214 }
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. import("//flutter/common/config.gni") # Builds the component in a non-product JIT build. This will # launch the vm service in the runner. dart_debug_build_cfg = { runner_dep = "//flutter/shell/platform/fuchsia/dart_runner:dart_jit_runner" platform_name = "dart_runner" is_aot = false is_product = false enable_asserts = true } # Builds the component in a non-product AOT build. This will # launch the vm service in the runner. # This configuration is not compatible with a --release build since the # profile aot runner is built without asserts. dart_aot_debug_build_cfg = { runner_dep = "//flutter/shell/platform/fuchsia/dart_runner:dart_aot_runner" platform_name = "dart_runner" is_aot = true is_product = false enable_asserts = true } # Builds the component in a non-product AOT build. This will # launch the vm service in the runner. dart_profile_build_cfg = { runner_dep = "//flutter/shell/platform/fuchsia/dart_runner:dart_aot_runner" platform_name = "dart_runner" is_aot = true is_product = false enable_asserts = false } # Builds the component in a product JIT build. This will # not launch the vm service in the runner. dart_jit_release_build_cfg = { runner_dep = "//flutter/shell/platform/fuchsia/dart_runner:dart_jit_product_runner" platform_name = "dart_runner" is_aot = true is_product = true enable_asserts = false } # Builds the component in a product AOT build. This will # not launch the vm service in the runner. dart_release_build_cfg = { runner_dep = "//flutter/shell/platform/fuchsia/dart_runner:dart_aot_product_runner" platform_name = "dart_runner" is_aot = true is_product = true enable_asserts = false }
engine/tools/fuchsia/dart/dart_build_config.gni/0
{ "file_path": "engine/tools/fuchsia/dart/dart_build_config.gni", "repo_id": "engine", "token_count": 638 }
416
#!/bin/bash # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # ### Starts a new branch from Fuchsia's checkout of the Flutter engine. ### This is necessary to avoid skew between the version of the Dart VM used in ### the flutter_runner and the version of the Dart SDK and VM used by the ### Flutter toolchain. See ### https://github.com/flutter/flutter/wiki/Compiling-the-engine#important-dart-version-synchronization-on-fuchsia ### for more details. ### ### Example: ### $ ./branch_from_fuchsia.sh my_new_feature_branch source "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"/lib/vars.sh || exit $? engine-info "git checkout Fuchsia's version of Flutter Engine..." source "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"/checkout_fuchsia_revision.sh || exit $? engine-info "Creating new branch '$1'." git checkout -b $1 if [ $? -ne 0 ] then engine-error "Failed to create new branch '$1'. Restoring previous checkout." git checkout - exit $? fi
engine/tools/fuchsia/devshell/branch_from_fuchsia.sh/0
{ "file_path": "engine/tools/fuchsia/devshell/branch_from_fuchsia.sh", "repo_id": "engine", "token_count": 368 }
417
# 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/tools/fuchsia/clang.gni") fuchsia_sdk_base = "//fuchsia/sdk/$host_os/arch/$target_cpu" fuchsia_sdk_dist = "$fuchsia_sdk_base/dist" sysroot_lib = "$fuchsia_sdk_base/sysroot/lib" sysroot_dist_lib = "$fuchsia_sdk_base/sysroot/dist/lib" ld_so_path = "" libcxx_so_2_path = "${clang_manifest_json.md5_19df03aecdc9eb27bc8b4038352f2b27}" libcxx_abi_so_1_path = "${clang_manifest_json.md5_6aff1b5f218d4a9278d85d63d0695af8}" libunwind_so_1_path = "${clang_manifest_json.md5_fb2bd871885ef42c2cf3138655f901ed}" if (is_asan) { ld_so_path = "asan/" libcxx_so_2_path = "${clang_manifest_json.md5_07cbd4a04b921d2ca61badc1b15a3b0b}" libcxx_abi_so_1_path = "${clang_manifest_json.md5_18f605e8fd52a92c5f9c6fde9be8206c}" libunwind_so_1_path = "${clang_manifest_json.md5_85b659ccd825be02f123e3479f1bc280}" libclang_rt_so_path = "${clang_manifest_json.md5_b76b69d6ab2c13408b7a3608f925b0c6}" } common_libs = [ { name = "libasync-default.so" path = rebase_path("$fuchsia_sdk_dist") }, { name = "libtrace-engine.so" path = rebase_path("$fuchsia_sdk_dist") }, { name = "libfdio.so" path = rebase_path("$fuchsia_sdk_dist") }, { name = "libvulkan.so" path = rebase_path("$fuchsia_sdk_dist") }, { name = "libtrace-provider-so.so" path = rebase_path("$fuchsia_sdk_dist") }, { name = "ld.so.1" path = rebase_path("$sysroot_dist_lib/$ld_so_path") output_path = ld_so_path }, { name = "libvfs_internal.so" path = rebase_path("$fuchsia_sdk_dist") }, ] # Note, for clang libs we use the md5 hashes here because of gn limitations of # json parsing. # This is a hack, and we can migrate to a better way soon. common_libs += [ { name = "libc++.so.2" path = rebase_path("$clang_base/$libcxx_so_2_path") }, { name = "libc++abi.so.1" path = rebase_path("$clang_base/$libcxx_abi_so_1_path") }, { name = "libunwind.so.1" path = rebase_path("$clang_base/$libunwind_so_1_path") }, ] if (is_asan) { common_libs += [ { name = "libclang_rt.asan.so" path = rebase_path("$clang_base/$libclang_rt_so_path") }, ] } vulkan_dist = "$fuchsia_sdk_base/dist" # Note that the other validation libraries in the Fuchsia SDK seem to have a bug right # now causing crashes, so it is only recommended that we use # VkLayer_khronos_validation.so until we have a confirmation that they are fixed. vulkan_validation_libs = [ { name = "VkLayer_khronos_validation.so" path = rebase_path("$vulkan_dist") }, ] vulkan_data_dir = "//fuchsia/sdk/$host_os/pkg/vulkan_layers/data/vulkan/explicit_layer.d" vulkan_icds = [ { path = rebase_path("$vulkan_data_dir/VkLayer_khronos_validation.json") dest = "vulkan/explicit_layer.d/VkLayer_khronos_validation.json" }, ]
engine/tools/fuchsia/fuchsia_libs.gni/0
{ "file_path": "engine/tools/fuchsia/fuchsia_libs.gni", "repo_id": "engine", "token_count": 1405 }
418
// 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 used to generate the switch statements in the Locale class. // See: ../lib/ui/window.dart // When running this script, use the output of this script to update the // comments that say when the script was last run (that comment appears twice in // window.dart), and then replace all the map entries with the output from // this script (the first set for _canonicalizeLanguageCode and the second set // for _canonicalizeRegionCode). // ignore_for_file: avoid_print import 'dart:async'; import 'dart:convert'; import 'dart:io'; const String registry = 'https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry'; Map<String, List<String>> parseSection(String section) { final Map<String, List<String>> result = <String, List<String>>{}; late List<String> lastHeading; for (final String line in section.split('\n')) { if (line == '') { continue; } if (line.startsWith(' ')) { lastHeading[lastHeading.length - 1] = '${lastHeading.last}${line.substring(1)}'; continue; } final int colon = line.indexOf(':'); if (colon <= 0) { throw StateError('not sure how to deal with "$line"'); } final String name = line.substring(0, colon); final String value = line.substring(colon + 2); lastHeading = result.putIfAbsent(name, () => <String>[])..add(value); } return result; } Future<void> main() async { final HttpClient client = HttpClient(); final String body = (await (await (await client.getUrl(Uri.parse(registry))).close()).transform(utf8.decoder).toList()).join(); final List<Map<String, List<String>>> sections = body.split('%%').map<Map<String, List<String>>>(parseSection).toList(); final Map<String, List<String>> outputs = <String, List<String>>{'language': <String>[], 'region': <String>[]}; String? fileDate; for (final Map<String, List<String>> section in sections) { if (fileDate == null) { // first block should contain a File-Date metadata line. fileDate = section['File-Date']!.single; continue; } assert(section.containsKey('Type'), section.toString()); final String type = section['Type']!.single; if ((type == 'language' || type == 'region') && (section.containsKey('Preferred-Value'))) { assert(section.containsKey('Subtag'), section.toString()); final String subtag = section['Subtag']!.single; final List<String> descriptions = section['Description']!; assert(descriptions.isNotEmpty); assert(section.containsKey('Deprecated')); final String comment = section.containsKey('Comment') ? section['Comment']!.single : 'deprecated ${section['Deprecated']!.single}'; final String preferredValue = section['Preferred-Value']!.single; outputs[type]!.add("'$subtag': '$preferredValue', // ${descriptions.join(", ")}; $comment"); } } print('// Mappings generated for language subtag registry as of $fileDate.'); print('// For languageCode:'); print(outputs['language']!.join('\n')); print('// For regionCode:'); print(outputs['region']!.join('\n')); }
engine/tools/gen_locale.dart/0
{ "file_path": "engine/tools/gen_locale.dart", "repo_id": "engine", "token_count": 1078 }
419
# Golden Tests Harvester A command-line tool that uploads golden images to Skia gold from a directory. ## Usage This program assumes you've _already run_ a suite of golden tests that produce a directory of images with a JSON digest named `digests.json`, which is [documented in `lib/golden_tests_harvester.dart`][lib]. Provide the directory as the only positional argument to the program: [lib]: lib/golden_tests_harvester.dart ```sh dart ./tools/golden_tests_harvester/bin/golden_tests_harvester.dart <path/to/digests> ``` > [!INFO] > Skia Gold must be setup and configured to accept the images being uploaded. > > In practice, that means it's the process is running on CI. _Optionally_, you can run in `--dry-run` mode to see what would be uploaded without actually uploading anything: ```sh dart ./tools/golden_tests_harvester/bin/golden_tests_harvester.dart --dry-run <path/to/digests> ``` This flag is automatically set when running locally (i.e. outside of CI).
engine/tools/golden_tests_harvester/README.md/0
{ "file_path": "engine/tools/golden_tests_harvester/README.md", "repo_id": "engine", "token_count": 306 }
420
#!/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_SRC_ROOT = 'flutter/shell/platform/android' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) def JavadocBin(): if sys.platform == 'darwin': return os.path.join( SCRIPT_DIR, '..', '..', '..', 'third_party', 'java', 'openjdk', 'Contents', 'Home', 'bin', 'javadoc' ) elif sys.platform.startswith(('cygwin', 'win')): return os.path.join( SCRIPT_DIR, '..', '..', '..', 'third_party', 'java', 'openjdk', 'bin', 'javadoc.exe' ) else: return os.path.join( SCRIPT_DIR, '..', '..', '..', 'third_party', 'java', 'openjdk', 'bin', 'javadoc' ) def main(): parser = argparse.ArgumentParser(description='Runs javadoc on Flutter Android libraries') parser.add_argument('--out-dir', type=str, required=True) parser.add_argument('--android-source-root', type=str, default=ANDROID_SRC_ROOT) parser.add_argument('--build-config-path', type=str) parser.add_argument('--third-party', type=str, default='third_party') parser.add_argument('--quiet', default=False, action='store_true') args = parser.parse_args() if not os.path.exists(args.android_source_root): print( 'This script must be run at the root of the Flutter source tree, or ' 'the --android-source-root must be set.' ) return 1 if not os.path.exists(args.out_dir): os.makedirs(args.out_dir) classpath = [ args.android_source_root, os.path.join(args.third_party, 'android_tools/sdk/platforms/android-34/android.jar'), os.path.join(args.third_party, 'android_embedding_dependencies', 'lib', '*'), ] if args.build_config_path: classpath.append(args.build_config_path) packages = [ 'io.flutter.app', 'io.flutter.embedding.android', 'io.flutter.embedding.engine', 'io.flutter.embedding.engine.dart', 'io.flutter.embedding.engine.loader', 'io.flutter.embedding.engine.mutatorsstack', 'io.flutter.embedding.engine.plugins', 'io.flutter.embedding.engine.plugins.activity', 'io.flutter.embedding.engine.plugins.broadcastreceiver', 'io.flutter.embedding.engine.plugins.contentprovider', 'io.flutter.embedding.engine.plugins.lifecycle', 'io.flutter.embedding.engine.plugins.service', 'io.flutter.embedding.engine.plugins.shim', 'io.flutter.embedding.engine.renderer', 'io.flutter.embedding.engine.systemchannels', 'io.flutter.plugin.common', 'io.flutter.plugin.editing', 'io.flutter.plugin.platform', 'io.flutter.util', 'io.flutter.view', ] android_package_list = os.path.join(SCRIPT_DIR, 'android_reference') command = [ JavadocBin(), '-classpath', ':'.join(classpath), '-d', args.out_dir, '-linkoffline', 'https://developer.android.com/reference/', android_package_list, '-source', '1.8', ] + packages if not args.quiet: print(' '.join(command)) try: output = subprocess.check_output(command, stderr=subprocess.STDOUT) if not args.quiet: print(output) except subprocess.CalledProcessError as e: print(e.output.decode('utf-8')) return e.returncode return 0 if __name__ == '__main__': sys.exit(main())
engine/tools/javadoc/gen_javadoc.py/0
{ "file_path": "engine/tools/javadoc/gen_javadoc.py", "repo_id": "engine", "token_count": 1421 }
421
Mozilla Public License Version 2.0 1. Definitions 1.1. “Contributor” means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. “Contributor Version” means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution. 1.3. “Contribution” means Covered Software of a particular Contributor. 1.4. “Covered Software” means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. “Incompatible With Secondary Licenses” means a. that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or b. that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. “Executable Form” means any form of the work other than Source Code Form. 1.7. “Larger Work” means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. “License” means this document. 1.9. “Licensable” means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. “Modifications” means any of the following: a. any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or b. any new file in Source Code Form that contains any Covered Software. 1.11. “Patent Claims” of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. “Secondary License” means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. “Source Code Form” means the form of the work preferred for making modifications. 1.14. “You” (or “Your”) means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: a. under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and b. under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: a. for any code that a Contributor has removed from Covered Software; or b. for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or c. under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: a. such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and b. You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. 6. Disclaimer of Warranty Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. 7. Limitation of Liability Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 8. Litigation Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims. 9. Miscellaneous This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - “Incompatible With Secondary Licenses” Notice This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0.
engine/tools/licenses/data/mozilla-2.0/0
{ "file_path": "engine/tools/licenses/data/mozilla-2.0", "repo_id": "engine", "token_count": 3357 }
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. import("//flutter/shell/version/version.gni") shared_library("path_ops") { public_configs = [ "//flutter:config" ] sources = [ "path_ops.cc", "path_ops.h", ] deps = [ "//flutter/skia" ] metadata = { entitlement_file_path = [ "libpath_ops.dylib" ] } }
engine/tools/path_ops/BUILD.gn/0
{ "file_path": "engine/tools/path_ops/BUILD.gn", "repo_id": "engine", "token_count": 160 }
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. #ifndef FLUTTER_VULKAN_SWIFTSHADER_PATH_H_ #define FLUTTER_VULKAN_SWIFTSHADER_PATH_H_ #ifndef VULKAN_SO_PATH #if FML_OS_MACOSX #define VULKAN_SO_PATH "libvk_swiftshader.dylib" #elif FML_OS_WIN #define VULKAN_SO_PATH "vk_swiftshader.dll" #else #define VULKAN_SO_PATH "libvk_swiftshader.so" #endif // !FML_OS_MACOSX && !FML_OS_WIN #endif // VULKAN_SO_PATH #endif // FLUTTER_VULKAN_SWIFTSHADER_PATH_H_
engine/vulkan/swiftshader_path.h/0
{ "file_path": "engine/vulkan/swiftshader_path.h", "repo_id": "engine", "token_count": 253 }
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. #ifndef FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_ANDROID_H_ #define FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_ANDROID_H_ #include "flutter/fml/macros.h" #include "vulkan_native_surface.h" struct ANativeWindow; typedef struct ANativeWindow ANativeWindow; namespace vulkan { class VulkanNativeSurfaceAndroid : public VulkanNativeSurface { public: /// Create a native surface from the valid ANativeWindow reference. Ownership /// of the ANativeWindow is assumed by this instance. explicit VulkanNativeSurfaceAndroid(ANativeWindow* native_window); ~VulkanNativeSurfaceAndroid(); const char* GetExtensionName() const override; uint32_t GetSkiaExtensionName() const override; VkSurfaceKHR CreateSurfaceHandle( VulkanProcTable& vk, const VulkanHandle<VkInstance>& instance) const override; bool IsValid() const override; SkISize GetSize() const override; private: ANativeWindow* native_window_; FML_DISALLOW_COPY_AND_ASSIGN(VulkanNativeSurfaceAndroid); }; } // namespace vulkan #endif // FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_ANDROID_H_
engine/vulkan/vulkan_native_surface_android.h/0
{ "file_path": "engine/vulkan/vulkan_native_surface_android.h", "repo_id": "engine", "token_count": 411 }
425
{ "comment:0": "NOTE: THIS FILE IS GENERATED. DO NOT EDIT.", "comment:1": "Instead modify 'flutter/web_sdk/libraries.yaml' and follow the instructions therein.", "dartdevc": { "include": [ { "path": "../dart-sdk/lib/libraries.json", "target": "dartdevc" } ], "libraries": { "ui": { "uri": "lib/ui/ui.dart" }, "ui_web": { "uri": "lib/ui_web/ui_web.dart" }, "_engine": { "uri": "lib/_engine/engine.dart" }, "_skwasm_stub": { "uri": "lib/_skwasm_stub/skwasm_stub.dart" }, "_web_unicode": { "uri": "lib/_web_unicode/web_unicode.dart" }, "_web_locale_keymap": { "uri": "lib/_web_locale_keymap/web_locale_keymap.dart" }, "_web_test_fonts": { "uri": "lib/_web_test_fonts/web_test_fonts.dart" } } }, "dart2js": { "include": [ { "path": "../dart-sdk/lib/libraries.json", "target": "dart2js" } ], "libraries": { "ui": { "uri": "lib/ui/ui.dart" }, "ui_web": { "uri": "lib/ui_web/ui_web.dart" }, "_engine": { "uri": "lib/_engine/engine.dart" }, "_skwasm_stub": { "uri": "lib/_skwasm_stub/skwasm_stub.dart" }, "_web_unicode": { "uri": "lib/_web_unicode/web_unicode.dart" }, "_web_locale_keymap": { "uri": "lib/_web_locale_keymap/web_locale_keymap.dart" }, "_web_test_fonts": { "uri": "lib/_web_test_fonts/web_test_fonts.dart" } } }, "wasm": { "include": [ { "path": "../dart-sdk/lib/libraries.json", "target": "wasm" } ], "libraries": { "ui": { "uri": "lib/ui/ui.dart" }, "ui_web": { "uri": "lib/ui_web/ui_web.dart" }, "_engine": { "uri": "lib/_engine/engine.dart" }, "_skwasm_impl": { "uri": "lib/_skwasm_impl/skwasm_impl.dart" }, "_web_unicode": { "uri": "lib/_web_unicode/web_unicode.dart" }, "_web_locale_keymap": { "uri": "lib/_web_locale_keymap/web_locale_keymap.dart" }, "_web_test_fonts": { "uri": "lib/_web_test_fonts/web_test_fonts.dart" } } } }
engine/web_sdk/libraries.json/0
{ "file_path": "engine/web_sdk/libraries.json", "repo_id": "engine", "token_count": 1323 }
426
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:image/image.dart'; import 'package:path/path.dart' as p; import 'package:skia_gold_client/skia_gold_client.dart'; /// Compares a screenshot taken through a test with its golden. /// /// Used by Flutter Web Engine unit tests and the integration tests. /// /// Returns the results of the tests as `String`. When tests passes the result /// is simply `OK`, however when they fail it contains a detailed explanation /// on which files are compared, their absolute locations and an HTML page /// that the developer can see the comparison. Future<String> compareImage( Image screenshot, bool doUpdateScreenshotGoldens, String filename, Directory suiteGoldenDirectory, SkiaGoldClient? skiaClient, { required bool isCanvaskitTest, required bool verbose, }) async { if (skiaClient == null) { return 'OK'; } final String screenshotPath = p.join(suiteGoldenDirectory.path, filename); final File screenshotFile = File(screenshotPath); await screenshotFile.create(recursive: true); await screenshotFile.writeAsBytes(encodePng(screenshot), flush: true); if (SkiaGoldClient.isLuciEnv()) { // This is temporary to get started by uploading existing screenshots to // Skia Gold. The next step would be to actually use Skia Gold for // comparison. final int screenshotSize = screenshot.width * screenshot.height; final int pixelColorDeltaPerChannel; final double differentPixelsRate; if (isCanvaskitTest) { differentPixelsRate = 0.1; pixelColorDeltaPerChannel = 7; } else if (skiaClient.dimensions != null && skiaClient.dimensions!['Browser'] == 'ios-safari') { differentPixelsRate = 0.15; pixelColorDeltaPerChannel = 16; } else { differentPixelsRate = 0.1; pixelColorDeltaPerChannel = 1; } skiaClient.addImg( filename, screenshotFile, screenshotSize: screenshotSize, differentPixelsRate: differentPixelsRate, pixelColorDelta: pixelColorDeltaPerChannel * 3, ); return 'OK'; } final Image? golden = await _getGolden(filename); if (doUpdateScreenshotGoldens) { return 'OK'; } if (golden == null) { // This is a new screenshot that doesn't have an existing golden. // At the moment, we don't support local screenshot testing because we use // Skia Gold to handle our screenshots and diffing. In the future, we might // implement local screenshot testing if there's a need. if (verbose) { print('Screenshot generated: file://$screenshotPath'); // ignore: avoid_print } return 'OK'; } // TODO(mdebbar): Use the Gold tool to locally diff the golden. return 'OK'; } Future<Image?> _getGolden(String filename) { // TODO(mdebbar): Fetch the golden from Skia Gold. return Future<Image?>.value(); }
engine/web_sdk/web_test_utils/lib/image_compare.dart/0
{ "file_path": "engine/web_sdk/web_test_utils/lib/image_compare.dart", "repo_id": "engine", "token_count": 933 }
427
<component name="libraryTable"> <library name="org.mockito:mockito-core:2.2.2" type="repository"> <properties maven-id="org.mockito:mockito-core:2.2.2" /> <CLASSES> <root url="jar://$MAVEN_REPOSITORY$/org/mockito/mockito-core/2.2.2/mockito-core-2.2.2.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/net/bytebuddy/byte-buddy/1.4.26/byte-buddy-1.4.26.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/net/bytebuddy/byte-buddy-agent/1.4.26/byte-buddy-agent-1.4.26.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/objenesis/objenesis/2.4/objenesis-2.4.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component>
flutter-intellij/.idea/libraries/org_mockito_mockito_core_2_2_2.xml/0
{ "file_path": "flutter-intellij/.idea/libraries/org_mockito_mockito_core_2_2_2.xml", "repo_id": "flutter-intellij", "token_count": 328 }
428
include: package:lints/recommended.yaml analyzer: exclude: - 'out/**' - 'tool/icon_generator/**' language: strict-casts: true linter: rules: - directives_ordering - unawaited_futures
flutter-intellij/analysis_options.yaml/0
{ "file_path": "flutter-intellij/analysis_options.yaml", "repo_id": "flutter-intellij", "token_count": 86 }
429
/* * 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.openapi.diagnostic.Logger 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 org.junit.Assert import org.junit.Test // Inspired by CommandLineProjectGuiTest @RunWithIde(CommunityIde::class) class SmokeTest : GuiTestCase() { private val LOG = Logger.getInstance(this.javaClass) @Test fun createBasicProject() { ProjectCreator.createProject(projectName = "guitest") checkProject() } @Test fun importSimpleProject() { ProjectCreator.importProject() checkProject() } private fun checkProject() { ideFrame { editor { // Wait until current file has appeared in current editor and set focus to editor. moveTo(1) } step("Verify open file has some content") { val editorCode = editor.getCurrentFileContents(false) Assert.assertTrue(editorCode!!.isNotEmpty()) } step("Close project") { closeProjectAndWaitWelcomeFrame() } } } }
flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/SmokeTest.kt/0
{ "file_path": "flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/SmokeTest.kt", "repo_id": "flutter-intellij", "token_count": 469 }
430
/* * 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.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import icons.FlutterIcons; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FlutterMessages { public static final String FLUTTER_NOTIFICATION_GROUP_ID = "Flutter Messages"; public static final String FLUTTER_LOGGING_NOTIFICATION_GROUP_ID = "Flutter Notifications"; private FlutterMessages() { } public static void showError(String title, String message, @Nullable Project project) { // TODO: Make the project parameter not nullable. Notifications.Bus.notify( new Notification(FLUTTER_NOTIFICATION_GROUP_ID, title, message, NotificationType.ERROR), project); } public static void showWarning(String title, String message, @Nullable Project project) { // TODO: Make the project parameter not nullable. Notifications.Bus.notify( new Notification( FLUTTER_NOTIFICATION_GROUP_ID, title, message, NotificationType.WARNING, NotificationListener.URL_OPENING_LISTENER), project); } public static void showInfo(String title, String message, @Nullable Project project) { // TODO: Make the project parameter not nullable. final Notification notification = new Notification( FLUTTER_NOTIFICATION_GROUP_ID, title, message, NotificationType.INFORMATION); notification.setIcon(FlutterIcons.Flutter); Notifications.Bus.notify(notification, project); } public static int showDialog(@Nullable Project project, @NotNull String message, @NotNull @Nls String title, @NotNull String[] options, int defaultOptionIndex) { return Messages.showIdeaMessageDialog(project, message, title, options, defaultOptionIndex, FlutterIcons.Flutter_2x, null); } }
flutter-intellij/flutter-idea/src/io/flutter/FlutterMessages.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/FlutterMessages.java", "repo_id": "flutter-intellij", "token_count": 971 }
431
/* * 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.analytics; import com.intellij.openapi.components.Service; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import java.util.Objects; @Service public final class TimeTracker { private final Project project; private Long projectOpenTime; @NotNull public static TimeTracker getInstance(@NotNull final Project project) { return Objects.requireNonNull(project.getService(TimeTracker.class)); } public TimeTracker(Project project) { this.project = project; } public void onProjectOpen() { this.projectOpenTime = System.currentTimeMillis(); } public int millisSinceProjectOpen() { if (projectOpenTime == null) { return 0; } return (int)(System.currentTimeMillis() - projectOpenTime); } }
flutter-intellij/flutter-idea/src/io/flutter/analytics/TimeTracker.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/analytics/TimeTracker.java", "repo_id": "flutter-intellij", "token_count": 298 }
432
/* * Copyright 2021 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.dart; import com.intellij.psi.PsiElement; import com.jetbrains.lang.dart.DartTokenTypes; import com.jetbrains.lang.dart.psi.DartArgumentList; import com.jetbrains.lang.dart.psi.DartArguments; import com.jetbrains.lang.dart.psi.DartExpression; import com.jetbrains.lang.dart.psi.DartNamedArgument; import com.jetbrains.lang.dart.util.DartPsiImplUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class DartPsiUtil { public static int parseLiteralNumber(@NotNull String val) throws NumberFormatException { return val.startsWith("0x") || val.startsWith("0X") ? Integer.parseUnsignedInt(val.substring(2), 16) : Integer.parseUnsignedInt(val); } @Nullable public static PsiElement getNewExprFromType(PsiElement element) { if (element.getNode().getElementType() != DartTokenTypes.SIMPLE_TYPE) return null; PsiElement parent = element.getParent(); if (parent == null) return null; parent = parent.getParent(); if (parent == null) return null; if (parent.getNode().getElementType() != DartTokenTypes.NEW_EXPRESSION) return null; return parent; } @Nullable public static String getValueOfPositionalArgument(@NotNull DartArguments arguments, int index) { final DartExpression expression = getPositionalArgument(arguments, index); if (expression == null) return null; if (expression.getNode().getElementType() != DartTokenTypes.LITERAL_EXPRESSION) return null; return expression.getText(); } @Nullable public static DartExpression getPositionalArgument(@NotNull DartArguments arguments, int index) { final DartArgumentList list = arguments.getArgumentList(); if (list == null) return null; if (index >= list.getExpressionList().size()) return null; return list.getExpressionList().get(index); } @Nullable public static String getValueOfNamedArgument(@NotNull DartArguments arguments, @NotNull String name) { final PsiElement family = getNamedArgumentExpression(arguments, "fontFamily"); if (family != null) { if (family.getNode().getElementType() == DartTokenTypes.STRING_LITERAL_EXPRESSION) { return DartPsiImplUtil.getUnquotedDartStringAndItsRange(family.getText()).first; } else { return ""; // Empty string indicates arg was found but value could not be determined easily. } } return null; } @Nullable public static PsiElement getNamedArgumentExpression(@NotNull DartArguments arguments, @NotNull String name) { final DartArgumentList list = arguments.getArgumentList(); if (list == null) return null; final List<DartNamedArgument> namedArgumentList = list.getNamedArgumentList(); for (DartNamedArgument namedArgument : namedArgumentList) { final DartExpression nameExpression = namedArgument.getParameterReferenceExpression(); final PsiElement childId = nameExpression.getFirstChild(); final PsiElement child = nameExpression.getFirstChild(); if (name.equals(child.getText())) { return namedArgument.getExpression(); } } return null; } @Nullable public static PsiElement topmostReferenceExpression(@NotNull PsiElement element) { final PsiElement id = element.getParent(); if (id == null || id.getNode().getElementType() != DartTokenTypes.ID) return null; PsiElement refExpr = id.getParent(); if (refExpr == null || refExpr.getNode().getElementType() != DartTokenTypes.REFERENCE_EXPRESSION) return null; PsiElement parent = refExpr.getParent(); while (parent != null && parent.getNode().getElementType() == DartTokenTypes.REFERENCE_EXPRESSION) { refExpr = parent; parent = parent.getParent(); } return refExpr; } }
flutter-intellij/flutter-idea/src/io/flutter/dart/DartPsiUtil.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/dart/DartPsiUtil.java", "repo_id": "flutter-intellij", "token_count": 1349 }
433
/* * Copyright 2021 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.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.ElementColorProvider; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.PsiFileFactoryImpl; import com.intellij.psi.impl.source.tree.AstBufferUtil; import com.jetbrains.lang.dart.DartLanguage; import com.jetbrains.lang.dart.DartTokenTypes; import com.jetbrains.lang.dart.psi.*; import io.flutter.FlutterBundle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.Arrays; import java.util.List; import static io.flutter.dart.DartPsiUtil.getNewExprFromType; import static io.flutter.dart.DartPsiUtil.topmostReferenceExpression; public class FlutterColorProvider implements ElementColorProvider { @Nullable @Override public Color getColorFrom(@NotNull PsiElement element) { // This must return null for non-leaf nodes and any language other than Dart. if (element.getNode().getElementType() != DartTokenTypes.IDENTIFIER) return null; final String name = element.getText(); if (name == null) return null; final PsiElement refExpr = topmostReferenceExpression(element); if (refExpr == null) return null; PsiElement parent = refExpr.getParent(); if (parent == null) return null; if (parent.getNode().getElementType() == DartTokenTypes.ARRAY_ACCESS_EXPRESSION) { // Colors.blue[200] if (name.equals(refExpr.getFirstChild().getText()) && refExpr.getChildren().length > 1) { // Avoid duplicate resolves. return null; } final String code = AstBufferUtil.getTextSkippingWhitespaceComments(parent.getNode()); return parseColorText(code.substring(code.indexOf(name)), name); } else if (parent.getNode().getElementType() == DartTokenTypes.CALL_EXPRESSION) { // foo(Color.fromRGBO(0, 255, 0, 0.5)) if (name.matches("fromARGB") || name.matches("fromRGBO")) { // Avoid duplicate resolves. return null; } if (parent.getLastChild() instanceof DartArguments && !name.matches("(Cupertino)?Color")) { final DartArgumentList argumentList = ((DartArguments)parent.getLastChild()).getArgumentList(); if (argumentList == null) { return null; } // Avoid duplicate resolves. Color color = null; final List<DartExpression> expressionList = argumentList.getExpressionList(); if (!expressionList.isEmpty()) { final DartExpression colorExpression = expressionList.get(0); color = parseColorElements(colorExpression, colorExpression.getFirstChild()); } if (color != null) return null; } // Color.fromRGBO(0, 255, 0, 0.5) return parseColorElements(parent, refExpr); } else if (parent.getNode().getElementType() == DartTokenTypes.SIMPLE_TYPE) { // const Color.fromARGB(100, 255, 0, 0) if (name.matches("fromARGB") || name.matches("fromRGBO")) { // Avoid duplicate resolves. return null; } // parent.getParent().getParent() is a new expr parent = getNewExprFromType(parent); if (parent == null) return null; return parseColorElements(parent, refExpr); } else { if (parent.getNode().getElementType() == DartTokenTypes.VAR_INIT || parent.getNode().getElementType() == DartTokenTypes.FUNCTION_BODY) { if (name.equals(refExpr.getFirstChild().getText()) && refExpr.getChildren().length > 1) { // Avoid duplicate resolves. return null; } final PsiElement reference = resolveReferencedElement(refExpr); if (reference != null && reference.getLastChild() != null) { Color tryParseColor; if (reference instanceof DartCallExpression) { final DartExpression expression = ((DartCallExpression)reference).getExpression(); if (expression != null && expression.getLastChild() instanceof DartReferenceExpression) { tryParseColor = parseColorElements(reference, expression); if (tryParseColor != null) return tryParseColor; } } final PsiElement lastChild = reference.getLastChild(); if (lastChild instanceof DartArguments && reference.getParent() != null) { tryParseColor = parseColorElements(reference, reference.getParent()); } else { tryParseColor = parseColorElements(reference, reference.getLastChild()); } if (tryParseColor != null) return tryParseColor; } } // name.equals(refExpr.getFirstChild().getText()) -> Colors.blue final PsiElement idNode = refExpr.getFirstChild(); if (idNode == null) return null; if (name.equals(idNode.getText())) { final PsiElement selectorNode = refExpr.getLastChild(); if (selectorNode == null) return null; final String code = AstBufferUtil.getTextSkippingWhitespaceComments(selectorNode.getNode()); return parseColorText(code, name); } // refExpr.getLastChild().getText().startsWith("shade") -> Colors.blue.shade200 final PsiElement child = refExpr.getLastChild(); if (child == null) return null; if (child.getText().startsWith("shade")) { if (idNode.getText().contains(name)) return null; // Avoid duplicate resolves. String code = AstBufferUtil.getTextSkippingWhitespaceComments(refExpr.getNode()); code = code.replaceFirst("(Cupertino)?Colors\\.", ""); return parseColorText(code, name); } } return null; } @Nullable private PsiElement resolveReferencedElement(@NotNull PsiElement element) { if (element instanceof DartCallExpression && element.getFirstChild().getText().equals("Color")) { return element; } final PsiElement symbol = element.getLastChild(); final PsiElement result; if (symbol instanceof DartReference) { result = ((DartReference)symbol).resolve(); } else if (element instanceof DartReference) { result = ((DartReference)element).resolve(); } else { return null; } if (!(result instanceof DartComponentName) || result.getParent() == null) return null; final PsiElement declaration = result.getParent().getParent(); if (declaration instanceof DartClassMembers) return declaration; if (!(declaration instanceof DartVarDeclarationList)) return null; final PsiElement lastChild = declaration.getLastChild(); if (!(lastChild instanceof DartVarInit)) return null; final PsiElement effectiveElement = lastChild.getLastChild(); // Recursively determine reference if the initialization is still a `DartReference`. if (effectiveElement instanceof DartReference && !(effectiveElement instanceof DartCallExpression)) { return resolveReferencedElement(effectiveElement); } return effectiveElement; } @Nullable private Color parseColorElements(@NotNull PsiElement parent, @NotNull PsiElement refExpr) { final PsiElement selectorNode = refExpr.getLastChild(); if (selectorNode == null) return null; final String selector = selectorNode.getText(); final boolean isFromARGB = "fromARGB".equals(selector); final boolean isFromRGBO = "fromRGBO".equals(selector); if (isFromARGB || isFromRGBO) { String code = AstBufferUtil.getTextSkippingWhitespaceComments(parent.getNode()); if (code.startsWith("constColor(") || code.startsWith("constColor.")) { code = code.substring(5); } return ExpressionParsingUtils.parseColorComponents(code.substring(code.indexOf(selector)), selector + "(", isFromARGB); } final PsiElement args = parent.getLastChild(); if (args != null && args.getNode().getElementType() == DartTokenTypes.ARGUMENTS) { String code = AstBufferUtil.getTextSkippingWhitespaceComments(parent.getNode()); if (code.startsWith("constColor(")) { code = code.substring(5); } return ExpressionParsingUtils.parseColor(code); } return null; } @Nullable private Color parseColorText(@NotNull String text, @NotNull String platform) { final FlutterColors.FlutterColor color; if ("CupertinoColors".equals(platform)) { color = FlutterCupertinoColors.getColor(text); } else { color = FlutterColors.getColor(text); } if (color != null) { return color.getAWTColor(); } return null; } @Override public void setColorTo(@NotNull PsiElement element, @NotNull Color color) { // Not trying to look up Material or Cupertino colors. // Unfortunately, there is no way to prevent the color picker from showing (if clicked) for those expressions. if (!element.getText().equals("Color")) return; final Document document = PsiDocumentManager.getInstance(element.getProject()).getDocument(element.getContainingFile()); final Runnable command = () -> { final PsiElement refExpr = topmostReferenceExpression(element); if (refExpr == null) return; PsiElement parent = refExpr.getParent(); if (parent == null) return; if (parent.getNode().getElementType() == DartTokenTypes.CALL_EXPRESSION) { // foo(Color.fromRGBO(0, 255, 0, 0.5)) replaceColor(parent, refExpr, color); } else if (parent.getNode().getElementType() == DartTokenTypes.SIMPLE_TYPE) { // const Color.fromARGB(100, 255, 0, 0) // parent.getParent().getParent() is a new expr parent = getNewExprFromType(parent); if (parent == null) return; replaceColor(parent, refExpr, color); } }; CommandProcessor.getInstance() .executeCommand(element.getProject(), command, FlutterBundle.message("change.color.command.text"), null, document); } private void replaceColor(@NotNull PsiElement parent, @NotNull PsiElement refExpr, Color color) { final PsiElement selectorNode = refExpr.getLastChild(); if (selectorNode == null) return; final String selector = selectorNode.getText(); final boolean isFromARGB = "fromARGB".equals(selector); final boolean isFromRGBO = "fromRGBO".equals(selector); final PsiElement args = parent.getLastChild(); if (args == null || args.getNode().getElementType() != DartTokenTypes.ARGUMENTS) return; final DartArgumentList list = ((DartArguments)args).getArgumentList(); if (list == null) return; if (isFromARGB) { replaceARGB(list.getExpressionList(), color); } else if (isFromRGBO) { replaceRGBO(list.getExpressionList(), color); } else { replaceArg(list.getExpressionList(), color); } } private void replaceARGB(@NotNull List<DartExpression> args, Color color) { if (args.size() != 4) return; final List<Integer> colors = Arrays.asList(color.getAlpha(), color.getRed(), color.getGreen(), color.getBlue()); for (int i = 0; i < args.size(); i++) { replaceInt(args.get(i), colors.get(i)); } } private void replaceRGBO(@NotNull List<DartExpression> args, Color color) { if (args.size() != 4) return; final List<Integer> colors = Arrays.asList(color.getRed(), color.getGreen(), color.getBlue()); for (int i = 0; i < colors.size(); i++) { replaceInt(args.get(i), colors.get(i)); } replaceDouble(args.get(3), (double)color.getAlpha() / 255.0); } private void replaceArg(@NotNull List<DartExpression> args, Color color) { if (args.size() != 1) return; replaceInt(args.get(0), color.getRGB()); } private void replaceInt(DartExpression expr, Integer value) { if (expr instanceof DartLiteralExpression) { final String source = expr.getText(); final String number = source.substring(Math.min(2, source.length())); // Preserve case of 0x separate from hex string, eg. 0xFFEE00DD. final boolean isHex = source.startsWith("0x") || source.startsWith("0X"); final boolean isUpper = isHex && number.toUpperCase().equals(number); final String newValue = isHex ? Integer.toHexString(value) : Integer.toString(value); final String num = isUpper ? newValue.toUpperCase() : newValue; final String hex = isHex ? source.substring(0, 2) + num : num; final PsiFileFactoryImpl factory = new PsiFileFactoryImpl(expr.getManager()); final PsiElement newPsi = factory.createElementFromText(hex, DartLanguage.INSTANCE, DartTokenTypes.LITERAL_EXPRESSION, expr.getContext()); if (newPsi != null) { expr.replace(newPsi); } } } private void replaceDouble(DartExpression expr, Double value) { if (expr instanceof DartLiteralExpression) { final PsiFileFactoryImpl factory = new PsiFileFactoryImpl(expr.getManager()); final String number = Double.toString(value); final PsiElement newPsi = factory.createElementFromText(number, DartLanguage.INSTANCE, DartTokenTypes.LITERAL_EXPRESSION, expr.getContext()); if (newPsi != null) { expr.replace(newPsi); } } } }
flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterColorProvider.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterColorProvider.java", "repo_id": "flutter-intellij", "token_count": 4900 }
434
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.editor; /** * A line range describing the extent of and indent guide. */ public class LineRange { LineRange(int startLine, int endLine) { this.startLine = startLine; this.endLine = endLine; } final int startLine; final int endLine; }
flutter-intellij/flutter-idea/src/io/flutter/editor/LineRange.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/LineRange.java", "repo_id": "flutter-intellij", "token_count": 135 }
435
/* * Copyright 2021 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.font; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.ProjectAndLibrariesScope; import com.jetbrains.lang.dart.DartFileType; import com.jetbrains.lang.dart.ide.index.DartLibraryIndex; import com.jetbrains.lang.dart.psi.DartComponentName; import com.jetbrains.lang.dart.resolve.ClassNameScopeProcessor; import com.jetbrains.lang.dart.resolve.DartPsiScopeProcessor; import com.jetbrains.lang.dart.util.DartResolveUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import io.flutter.FlutterBundle; import io.flutter.editor.FlutterIconLineMarkerProvider; import io.flutter.settings.FlutterSettings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static io.flutter.editor.FlutterIconLineMarkerProvider.KnownPaths; public class FontPreviewProcessor { public static final String PACKAGE_SEPARATORS = "[,\r\n]"; public static final Map<String, String> UNSUPPORTED_PACKAGES = new THashMap<>(); // If there are triple quotes around a package URL they won't be recognized. private static final Pattern EXPORT_STATEMENT_PATTERN = Pattern.compile("^\\s*export\\s+[\"']([-_. $A-Za-z0-9/]+\\.dart)[\"'].*"); private static final Pattern IMPORT_STATEMENT_PATTERN = Pattern.compile("^\\s*import\\s+[\"']([-_. $A-Za-z0-9/]+\\.dart)[\"'].*"); private static final Map<String, Set<String>> ANALYZED_PROJECT_FILES = new THashMap<>(); private static final Map<String, WorkItem> WORK_ITEMS = new THashMap<>(); private static Logger LOG = Logger.getInstance(FontPreviewProcessor.class); static { UNSUPPORTED_PACKAGES.put("flutter_icons", FlutterBundle.message("icon.preview.disallow.flutter_icons")); UNSUPPORTED_PACKAGES.put("flutter_vector_icons", FlutterBundle.message("icon.preview.disallow.flutter_vector_icons")); UNSUPPORTED_PACKAGES.put("material_design_icons_flutter", FlutterBundle.message("icon.preview.disallow.material_design_icons_flutter")); } public static void analyze(@NotNull Project project) { final FontPreviewProcessor service = ApplicationManager.getApplication().getService(FontPreviewProcessor.class); service.generate(project); } public static void reanalyze(@NotNull Project project) { clearProjectCaches(project); analyze(project); } public void generate(@NotNull Project project) { if (ANALYZED_PROJECT_FILES.containsKey(project.getBasePath())) { return; } LOG = FlutterSettings.getInstance().isVerboseLogging() ? Logger.getInstance(FontPreviewProcessor.class) : null; log("Analyzing project ", project.getName()); ANALYZED_PROJECT_FILES.put(project.getBasePath(), new THashSet<>()); ProjectManager.getInstance().addProjectManagerListener(project, new ProjectManagerListener() { @Override public void projectClosed(@NotNull Project project) { clearProjectCaches(project); ProjectManagerListener.super.projectClosed(project); } }); final String projectPath = project.getBasePath(); final WorkItem item = new WorkItem(projectPath); WORK_ITEMS.put(projectPath, item); final String packagesText = FlutterSettings.getInstance().getFontPackages(); final String[] packages = packagesText.split(PACKAGE_SEPARATORS); item.addPackages( Arrays.stream(packages) .map(String::trim) .filter((each) -> !each.isEmpty() || FontPreviewProcessor.UNSUPPORTED_PACKAGES.get(each) != null) .collect(Collectors.toList())); processItems(project); } void processItems(@NotNull Project project) { final Task.Backgroundable task = new Task.Backgroundable(project, FlutterBundle.message("icon.preview.analysis"), true) { public void run(@NotNull final ProgressIndicator indicator) { final AtomicBoolean isRunning = new AtomicBoolean(true); final long startTime = System.currentTimeMillis(); while (isRunning.get()) { final String path = project.getBasePath(); final WorkItem item = WORK_ITEMS.get(path); if (!processNextItem(project, item)) { if (item.filesWithNoClasses.isEmpty()) { // Finished, clean up and exit. synchronized (this) { if (item == WORK_ITEMS.get(path)) { WORK_ITEMS.remove(path); } isRunning.set(false); if (System.currentTimeMillis() - startTime > 1000) { // If this analysis takes too long there is a good chance the highlighting pass completed before all // icon classes were found. That might cause some icons to not get displayed, so just run it again. DaemonCodeAnalyzer.getInstance(project).restart(); } } } else { for (String key : item.filesWithNoClasses.keySet()) { final PathInfo info = item.filesWithNoClasses.get(key); final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(info.filePath); if (virtualFile != null) { item.addFileToCheck(info.packageName, info.filePath, virtualFile); } } item.filesWithNoClasses.clear(); } } } } public void onCancel() { if (project.isDisposed()) { return; } clearProjectCaches(project); DaemonCodeAnalyzer.getInstance(project).restart(); } }; ProgressManager.getInstance().run(task); } // Analyze the next item in the queue. Leave it in the queue until analysis is complete. // Any switch to dumb mode during a read action or a write action will cancel this analysis, // which will restart with the same item. boolean processNextItem(@NotNull Project project, @NotNull WorkItem item) { if (item.isCancelled) { return false; } final Application app = ApplicationManager.getApplication(); if (item.hasFilesToRewrite()) { app.invokeLater(() -> rewriteNextFile(project, item)); return true; } else if (item.hasClasses()) { analyzeNextClass(project, item); return true; } else if (item.hasFilesToAnalyze()) { analyzeNextFile(project, item); return true; } else if (item.hasPackages()) { analyzeNextPackage(project, item); return true; } else if (item.hasFilesToCheck()) { checkNextFile(project, item); return true; } else if (item.hasFilesToDelete()) { app.invokeLater(() -> deleteNextFile(project, item)); return true; } return false; } private void analyzeNextPackage(@NotNull Project project, @NotNull WorkItem item) { if (project.isDisposed() || item.isCancelled) { return; } final String info = item.getPackage(); if (info == null) { return; } findFontFiles(project, info, item); item.removePackage(); } private void rewriteNextFile(@NotNull Project project, @NotNull WorkItem item) { if (project.isDisposed() || item.isCancelled) { return; } final FileInfo info = item.getFileToRewrite(); if (info == null) { return; } final VirtualFile file = info.file; final String packageName = info.packageName; final String path = file.getPath(); final int packageIndex = path.indexOf(packageName); if (ANALYZED_PROJECT_FILES.get(item.projectPath).contains(path)) { item.removeFileToRewrite(); return; } log("Rewriting file ", file.getName(), " in ", packageName); // Remove import statements in an attempt to minimize extraneous analysis. final VirtualFile filteredFile = filterImports(file); if (filteredFile == null) { log("Cannot filter imports in ", file.getName()); return; } item.filesWithNoClasses.put(path, new PathInfo(packageName, path)); item.addFileToAnalyze(packageName, path, filteredFile); item.addFileToDelete(filteredFile); item.removeFileToRewrite(); } private void analyzeNextFile(@NotNull Project project, @NotNull WorkItem item) { if (project.isDisposed() || item.isCancelled) { return; } final FileInfo info = item.getFileToAnalyze(); if (info == null) { return; } final String packageName = info.packageName; final String path = info.originalPath; final VirtualFile file = info.file; final Set<String> analyzedProjectFiles = ANALYZED_PROJECT_FILES.get(item.projectPath); if (analyzedProjectFiles.contains(path)) { item.removeFileToAnalyze(); return; } log("Analyzing file ", file.getPath(), " path ", path); analyzedProjectFiles.add(path); final PsiFile psiFile = DumbService.getInstance(project).runReadActionInSmartMode(() -> PsiManager.getInstance(project).findFile(file)); if (psiFile == null) { log("Cannot get PSI file for ", file.getName()); return; } final Set<DartComponentName> classNames = new THashSet<>(); final DartPsiScopeProcessor processor = new ClassNameScopeProcessor(classNames); final boolean success = DumbService.getInstance(project).runReadActionInSmartMode(() -> { final boolean result = DartResolveUtil.processTopLevelDeclarations(psiFile, processor, file, null); if (result) { final Set<DartComponentName> keep = new THashSet<>(); for (DartComponentName name : classNames) { if (file.equals(name.getContainingFile().getVirtualFile())) { keep.add(name); } } classNames.clear(); classNames.addAll(keep); } return result; // Return from lambda, not method, setting value of success. }); if (success) { log("Queueing ", String.valueOf(classNames.size()), " classes for ", path); item.addClasses(packageName, path, classNames); } else { log("Resolution failed for ", path); } item.removeFileToAnalyze(); } private void analyzeNextClass(@NotNull Project project, @NotNull WorkItem item) { if (project.isDisposed() || item.isCancelled) { return; } final ClassInfo info = item.getClassToCheck(); if (info == null) { return; } final String packageName = info.packageName; final String path = info.filePath; final PsiFile psiFile = DumbService.getInstance(project).runReadActionInSmartMode(info.name::getContainingFile); if (path.contains(packageName)) { final String name = DumbService.getInstance(project).runReadActionInSmartMode(info.name::getName); log("Adding ", name, " -> ", path); final Set<String> knownPaths = KnownPaths.get(name); if (knownPaths == null) { KnownPaths.put(name, new THashSet<>(Collections.singleton(path))); } else { knownPaths.add(path); } item.filesWithNoClasses.remove(path); } item.removeClassToCheck(); } private void checkNextFile(@NotNull Project project, @NotNull WorkItem item) { if (project.isDisposed() || item.isCancelled) { return; } // If no classes were found then the file may be a list of export statements that refer to files that do define icons. try { final FileInfo info = item.getFileToCheck(); if (info == null) { return; } final VirtualFile file = info.file; log("Checking for exports in ", file.getPath(), " path ", info.originalPath); final String packageName = info.packageName; final String source = new String(file.contentsToByteArray()); final BufferedReader reader = new BufferedReader(new StringReader(source)); String line; while ((line = reader.readLine()) != null) { final Matcher matcher = EXPORT_STATEMENT_PATTERN.matcher(line); if (!matcher.matches()) { continue; } final String name = matcher.group(1); if (name != null) { final VirtualFile next = LocalFileSystem.getInstance().findFileByNioFile(Paths.get(file.getParent().getPath(), name)); final String nextPath; if (next == null || isInSdk(nextPath = next.getPath())) { continue; } if (ANALYZED_PROJECT_FILES.get(project.getBasePath()).contains(nextPath)) { continue; } item.addFileToAnalyze(packageName, nextPath, next); } } item.removeFileToCheck(); } catch (IOException e) { // ignored log("IOException", e); } } private void deleteNextFile(Project project, WorkItem item) { final VirtualFile filteredFile = item.getFileToDelete(); if (filteredFile != null) { ApplicationManager.getApplication().runWriteAction(() -> { try { log("Deleting file ", filteredFile.getName()); filteredFile.delete(this); // need write access item.removeFileToDelete(); } catch (IOException e) { // ignored } }); } } private static void clearProjectCaches(@NotNull Project project) { ANALYZED_PROJECT_FILES.remove(project.getBasePath()); WORK_ITEMS.remove(project.getBasePath()); FlutterIconLineMarkerProvider.initialize(); } // Look for classes in a package that define static variables with named icons. // We may have to analyze exports to get to them, as is done by some icon aggregator packages. private void findFontFiles(@NotNull Project project, @NotNull String packageName, @NotNull WorkItem item) { if (packageName.isEmpty() || FontPreviewProcessor.UNSUPPORTED_PACKAGES.get(packageName) != null) { return; } log("Analyzing package ", packageName); final Application application = ApplicationManager.getApplication(); final GlobalSearchScope projectScope = new ProjectAndLibrariesScope(project); Collection<VirtualFile> files = DumbService.getInstance(project) .runReadActionInSmartMode(() -> DartLibraryIndex.getFilesByLibName(projectScope, packageName)); if (files.isEmpty()) { final GlobalSearchScope scope = GlobalSearchScope.allScope(project); files = DumbService.getInstance(project).runReadActionInSmartMode(() -> FileTypeIndex.getFiles(DartFileType.INSTANCE, scope)); // TODO(messick) This finds way too many files. Optimize. } item.addFilesToRewrite(packageName, files); } private VirtualFile filterImports(VirtualFile file) { final StringBuilder newSource = new StringBuilder(); final String source; try { source = new String(file.contentsToByteArray()); final BufferedReader reader = new BufferedReader(new StringReader(source)); String line; while ((line = reader.readLine()) != null) { final Matcher matcher = IMPORT_STATEMENT_PATTERN.matcher(line); if (matcher.matches()) { continue; } newSource.append(line); newSource.append('\n'); } final File ioFile = FileUtil.createTempFile(file.getNameWithoutExtension(), ".dart"); final VirtualFile newFile = LocalFileSystem.getInstance().findFileByIoFile(ioFile); if (newFile == null) { return null; } final Application app = ApplicationManager.getApplication(); app.invokeAndWait(() -> { app.runWriteAction(() -> { try { newFile.setBinaryContent(newSource.toString().getBytes(StandardCharsets.UTF_8)); newFile.setCharset(StandardCharsets.UTF_8); } catch (IOException ex) { // ignored } }); }); return newFile; } catch (IOException e) { // ignored } return null; } private static boolean isInSdk(String path) { return path.contains("flutter/packages/flutter/lib") || path.contains("flutter/bin/cache/dart-sdk"); } private static void log(String msg, String... msgs) { if (LOG != null) { final StringBuilder b = new StringBuilder("ICONS -- "); b.append(msg); for (String s : msgs) { b.append(" ").append(s); } LOG.info(b.toString()); } } private static void log(String msg, Exception ex) { if (LOG != null) { LOG.info("ICONS--" + msg, ex); } } static class WorkItem { final Queue<String> packagesToAnalyze = new LinkedList<>(); final Queue<FileInfo> filesToAnalyze = new LinkedList<>(); final Queue<VirtualFile> filesToDelete = new LinkedList<>(); final Queue<FileInfo> filesToRewrite = new LinkedList<>(); final Queue<ClassInfo> classesToAnalyze = new LinkedList<>(); final Queue<FileInfo> filesToCheck = new LinkedList<>(); final Map<String, PathInfo> filesWithNoClasses = new THashMap<>(); final String projectPath; boolean isCancelled = false; WorkItem(String packageName) { this.projectPath = packageName; } boolean hasClasses() { return !classesToAnalyze.isEmpty(); } boolean hasFilesToAnalyze() { return !filesToAnalyze.isEmpty(); } boolean hasFilesToCheck() { return !filesToCheck.isEmpty(); } boolean hasFilesToDelete() { return !filesToDelete.isEmpty(); } boolean hasFilesToRewrite() { return !filesToRewrite.isEmpty(); } boolean hasPackages() { return !packagesToAnalyze.isEmpty(); } void addFileToAnalyze(@NotNull String packageName, @NotNull String path, @NotNull VirtualFile name) { filesToAnalyze.add(new FileInfo(packageName, path, name)); } void addFileToCheck(@NotNull String packageName, @NotNull String path, @NotNull VirtualFile name) { filesToCheck.add(new FileInfo(packageName, path, name)); } public void addFileToDelete(@NotNull VirtualFile file) { filesToDelete.add(file); } void addFileToRewrite(@NotNull String packageName, @NotNull String path, @NotNull VirtualFile name) { filesToRewrite.add(new FileInfo(packageName, path, name)); } @Nullable FileInfo getFileToAnalyze() { return filesToAnalyze.peek(); } @Nullable ClassInfo getClassToCheck() { return classesToAnalyze.peek(); } void removeClassToCheck() { classesToAnalyze.remove(); } void removeFileToAnalyze() { filesToAnalyze.remove(); } @Nullable FileInfo getFileToCheck() { return filesToCheck.peek(); } void removeFileToCheck() { filesToCheck.remove(); } @Nullable FileInfo getFileToRewrite() { return filesToRewrite.peek(); } void removeFileToRewrite() { synchronized (this) { if (!filesToRewrite.isEmpty()) { filesToRewrite.remove(); } } } @Nullable VirtualFile getFileToDelete() { return filesToDelete.peek(); } void removeFileToDelete() { synchronized (this) { if (!filesToDelete.isEmpty()) { filesToDelete.remove(); } } } @Nullable String getPackage() { return packagesToAnalyze.peek(); } void removePackage() { packagesToAnalyze.remove(); } void addPackages(@NotNull List<String> packages) { packagesToAnalyze.addAll(packages); } public void addClasses(@NotNull String packageName, @NotNull String filePath, @NotNull Set<DartComponentName> names) { classesToAnalyze.addAll( names.stream() .map((each) -> new ClassInfo(packageName, filePath, each)) .collect(Collectors.toList())); } void addFilesToRewrite(@NotNull String packageName, @NotNull Collection<VirtualFile> files) { filesToRewrite.addAll( files.stream() .filter((each) -> { final String path = each.getPath(); final int packageIndex = path.indexOf(packageName); return !(packageIndex < 0 || isInSdk(path)); }) .map((each) -> new FileInfo(packageName, each.getPath(), each)) .collect(Collectors.toList())); } } static class ClassInfo { private final String packageName; private final String filePath; private final DartComponentName name; ClassInfo(String packageName, String filePath, DartComponentName name) { this.packageName = packageName; this.filePath = filePath; this.name = name; } } static class FileInfo { private final String packageName; private final String originalPath; private final VirtualFile file; FileInfo(String packageName, String path, VirtualFile file) { this.packageName = packageName; this.originalPath = path; this.file = file; } } static class PathInfo { private final String packageName; private final String filePath; PathInfo(String packageName, String filePath) { this.packageName = packageName; this.filePath = filePath; } } }
flutter-intellij/flutter-idea/src/io/flutter/font/FontPreviewProcessor.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/font/FontPreviewProcessor.java", "repo_id": "flutter-intellij", "token_count": 8444 }
436
/* * 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.inspector; import java.util.Objects; /** * Reference to a Dart object. * <p> * This class is similar to the Observatory protocol InstanceRef with the * difference that InspectorInstanceRef objects do not expire and all * instances of the same Dart object are guaranteed to have the same * InspectorInstanceRef id. The tradeoff is the consumer of * InspectorInstanceRef objects is responsible for managing their lifecycles. */ public class InspectorInstanceRef { public InspectorInstanceRef(String id) { this.id = id; } @Override public boolean equals(Object other) { if (other instanceof InspectorInstanceRef) { final InspectorInstanceRef otherRef = (InspectorInstanceRef)other; return Objects.equals(id, otherRef.id); } return false; } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } @Override public String toString() { return "instance-" + id; } public String getId() { return id; } private final String id; }
flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorInstanceRef.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorInstanceRef.java", "repo_id": "flutter-intellij", "token_count": 356 }
437
package io.flutter.jxbrowser; public enum FailureType { SYSTEM_INCOMPATIBLE, FILE_DOWNLOAD_FAILED, MISSING_KEY, DIRECTORY_CREATION_FAILED, MISSING_PLATFORM_FILES, CLASS_LOAD_FAILED, CLASS_NOT_FOUND, }
flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/FailureType.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/FailureType.java", "repo_id": "flutter-intellij", "token_count": 105 }
438
<?xml version="1.0" encoding="UTF-8"?> <form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="io.flutter.module.settings.ProjectType"> <grid id="27dc6" binding="projectTypePanel" layout-manager="GridLayoutManager" row-count="2" 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="297" height="400"/> </constraints> <properties/> <border type="none"/> <children> <component id="2e1c4" class="com.intellij.openapi.ui.ComboBox" binding="projectTypeCombo" custom-create="true"> <constraints> <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <toolTipText resource-bundle="io/flutter/FlutterBundle" key="flutter.module.create.settings.type.tip"/> </properties> </component> <vspacer id="7f479"> <constraints> <grid row="1" 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> <hspacer id="54647"> <constraints> <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/> </constraints> </hspacer> </children> </grid> </form>
flutter-intellij/flutter-idea/src/io/flutter/module/settings/ProjectType.form/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/settings/ProjectType.form", "repo_id": "flutter-intellij", "token_count": 682 }
439
/* * 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 path. */ package io.flutter.perf; import com.google.common.base.Objects; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.impl.XSourcePositionImpl; /** * Source location within a file with an id that is unique with the current * running Flutter application. */ public class Location { public Location(String path, int line, int column, int id, TextRange textRange, String name) { this.path = path; this.line = line; this.column = column; this.id = id; this.textRange = textRange; this.name = name; } @Override public boolean equals(Object obj) { if (!(obj instanceof Location)) return false; final Location other = (Location)obj; return Objects.equal(line, other.line) && Objects.equal(column, other.column) && Objects.equal(path, other.path) && Objects.equal(id, other.id); } @Override public int hashCode() { return Objects.hashCode(line, column, path, id); } public final int line; public final int column; public final int id; public final String path; public XSourcePosition getXSourcePosition() { final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); if (file == null) { return null; } return XSourcePositionImpl.create(file, line - 1, column - 1); } /** * Range in the file corresponding to the identify name at this location. */ public final TextRange textRange; /** * Text of the identifier at this location. * <p> * Typically this is the name of a widget class. */ public final String name; }
flutter-intellij/flutter-idea/src/io/flutter/perf/Location.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/Location.java", "repo_id": "flutter-intellij", "token_count": 633 }
440
/* * 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.performance; import com.intellij.execution.runners.ExecutionUtil; import com.intellij.icons.AllIcons; import com.intellij.ide.browsers.BrowserLauncher; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.SideBorder; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.labels.LinkLabel; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import icons.FlutterIcons; import io.flutter.bazel.WorkspaceCache; import io.flutter.devtools.DevToolsUrl; import io.flutter.run.FlutterDevice; import io.flutter.run.FlutterLaunchMode; import io.flutter.run.daemon.DevToolsService; import io.flutter.run.daemon.FlutterApp; import io.flutter.sdk.FlutterSdk; import io.flutter.utils.AsyncUtils; import io.flutter.utils.VmServiceListenerAdapter; import io.flutter.view.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.CompoundBorder; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FlutterPerformanceView implements Disposable { public static final String TOOL_WINDOW_ID = "Flutter Performance"; private static final Logger LOG = Logger.getInstance(FlutterPerformanceView.class); @NotNull private final Project myProject; private final Map<FlutterApp, PerfViewAppState> perAppViewState = new HashMap<>(); private Content emptyContent; public FlutterPerformanceView(@NotNull Project project) { myProject = project; } void initToolWindow(ToolWindow window) { if (window.isDisposed()) return; updateForEmptyContent(window); } @Override public void dispose() { Disposer.dispose(this); } @NotNull public Project getProject() { return myProject; } private void updateForEmptyContent(ToolWindow toolWindow) { // There's a possible race here where the tool window gets disposed while we're displaying contents. if (toolWindow.isDisposed()) { return; } toolWindow.setIcon(FlutterIcons.Flutter_13); // Display a 'No running applications' message. final ContentManager contentManager = toolWindow.getContentManager(); final JPanel panel = new JPanel(new BorderLayout()); final JBLabel label = new JBLabel("No running applications", SwingConstants.CENTER); label.setForeground(UIUtil.getLabelDisabledForeground()); panel.add(label, BorderLayout.CENTER); emptyContent = contentManager.getFactory().createContent(panel, null, false); contentManager.addContent(emptyContent); } void debugActive(@NotNull FlutterViewMessages.FlutterDebugEvent event) { final FlutterApp app = event.app; final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); if (!(toolWindowManager instanceof ToolWindowManagerEx)) { return; } final ToolWindow toolWindow = toolWindowManager.getToolWindow(TOOL_WINDOW_ID); if (toolWindow == null) { return; } if (!toolWindow.isAvailable()) { toolWindow.setAvailable(true, null); } addPerformanceViewContent(app, toolWindow); app.getVmService().addVmServiceListener(new VmServiceListenerAdapter() { @Override public void connectionOpened() { onAppChanged(app); } @Override public void connectionClosed() { ApplicationManager.getApplication().invokeLater(() -> { if (toolWindow.isDisposed()) return; final ContentManager contentManager = toolWindow.getContentManager(); onAppChanged(app); final PerfViewAppState state = perAppViewState.remove(app); if (state != null) { if (state.content != null) { contentManager.removeContent(state.content, true); } if (state.disposable != null) { Disposer.dispose(state.disposable); } } if (perAppViewState.isEmpty()) { // No more applications are running. updateForEmptyContent(toolWindow); } }); } }); onAppChanged(app); } private void addPerformanceViewContent(FlutterApp app, ToolWindow toolWindow) { final ContentManager contentManager = toolWindow.getContentManager(); final SimpleToolWindowPanel toolWindowPanel = new SimpleToolWindowPanel(true); final FlutterDevice device = app.device(); final List<FlutterDevice> existingDevices = new ArrayList<>(); for (FlutterApp otherApp : perAppViewState.keySet()) { existingDevices.add(otherApp.device()); } final String tabName = device.getUniqueName(existingDevices); // mainContentPanel contains the toolbar, perfViewsPanel, and the footer final JPanel mainContentPanel = new JPanel(new BorderLayout()); final Content content = contentManager.getFactory().createContent(null, tabName, false); content.setComponent(mainContentPanel); content.putUserData(ToolWindow.SHOW_CONTENT_ICON, Boolean.TRUE); content.setIcon(FlutterIcons.Phone); contentManager.addContent(content); // perfViewsPanel contains the three performance views final JComponent perfViewsPanel = Box.createVerticalBox(); perfViewsPanel.setBorder(JBUI.Borders.empty(0, 3)); mainContentPanel.add(perfViewsPanel, BorderLayout.CENTER); if (emptyContent != null) { contentManager.removeContent(emptyContent, true); emptyContent = null; } toolWindow.setIcon(ExecutionUtil.getLiveIndicator(FlutterIcons.Flutter_13)); final PerfViewAppState state = getOrCreateStateForApp(app); assert (state.content == null); state.content = content; final DefaultActionGroup toolbarGroup = createToolbar(toolWindow, app, this); toolWindowPanel.setToolbar(ActionManager.getInstance().createActionToolbar( "FlutterPerfViewToolbar", toolbarGroup, true).getComponent()); final ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("PerformanceToolbar", toolbarGroup, true); final JComponent toolbarComponent = toolbar.getComponent(); toolbarComponent.setBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM)); mainContentPanel.add(toolbarComponent, BorderLayout.NORTH); // devtools link and run mode footer final JPanel footer = new JPanel(new BorderLayout()); footer.setBorder(new CompoundBorder( IdeBorderFactory.createBorder(SideBorder.TOP), JBUI.Borders.empty(5, 7))); final JLabel runModeLabel = new JBLabel("Run mode: " + app.getLaunchMode()); if (app.getLaunchMode() == FlutterLaunchMode.DEBUG) { runModeLabel.setIcon(AllIcons.General.BalloonInformation); runModeLabel.setToolTipText("Note: debug mode frame rendering times are not indicative of release mode performance"); } final LinkLabel<String> openDevtools = new LinkLabel<>("Open DevTools...", null); openDevtools.setListener((linkLabel, data) -> { AsyncUtils.whenCompleteUiThread(DevToolsService.getInstance(app.getProject()).getDevToolsInstance(), (instance, ex) -> { if (app.getProject().isDisposed()) { return; } if (ex != null) { LOG.error(ex); return; } FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(app.getProject()); BrowserLauncher.getInstance().browse( (new DevToolsUrl(instance.host, instance.port, app.getConnector().getBrowserUrl(), null, false, null, null, flutterSdk == null ? null : flutterSdk.getVersion(), WorkspaceCache.getInstance(app.getProject()), null)).getUrlString(), null ); }); }, null); footer.add(runModeLabel, BorderLayout.WEST); footer.add(openDevtools, BorderLayout.EAST); mainContentPanel.add(footer, BorderLayout.SOUTH); final boolean debugConnectionAvailable = app.getLaunchMode().supportsDebugConnection(); final boolean isInProfileMode = app.getMode().isProfiling() || app.getLaunchMode().isProfiling(); // If the inspector is available (non-release mode), then show it. if (debugConnectionAvailable) { state.disposable = Disposer.newDisposable(); // Create the three FPS, memory, and widget recount areas. final PerfFPSPanel fpsPanel = new PerfFPSPanel(app, this); perfViewsPanel.add(fpsPanel); final PerfMemoryPanel memoryPanel = new PerfMemoryPanel(app, this); perfViewsPanel.add(memoryPanel); final PerfWidgetRebuildsPanel widgetRebuildsPanel = new PerfWidgetRebuildsPanel(app, this); perfViewsPanel.add(widgetRebuildsPanel); // If in profile mode, auto-open the performance tool window. if (isInProfileMode) { activateToolWindow(); } } else { // Add a message about the inspector not being available in release mode. final JBLabel label = new JBLabel("Profiling is not available in release mode", SwingConstants.CENTER); label.setForeground(UIUtil.getLabelDisabledForeground()); mainContentPanel.add(label, BorderLayout.CENTER); } } private DefaultActionGroup createToolbar(@NotNull ToolWindow toolWindow, @NotNull FlutterApp app, Disposable parentDisposable) { final DefaultActionGroup toolbarGroup = new DefaultActionGroup(); toolbarGroup.add(registerAction(new PerformanceOverlayAction(app))); toolbarGroup.addSeparator(); toolbarGroup.add(registerAction(new DebugPaintAction(app))); toolbarGroup.add(registerAction(new ShowPaintBaselinesAction(app, true))); toolbarGroup.addSeparator(); toolbarGroup.add(registerAction(new TimeDilationAction(app, true))); return toolbarGroup; } FlutterViewAction registerAction(FlutterViewAction action) { getOrCreateStateForApp(action.app).flutterViewActions.add(action); return action; } public void showForApp(@NotNull FlutterApp app) { final PerfViewAppState appState = perAppViewState.get(app); if (appState != null) { final ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(TOOL_WINDOW_ID); if (toolWindow != null) { toolWindow.getContentManager().setSelectedContent(appState.content); } } } public void showForAppRebuildCounts(@NotNull FlutterApp app) { final PerfViewAppState appState = perAppViewState.get(app); if (appState != null) { final ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(TOOL_WINDOW_ID); if (toolWindow != null) { toolWindow.getContentManager().setSelectedContent(appState.content); } } } private void onAppChanged(FlutterApp app) { if (myProject.isDisposed()) { return; } final ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(TOOL_WINDOW_ID); if (toolWindow == null) { //noinspection UnnecessaryReturnStatement return; } } /** * Activate the tool window. */ private void activateToolWindow() { final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); final ToolWindow toolWindow = toolWindowManager.getToolWindow(TOOL_WINDOW_ID); if (toolWindow == null || toolWindow.isVisible()) { return; } toolWindow.show(null); } private PerfViewAppState getStateForApp(FlutterApp app) { return perAppViewState.get(app); } private PerfViewAppState getOrCreateStateForApp(FlutterApp app) { return perAppViewState.computeIfAbsent(app, k -> new PerfViewAppState()); } } class PerfViewAppState { ArrayList<FlutterViewAction> flutterViewActions = new ArrayList<>(); @Nullable Disposable disposable; Content content; FlutterViewAction registerAction(FlutterViewAction action) { flutterViewActions.add(action); return action; } }
flutter-intellij/flutter-idea/src/io/flutter/performance/FlutterPerformanceView.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/performance/FlutterPerformanceView.java", "repo_id": "flutter-intellij", "token_count": 4435 }
441
/* * 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 com.google.common.util.concurrent.Uninterruptibles; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.jetbrains.lang.dart.assists.AssistUtils; import com.jetbrains.lang.dart.assists.DartSourceEditException; import icons.FlutterIcons; import io.flutter.FlutterInitializer; import io.flutter.FlutterMessages; import io.flutter.dart.FlutterDartAnalysisServer; import io.flutter.inspector.InspectorGroupManagerService; import io.flutter.inspector.InspectorService; import io.flutter.run.FlutterReloadManager; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.EventStream; import org.dartlang.analysis.server.protocol.FlutterOutline; import org.dartlang.analysis.server.protocol.SourceChange; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; import java.util.concurrent.TimeUnit; /** * Toolbar containing all the widget refactor actions. * <p> * This toolbar is extracted out from the OutlineView so that it can be reused * anywhere we want to expose Flutter widget refactors. For example, as a * toolbar of a property editing popop exposed directly in a code editor. */ public class WidgetEditToolbar { private class QuickAssistAction extends AnAction { private final String id; QuickAssistAction(@NotNull String id, Icon icon, String assistMessage) { super(assistMessage, null, icon); this.id = id; messageToActionMap.put(assistMessage, this); } @Override public void actionPerformed(@NotNull AnActionEvent e) { sendAnalyticEvent(id); final SourceChange change; synchronized (actionToChangeMap) { change = actionToChangeMap.get(this); actionToChangeMap.clear(); } if (change != null) { applyChangeAndShowException(change); } } @Override public void update(AnActionEvent e) { final boolean hasChange = actionToChangeMap.containsKey(this); e.getPresentation().setEnabled(hasChange); } boolean isEnabled() { return actionToChangeMap.containsKey(this); } } private class ExtractMethodAction extends AnAction { private final String id = "dart.assist.flutter.extractMethod"; ExtractMethodAction() { super("Extract Method...", null, FlutterIcons.ExtractMethod); } @Override public void actionPerformed(@NotNull AnActionEvent e) { final AnAction action = ActionManager.getInstance().getAction("ExtractMethod"); if (action != null) { final FlutterOutline outline = getWidgetOutline(); if (outline != null) { TransactionGuard.submitTransaction(project, () -> { final Editor editor = getCurrentEditor(); if (editor == null) { // It is a race condition if we hit this. Gracefully assume // the action has just been canceled. return; } final OutlineOffsetConverter converter = new OutlineOffsetConverter(project, activeFile.getValue()); final int offset = converter.getConvertedOutlineOffset(outline); editor.getCaretModel().moveToOffset(offset); final JComponent editorComponent = editor.getComponent(); final DataContext editorContext = DataManager.getInstance().getDataContext(editorComponent); final AnActionEvent editorEvent = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, editorContext); action.actionPerformed(editorEvent); }); } } } @Override public void update(AnActionEvent e) { final boolean isEnabled = isEnabled(); e.getPresentation().setEnabled(isEnabled); } boolean isEnabled() { return getWidgetOutline() != null && getCurrentEditor() != null; } } private class ExtractWidgetAction extends AnAction { private final String id = "dart.assist.flutter.extractwidget"; ExtractWidgetAction() { super("Extract Widget..."); } @Override public void actionPerformed(@NotNull AnActionEvent e) { final AnAction action = ActionManager.getInstance().getAction("Flutter.ExtractWidget"); if (action != null) { TransactionGuard.submitTransaction(project, () -> { final Editor editor = getCurrentEditor(); if (editor == null) { // It is a race condition if we hit this. Gracefully assume // the action has just been canceled. return; } final JComponent editorComponent = editor.getComponent(); final DataContext editorContext = DataManager.getInstance().getDataContext(editorComponent); final AnActionEvent editorEvent = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, editorContext); action.actionPerformed(editorEvent); }); } } @Override public void update(AnActionEvent e) { final boolean isEnabled = isEnabled(); e.getPresentation().setEnabled(isEnabled); } boolean isEnabled() { return getWidgetOutline() != null && getCurrentEditor() != null; } } final QuickAssistAction actionCenter; final QuickAssistAction actionPadding; final QuickAssistAction actionColumn; final QuickAssistAction actionRow; final QuickAssistAction actionContainer; final QuickAssistAction actionMoveUp; final QuickAssistAction actionMoveDown; final QuickAssistAction actionRemove; final ExtractMethodAction actionExtractMethod; final ExtractWidgetAction actionExtractWidget; private final FlutterDartAnalysisServer flutterAnalysisServer; private final EventStream<VirtualFile> activeFile; private final Map<String, AnAction> messageToActionMap = new HashMap<>(); private final Map<AnAction, SourceChange> actionToChangeMap = new HashMap<>(); private final Project project; /** * Wheter to trigger a hot reload after the widget refactor is executed. */ private final boolean hotReloadOnAction; /** * EventStream providing the outline(s) that are currently considered active. */ EventStream<List<FlutterOutline>> activeOutlines; private ActionToolbar toolbar; public WidgetEditToolbar( boolean hotReloadOnAction, EventStream<List<FlutterOutline>> activeOutlines, EventStream<VirtualFile> activeFile, Project project, FlutterDartAnalysisServer flutterAnalysisServer ) { this.hotReloadOnAction = hotReloadOnAction; this.project = project; this.flutterAnalysisServer = flutterAnalysisServer; this.activeFile = activeFile; actionCenter = new QuickAssistAction("dart.assist.flutter.wrap.center", FlutterIcons.Center, "Wrap with Center"); actionPadding = new QuickAssistAction("dart.assist.flutter.wrap.padding", FlutterIcons.Padding, "Wrap with Padding"); actionColumn = new QuickAssistAction("dart.assist.flutter.wrap.column", FlutterIcons.Column, "Wrap with Column"); actionRow = new QuickAssistAction("dart.assist.flutter.wrap.row", FlutterIcons.Row, "Wrap with Row"); actionContainer = new QuickAssistAction("dart.assist.flutter.wrap.container", FlutterIcons.Container, "Wrap with Container"); actionMoveUp = new QuickAssistAction("dart.assist.flutter.move.up", FlutterIcons.Up, "Move widget up"); actionMoveDown = new QuickAssistAction("dart.assist.flutter.move.down", FlutterIcons.Down, "Move widget down"); actionRemove = new QuickAssistAction("dart.assist.flutter.removeWidget", FlutterIcons.RemoveWidget, "Remove this widget"); actionExtractMethod = new ExtractMethodAction(); actionExtractWidget = new ExtractWidgetAction(); this.activeOutlines = activeOutlines; activeOutlines.listen(this::activeOutlineChanged); } Editor getCurrentEditor() { final VirtualFile file = activeFile.getValue(); if (file == null) return null; final FileEditor fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(file); if (fileEditor instanceof TextEditor) { final TextEditor textEditor = (TextEditor)fileEditor; final Editor editor = textEditor.getEditor(); if (!editor.isDisposed()) { return editor; } } return null; } public ActionToolbar getToolbar() { if (toolbar == null) { final DefaultActionGroup toolbarGroup = new DefaultActionGroup(); toolbarGroup.add(actionCenter); toolbarGroup.add(actionPadding); toolbarGroup.add(actionColumn); toolbarGroup.add(actionRow); toolbarGroup.add(actionContainer); toolbarGroup.addSeparator(); toolbarGroup.add(actionExtractMethod); toolbarGroup.addSeparator(); toolbarGroup.add(actionMoveUp); toolbarGroup.add(actionMoveDown); toolbarGroup.addSeparator(); toolbarGroup.add(actionRemove); toolbar = ActionManager.getInstance().createActionToolbar("PreviewViewToolbar", toolbarGroup, true); } return toolbar; } private void activeOutlineChanged(List<FlutterOutline> outlines) { synchronized (actionToChangeMap) { actionToChangeMap.clear(); } final VirtualFile selectionFile = activeFile.getValue(); if (selectionFile != null && !outlines.isEmpty()) { ApplicationManager.getApplication().executeOnPooledThread(() -> { final OutlineOffsetConverter converter = new OutlineOffsetConverter(project, activeFile.getValue()); final FlutterOutline firstOutline = outlines.get(0); final FlutterOutline lastOutline = outlines.get(outlines.size() - 1); final int offset = converter.getConvertedOutlineOffset(firstOutline); final int length = converter.getConvertedOutlineEnd(lastOutline) - offset; final List<SourceChange> changes = flutterAnalysisServer.edit_getAssists(selectionFile, offset, length); // If the current file or outline are different, ignore the changes. // We will eventually get new changes. final List<FlutterOutline> newOutlines = activeOutlines.getValue(); if (!Objects.equals(activeFile.getValue(), selectionFile) || !outlines.equals(newOutlines)) { return; } // Associate changes with actions. // Actions will be enabled / disabled in background. for (SourceChange change : changes) { final AnAction action = messageToActionMap.get(change.getMessage()); if (action != null) { actionToChangeMap.put(action, change); } } // Update actions immediately. if (getToolbar() != null) { ApplicationManager.getApplication().invokeLater(() -> getToolbar().updateActionsImmediately()); } }); } } FlutterOutline getWidgetOutline() { final List<FlutterOutline> outlines = activeOutlines.getValue(); if (outlines.size() == 1) { final FlutterOutline outline = outlines.get(0); if (outline.getDartElement() == null) { return outline; } } return null; } private void sendAnalyticEvent(@NotNull String name) { FlutterInitializer.getAnalytics().sendEvent("preview", name); } private void applyChangeAndShowException(SourceChange change) { ApplicationManager.getApplication().runWriteAction(() -> { try { AssistUtils.applySourceChange(project, change, false); if (hotReloadOnAction) { final InspectorService inspectorService = InspectorGroupManagerService.getInstance(project).getInspectorService(); if (inspectorService != null) { final ArrayList<FlutterApp> apps = new ArrayList<>(); apps.add(inspectorService.getApp()); FlutterReloadManager.getInstance(project).saveAllAndReloadAll(apps, "Refactor widget"); } } } catch (DartSourceEditException exception) { FlutterMessages.showError("Error applying change", exception.getMessage(), project); } }); } public void createPopupMenu(Component comp, int x, int y) { // The corresponding tree item may have just been selected. // Wait short time for receiving assists from the server. // TODO(jacobr): this hard coded sleep seems like a hack. Figure out a // more robust way to wait for all assists to be received. for (int i = 0; i < 20 && actionToChangeMap.isEmpty(); i++) { Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS); } final DefaultActionGroup group = new DefaultActionGroup(); boolean hasAction = false; if (actionCenter.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionCenter)); } if (actionPadding.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionPadding)); } if (actionColumn.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionColumn)); } if (actionRow.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionRow)); } if (actionContainer.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionContainer)); } group.addSeparator(); if (actionExtractMethod.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionExtractMethod)); } if (actionExtractWidget.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionExtractWidget)); } group.addSeparator(); if (actionMoveUp.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionMoveUp)); } if (actionMoveDown.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionMoveDown)); } group.addSeparator(); if (actionRemove.isEnabled()) { hasAction = true; group.add(new TextOnlyActionWrapper(actionRemove)); } // Don't show the empty popup. if (!hasAction) { return; } final ActionManager actionManager = ActionManager.getInstance(); final ActionPopupMenu popupMenu = actionManager.createActionPopupMenu(ActionPlaces.UNKNOWN, group); popupMenu.getComponent().show(comp, x, y); } }
flutter-intellij/flutter-idea/src/io/flutter/preview/WidgetEditToolbar.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/preview/WidgetEditToolbar.java", "repo_id": "flutter-intellij", "token_count": 5137 }
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.run; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerManager; import com.intellij.xdebugger.frame.XStackFrame; import io.flutter.FlutterBundle; import io.flutter.vmService.frame.DartVmServiceStackFrame; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FlutterPopFrameAction extends AnAction implements DumbAware { public FlutterPopFrameAction() { final Presentation presentation = getTemplatePresentation(); presentation.setText(FlutterBundle.message("flutter.pop.frame.action.text")); presentation.setDescription(FlutterBundle.message("flutter.pop.frame.action.description")); presentation.setIcon(AllIcons.Actions.PopFrame); } public void actionPerformed(@NotNull AnActionEvent e) { final DartVmServiceStackFrame frame = getStackFrame(e); if (frame != null) { frame.dropFrame(); } } public void update(@NotNull AnActionEvent e) { final DartVmServiceStackFrame frame = getStackFrame(e); final boolean enabled = frame != null && frame.canDrop(); if (ActionPlaces.isMainMenuOrActionSearch(e.getPlace()) || ActionPlaces.DEBUGGER_TOOLBAR.equals(e.getPlace())) { e.getPresentation().setEnabled(enabled); } else { e.getPresentation().setVisible(enabled); } } @Nullable private static DartVmServiceStackFrame getStackFrame(@NotNull final AnActionEvent e) { final Project project = e.getProject(); if (project == null) return null; XDebugSession session = e.getData(XDebugSession.DATA_KEY); if (session == null) { session = XDebuggerManager.getInstance(project).getCurrentSession(); } if (session != null) { final XStackFrame frame = session.getCurrentStackFrame(); if (frame instanceof DartVmServiceStackFrame) { return ((DartVmServiceStackFrame)frame); } } return null; } }
flutter-intellij/flutter-idea/src/io/flutter/run/FlutterPopFrameAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/FlutterPopFrameAction.java", "repo_id": "flutter-intellij", "token_count": 826 }
443
/* * 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.bazel; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.CommandLineTokenizer; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.RuntimeConfigurationError; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.jetbrains.lang.dart.sdk.DartConfigurable; import com.jetbrains.lang.dart.sdk.DartSdk; import io.flutter.FlutterBundle; import io.flutter.FlutterMessages; import io.flutter.bazel.Workspace; import io.flutter.bazel.WorkspaceCache; import io.flutter.dart.DartPlugin; import io.flutter.run.FlutterDevice; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.DevToolsInstance; import io.flutter.run.daemon.DevToolsService; import io.flutter.settings.FlutterSettings; import io.flutter.utils.ElementIO; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import static io.flutter.run.common.RunMode.DEBUG; import static io.flutter.run.common.RunMode.PROFILE; /** * The fields in a Bazel run configuration. * <p> * This class is immutable. */ public class BazelFields { private static final Logger LOG = Logger.getInstance(BazelFields.class); /** * The Bazel target or Dart file to invoke. */ @Nullable private final String target; /** * Whether or not to run the app with --define flutter_build_mode=release. * * <p> * If this is not set, then the flutter_build_mode will depend on which button * the user pressed to run the app. * <ul> * <li>If the user pressed 'run' or 'debug', then flutter_build_mode=debug.</li> * <li>If the user pressed 'profile', then flutter_build_mode=profile.</li> * </ul> * * <p> * If the user overrides --define flutter_build_mode in {@link #bazelArgs}, then this field will be ignored. */ private final boolean enableReleaseMode; /** * Parameters to pass to Bazel, such as --define release_channel=beta3. */ @Nullable private final String bazelArgs; /** * This is to set a DevToolsService ahead of time, intended for testing. */ @Nullable private final DevToolsService devToolsService; /** * Parameters to pass to Flutter, such as --start-paused. */ @Nullable private final String additionalArgs; BazelFields(@Nullable String target, @Nullable String bazelArgs, @Nullable String additionalArgs, boolean enableReleaseMode) { this(target, bazelArgs, additionalArgs, enableReleaseMode, null); } BazelFields(@Nullable String target, @Nullable String bazelArgs, @Nullable String additionalArgs, boolean enableReleaseMode, @Nullable DevToolsService devToolsService) { this.target = target; this.bazelArgs = bazelArgs; this.additionalArgs = additionalArgs; this.enableReleaseMode = enableReleaseMode; this.devToolsService = devToolsService; } /** * Copy constructor */ BazelFields(@NotNull BazelFields original) { target = original.target; enableReleaseMode = original.enableReleaseMode; bazelArgs = original.bazelArgs; additionalArgs = original.additionalArgs; devToolsService = original.devToolsService; } @Nullable public String getBazelArgs() { return bazelArgs; } @Nullable public String getAdditionalArgs() { return additionalArgs; } /** * This can be either a bazel or a dart target. */ @Nullable public String getTarget() { return target; } public boolean getEnableReleaseMode() { return enableReleaseMode; } BazelFields copy() { return new BazelFields(this); } @Nullable private String getRunScriptFromWorkspace(@NotNull final Project project) { final Workspace workspace = getWorkspace(project); String runScript = workspace == null ? null : workspace.getRunScript(); if (runScript != null) { runScript = workspace.getRoot().getPath() + "/" + runScript; } return runScript; } private String getToolsScriptFromWorkspace(@NotNull final Project project) { final Workspace workspace = getWorkspace(project); String toolsScript = workspace == null ? null : workspace.getToolsScript(); if (toolsScript != null) { toolsScript = workspace.getRoot().getPath() + File.separatorChar + toolsScript; } return toolsScript; } // TODO(djshuckerow): this is dependency injection; switch this to a framework as we need more DI. @Nullable protected Workspace getWorkspace(@NotNull Project project) { return WorkspaceCache.getInstance(project).get(); } /** * Reports an error in the run config that the user should correct. * <p> * This will be called while the user is typing into a non-template run config. * (See RunConfiguration.checkConfiguration.) * * @throws RuntimeConfigurationError for an error that that the user must correct before running. */ void checkRunnable(@NotNull final Project project) throws RuntimeConfigurationError { // The UI only shows one error message at a time. // The order we do the checks here determines priority. final DartSdk sdk = DartPlugin.getDartSdk(project); if (sdk == null) { throw new RuntimeConfigurationError(FlutterBundle.message("dart.sdk.is.not.configured"), () -> DartConfigurable.openDartSettings(project)); } final String runScript = getRunScriptFromWorkspace(project); if (runScript == null) { throw new RuntimeConfigurationError(FlutterBundle.message("flutter.run.bazel.noLaunchingScript")); } final VirtualFile scriptFile = LocalFileSystem.getInstance().findFileByPath(runScript); if (scriptFile == null) { throw new RuntimeConfigurationError( FlutterBundle.message("flutter.run.bazel.launchingScriptNotFound", FileUtil.toSystemDependentName(runScript))); } // Check that target field is populated. if (StringUtil.isEmptyOrSpaces(target)) { throw new RuntimeConfigurationError(FlutterBundle.message("flutter.run.bazel.noBazelOrDartTargetSet")); } else if (!target.endsWith("dart") && !target.startsWith("//")) { throw new RuntimeConfigurationError(FlutterBundle.message("flutter.run.bazel.startWithSlashSlash")); } } GeneralCommandLine getLaunchCommand(@NotNull Project project, @Nullable FlutterDevice device, @NotNull RunMode mode) throws ExecutionException { return getLaunchCommand(project, device, mode, false); } /** * Returns the command to use to launch the Flutter app. (Via running the Bazel target.) */ GeneralCommandLine getLaunchCommand(@NotNull Project project, @Nullable FlutterDevice device, @NotNull RunMode mode, boolean isAttach) throws ExecutionException { try { checkRunnable(project); } catch (RuntimeConfigurationError e) { throw new ExecutionException(e); } final Workspace workspace = getWorkspace(project); final String launchingScript = isAttach ? getToolsScriptFromWorkspace(project) : getRunScriptFromWorkspace(project); assert launchingScript != null; // already checked assert workspace != null; // if the workspace is null, then so is the launching script, therefore this was already checked. final String target = getTarget(); assert target != null; // already checked final String additionalArgs = getAdditionalArgs(); final GeneralCommandLine commandLine = new GeneralCommandLine() .withWorkDirectory(workspace.getRoot().getPath()); commandLine.setCharset(StandardCharsets.UTF_8); commandLine.setExePath(FileUtil.toSystemDependentName(launchingScript)); if (isAttach) { commandLine.addParameter("attach"); } final String inputBazelArgs = StringUtil.notNullize(bazelArgs); if (!inputBazelArgs.isEmpty()) { commandLine.addParameter(String.format("--bazel-options=%s", inputBazelArgs)); } // Potentially add the flag related to build mode. if (enableReleaseMode) { commandLine.addParameter("--release"); } else if (mode.equals(PROFILE)) { commandLine.addParameter("--profile"); } // Tell the flutter command-line tools that we want a machine interface on stdio. commandLine.addParameter("--machine"); // Pause the app at startup in order to set breakpoints. if (!enableReleaseMode && mode == DEBUG) { commandLine.addParameter("--start-paused"); } // User specified additional target arguments. final CommandLineTokenizer additionalArgsTokenizer = new CommandLineTokenizer( StringUtil.notNullize(additionalArgs)); while (additionalArgsTokenizer.hasMoreTokens()) { commandLine.addParameter(additionalArgsTokenizer.nextToken()); } final String enableBazelHotRestartParam = "--enable-google3-hot-reload"; final String disableBazelHotRestartParam = "--no-enable-google3-hot-reload"; final boolean hasEnabledArg = StringUtil.notNullize(additionalArgs).contains(enableBazelHotRestartParam); final boolean hasDisabledArg = StringUtil.notNullize(additionalArgs).contains(disableBazelHotRestartParam); if (!FlutterSettings.getInstance().isEnableBazelHotRestart() && hasDisabledArg) { final Notification notification = new Notification( FlutterMessages.FLUTTER_NOTIFICATION_GROUP_ID, "Google3-specific hot restart is disabled by default", "You can now remove this flag from your configuration's additional args: " + disableBazelHotRestartParam, NotificationType.INFORMATION); Notifications.Bus.notify(notification, project); } else if (FlutterSettings.getInstance().isEnableBazelHotRestart() && !hasEnabledArg && !hasDisabledArg) { commandLine.addParameter(enableBazelHotRestartParam); } // Send in the deviceId. if (device != null) { commandLine.addParameter("-d"); commandLine.addParameter(device.deviceId()); final String message = workspace.getUpdatedIosRunMessage(); if (message != null && FlutterSettings.getInstance().isShowBazelIosRunNotification()) { final String title = device.isIOS() ? "Running iOS apps has improved!" : "Try running an iOS app!"; final Notification notification = new Notification( FlutterMessages.FLUTTER_NOTIFICATION_GROUP_ID, title, message, NotificationType.INFORMATION); Notifications.Bus.notify(notification, project); FlutterSettings.getInstance().setShowBazelIosRunNotification(false); } } try { final ProgressManager progress = ProgressManager.getInstance(); final CompletableFuture<DevToolsInstance> devToolsFuture = new CompletableFuture<>(); progress.runProcessWithProgressSynchronously(() -> { progress.getProgressIndicator().setIndeterminate(true); try { final DevToolsService service = this.devToolsService == null ? DevToolsService.getInstance(project) : this.devToolsService; final DevToolsInstance instance = service.getDevToolsInstance().get(30, TimeUnit.SECONDS); if (instance != null) { devToolsFuture.complete(instance); } else { devToolsFuture.completeExceptionally(new Exception("DevTools instance not available.")); } } catch (Exception e) { devToolsFuture.completeExceptionally(e); } }, "Starting DevTools", false, project); final DevToolsInstance instance = devToolsFuture.get(); commandLine.addParameter("--devtools-server-address=http://" + instance.host + ":" + instance.port); } catch (Exception e) { LOG.info(e); } commandLine.addParameter(target); return commandLine; } public void writeTo(Element element) { ElementIO.addOption(element, "target", target); ElementIO.addOption(element, "bazelArgs", bazelArgs); ElementIO.addOption(element, "additionalArgs", additionalArgs); ElementIO.addOption(element, "enableReleaseMode", Boolean.toString(enableReleaseMode)); } public static BazelFields readFrom(Element element) { final Map<String, String> options = ElementIO.readOptions(element); // Use old field name of bazelTarget if the newer one has not been set. final String bazelOrDartTarget = options.get("target") != null ? options.get("target") : options.get("bazelTarget"); final String bazelArgs = options.get("bazelArgs"); final String additionalArgs = options.get("additionalArgs"); final String enableReleaseMode = options.get("enableReleaseMode"); try { return new BazelFields(bazelOrDartTarget, bazelArgs, additionalArgs, Boolean.parseBoolean(enableReleaseMode)); } catch (IllegalArgumentException e) { throw new InvalidDataException(e.getMessage()); } } }
flutter-intellij/flutter-idea/src/io/flutter/run/bazel/BazelFields.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazel/BazelFields.java", "repo_id": "flutter-intellij", "token_count": 4686 }
444
/* * 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.run.bazelTest; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationTypeBase; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.run.bazel.FlutterBazelRunConfigurationType; import io.flutter.run.test.FlutterTestConfigType; import org.jetbrains.annotations.NotNull; /** * The Bazel version of the {@link FlutterTestConfigType} configuration. */ public class FlutterBazelTestConfigurationType extends ConfigurationTypeBase { final ConfigurationFactory factory = new Factory(this); final ConfigurationFactory watchFactory = new WatchFactory(this); protected FlutterBazelTestConfigurationType() { super("FlutterBazelTestConfigurationType", FlutterBundle.message("runner.flutter.bazel.test.configuration.name"), FlutterBundle.message("runner.flutter.bazel.configuration.description"), FlutterIcons.BazelRun); // Note that for both factories to produce inline run configurations for the left-hand tray context menu, // the Registry flag `suggest.all.run.configurations.from.context` should be enabled. // Otherwise, only one configuration may show up. addFactory(factory); addFactory(watchFactory); } public static FlutterBazelTestConfigurationType getInstance() { return Extensions.findExtension(CONFIGURATION_TYPE_EP, FlutterBazelTestConfigurationType.class); } /** * {@link ConfigurationFactory} for Flutter Bazel tests that run one-off. */ static class Factory extends ConfigurationFactory { private Factory(FlutterBazelTestConfigurationType type) { super(type); } @Override @NotNull public RunConfiguration createTemplateConfiguration(@NotNull Project project) { // This is always called first when loading a run config, even when it's a non-template config. // See RunManagerImpl.doCreateConfiguration return new BazelTestConfig(project, this, FlutterBundle.message("runner.flutter.bazel.test.configuration.name")); } @Override public boolean isApplicable(@NotNull Project project) { return FlutterBazelRunConfigurationType.doShowBazelRunConfigurationForProject(project); } @Override @NotNull public String getId() { return FlutterBundle.message("runner.flutter.bazel.test.configuration.name"); } } /** * {@link ConfigurationFactory} for Flutter Bazel tests that watch test results and re-run them. */ static class WatchFactory extends ConfigurationFactory { private WatchFactory(FlutterBazelTestConfigurationType type) { super(type); } @Override @NotNull public RunConfiguration createTemplateConfiguration(@NotNull Project project) { // This is always called first when loading a run config, even when it's a non-template config. // See RunManagerImpl.doCreateConfiguration final BazelTestConfig config = new BazelTestConfig(project, this, FlutterBundle.message("runner.flutter.bazel.test.configuration.name")); // TODO(djshuckerow): To make test watching work well with the detailed test output, we need to reset the test window every re-run. // Until then, we'll default watch configurations to running with --no-machine. config.setFields(new BazelTestFields(null, null, null, BazelTestFields.Flags.watch + " " + BazelTestFields.Flags.noMachine)); return config; } @Override public boolean isApplicable(@NotNull Project project) { return FlutterBazelRunConfigurationType.doShowBazelRunConfigurationForProject(project); } @Override @NotNull public String getName() { return "Watch " + super.getName(); } @Override @NotNull public String getId() { return FlutterBundle.message("runner.flutter.bazel.watch.test.configuration.name"); } } }
flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/FlutterBazelTestConfigurationType.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/FlutterBazelTestConfigurationType.java", "repo_id": "flutter-intellij", "token_count": 1296 }
445
/* * 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.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * <p>A message received from a Flutter process that's not in response to a particular request. * * <p>The protocol is specified in * <a href="https://github.com/flutter/flutter/wiki/The-flutter-daemon-mode" * >The Flutter Daemon Mode</a>. */ abstract class DaemonEvent { /** * Parses an event and sends it to the listener. */ static void dispatch(@NotNull JsonObject obj, @NotNull Listener listener) { final JsonPrimitive primEvent = obj.getAsJsonPrimitive("event"); if (primEvent == null) { LOG.info("Missing event field in JSON from flutter process: " + obj); return; } final String eventName = primEvent.getAsString(); if (eventName == null) { LOG.info("Unexpected event field in JSON from flutter process: " + obj); return; } final JsonObject params = obj.getAsJsonObject("params"); if (params == null) { LOG.info("Missing parameters in event from flutter process: " + obj); return; } final DaemonEvent event = create(eventName, params); if (event == null) { return; // Drop unknown event. } event.accept(listener); } @Nullable static DaemonEvent create(@NotNull String eventName, @NotNull JsonObject params) { try { switch (eventName) { case "daemon.connected": return GSON.fromJson(params, DaemonConnected.class); case "daemon.log": return GSON.fromJson(params, DaemonLog.class); case "daemon.logMessage": return GSON.fromJson(params, DaemonLogMessage.class); case "daemon.showMessage": return GSON.fromJson(params, DaemonShowMessage.class); case "app.start": return GSON.fromJson(params, AppStarting.class); case "app.debugPort": return GSON.fromJson(params, AppDebugPort.class); case "app.started": return GSON.fromJson(params, AppStarted.class); case "app.log": return GSON.fromJson(params, AppLog.class); case "app.progress": return GSON.fromJson(params, AppProgress.class); case "app.stop": return GSON.fromJson(params, AppStopped.class); case "device.added": return GSON.fromJson(params, DeviceAdded.class); case "device.removed": return GSON.fromJson(params, DeviceRemoved.class); default: return null; // Drop an unknown event. } } catch (JsonSyntaxException e) { LOG.info("Unexpected parameters in event from flutter process: " + params); return null; } } abstract void accept(Listener listener); @Override public String toString() { return GSON.toJson(this, getClass()); } /** * Receives events from a Flutter daemon process. */ interface Listener { // process lifecycle default void processWillTerminate() { } default void processTerminated(int exitCode) { } // daemon domain default void onDaemonConnected(DaemonConnected event) { } default void onDaemonLog(DaemonLog event) { } default void onDaemonLogMessage(DaemonLogMessage event) { } default void onDaemonShowMessage(DaemonShowMessage event) { } // app domain default void onAppStarting(AppStarting event) { } default void onAppDebugPort(AppDebugPort event) { } default void onAppStarted(AppStarted event) { } default void onAppLog(AppLog event) { } default void onAppProgressStarting(AppProgress event) { } default void onAppProgressFinished(AppProgress event) { } default void onAppStopped(AppStopped event) { } // device domain default void onDeviceAdded(DeviceAdded event) { } default void onDeviceRemoved(DeviceRemoved event) { } } // daemon domain static class DaemonConnected extends DaemonEvent { // "event":"daemon.log" String version; long pid; void accept(Listener listener) { listener.onDaemonConnected(this); } } static class DaemonLog extends DaemonEvent { // "event":"daemon.log" String log; boolean error; void accept(Listener listener) { listener.onDaemonLog(this); } } static class DaemonLogMessage extends DaemonEvent { // "event":"daemon.logMessage" String level; String message; String stackTrace; void accept(Listener listener) { listener.onDaemonLogMessage(this); } } static class DaemonShowMessage extends DaemonEvent { // "event":"daemon.showMessage" String level; String title; String message; void accept(Listener listener) { listener.onDaemonShowMessage(this); } } // app domain static class AppStarting extends DaemonEvent { public static final String LAUNCH_MODE_RUN = "run"; public static final String LAUNCH_MODE_ATTACH = "attach"; // "event":"app.start" String appId; String deviceId; String directory; String launchMode; boolean supportsRestart; void accept(Listener listener) { listener.onAppStarting(this); } } static class AppDebugPort extends DaemonEvent { // "event":"app.eventDebugPort" String appId; // <code>port</code> is deprecated; prefer using <code>wsUri</code>. // int port; String wsUri; String baseUri; void accept(Listener listener) { listener.onAppDebugPort(this); } } static class AppStarted extends DaemonEvent { // "event":"app.started" String appId; void accept(Listener listener) { listener.onAppStarted(this); } } static class AppLog extends DaemonEvent { // "event":"app.log" String appId; String log; boolean error; void accept(Listener listener) { listener.onAppLog(this); } } static class AppProgress extends DaemonEvent { // "event":"app.progress" // (technically undocumented) String appId; String id; /** * Undocumented, optional field; seems to be a progress event subtype. * See <a href="https://github.com/flutter/flutter/search?q=startProgress+progressId">code</a>. */ private String progressId; String message; private Boolean finished; @NotNull String getType() { return StringUtil.notNullize(progressId); } boolean isStarting() { return !isFinished(); } boolean isFinished() { return finished != null && finished; } void accept(Listener listener) { if (isStarting()) { listener.onAppProgressStarting(this); } else { listener.onAppProgressFinished(this); } } } static class AppStopped extends DaemonEvent { // "event":"app.stop" String appId; String error; void accept(Listener listener) { listener.onAppStopped(this); } } // device domain static class DeviceAdded extends DaemonEvent { // "event":"device.added" String id; String name; String platform; String emulatorId; Boolean emulator; @Nullable String category; @Nullable String platformType; @Nullable Boolean ephemeral; void accept(Listener listener) { listener.onDeviceAdded(this); } } static class DeviceRemoved extends DaemonEvent { // "event":"device.removed" String id; String name; String platform; boolean emulator; void accept(Listener listener) { listener.onDeviceRemoved(this); } } private static final Gson GSON = new Gson(); private static final Logger LOG = Logger.getInstance(DaemonEvent.class); }
flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DaemonEvent.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DaemonEvent.java", "repo_id": "flutter-intellij", "token_count": 2996 }
446
/* * 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.intellij.psi.PsiElement; import com.jetbrains.lang.dart.psi.DartFile; import io.flutter.FlutterUtils; import io.flutter.run.common.CommonTestConfigUtils; import io.flutter.run.common.TestType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class TestConfigUtils extends CommonTestConfigUtils { private static TestConfigUtils instance; public static TestConfigUtils getInstance() { if (instance == null) { instance = new TestConfigUtils(); } return instance; } private TestConfigUtils() { } @Nullable @Override public TestType asTestCall(@NotNull PsiElement element) { final DartFile file = FlutterUtils.getDartFile(element); if (!FlutterUtils.isInTestDir(file)) { return null; } return super.asTestCall(element); } }
flutter-intellij/flutter-idea/src/io/flutter/run/test/TestConfigUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/TestConfigUtils.java", "repo_id": "flutter-intellij", "token_count": 351 }
447
/* * 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.sdk; import com.intellij.openapi.roots.libraries.LibraryProperties; import com.intellij.util.xmlb.XmlSerializerUtil; import com.intellij.util.xmlb.annotations.Attribute; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FlutterPluginLibraryProperties extends LibraryProperties<FlutterPluginLibraryProperties> { public FlutterPluginLibraryProperties() { } @Override public boolean equals(Object other) { return other instanceof FlutterPluginLibraryProperties; } @Override public int hashCode() { return 0; } @Nullable @Override public FlutterPluginLibraryProperties getState() { return this; } // This attribute exists only to silence the "com.intellij.util.xmlb.Binding - no accessors for class" warning. @Attribute(value = "placeholder") public String placeholder; @Override public void loadState(@NotNull FlutterPluginLibraryProperties properties) { XmlSerializerUtil.copyBean(properties, this); } }
flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterPluginLibraryProperties.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterPluginLibraryProperties.java", "repo_id": "flutter-intellij", "token_count": 362 }
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.survey; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.io.HttpRequests; import io.flutter.utils.JsonUtils; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.concurrent.TimeUnit; public class FlutterSurveyService { private static final String FLUTTER_LAST_SURVEY_CONTENT_CHECK_KEY = "FLUTTER_LAST_SURVEY_CONTENT_CHECK_KEY"; private static final long CHECK_INTERVAL_IN_MS = TimeUnit.HOURS.toMillis(40); private static final String CONTENT_URL = "https://docs.flutter.dev/f/flutter-survey-metadata.json"; private static final PropertiesComponent properties = PropertiesComponent.getInstance(); private static final Logger LOG = Logger.getInstance(FlutterSurveyService.class); private static FlutterSurvey cachedSurvey; private static boolean timeToUpdateCachedContent() { // Don't check more often than daily. final long currentTimeMillis = System.currentTimeMillis(); final long lastCheckedMillis = properties.getLong(FLUTTER_LAST_SURVEY_CONTENT_CHECK_KEY, 0); final boolean timeToUpdateCache = currentTimeMillis - lastCheckedMillis >= CHECK_INTERVAL_IN_MS; if (timeToUpdateCache) { properties.setValue(FLUTTER_LAST_SURVEY_CONTENT_CHECK_KEY, String.valueOf(currentTimeMillis)); return true; } return false; } @Nullable static FlutterSurvey getLatestSurveyContent() { if (timeToUpdateCachedContent()) { // This async call will set the survey cache when content is fetched. (It's important that we not block the UI thread.) // The fetched content will get picked up in a subsequent call (on editor open or tab change). ApplicationManager.getApplication().executeOnPooledThread(() -> { cachedSurvey = fetchSurveyContent(); }); } return cachedSurvey; } @Nullable private static FlutterSurvey fetchSurveyContent() { try { final String contents = HttpRequests.request(CONTENT_URL).readString(); final JsonObject json = JsonUtils.parseString(contents).getAsJsonObject(); return FlutterSurvey.fromJson(json); } catch (IOException | JsonSyntaxException e) { // Null content is OK in case of a transient exception. } return null; } }
flutter-intellij/flutter-idea/src/io/flutter/survey/FlutterSurveyService.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/survey/FlutterSurveyService.java", "repo_id": "flutter-intellij", "token_count": 865 }
449
/* * 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.utils; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Multimap; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.util.messages.MessageBusConnection; import io.flutter.FlutterUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; /** * Watches a set of VirtualFiles for changes. * * <p>Each FileWatch instance represents one subscription. * * <p>The callback will be called when the IntelliJ Platform notices the change, * which may be different from when it's changed on disk, due to caching. */ public class FileWatch { private final @NotNull ImmutableSet<Location> watched; private final @NotNull Runnable callback; /** * When true, no more events should be delivered. */ private final AtomicBoolean unsubscribed = new AtomicBoolean(); /** * The representation of this FileWatch in IntelliJ's dispose tree. * * <p>(Private so that nobody can add children.) */ private final Disposable disposeLeaf; private FileWatch(@NotNull ImmutableSet<Location> watched, @NotNull Runnable callback) { this.watched = watched; this.callback = callback; this.disposeLeaf = this::unsubscribe; } /** * Starts watching a single file or directory. */ public static @NotNull FileWatch subscribe(@NotNull VirtualFile file, @NotNull Runnable callback) { final FileWatch watcher = new FileWatch(ImmutableSet.of(new Location(file, null)), callback); subscriptions.subscribe(watcher); return watcher; } /** * Starts watching some paths beneath a VirtualFile. * * <p>Each path is relative to the VirtualFile and need not exist. * * @param callback will be run asynchronously sometime after the file changed. */ public static @NotNull FileWatch subscribe(@NotNull VirtualFile base, @NotNull Iterable<String> paths, @NotNull Runnable callback) { final ImmutableSet.Builder<Location> builder = ImmutableSet.builder(); for (String path : paths) { builder.add(new Location(base, path)); } final FileWatch watcher = new FileWatch(builder.build(), callback); subscriptions.subscribe(watcher); return watcher; } /** * Returns true if the given file matches this watch. */ public boolean matches(VirtualFile file) { for (Location loc : watched) { if (loc.matches(file)) { return true; } } return false; } /** * Unsubscribes this FileWatch from events. */ public void unsubscribe() { if (!unsubscribed.compareAndSet(false, true)) { return; // already unsubscribed } subscriptions.unsubscribe(this); // Remove from dispose tree. Calls unsubscribe() again, harmlessly. Disposer.dispose(disposeLeaf); } /** * Automatically unsubscribes when a parent object is disposed. * * <p>Only one parent can be registered at a time. Auto-unsubscribe * will stop working for any object previously passed to this * method. */ public void setDisposeParent(@NotNull Disposable parent) { if (unsubscribed.get()) return; Disposer.register(parent, disposeLeaf); } private void fireEvent() { if (unsubscribed.get()) return; try { callback.run(); } catch (Exception e) { FlutterUtils.warn(LOG, "Uncaught exception in FileWatch callback", e); unsubscribe(); // avoid further errors } } /** * The location of a file or directory being watched. * <p> * Since it might not exist yet, this consists of a base VirtualFile and a path to where it might appear. */ private static class Location { private final @NotNull VirtualFile base; private final @Nullable String path; /** * The segments in the watched path, in reverse order (from leaf to base). */ private final @NotNull List<String> reversedNames; Location(@NotNull VirtualFile base, @Nullable String path) { if (path != null && path.isEmpty()) { throw new IllegalArgumentException("can't watch an empty path"); } this.base = base; this.path = path; this.reversedNames = path == null ? ImmutableList.of() : ImmutableList.copyOf(splitter.splitToList(path)).reverse(); } /** * Returns the name at the end of the path being watched. */ String getName() { if (reversedNames.isEmpty()) { return base.getName(); } else { return reversedNames.get(0); } } /** * Returns true if the given VirtualFile is at this location. */ boolean matches(VirtualFile file) { for (String name : reversedNames) { if (file == null || !file.getName().equals(name)) { return false; } file = file.getParent(); } return base.equals(file); } private static final Splitter splitter = Splitter.on('/'); } private static final Subscriptions subscriptions = new Subscriptions(); private static class Subscriptions { /** * For each VirtualFile name, the FileWatches that are subscribed (across all Projects). * * <p>For thread safety, all access should be synchronized. */ private final Multimap<String, FileWatch> byFile = LinkedListMultimap.create(); private final Delivery delivery = new Delivery(); synchronized void subscribe(FileWatch w) { for (Location loc : w.watched) { byFile.put(loc.getName(), w); } delivery.enable(!byFile.isEmpty()); } synchronized void unsubscribe(FileWatch w) { for (Location loc : w.watched) { byFile.remove(loc.getName(), w); } delivery.enable(!byFile.isEmpty()); } synchronized void addWatchesForFile(@NotNull Set<FileWatch> out, @Nullable VirtualFile f) { if (f == null) return; for (FileWatch w : byFile.get(f.getName())) { if (w.matches(f)) { out.add(w); } } } } private static class Delivery implements BulkFileListener { /** * The shared connection to IDEA's event system. * * <p>This will be non-null when there are one or more subscriptions. * * <p>For thread safety, all access should be synchronized. */ private @Nullable MessageBusConnection bus; void enable(boolean enabled) { if (enabled) { if (bus == null) { final Application app = ApplicationManager.getApplication(); bus = app.getMessageBus().connect(); bus.subscribe(VirtualFileManager.VFS_CHANGES, this); } } else { if (bus != null) { bus.disconnect(); bus = null; } } } @Override public void before(@NotNull List<? extends VFileEvent> events) { } @Override public void after(@NotNull List<? extends VFileEvent> events) { final Set<FileWatch> todo = new LinkedHashSet<>(); synchronized (subscriptions) { for (VFileEvent event : events) { subscriptions.addWatchesForFile(todo, event.getFile()); } } // Deliver changes synchronously, but after releasing the lock in case // the callback subscribes/unsubscribes. for (FileWatch w : todo) { w.fireEvent(); } } } private static final Logger LOG = Logger.getInstance(FileWatch.class); }
flutter-intellij/flutter-idea/src/io/flutter/utils/FileWatch.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/FileWatch.java", "repo_id": "flutter-intellij", "token_count": 2906 }
450
package io.flutter.utils; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.ex.ToolWindowManagerListener; import org.jetbrains.annotations.NotNull; /** * Helps to initialize a tool window with the same visibility state as when the project was previously closed. */ public abstract class ViewListener implements ToolWindowManagerListener { private final @NotNull Project project; private final String toolWindowId; private final String toolWindowVisibleProperty; public ViewListener(@NotNull Project project, String toolWindowId, String toolWindowVisibleProperty) { this.project = project; this.toolWindowId = toolWindowId; this.toolWindowVisibleProperty = toolWindowVisibleProperty; } @Override public void stateChanged(@NotNull ToolWindowManager toolWindowManager) { ToolWindow toolWindow = toolWindowManager.getToolWindow(toolWindowId); // We only make tool windows available once we've found a Flutter project, so we want to avoid setting the visible property until then. if (toolWindow != null && toolWindow.isAvailable()) { PropertiesComponent.getInstance(project).setValue(toolWindowVisibleProperty, toolWindow.isVisible(), false); } } }
flutter-intellij/flutter-idea/src/io/flutter/utils/ViewListener.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/ViewListener.java", "repo_id": "flutter-intellij", "token_count": 381 }
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.view; import com.google.gson.JsonObject; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.ui.JBColor; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.speedSearch.SpeedSearchSupply; import com.intellij.util.ui.UIUtil; import io.flutter.editor.FlutterMaterialIcons; import io.flutter.inspector.DiagnosticLevel; import io.flutter.inspector.DiagnosticsNode; import io.flutter.utils.ColorIconMaker; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static io.flutter.utils.JsonUtils.getIntMember; class DiagnosticsTreeCellRenderer extends InspectorColoredTreeCellRenderer { // TODO(jacobr): enable this experiment once we make the link actually clickable. private static final boolean SHOW_RENDER_OBJECT_PROPERTIES_AS_LINKS = false; private final InspectorPanel panel; /** * Split text into two groups, word characters at the start of a string and all other * characters. Skip an <code>-</code> or <code>#</code> between the two groups. */ private final Pattern primaryDescriptionPattern = Pattern.compile("([\\w ]+)[-#]?(.*)"); private JTree tree; private boolean selected; final ColorIconMaker colorIconMaker = new ColorIconMaker(); // Yellow color scheme for showing selecting and matching nodes. // TODO(jacobr): consider a scheme where the selected node is blue // to be more consistent with regular IntelliJ selected node display. // The main problem is in the regular scheme, selected but not focused // nodes are grey which makes the correlation between the selection in // the two views less obvious. private static final JBColor HIGHLIGHT_COLOR = new JBColor(new Color(202, 191, 69), new Color(99, 101, 103)); private static final JBColor SHOW_MATCH_COLOR = new JBColor(new Color(225, 225, 0), new Color(90, 93, 96)); private static final JBColor LINKED_COLOR = new JBColor(new Color(255, 255, 220), new Color(70, 73, 76)); public DiagnosticsTreeCellRenderer(InspectorPanel panel) { this.panel = panel; } public void customizeCellRenderer( @NotNull final JTree tree, final Object value, final boolean selected, final boolean expanded, final boolean leaf, final int row, final boolean hasFocus ) { this.tree = tree; this.selected = selected; setOpaque(false); setIconOpaque(false); setTransparentIconBackground(true); final Object userObject = ((DefaultMutableTreeNode)value).getUserObject(); if (userObject instanceof String) { appendText((String)userObject, SimpleTextAttributes.GRAYED_ATTRIBUTES); return; } if (!(userObject instanceof DiagnosticsNode)) return; final DiagnosticsNode node = (DiagnosticsNode)userObject; boolean highlight = selected; boolean isLinkedChild = false; // Highlight nodes that exist in both the details and summary tree to // show how the trees are linked together. if (!highlight && panel.isHighlightNodesShownInBothTrees()) { if (panel.detailsSubtree && panel.isCreatedByLocalProject(node)) { isLinkedChild = panel.parentTree.hasDiagnosticsValue(node.getValueRef()); } else { if (panel.subtreePanel != null) { isLinkedChild = panel.subtreePanel.hasDiagnosticsValue(node.getValueRef()); } } } if (highlight) { setOpaque(true); setIconOpaque(false); setTransparentIconBackground(true); setBackground(HIGHLIGHT_COLOR); // TODO(jacobr): consider using UIUtil.getTreeSelectionBackground() instead. } else if (isLinkedChild || panel.currentShowNode == value) { setOpaque(true); setIconOpaque(false); setTransparentIconBackground(true); setBackground(panel.currentShowNode == value ? SHOW_MATCH_COLOR : LINKED_COLOR); } final String name = node.getName(); SimpleTextAttributes textAttributes = InspectorPanel.textAttributesForLevel(node.getLevel()); if (node.isProperty()) { // Display of inline properties. final String propertyType = node.getPropertyType(); final JsonObject properties = node.getValuePropertiesJson(); if (panel.isCreatedByLocalProject(node)) { textAttributes = textAttributes .derive(SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES.getStyle(), null, null, null); } if (StringUtils.isNotEmpty(name) && node.getShowName()) { appendText(name + node.getSeparator() + " ", textAttributes); } String description = node.getDescription(); if (propertyType != null && properties != null) { switch (propertyType) { case "Color": { final int alpha = getIntMember(properties, "alpha"); final int red = getIntMember(properties, "red"); final int green = getIntMember(properties, "green"); final int blue = getIntMember(properties, "blue"); if (alpha == 255) { description = String.format("#%02x%02x%02x", red, green, blue); } else { description = String.format("#%02x%02x%02x%02x", alpha, red, green, blue); } //noinspection UseJBColor final Color color = new Color(red, green, blue, alpha); this.addIcon(colorIconMaker.getCustomIcon(color)); this.setIconOpaque(false); this.setTransparentIconBackground(true); break; } case "IconData": { final int codePoint = getIntMember(properties, "codePoint"); if (codePoint > 0) { final Icon icon = FlutterMaterialIcons.getIconForHex(String.format("%1$04x", codePoint)); if (icon != null) { this.addIcon(icon); this.setIconOpaque(false); this.setTransparentIconBackground(true); } } break; } } } if (SHOW_RENDER_OBJECT_PROPERTIES_AS_LINKS && propertyType.equals("RenderObject")) { textAttributes = textAttributes .derive(SimpleTextAttributes.LINK_ATTRIBUTES.getStyle(), JBColor.blue, null, null); } // TODO(jacobr): custom display for units, iterables, and padding. appendText(description, textAttributes); if (node.getLevel().equals(DiagnosticLevel.fine) && node.hasDefaultValue()) { appendText(" ", textAttributes); this.addIcon(panel.defaultIcon); } } else { // Non property, regular node case. if (StringUtils.isNotEmpty(name) && node.getShowName() && !name.equals("child")) { if (name.startsWith("child ")) { appendText(name, SimpleTextAttributes.GRAYED_ATTRIBUTES); } else { appendText(name, textAttributes); } if (node.getShowSeparator()) { appendText(node.getSeparator(), SimpleTextAttributes.GRAY_ATTRIBUTES); } else { appendText(" ", SimpleTextAttributes.GRAY_ATTRIBUTES); } } if (panel.detailsSubtree && panel.isCreatedByLocalProject(node) && !panel.isHighlightNodesShownInBothTrees()) { textAttributes = textAttributes.derive( SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES.getStyle(), null, null, null); } final String description = node.getDescription(); final Matcher match = primaryDescriptionPattern.matcher(description); if (match.matches()) { appendText(" ", SimpleTextAttributes.GRAY_ATTRIBUTES); appendText(match.group(1), textAttributes); appendText(" ", textAttributes); appendText(match.group(2), SimpleTextAttributes.GRAYED_ATTRIBUTES); } else if (!node.getDescription().isEmpty()) { appendText(" ", SimpleTextAttributes.GRAY_ATTRIBUTES); appendText(node.getDescription(), textAttributes); } // TODO(devoncarew): For widgets that are definied in the current project, we could consider // appending the relative path to the defining library ('lib/src/foo_page.dart'). final Icon icon = node.getIcon(); if (icon != null) { setIcon(icon); } } } private void appendText(@NotNull String text, @NotNull SimpleTextAttributes attributes) { appendFragmentsForSpeedSearch(tree, text, attributes, selected, this); } // Generally duplicated from SpeedSearchUtil.appendFragmentsForSpeedSearch public void appendFragmentsForSpeedSearch(@NotNull JComponent speedSearchEnabledComponent, @NotNull String text, @NotNull SimpleTextAttributes attributes, boolean selected, @NotNull MultiIconSimpleColoredComponent simpleColoredComponent) { final SpeedSearchSupply speedSearch = SpeedSearchSupply.getSupply(speedSearchEnabledComponent); if (speedSearch != null) { final Iterable<TextRange> fragments = speedSearch.matchingFragments(text); if (fragments != null) { final Color fg = attributes.getFgColor(); final Color bg = selected ? UIUtil.getTreeSelectionBackground() : UIUtil.getTreeTextBackground(); final int style = attributes.getStyle(); final SimpleTextAttributes plain = new SimpleTextAttributes(style, fg); final SimpleTextAttributes highlighted = new SimpleTextAttributes(bg, fg, null, style | SimpleTextAttributes.STYLE_SEARCH_MATCH); appendColoredFragments(simpleColoredComponent, text, fragments, plain, highlighted); return; } } simpleColoredComponent.append(text, attributes); } public void appendColoredFragments(final MultiIconSimpleColoredComponent simpleColoredComponent, final String text, Iterable<TextRange> colored, final SimpleTextAttributes plain, final SimpleTextAttributes highlighted) { final List<Pair<String, Integer>> searchTerms = new ArrayList<>(); for (TextRange fragment : colored) { searchTerms.add(Pair.create(fragment.substring(text), fragment.getStartOffset())); } int lastOffset = 0; for (Pair<String, Integer> pair : searchTerms) { if (pair.second > lastOffset) { simpleColoredComponent.append(text.substring(lastOffset, pair.second), plain); } simpleColoredComponent.append(text.substring(pair.second, pair.second + pair.first.length()), highlighted); lastOffset = pair.second + pair.first.length(); } if (lastOffset < text.length()) { simpleColoredComponent.append(text.substring(lastOffset), plain); } } }
flutter-intellij/flutter-idea/src/io/flutter/view/DiagnosticsTreeCellRenderer.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/DiagnosticsTreeCellRenderer.java", "repo_id": "flutter-intellij", "token_count": 4274 }
452
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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. */ /* * 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.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.JBColor; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.MouseEventAdapter; import com.intellij.util.ui.UIUtil; import icons.FlutterIcons; import io.flutter.inspector.DiagnosticsNode; import io.flutter.inspector.DiagnosticsTreeStyle; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import static io.flutter.inspector.TreeUtils.maybeGetDiagnostic; public class InspectorTreeUI extends BasicTreeUI { public static final String TREE_TABLE_TREE_KEY = "TreeTableTree"; @NonNls public static final String SOURCE_LIST_CLIENT_PROPERTY = "mac.ui.source.list"; @NonNls public static final String STRIPED_CLIENT_PROPERTY = "mac.ui.striped"; private static final Border LIST_BACKGROUND_PAINTER = UIManager.getBorder("List.sourceListBackgroundPainter"); private static final Border LIST_SELECTION_BACKGROUND_PAINTER = UIManager.getBorder("List.sourceListSelectionBackgroundPainter"); private static final Border LIST_FOCUSED_SELECTION_BACKGROUND_PAINTER = UIManager.getBorder("List.sourceListFocusedSelectionBackgroundPainter"); @NotNull private final Condition<Integer> myWideSelectionCondition; private boolean myWideSelection; private boolean myOldRepaintAllRowValue; private boolean mySkinny = false; boolean leftToRight = true; // TODO(jacobr): actually support RTL mode. public InspectorTreeUI() { this(false, Conditions.alwaysFalse()); } /** * Creates new {@code InspectorTreeUI} object. * * @param wideSelection flag that determines if wide selection should be used * @param wideSelectionCondition strategy that determine if wide selection should be used for a target row (it's zero-based index * is given to the condition as an argument) */ public InspectorTreeUI(final boolean wideSelection, @NotNull Condition<Integer> wideSelectionCondition) { myWideSelection = wideSelection; myWideSelectionCondition = wideSelectionCondition; } @Override public int getRightChildIndent() { return isCustomIndent() ? getCustomIndent() : super.getRightChildIndent(); } public boolean isCustomIndent() { return getCustomIndent() > 0; } protected int getCustomIndent() { return JBUI.scale(Registry.intValue("ide.ui.tree.indent")); } @Override protected MouseListener createMouseListener() { return new MouseEventAdapter<MouseListener>(super.createMouseListener()) { @Override public void mouseDragged(MouseEvent event) { final JTree tree = (JTree)event.getSource(); final Object property = tree.getClientProperty("DnD Source"); // DnDManagerImpl.SOURCE_KEY if (property == null) { super.mouseDragged(event); // use Swing-based DnD only if custom DnD is not set } } @NotNull @Override protected MouseEvent convert(@NotNull MouseEvent event) { if (!event.isConsumed() && SwingUtilities.isLeftMouseButton(event)) { int x = event.getX(); final int y = event.getY(); final JTree tree = (JTree)event.getSource(); if (tree.isEnabled()) { final TreePath path = getClosestPathForLocation(tree, x, y); if (path != null && !isLocationInExpandControl(path, x, y)) { final Rectangle bounds = getPathBounds(tree, path); if (bounds != null && bounds.y <= y && y <= (bounds.y + bounds.height)) { x = Math.max(bounds.x, Math.min(x, bounds.x + bounds.width - 1)); if (x != event.getX()) { event = convert(event, tree, x, y); } } } } } return event; } }; } @Override protected void completeUIInstall() { super.completeUIInstall(); myOldRepaintAllRowValue = UIManager.getBoolean("Tree.repaintWholeRow"); UIManager.put("Tree.repaintWholeRow", true); tree.setShowsRootHandles(true); } @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); UIManager.put("Tree.repaintWholeRow", myOldRepaintAllRowValue); } @Override protected void installKeyboardActions() { super.installKeyboardActions(); if (Boolean.TRUE.equals(tree.getClientProperty("MacTreeUi.actionsInstalled"))) return; tree.putClientProperty("MacTreeUi.actionsInstalled", Boolean.TRUE); final InputMap inputMap = tree.getInputMap(JComponent.WHEN_FOCUSED); inputMap.put(KeyStroke.getKeyStroke("pressed LEFT"), "collapse_or_move_up"); inputMap.put(KeyStroke.getKeyStroke("pressed RIGHT"), "expand"); final ActionMap actionMap = tree.getActionMap(); final Action expandAction = actionMap.get("expand"); if (expandAction != null) { actionMap.put("expand", new TreeUIAction() { @Override public void actionPerformed(ActionEvent e) { final Object source = e.getSource(); if (source instanceof JTree) { final JTree tree = (JTree)source; final int selectionRow = tree.getLeadSelectionRow(); if (selectionRow != -1) { final TreePath selectionPath = tree.getPathForRow(selectionRow); if (selectionPath != null) { final boolean leaf = tree.getModel().isLeaf(selectionPath.getLastPathComponent()); int toSelect = -1; int toScroll = -1; if (leaf || tree.isExpanded(selectionRow)) { if (selectionRow + 1 < tree.getRowCount()) { toSelect = selectionRow + 1; toScroll = toSelect; } } //todo[kb]: make cycle scrolling if (toSelect != -1) { tree.setSelectionInterval(toSelect, toSelect); } if (toScroll != -1) { tree.scrollRowToVisible(toScroll); } if (toSelect != -1 || toScroll != -1) return; } } } expandAction.actionPerformed(e); } }); } actionMap.put("collapse_or_move_up", new TreeUIAction() { @Override public void actionPerformed(final ActionEvent e) { final Object source = e.getSource(); if (source instanceof JTree) { final JTree tree = (JTree)source; final int selectionRow = tree.getLeadSelectionRow(); if (selectionRow == -1) return; final TreePath selectionPath = tree.getPathForRow(selectionRow); if (selectionPath == null) return; if (tree.getModel().isLeaf(selectionPath.getLastPathComponent()) || tree.isCollapsed(selectionRow)) { final TreePath parentPath = tree.getPathForRow(selectionRow).getParentPath(); if (parentPath != null) { if (parentPath.getParentPath() != null || tree.isRootVisible()) { final int parentRow = tree.getRowForPath(parentPath); tree.scrollRowToVisible(parentRow); tree.setSelectionInterval(parentRow, parentRow); } } } else { tree.collapseRow(selectionRow); } } } }); } private abstract static class TreeUIAction extends AbstractAction implements UIResource { } @Override protected int getRowX(int row, int depth) { if (isCustomIndent()) { final int off = tree.isRootVisible() ? 8 : 0; return 8 * depth + 8 + off; } else { return super.getRowX(row, depth); } } @Override protected void paintHorizontalPartOfLeg(final Graphics g, final Rectangle clipBounds, final Insets insets, final Rectangle bounds, final TreePath path, final int row, final boolean isExpanded, final boolean hasBeenExpanded, final boolean isLeaf) { if (path.getPathCount() < 2) { // We could draw lines for nodes with a single child but we omit them // to more of an emphasis of lines for nodes with multiple children. return; } if (path.getPathCount() >= 2) { final Object treeNode = path.getPathComponent(path.getPathCount() - 2); if (treeNode instanceof DefaultMutableTreeNode) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode)treeNode; if (node.getChildCount() < 2) { return; } } } boolean dashed = false; final DiagnosticsNode diagnosticsNode = maybeGetDiagnostic((DefaultMutableTreeNode)path.getLastPathComponent()); if (diagnosticsNode != null) { if (diagnosticsNode.isProperty()) { // Intentionally avoid ever drawing lines for properties as we need to // distinguish them from other nodes. See the DiagnosticsNode class in // Flutter which applies the same concept rendering properties inline // as part of ascii art tree display. return; } // This also consistent with the ascii art tree display where offstage // nodes are rendered using dashed lines. if (diagnosticsNode.getStyle() == DiagnosticsTreeStyle.offstage) { dashed = true; } } final int depth = path.getPathCount() - 1; if ((depth == 0 || (depth == 1 && !isRootVisible())) && !getShowsRootHandles()) { return; } final int lineY = bounds.y + bounds.height / 2; final int leafChildLineInset = 4; if (leftToRight) { int leftX = bounds.x - getRightChildIndent(); int nodeX = bounds.x - getHorizontalLegBuffer(); leftX = getRowX(row, depth - 1) - getRightChildIndent() + insets.left; nodeX = isLeaf ? getRowX(row, depth) - leafChildLineInset : getRowX(row, depth - 1); nodeX += insets.left; if (clipBounds.intersects(leftX, lineY, nodeX - leftX, 1)) { g.setColor(JBColor.GRAY); if (dashed) { drawDashedHorizontalLine(g, lineY, leftX, nodeX - 1); } else { paintHorizontalLine(g, tree, lineY, leftX, nodeX - 1); } } } // TODO(jacobr): implement RTL case. } @Override protected boolean isToggleSelectionEvent(MouseEvent e) { return UIUtil.isToggleListSelectionEvent(e); } @Override protected void paintVerticalPartOfLeg(final Graphics g, final Rectangle clipBounds, final Insets insets, final TreePath path) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); if (node.getChildCount() < 2) { // We could draw lines for nodes with a single child but we omit them // to more of an emphasis of lines for nodes with multiple children. return; } final DiagnosticsNode diagnostic = maybeGetDiagnostic(node); if (diagnostic != null && !diagnostic.hasChildren()) { // This avoids drawing lines for nodes with only property children. return; } final int depth = path.getPathCount() - 1; if (depth == 0 && !getShowsRootHandles() && !isRootVisible()) { return; } int lineX = getRowX(-1, depth); if (leftToRight) { lineX = lineX - getRightChildIndent() + insets.left; } else { lineX = tree.getWidth() - lineX - insets.right + getRightChildIndent() - 1; } final int clipLeft = clipBounds.x; final int clipRight = clipBounds.x + (clipBounds.width - 1); if (lineX >= clipLeft && lineX <= clipRight) { final int clipTop = clipBounds.y; final int clipBottom = clipBounds.y + clipBounds.height; Rectangle parentBounds = getPathBounds(tree, path); boolean previousDashed = false; int top; if (parentBounds == null) { top = Math.max(insets.top + getVerticalLegBuffer(), clipTop); } else { top = Math.max(parentBounds.y + parentBounds.height + getVerticalLegBuffer(), clipTop); } if (depth == 0 && !isRootVisible()) { final TreeModel model = getModel(); if (model != null) { final Object root = model.getRoot(); if (model.getChildCount(root) > 0) { parentBounds = getPathBounds(tree, path. pathByAddingChild(model.getChild(root, 0))); if (parentBounds != null) { top = Math.max(insets.top + getVerticalLegBuffer(), parentBounds.y + parentBounds.height / 2); } } } } for (int i = 0; i < node.getChildCount(); ++i) { final DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i); final DiagnosticsNode childDiagnostic = maybeGetDiagnostic(child); boolean dashed = false; if (childDiagnostic != null) { dashed = childDiagnostic.getStyle() == DiagnosticsTreeStyle.offstage; } final Rectangle childBounds = getPathBounds(tree, path.pathByAddingChild(child)); if (childBounds == null) // This shouldn't happen, but if the model is modified // in another thread it is possible for this to happen. // Swing isn't multithreaded, but I'll add this check in // anyway. { continue; } final int bottom = Math.min(childBounds.y + (childBounds.height / 2), clipBottom); if (top <= bottom && bottom >= clipTop && top <= clipBottom) { g.setColor(JBColor.GRAY); paintVerticalLine(g, tree, lineX, top, bottom, dashed); } top = bottom; previousDashed = dashed; } } } protected void paintVerticalLine(Graphics g, JComponent c, int x, int top, int bottom, boolean dashed) { if (dashed) { drawDashedVerticalLine(g, x, top, bottom); } else { g.drawLine(x, top, x, bottom); } } public @NotNull TreePath getLastExpandedDescendant(TreePath path) { while (tree.isExpanded(path)) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); if (node.isLeaf()) { break; } path = path.pathByAddingChild(node.getLastChild()); } return path; } private Rectangle getSubtreeBounds(DefaultMutableTreeNode node, Rectangle clipBounds) { if (node == null) { return null; } final TreePath path = new TreePath(node.getPath()); final int depth = path.getPathCount() - 1; final Rectangle rootBounds = tree.getPathBounds(path); if (rootBounds == null) { return null; } // We use getRowX instead of the value from rootBounds as we want to include // the down arrows final int minX = getRowX(-1, depth - 1); final int minY = rootBounds.y; final Rectangle bounds; final Rectangle descendantBounds = tree.getPathBounds(getLastExpandedDescendant(path)); if (descendantBounds != null) { final int maxY = (int)descendantBounds.getMaxY(); final int maxX = (int)clipBounds.getMaxX(); bounds = new Rectangle(minX, minY, maxX - minX, maxY - minY); } else { // This case shouldn't really happen unless we have a bug but using just // the root node bounds is a safe fallback. bounds = rootBounds; } return bounds.intersection(clipBounds); } @Override protected Color getHashColor() { //if (invertLineColor && !ComparatorUtil.equalsNullable(UIUtil.getTreeSelectionForeground(), UIUtil.getTreeForeground())) { // final Color c = UIUtil.getTreeSelectionForeground(); // if (c != null) { // return c.darker(); // } //} return super.getHashColor(); } public boolean isWideSelection() { return myWideSelection; } @Override protected void paintRow(final Graphics g, final Rectangle clipBounds, final Insets insets, final Rectangle bounds, final TreePath path, final int row, final boolean isExpanded, final boolean hasBeenExpanded, final boolean isLeaf) { final int containerWidth = tree.getParent() instanceof JViewport ? tree.getParent().getWidth() : tree.getWidth(); final int xOffset = tree.getParent() instanceof JViewport ? ((JViewport)tree.getParent()).getViewPosition().x : 0; if (path != null && myWideSelection) { final boolean selected = tree.isPathSelected(path); final Graphics2D rowGraphics = (Graphics2D)g.create(); rowGraphics.setClip(clipBounds); final Object sourceList = tree.getClientProperty(SOURCE_LIST_CLIENT_PROPERTY); Color background = tree.getBackground(); if ((row % 2) == 0 && Boolean.TRUE.equals(tree.getClientProperty(STRIPED_CLIENT_PROPERTY))) { background = UIUtil.getDecoratedRowColor(); } if (sourceList != null && (Boolean)sourceList) { if (selected) { if (tree.hasFocus()) { LIST_FOCUSED_SELECTION_BACKGROUND_PAINTER.paintBorder(tree, rowGraphics, xOffset, bounds.y, containerWidth, bounds.height); } else { LIST_SELECTION_BACKGROUND_PAINTER.paintBorder(tree, rowGraphics, xOffset, bounds.y, containerWidth, bounds.height); } } else if (myWideSelectionCondition.value(row)) { rowGraphics.setColor(background); rowGraphics.fillRect(xOffset, bounds.y, containerWidth, bounds.height); } } else { if (selected && (UIUtil.isUnderAquaBasedLookAndFeel() || UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF())) { final Color bg = getSelectionBackground(tree, true); if (myWideSelectionCondition.value(row)) { rowGraphics.setColor(bg); rowGraphics.fillRect(xOffset, bounds.y, containerWidth, bounds.height); } } } if (shouldPaintExpandControl(path, row, isExpanded, hasBeenExpanded, isLeaf)) { paintExpandControl(rowGraphics, bounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); } super.paintRow(rowGraphics, clipBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); rowGraphics.dispose(); } else { super.paintRow(g, clipBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); } } @Override protected void paintExpandControl(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { final boolean isPathSelected = tree.getSelectionModel().isPathSelected(path); boolean isPropertyNode = false; if (!isLeaf(row)) { final Object lastPathComponent = path.getLastPathComponent(); if (lastPathComponent instanceof DefaultMutableTreeNode) { final DiagnosticsNode diagnostic = maybeGetDiagnostic((DefaultMutableTreeNode)lastPathComponent); if (diagnostic != null) { isPropertyNode = diagnostic.isProperty(); } } if (isPropertyNode) { setExpandedIcon(FlutterIcons.CollapseProperty); setCollapsedIcon(FlutterIcons.ExpandProperty); } else { setExpandedIcon(UIUtil.getTreeNodeIcon(true, false, false)); setCollapsedIcon(UIUtil.getTreeNodeIcon(false, false, false)); } } super.paintExpandControl(g, clipBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); } @Override protected CellRendererPane createCellRendererPane() { return new CellRendererPane() { @Override public void paintComponent(Graphics g, Component c, Container p, int x, int y, int w, int h, boolean shouldValidate) { if (c instanceof JComponent && myWideSelection) { if (c.isOpaque()) { ((JComponent)c).setOpaque(false); } } super.paintComponent(g, c, p, x, y, w, h, shouldValidate); } }; } @Nullable private static Color getSelectionBackground(@NotNull JTree tree, boolean checkProperty) { final Object property = tree.getClientProperty(TREE_TABLE_TREE_KEY); if (property instanceof JTable) { return ((JTable)property).getSelectionBackground(); } boolean selection = tree.hasFocus(); if (!selection && checkProperty) { selection = Boolean.TRUE.equals(property); } return UIUtil.getTreeSelectionBackground(selection); } public void invalidateNodeSizes() { treeState.invalidateSizes(); } }
flutter-intellij/flutter-idea/src/io/flutter/view/InspectorTreeUI.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/InspectorTreeUI.java", "repo_id": "flutter-intellij", "token_count": 9432 }
453