text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_PRODUCER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_PRODUCER_H_
#include <lib/async/cpp/time.h>
#include <lib/async/default.h>
#include "flutter/flutter_vma/flutter_skia_vma.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/vulkan/procs/vulkan_proc_table.h"
#include "flutter/vulkan/vulkan_application.h"
#include "flutter/vulkan/vulkan_device.h"
#include "flutter/vulkan/vulkan_provider.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "logging.h"
#include "vulkan_surface.h"
#include "vulkan_surface_pool.h"
namespace flutter_runner {
class VulkanSurfaceProducer final : public SurfaceProducer,
public vulkan::VulkanProvider {
public:
explicit VulkanSurfaceProducer();
~VulkanSurfaceProducer() override;
bool IsValid() const { return valid_; }
// |SurfaceProducer|
GrDirectContext* gr_context() const override { return context_.get(); }
// |SurfaceProducer|
std::unique_ptr<SurfaceProducerSurface> ProduceOffscreenSurface(
const SkISize& size) override;
// |SurfaceProducer|
std::unique_ptr<SurfaceProducerSurface> ProduceSurface(
const SkISize& size) override;
// |SurfaceProducer|
void SubmitSurfaces(
std::vector<std::unique_ptr<SurfaceProducerSurface>> surfaces) override;
private:
// VulkanProvider
const vulkan::VulkanProcTable& vk() override { return *vk_.get(); }
const vulkan::VulkanHandle<VkDevice>& vk_device() override {
return logical_device_->GetHandle();
}
bool Initialize();
void SubmitSurface(std::unique_ptr<SurfaceProducerSurface> surface);
bool TransitionSurfacesToExternal(
const std::vector<std::unique_ptr<SurfaceProducerSurface>>& surfaces);
// Keep track of the last time we produced a surface. This is used to
// determine whether it is safe to shrink |surface_pool_| or not.
zx::time last_produce_time_ = async::Now(async_get_default_dispatcher());
// Disallow copy and assignment.
VulkanSurfaceProducer(const VulkanSurfaceProducer&) = delete;
VulkanSurfaceProducer& operator=(const VulkanSurfaceProducer&) = delete;
// Note: the order here is very important. The proctable must be destroyed
// last because it contains the function pointers for VkDestroyDevice and
// VkDestroyInstance.
fml::RefPtr<vulkan::VulkanProcTable> vk_;
std::unique_ptr<vulkan::VulkanApplication> application_;
std::unique_ptr<vulkan::VulkanDevice> logical_device_;
sk_sp<GrDirectContext> context_;
std::unique_ptr<VulkanSurfacePool> surface_pool_;
sk_sp<skgpu::VulkanMemoryAllocator> memory_allocator_;
bool valid_ = false;
// WeakPtrFactory must be the last member.
fml::WeakPtrFactory<VulkanSurfaceProducer> weak_factory_{this};
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_PRODUCER_H_
| engine/shell/platform/fuchsia/flutter/vulkan_surface_producer.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/vulkan_surface_producer.h",
"repo_id": "engine",
"token_count": 1106
} | 351 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_MAPPED_RESOURCE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_MAPPED_RESOURCE_H_
#include <fuchsia/mem/cpp/fidl.h>
#include <lib/fdio/namespace.h>
#include "third_party/dart/runtime/bin/elf_loader.h"
namespace dart_utils {
class ElfSnapshot {
public:
ElfSnapshot() {}
~ElfSnapshot();
ElfSnapshot(ElfSnapshot&& other) : handle_(other.handle_) {
other.handle_ = nullptr;
}
ElfSnapshot& operator=(ElfSnapshot&& other) {
std::swap(handle_, other.handle_);
return *this;
}
bool Load(fdio_ns_t* namespc, const std::string& path);
bool Load(int dirfd, const std::string& path);
const uint8_t* VmData() const { return vm_data_; }
const uint8_t* VmInstrs() const { return vm_instrs_; }
const uint8_t* IsolateData() const { return isolate_data_; }
const uint8_t* IsolateInstrs() const { return isolate_instrs_; }
private:
bool Load(int fd);
Dart_LoadedElf* handle_ = nullptr;
const uint8_t* vm_data_ = nullptr;
const uint8_t* vm_instrs_ = nullptr;
const uint8_t* isolate_data_ = nullptr;
const uint8_t* isolate_instrs_ = nullptr;
// Disallow copy and assignment.
ElfSnapshot(const ElfSnapshot&) = delete;
ElfSnapshot& operator=(const ElfSnapshot&) = delete;
};
class MappedResource {
public:
MappedResource() : address_(nullptr), size_(0) {}
MappedResource(MappedResource&& other)
: address_(other.address_), size_(other.size_) {
other.address_ = nullptr;
other.size_ = 0;
}
MappedResource& operator=(MappedResource&& other) {
address_ = other.address_;
size_ = other.size_;
other.address_ = nullptr;
other.size_ = 0;
return *this;
}
~MappedResource();
// Loads the content of a file from the given namespace and maps it into the
// current process's address space. If namespace is null, the fdio "global"
// namespace is used (in which case, ./pkg means the dart_runner's package).
// The content is unmapped when the MappedResource goes out of scope. Returns
// true on success.
static bool LoadFromNamespace(fdio_ns_t* namespc,
const std::string& path,
MappedResource& resource,
bool executable = false);
// Same as LoadFromNamespace, but takes a file descriptor to an opened
// directory instead of a namespace.
static bool LoadFromDir(int dirfd,
const std::string& path,
MappedResource& resource,
bool executable = false);
// Maps a VMO into the current process's address space. The content is
// unmapped when the MappedResource goes out of scope. Returns true on
// success. The path is used only for error messages.
static bool LoadFromVmo(const std::string& path,
fuchsia::mem::Buffer resource_vmo,
MappedResource& resource,
bool executable = false);
const uint8_t* address() const {
return reinterpret_cast<const uint8_t*>(address_);
}
size_t size() const { return size_; }
private:
void* address_;
size_t size_;
// Disallow copy and assignment.
MappedResource(const MappedResource&) = delete;
MappedResource& operator=(const MappedResource&) = delete;
};
} // namespace dart_utils
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_MAPPED_RESOURCE_H_
| engine/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.h/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/mapped_resource.h",
"repo_id": "engine",
"token_count": 1402
} | 352 |
// 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/client_wrapper/include/flutter/flutter_window_controller.h"
#include <memory>
#include <string>
#include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h"
#include "gtest/gtest.h"
namespace flutter {
namespace {
// Stub implementation to validate calls to the API.
class TestGlfwApi : public testing::StubFlutterGlfwApi {
public:
// |flutter::testing::StubFlutterGlfwApi|
bool Init() override {
init_called_ = true;
return true;
}
// |flutter::testing::StubFlutterGlfwApi|
void Terminate() override { terminate_called_ = true; }
bool init_called() { return init_called_; }
bool terminate_called() { return terminate_called_; }
private:
bool init_called_ = false;
bool terminate_called_ = false;
};
} // namespace
TEST(FlutterViewControllerTest, CreateDestroy) {
const std::string icu_data_path = "fake/path/to/icu";
testing::ScopedStubFlutterGlfwApi scoped_api_stub(
std::make_unique<TestGlfwApi>());
auto test_api = static_cast<TestGlfwApi*>(scoped_api_stub.stub());
{
FlutterWindowController controller(icu_data_path);
EXPECT_EQ(test_api->init_called(), true);
EXPECT_EQ(test_api->terminate_called(), false);
}
EXPECT_EQ(test_api->init_called(), true);
EXPECT_EQ(test_api->terminate_called(), true);
}
} // namespace flutter
| engine/shell/platform/glfw/client_wrapper/flutter_window_controller_unittests.cc/0 | {
"file_path": "engine/shell/platform/glfw/client_wrapper/flutter_window_controller_unittests.cc",
"repo_id": "engine",
"token_count": 550
} | 353 |
// 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_GLFW_HEADLESS_EVENT_LOOP_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_HEADLESS_EVENT_LOOP_H_
#include <condition_variable>
#include "flutter/shell/platform/glfw/event_loop.h"
namespace flutter {
// An event loop implementation that only handles Flutter Engine task
// scheduling.
class HeadlessEventLoop : public EventLoop {
public:
using TaskExpiredCallback = std::function<void(const FlutterTask*)>;
HeadlessEventLoop(std::thread::id main_thread_id,
const TaskExpiredCallback& on_task_expired);
~HeadlessEventLoop();
// Disallow copy.
HeadlessEventLoop(const HeadlessEventLoop&) = delete;
HeadlessEventLoop& operator=(const HeadlessEventLoop&) = delete;
private:
// |EventLoop|
void WaitUntil(const TaskTimePoint& time) override;
// |EventLoop|
void Wake() override;
std::condition_variable task_queue_condition_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_HEADLESS_EVENT_LOOP_H_
| engine/shell/platform/glfw/headless_event_loop.h/0 | {
"file_path": "engine/shell/platform/glfw/headless_event_loop.h",
"repo_id": "engine",
"token_count": 387
} | 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.
// Included first as it collides with the X11 headers.
#include "gtest/gtest.h"
#include "flutter/shell/platform/linux/fl_accessible_node.h"
#include "flutter/shell/platform/linux/testing/fl_test.h"
// Checks can build a tree of nodes.
TEST(FlAccessibleNodeTest, BuildTree) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) root = fl_accessible_node_new(engine, 0);
g_autoptr(FlAccessibleNode) child1 = fl_accessible_node_new(engine, 1);
fl_accessible_node_set_parent(child1, ATK_OBJECT(root), 0);
g_autoptr(FlAccessibleNode) child2 = fl_accessible_node_new(engine, 1);
fl_accessible_node_set_parent(child2, ATK_OBJECT(root), 1);
g_autoptr(GPtrArray) children =
g_ptr_array_new_with_free_func(g_object_unref);
g_ptr_array_add(children, g_object_ref(child1));
g_ptr_array_add(children, g_object_ref(child2));
fl_accessible_node_set_children(root, children);
EXPECT_EQ(atk_object_get_n_accessible_children(ATK_OBJECT(root)), 2);
EXPECT_EQ(atk_object_get_index_in_parent(ATK_OBJECT(root)), 0);
g_autoptr(AtkObject) c1 =
atk_object_ref_accessible_child(ATK_OBJECT(root), 0);
EXPECT_EQ(ATK_OBJECT(child1), c1);
g_autoptr(AtkObject) c2 =
atk_object_ref_accessible_child(ATK_OBJECT(root), 1);
EXPECT_EQ(ATK_OBJECT(child2), c2);
EXPECT_EQ(atk_object_get_parent(ATK_OBJECT(root)), nullptr);
EXPECT_EQ(atk_object_get_parent(ATK_OBJECT(child1)), ATK_OBJECT(root));
EXPECT_EQ(atk_object_get_index_in_parent(ATK_OBJECT(child1)), 0);
EXPECT_EQ(atk_object_get_n_accessible_children(ATK_OBJECT(child1)), 0);
EXPECT_EQ(atk_object_get_parent(ATK_OBJECT(child2)), ATK_OBJECT(root));
EXPECT_EQ(atk_object_get_index_in_parent(ATK_OBJECT(child2)), 1);
EXPECT_EQ(atk_object_get_n_accessible_children(ATK_OBJECT(child2)), 0);
}
// Checks node name is exposed to ATK.
TEST(FlAccessibleNodeTest, SetName) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_node_new(engine, 0);
fl_accessible_node_set_name(node, "test");
EXPECT_STREQ(atk_object_get_name(ATK_OBJECT(node)), "test");
}
// Checks node extents are exposed to ATK.
TEST(FlAccessibleNodeTest, SetExtents) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_node_new(engine, 0);
fl_accessible_node_set_extents(node, 1, 2, 3, 4);
gint x, y, width, height;
atk_component_get_extents(ATK_COMPONENT(node), &x, &y, &width, &height,
ATK_XY_PARENT);
EXPECT_EQ(x, 1);
EXPECT_EQ(y, 2);
EXPECT_EQ(width, 3);
EXPECT_EQ(height, 4);
}
// Checks Flutter flags are mapped to appropriate ATK state.
TEST(FlAccessibleNodeTest, SetFlags) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_node_new(engine, 0);
fl_accessible_node_set_flags(
node, static_cast<FlutterSemanticsFlag>(kFlutterSemanticsFlagIsEnabled |
kFlutterSemanticsFlagIsFocusable |
kFlutterSemanticsFlagIsFocused));
AtkStateSet* state = atk_object_ref_state_set(ATK_OBJECT(node));
EXPECT_TRUE(atk_state_set_contains_state(state, ATK_STATE_ENABLED));
EXPECT_TRUE(atk_state_set_contains_state(state, ATK_STATE_SENSITIVE));
EXPECT_TRUE(atk_state_set_contains_state(state, ATK_STATE_FOCUSABLE));
EXPECT_TRUE(atk_state_set_contains_state(state, ATK_STATE_FOCUSED));
EXPECT_TRUE(!atk_state_set_contains_state(state, ATK_STATE_CHECKED));
g_object_unref(state);
}
// Checks Flutter flags are mapped to appropriate ATK roles.
TEST(FlAccessibleNodeTest, GetRole) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_node_new(engine, 0);
fl_accessible_node_set_flags(
node, static_cast<FlutterSemanticsFlag>(kFlutterSemanticsFlagIsButton));
EXPECT_EQ(atk_object_get_role(ATK_OBJECT(node)), ATK_ROLE_PUSH_BUTTON);
fl_accessible_node_set_flags(node, static_cast<FlutterSemanticsFlag>(
kFlutterSemanticsFlagHasCheckedState));
EXPECT_EQ(atk_object_get_role(ATK_OBJECT(node)), ATK_ROLE_CHECK_BOX);
fl_accessible_node_set_flags(
node, static_cast<FlutterSemanticsFlag>(
kFlutterSemanticsFlagHasCheckedState |
kFlutterSemanticsFlagIsInMutuallyExclusiveGroup));
EXPECT_EQ(atk_object_get_role(ATK_OBJECT(node)), ATK_ROLE_RADIO_BUTTON);
fl_accessible_node_set_flags(node, static_cast<FlutterSemanticsFlag>(
kFlutterSemanticsFlagHasToggledState));
EXPECT_EQ(atk_object_get_role(ATK_OBJECT(node)), ATK_ROLE_TOGGLE_BUTTON);
fl_accessible_node_set_flags(node, kFlutterSemanticsFlagIsTextField);
EXPECT_EQ(atk_object_get_role(ATK_OBJECT(node)), ATK_ROLE_TEXT);
fl_accessible_node_set_flags(
node, static_cast<FlutterSemanticsFlag>(kFlutterSemanticsFlagIsTextField |
kFlutterSemanticsFlagIsObscured));
EXPECT_EQ(atk_object_get_role(ATK_OBJECT(node)), ATK_ROLE_PASSWORD_TEXT);
}
// Checks Flutter actions are mapped to the appropriate ATK actions.
TEST(FlAccessibleNodeTest, SetActions) {
g_autoptr(FlEngine) engine = make_mock_engine();
g_autoptr(FlAccessibleNode) node = fl_accessible_node_new(engine, 0);
fl_accessible_node_set_actions(
node, static_cast<FlutterSemanticsAction>(
kFlutterSemanticsActionTap | kFlutterSemanticsActionLongPress));
EXPECT_EQ(atk_action_get_n_actions(ATK_ACTION(node)), 2);
EXPECT_STREQ(atk_action_get_name(ATK_ACTION(node), 0), "Tap");
EXPECT_STREQ(atk_action_get_name(ATK_ACTION(node), 1), "LongPress");
}
| engine/shell/platform/linux/fl_accessible_node_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_accessible_node_test.cc",
"repo_id": "engine",
"token_count": 2484
} | 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.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h"
#include <gmodule.h>
#include <cstring>
#include <string>
#include <vector>
#include "flutter/common/constants.h"
#include "flutter/shell/platform/common/app_lifecycle_state.h"
#include "flutter/shell/platform/common/engine_switches.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/linux/fl_binary_messenger_private.h"
#include "flutter/shell/platform/linux/fl_dart_project_private.h"
#include "flutter/shell/platform/linux/fl_engine_private.h"
#include "flutter/shell/platform/linux/fl_pixel_buffer_texture_private.h"
#include "flutter/shell/platform/linux/fl_plugin_registrar_private.h"
#include "flutter/shell/platform/linux/fl_renderer.h"
#include "flutter/shell/platform/linux/fl_renderer_headless.h"
#include "flutter/shell/platform/linux/fl_settings_plugin.h"
#include "flutter/shell/platform/linux/fl_texture_gl_private.h"
#include "flutter/shell/platform/linux/fl_texture_registrar_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registry.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_string_codec.h"
// Unique number associated with platform tasks.
static constexpr size_t kPlatformTaskRunnerIdentifier = 1;
// Use different device ID for mouse and pan/zoom events, since we can't
// differentiate the actual device (mouse v.s. trackpad)
static constexpr int32_t kMousePointerDeviceId = 0;
static constexpr int32_t kPointerPanZoomDeviceId = 1;
static constexpr const char* kFlutterLifecycleChannel = "flutter/lifecycle";
struct _FlEngine {
GObject parent_instance;
// Thread the GLib main loop is running on.
GThread* thread;
FlDartProject* project;
FlRenderer* renderer;
FlBinaryMessenger* binary_messenger;
FlSettingsPlugin* settings_plugin;
FlTextureRegistrar* texture_registrar;
FlTaskRunner* task_runner;
FlutterEngineAOTData aot_data;
FLUTTER_API_SYMBOL(FlutterEngine) engine;
FlutterEngineProcTable embedder_api;
// Function to call when a platform message is received.
FlEnginePlatformMessageHandler platform_message_handler;
gpointer platform_message_handler_data;
GDestroyNotify platform_message_handler_destroy_notify;
// Function to call when a semantic node is received.
FlEngineUpdateSemanticsHandler update_semantics_handler;
gpointer update_semantics_handler_data;
GDestroyNotify update_semantics_handler_destroy_notify;
// Function to call right before the engine is restarted.
FlEngineOnPreEngineRestartHandler on_pre_engine_restart_handler;
gpointer on_pre_engine_restart_handler_data;
GDestroyNotify on_pre_engine_restart_handler_destroy_notify;
};
G_DEFINE_QUARK(fl_engine_error_quark, fl_engine_error)
static void fl_engine_plugin_registry_iface_init(
FlPluginRegistryInterface* iface);
G_DEFINE_TYPE_WITH_CODE(
FlEngine,
fl_engine,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_plugin_registry_get_type(),
fl_engine_plugin_registry_iface_init))
enum { kProp0, kPropBinaryMessenger, kPropLast };
// Parse a locale into its components.
static void parse_locale(const gchar* locale,
gchar** language,
gchar** territory,
gchar** codeset,
gchar** modifier) {
gchar* l = g_strdup(locale);
// Locales are in the form "language[_territory][.codeset][@modifier]"
gchar* match = strrchr(l, '@');
if (match != nullptr) {
if (modifier != nullptr) {
*modifier = g_strdup(match + 1);
}
*match = '\0';
} else if (modifier != nullptr) {
*modifier = nullptr;
}
match = strrchr(l, '.');
if (match != nullptr) {
if (codeset != nullptr) {
*codeset = g_strdup(match + 1);
}
*match = '\0';
} else if (codeset != nullptr) {
*codeset = nullptr;
}
match = strrchr(l, '_');
if (match != nullptr) {
if (territory != nullptr) {
*territory = g_strdup(match + 1);
}
*match = '\0';
} else if (territory != nullptr) {
*territory = nullptr;
}
if (language != nullptr) {
*language = l;
}
}
static void set_app_lifecycle_state(FlEngine* self,
const flutter::AppLifecycleState state) {
FlBinaryMessenger* binary_messenger = fl_engine_get_binary_messenger(self);
g_autoptr(FlValue) value =
fl_value_new_string(flutter::AppLifecycleStateToString(state));
g_autoptr(FlStringCodec) codec = fl_string_codec_new();
g_autoptr(GBytes) message =
fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, nullptr);
if (message == nullptr) {
return;
}
fl_binary_messenger_send_on_channel(binary_messenger,
kFlutterLifecycleChannel, message,
nullptr, nullptr, nullptr);
}
// Passes locale information to the Flutter engine.
static void setup_locales(FlEngine* self) {
const gchar* const* languages = g_get_language_names();
g_autoptr(GPtrArray) locales_array = g_ptr_array_new_with_free_func(g_free);
// Helper array to take ownership of the strings passed to Flutter.
g_autoptr(GPtrArray) locale_strings = g_ptr_array_new_with_free_func(g_free);
for (int i = 0; languages[i] != nullptr; i++) {
gchar *language, *territory;
parse_locale(languages[i], &language, &territory, nullptr, nullptr);
if (language != nullptr) {
g_ptr_array_add(locale_strings, language);
}
if (territory != nullptr) {
g_ptr_array_add(locale_strings, territory);
}
FlutterLocale* locale =
static_cast<FlutterLocale*>(g_malloc0(sizeof(FlutterLocale)));
g_ptr_array_add(locales_array, locale);
locale->struct_size = sizeof(FlutterLocale);
locale->language_code = language;
locale->country_code = territory;
locale->script_code = nullptr;
locale->variant_code = nullptr;
}
FlutterLocale** locales =
reinterpret_cast<FlutterLocale**>(locales_array->pdata);
FlutterEngineResult result = self->embedder_api.UpdateLocales(
self->engine, const_cast<const FlutterLocale**>(locales),
locales_array->len);
if (result != kSuccess) {
g_warning("Failed to set up Flutter locales");
}
}
// Called when engine needs a backing store for a specific #FlutterLayer.
static bool compositor_create_backing_store_callback(
const FlutterBackingStoreConfig* config,
FlutterBackingStore* backing_store_out,
void* user_data) {
g_return_val_if_fail(FL_IS_RENDERER(user_data), false);
return fl_renderer_create_backing_store(FL_RENDERER(user_data), config,
backing_store_out);
}
// Called when the backing store is to be released.
static bool compositor_collect_backing_store_callback(
const FlutterBackingStore* renderer,
void* user_data) {
g_return_val_if_fail(FL_IS_RENDERER(user_data), false);
return fl_renderer_collect_backing_store(FL_RENDERER(user_data), renderer);
}
// Called when embedder should composite contents of each layer onto the screen.
static bool compositor_present_layers_callback(const FlutterLayer** layers,
size_t layers_count,
void* user_data) {
g_return_val_if_fail(FL_IS_RENDERER(user_data), false);
return fl_renderer_present_layers(FL_RENDERER(user_data), layers,
layers_count);
}
// Flutter engine rendering callbacks.
static void* fl_engine_gl_proc_resolver(void* user_data, const char* name) {
FlEngine* self = static_cast<FlEngine*>(user_data);
return fl_renderer_get_proc_address(self->renderer, name);
}
static bool fl_engine_gl_make_current(void* user_data) {
FlEngine* self = static_cast<FlEngine*>(user_data);
fl_renderer_make_current(self->renderer);
return true;
}
static bool fl_engine_gl_clear_current(void* user_data) {
FlEngine* self = static_cast<FlEngine*>(user_data);
fl_renderer_clear_current(self->renderer);
return true;
}
static uint32_t fl_engine_gl_get_fbo(void* user_data) {
FlEngine* self = static_cast<FlEngine*>(user_data);
return fl_renderer_get_fbo(self->renderer);
}
static bool fl_engine_gl_present(void* user_data) {
// No action required, as this is handled in
// compositor_present_layers_callback.
return true;
}
static bool fl_engine_gl_make_resource_current(void* user_data) {
FlEngine* self = static_cast<FlEngine*>(user_data);
fl_renderer_make_resource_current(self->renderer);
return true;
}
// Called by the engine to retrieve an external texture.
static bool fl_engine_gl_external_texture_frame_callback(
void* user_data,
int64_t texture_id,
size_t width,
size_t height,
FlutterOpenGLTexture* opengl_texture) {
FlEngine* self = static_cast<FlEngine*>(user_data);
if (!self->texture_registrar) {
return false;
}
FlTexture* texture =
fl_texture_registrar_lookup_texture(self->texture_registrar, texture_id);
if (texture == nullptr) {
g_warning("Unable to find texture %" G_GINT64_FORMAT, texture_id);
return false;
}
gboolean result;
g_autoptr(GError) error = nullptr;
if (FL_IS_TEXTURE_GL(texture)) {
result = fl_texture_gl_populate(FL_TEXTURE_GL(texture), width, height,
opengl_texture, &error);
} else if (FL_IS_PIXEL_BUFFER_TEXTURE(texture)) {
result =
fl_pixel_buffer_texture_populate(FL_PIXEL_BUFFER_TEXTURE(texture),
width, height, opengl_texture, &error);
} else {
g_warning("Unsupported texture type %" G_GINT64_FORMAT, texture_id);
return false;
}
if (!result) {
g_warning("%s", error->message);
return false;
}
return true;
}
// Called by the engine to determine if it is on the GTK thread.
static bool fl_engine_runs_task_on_current_thread(void* user_data) {
FlEngine* self = static_cast<FlEngine*>(user_data);
return self->thread == g_thread_self();
}
// Called when the engine has a task to perform in the GTK thread.
static void fl_engine_post_task(FlutterTask task,
uint64_t target_time_nanos,
void* user_data) {
FlEngine* self = static_cast<FlEngine*>(user_data);
fl_task_runner_post_task(self->task_runner, task, target_time_nanos);
}
// Called when a platform message is received from the engine.
static void fl_engine_platform_message_cb(const FlutterPlatformMessage* message,
void* user_data) {
FlEngine* self = FL_ENGINE(user_data);
gboolean handled = FALSE;
if (self->platform_message_handler != nullptr) {
g_autoptr(GBytes) data =
g_bytes_new(message->message, message->message_size);
handled = self->platform_message_handler(
self, message->channel, data, message->response_handle,
self->platform_message_handler_data);
}
if (!handled) {
fl_engine_send_platform_message_response(self, message->response_handle,
nullptr, nullptr);
}
}
// Called when a semantic node update is received from the engine.
static void fl_engine_update_semantics_cb(const FlutterSemanticsUpdate2* update,
void* user_data) {
FlEngine* self = FL_ENGINE(user_data);
if (self->update_semantics_handler != nullptr) {
self->update_semantics_handler(self, update,
self->update_semantics_handler_data);
}
}
// Called right before the engine is restarted.
//
// This method should reset states to as if the engine has just been started,
// which usually indicates the user has requested a hot restart (Shift-R in the
// Flutter CLI.)
static void fl_engine_on_pre_engine_restart_cb(void* user_data) {
FlEngine* self = FL_ENGINE(user_data);
if (self->on_pre_engine_restart_handler != nullptr) {
self->on_pre_engine_restart_handler(
self, self->on_pre_engine_restart_handler_data);
}
}
// Called when a response to a sent platform message is received from the
// engine.
static void fl_engine_platform_message_response_cb(const uint8_t* data,
size_t data_length,
void* user_data) {
g_autoptr(GTask) task = G_TASK(user_data);
g_task_return_pointer(task, g_bytes_new(data, data_length),
reinterpret_cast<GDestroyNotify>(g_bytes_unref));
}
// Implements FlPluginRegistry::get_registrar_for_plugin.
static FlPluginRegistrar* fl_engine_get_registrar_for_plugin(
FlPluginRegistry* registry,
const gchar* name) {
FlEngine* self = FL_ENGINE(registry);
return fl_plugin_registrar_new(nullptr, self->binary_messenger,
self->texture_registrar);
}
static void fl_engine_plugin_registry_iface_init(
FlPluginRegistryInterface* iface) {
iface->get_registrar_for_plugin = fl_engine_get_registrar_for_plugin;
}
static void fl_engine_set_property(GObject* object,
guint prop_id,
const GValue* value,
GParamSpec* pspec) {
FlEngine* self = FL_ENGINE(object);
switch (prop_id) {
case kPropBinaryMessenger:
g_set_object(&self->binary_messenger,
FL_BINARY_MESSENGER(g_value_get_object(value)));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void fl_engine_dispose(GObject* object) {
FlEngine* self = FL_ENGINE(object);
if (self->engine != nullptr) {
self->embedder_api.Shutdown(self->engine);
self->engine = nullptr;
}
if (self->aot_data != nullptr) {
self->embedder_api.CollectAOTData(self->aot_data);
self->aot_data = nullptr;
}
g_clear_object(&self->project);
g_clear_object(&self->renderer);
g_clear_object(&self->texture_registrar);
g_clear_object(&self->binary_messenger);
g_clear_object(&self->settings_plugin);
g_clear_object(&self->task_runner);
if (self->platform_message_handler_destroy_notify) {
self->platform_message_handler_destroy_notify(
self->platform_message_handler_data);
}
self->platform_message_handler_data = nullptr;
self->platform_message_handler_destroy_notify = nullptr;
if (self->update_semantics_handler_destroy_notify) {
self->update_semantics_handler_destroy_notify(
self->update_semantics_handler_data);
}
self->update_semantics_handler_data = nullptr;
self->update_semantics_handler_destroy_notify = nullptr;
if (self->on_pre_engine_restart_handler_destroy_notify) {
self->on_pre_engine_restart_handler_destroy_notify(
self->on_pre_engine_restart_handler_data);
}
self->on_pre_engine_restart_handler_data = nullptr;
self->on_pre_engine_restart_handler_destroy_notify = nullptr;
G_OBJECT_CLASS(fl_engine_parent_class)->dispose(object);
}
static void fl_engine_class_init(FlEngineClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_engine_dispose;
G_OBJECT_CLASS(klass)->set_property = fl_engine_set_property;
g_object_class_install_property(
G_OBJECT_CLASS(klass), kPropBinaryMessenger,
g_param_spec_object(
"binary-messenger", "messenger", "Binary messenger",
fl_binary_messenger_get_type(),
static_cast<GParamFlags>(G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
G_PARAM_STATIC_STRINGS)));
}
static void fl_engine_init(FlEngine* self) {
self->thread = g_thread_self();
self->embedder_api.struct_size = sizeof(FlutterEngineProcTable);
FlutterEngineGetProcAddresses(&self->embedder_api);
self->texture_registrar = fl_texture_registrar_new(self);
}
FlEngine* fl_engine_new(FlDartProject* project, FlRenderer* renderer) {
g_return_val_if_fail(FL_IS_DART_PROJECT(project), nullptr);
g_return_val_if_fail(FL_IS_RENDERER(renderer), nullptr);
FlEngine* self = FL_ENGINE(g_object_new(fl_engine_get_type(), nullptr));
self->project = FL_DART_PROJECT(g_object_ref(project));
self->renderer = FL_RENDERER(g_object_ref(renderer));
self->binary_messenger = fl_binary_messenger_new(self);
return self;
}
G_MODULE_EXPORT FlEngine* fl_engine_new_headless(FlDartProject* project) {
g_autoptr(FlRendererHeadless) renderer = fl_renderer_headless_new();
return fl_engine_new(project, FL_RENDERER(renderer));
}
gboolean fl_engine_start(FlEngine* self, GError** error) {
g_return_val_if_fail(FL_IS_ENGINE(self), FALSE);
self->task_runner = fl_task_runner_new(self);
FlutterRendererConfig config = {};
config.type = kOpenGL;
config.open_gl.struct_size = sizeof(FlutterOpenGLRendererConfig);
config.open_gl.gl_proc_resolver = fl_engine_gl_proc_resolver;
config.open_gl.make_current = fl_engine_gl_make_current;
config.open_gl.clear_current = fl_engine_gl_clear_current;
config.open_gl.fbo_callback = fl_engine_gl_get_fbo;
config.open_gl.present = fl_engine_gl_present;
config.open_gl.make_resource_current = fl_engine_gl_make_resource_current;
config.open_gl.gl_external_texture_frame_callback =
fl_engine_gl_external_texture_frame_callback;
FlutterTaskRunnerDescription platform_task_runner = {};
platform_task_runner.struct_size = sizeof(FlutterTaskRunnerDescription);
platform_task_runner.user_data = self;
platform_task_runner.runs_task_on_current_thread_callback =
fl_engine_runs_task_on_current_thread;
platform_task_runner.post_task_callback = fl_engine_post_task;
platform_task_runner.identifier = kPlatformTaskRunnerIdentifier;
FlutterCustomTaskRunners custom_task_runners = {};
custom_task_runners.struct_size = sizeof(FlutterCustomTaskRunners);
custom_task_runners.platform_task_runner = &platform_task_runner;
custom_task_runners.render_task_runner = &platform_task_runner;
g_autoptr(GPtrArray) command_line_args = fl_engine_get_switches(self);
// FlutterProjectArgs expects a full argv, so when processing it for flags
// the first item is treated as the executable and ignored. Add a dummy value
// so that all switches are used.
g_ptr_array_insert(command_line_args, 0, g_strdup("flutter"));
gchar** dart_entrypoint_args =
fl_dart_project_get_dart_entrypoint_arguments(self->project);
FlutterProjectArgs args = {};
args.struct_size = sizeof(FlutterProjectArgs);
args.assets_path = fl_dart_project_get_assets_path(self->project);
args.icu_data_path = fl_dart_project_get_icu_data_path(self->project);
args.command_line_argc = command_line_args->len;
args.command_line_argv =
reinterpret_cast<const char* const*>(command_line_args->pdata);
args.platform_message_callback = fl_engine_platform_message_cb;
args.update_semantics_callback2 = fl_engine_update_semantics_cb;
args.custom_task_runners = &custom_task_runners;
args.shutdown_dart_vm_when_done = true;
args.on_pre_engine_restart_callback = fl_engine_on_pre_engine_restart_cb;
args.dart_entrypoint_argc =
dart_entrypoint_args != nullptr ? g_strv_length(dart_entrypoint_args) : 0;
args.dart_entrypoint_argv =
reinterpret_cast<const char* const*>(dart_entrypoint_args);
FlutterCompositor compositor = {};
compositor.struct_size = sizeof(FlutterCompositor);
compositor.user_data = self->renderer;
compositor.create_backing_store_callback =
compositor_create_backing_store_callback;
compositor.collect_backing_store_callback =
compositor_collect_backing_store_callback;
compositor.present_layers_callback = compositor_present_layers_callback;
args.compositor = &compositor;
if (self->embedder_api.RunsAOTCompiledDartCode()) {
FlutterEngineAOTDataSource source = {};
source.type = kFlutterEngineAOTDataSourceTypeElfPath;
source.elf_path = fl_dart_project_get_aot_library_path(self->project);
if (self->embedder_api.CreateAOTData(&source, &self->aot_data) !=
kSuccess) {
g_set_error(error, fl_engine_error_quark(), FL_ENGINE_ERROR_FAILED,
"Failed to create AOT data");
return FALSE;
}
args.aot_data = self->aot_data;
}
FlutterEngineResult result = self->embedder_api.Initialize(
FLUTTER_ENGINE_VERSION, &config, &args, self, &self->engine);
if (result != kSuccess) {
g_set_error(error, fl_engine_error_quark(), FL_ENGINE_ERROR_FAILED,
"Failed to initialize Flutter engine");
return FALSE;
}
result = self->embedder_api.RunInitialized(self->engine);
if (result != kSuccess) {
g_set_error(error, fl_engine_error_quark(), FL_ENGINE_ERROR_FAILED,
"Failed to run Flutter engine");
return FALSE;
}
setup_locales(self);
g_autoptr(FlSettings) settings = fl_settings_new();
self->settings_plugin = fl_settings_plugin_new(self);
fl_settings_plugin_start(self->settings_plugin, settings);
result = self->embedder_api.UpdateSemanticsEnabled(self->engine, TRUE);
if (result != kSuccess) {
g_warning("Failed to enable accessibility features on Flutter engine");
}
return TRUE;
}
FlutterEngineProcTable* fl_engine_get_embedder_api(FlEngine* self) {
return &(self->embedder_api);
}
void fl_engine_set_platform_message_handler(
FlEngine* self,
FlEnginePlatformMessageHandler handler,
gpointer user_data,
GDestroyNotify destroy_notify) {
g_return_if_fail(FL_IS_ENGINE(self));
g_return_if_fail(handler != nullptr);
if (self->platform_message_handler_destroy_notify) {
self->platform_message_handler_destroy_notify(
self->platform_message_handler_data);
}
self->platform_message_handler = handler;
self->platform_message_handler_data = user_data;
self->platform_message_handler_destroy_notify = destroy_notify;
}
void fl_engine_set_update_semantics_handler(
FlEngine* self,
FlEngineUpdateSemanticsHandler handler,
gpointer user_data,
GDestroyNotify destroy_notify) {
g_return_if_fail(FL_IS_ENGINE(self));
if (self->update_semantics_handler_destroy_notify) {
self->update_semantics_handler_destroy_notify(
self->update_semantics_handler_data);
}
self->update_semantics_handler = handler;
self->update_semantics_handler_data = user_data;
self->update_semantics_handler_destroy_notify = destroy_notify;
}
void fl_engine_set_on_pre_engine_restart_handler(
FlEngine* self,
FlEngineOnPreEngineRestartHandler handler,
gpointer user_data,
GDestroyNotify destroy_notify) {
g_return_if_fail(FL_IS_ENGINE(self));
if (self->on_pre_engine_restart_handler_destroy_notify) {
self->on_pre_engine_restart_handler_destroy_notify(
self->on_pre_engine_restart_handler_data);
}
self->on_pre_engine_restart_handler = handler;
self->on_pre_engine_restart_handler_data = user_data;
self->on_pre_engine_restart_handler_destroy_notify = destroy_notify;
}
// Note: This function can be called from any thread.
gboolean fl_engine_send_platform_message_response(
FlEngine* self,
const FlutterPlatformMessageResponseHandle* handle,
GBytes* response,
GError** error) {
g_return_val_if_fail(FL_IS_ENGINE(self), FALSE);
g_return_val_if_fail(handle != nullptr, FALSE);
if (self->engine == nullptr) {
g_set_error(error, fl_engine_error_quark(), FL_ENGINE_ERROR_FAILED,
"No engine to send response to");
return FALSE;
}
gsize data_length = 0;
const uint8_t* data = nullptr;
if (response != nullptr) {
data =
static_cast<const uint8_t*>(g_bytes_get_data(response, &data_length));
}
FlutterEngineResult result = self->embedder_api.SendPlatformMessageResponse(
self->engine, handle, data, data_length);
if (result != kSuccess) {
g_set_error(error, fl_engine_error_quark(), FL_ENGINE_ERROR_FAILED,
"Failed to send platform message response");
return FALSE;
}
return TRUE;
}
void fl_engine_send_platform_message(FlEngine* self,
const gchar* channel,
GBytes* message,
GCancellable* cancellable,
GAsyncReadyCallback callback,
gpointer user_data) {
g_return_if_fail(FL_IS_ENGINE(self));
GTask* task = nullptr;
FlutterPlatformMessageResponseHandle* response_handle = nullptr;
if (callback != nullptr) {
task = g_task_new(self, cancellable, callback, user_data);
if (self->engine == nullptr) {
g_task_return_new_error(task, fl_engine_error_quark(),
FL_ENGINE_ERROR_FAILED, "No engine to send to");
return;
}
FlutterEngineResult result =
self->embedder_api.PlatformMessageCreateResponseHandle(
self->engine, fl_engine_platform_message_response_cb, task,
&response_handle);
if (result != kSuccess) {
g_task_return_new_error(task, fl_engine_error_quark(),
FL_ENGINE_ERROR_FAILED,
"Failed to create response handle");
g_object_unref(task);
return;
}
} else if (self->engine == nullptr) {
return;
}
FlutterPlatformMessage fl_message = {};
fl_message.struct_size = sizeof(fl_message);
fl_message.channel = channel;
fl_message.message =
message != nullptr
? static_cast<const uint8_t*>(g_bytes_get_data(message, nullptr))
: nullptr;
fl_message.message_size = message != nullptr ? g_bytes_get_size(message) : 0;
fl_message.response_handle = response_handle;
FlutterEngineResult result =
self->embedder_api.SendPlatformMessage(self->engine, &fl_message);
if (result != kSuccess && task != nullptr) {
g_task_return_new_error(task, fl_engine_error_quark(),
FL_ENGINE_ERROR_FAILED,
"Failed to send platform messages");
g_object_unref(task);
}
if (response_handle != nullptr) {
self->embedder_api.PlatformMessageReleaseResponseHandle(self->engine,
response_handle);
}
}
GBytes* fl_engine_send_platform_message_finish(FlEngine* self,
GAsyncResult* result,
GError** error) {
g_return_val_if_fail(FL_IS_ENGINE(self), FALSE);
g_return_val_if_fail(g_task_is_valid(result, self), FALSE);
return static_cast<GBytes*>(g_task_propagate_pointer(G_TASK(result), error));
}
void fl_engine_send_window_state_event(FlEngine* self,
gboolean visible,
gboolean focused) {
if (visible && focused) {
set_app_lifecycle_state(self, flutter::AppLifecycleState::kResumed);
} else if (visible) {
set_app_lifecycle_state(self, flutter::AppLifecycleState::kInactive);
} else {
set_app_lifecycle_state(self, flutter::AppLifecycleState::kHidden);
}
}
void fl_engine_send_window_metrics_event(FlEngine* self,
size_t width,
size_t height,
double pixel_ratio) {
g_return_if_fail(FL_IS_ENGINE(self));
if (self->engine == nullptr) {
return;
}
FlutterWindowMetricsEvent event = {};
event.struct_size = sizeof(FlutterWindowMetricsEvent);
event.width = width;
event.height = height;
event.pixel_ratio = pixel_ratio;
// TODO(dkwingsmt): Assign the correct view ID once the Linux embedder
// supports multiple views.
// https://github.com/flutter/flutter/issues/138178
event.view_id = flutter::kFlutterImplicitViewId;
self->embedder_api.SendWindowMetricsEvent(self->engine, &event);
}
void fl_engine_send_mouse_pointer_event(FlEngine* 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_ENGINE(self));
if (self->engine == nullptr) {
return;
}
FlutterPointerEvent fl_event = {};
fl_event.struct_size = sizeof(fl_event);
fl_event.phase = phase;
fl_event.timestamp = timestamp;
fl_event.x = x;
fl_event.y = y;
if (scroll_delta_x != 0 || scroll_delta_y != 0) {
fl_event.signal_kind = kFlutterPointerSignalKindScroll;
}
fl_event.scroll_delta_x = scroll_delta_x;
fl_event.scroll_delta_y = scroll_delta_y;
fl_event.device_kind = kFlutterPointerDeviceKindMouse;
fl_event.buttons = buttons;
fl_event.device = kMousePointerDeviceId;
// TODO(dkwingsmt): Assign the correct view ID once the Linux embedder
// supports multiple views.
// https://github.com/flutter/flutter/issues/138178
fl_event.view_id = flutter::kFlutterImplicitViewId;
self->embedder_api.SendPointerEvent(self->engine, &fl_event, 1);
}
void fl_engine_send_pointer_pan_zoom_event(FlEngine* 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_ENGINE(self));
if (self->engine == nullptr) {
return;
}
FlutterPointerEvent fl_event = {};
fl_event.struct_size = sizeof(fl_event);
fl_event.timestamp = timestamp;
fl_event.x = x;
fl_event.y = y;
fl_event.phase = phase;
fl_event.pan_x = pan_x;
fl_event.pan_y = pan_y;
fl_event.scale = scale;
fl_event.rotation = rotation;
fl_event.device = kPointerPanZoomDeviceId;
fl_event.device_kind = kFlutterPointerDeviceKindTrackpad;
// TODO(dkwingsmt): Assign the correct view ID once the Linux embedder
// supports multiple views.
// https://github.com/flutter/flutter/issues/138178
fl_event.view_id = flutter::kFlutterImplicitViewId;
self->embedder_api.SendPointerEvent(self->engine, &fl_event, 1);
}
void fl_engine_send_key_event(FlEngine* self,
const FlutterKeyEvent* event,
FlutterKeyEventCallback callback,
void* user_data) {
g_return_if_fail(FL_IS_ENGINE(self));
if (self->engine == nullptr) {
return;
}
self->embedder_api.SendKeyEvent(self->engine, event, callback, user_data);
}
void fl_engine_dispatch_semantics_action(FlEngine* self,
uint64_t id,
FlutterSemanticsAction action,
GBytes* data) {
g_return_if_fail(FL_IS_ENGINE(self));
if (self->engine == nullptr) {
return;
}
const uint8_t* action_data = nullptr;
size_t action_data_length = 0;
if (data != nullptr) {
action_data = static_cast<const uint8_t*>(
g_bytes_get_data(data, &action_data_length));
}
self->embedder_api.DispatchSemanticsAction(self->engine, id, action,
action_data, action_data_length);
}
gboolean fl_engine_mark_texture_frame_available(FlEngine* self,
int64_t texture_id) {
g_return_val_if_fail(FL_IS_ENGINE(self), FALSE);
return self->embedder_api.MarkExternalTextureFrameAvailable(
self->engine, texture_id) == kSuccess;
}
gboolean fl_engine_register_external_texture(FlEngine* self,
int64_t texture_id) {
g_return_val_if_fail(FL_IS_ENGINE(self), FALSE);
return self->embedder_api.RegisterExternalTexture(self->engine, texture_id) ==
kSuccess;
}
gboolean fl_engine_unregister_external_texture(FlEngine* self,
int64_t texture_id) {
g_return_val_if_fail(FL_IS_ENGINE(self), FALSE);
return self->embedder_api.UnregisterExternalTexture(self->engine,
texture_id) == kSuccess;
}
G_MODULE_EXPORT FlBinaryMessenger* fl_engine_get_binary_messenger(
FlEngine* self) {
g_return_val_if_fail(FL_IS_ENGINE(self), nullptr);
return self->binary_messenger;
}
FlTaskRunner* fl_engine_get_task_runner(FlEngine* self) {
g_return_val_if_fail(FL_IS_ENGINE(self), nullptr);
return self->task_runner;
}
void fl_engine_execute_task(FlEngine* self, FlutterTask* task) {
g_return_if_fail(FL_IS_ENGINE(self));
self->embedder_api.RunTask(self->engine, task);
}
G_MODULE_EXPORT FlTextureRegistrar* fl_engine_get_texture_registrar(
FlEngine* self) {
g_return_val_if_fail(FL_IS_ENGINE(self), nullptr);
return self->texture_registrar;
}
void fl_engine_update_accessibility_features(FlEngine* self, int32_t flags) {
g_return_if_fail(FL_IS_ENGINE(self));
if (self->engine == nullptr) {
return;
}
self->embedder_api.UpdateAccessibilityFeatures(
self->engine, static_cast<FlutterAccessibilityFeature>(flags));
}
GPtrArray* fl_engine_get_switches(FlEngine* self) {
GPtrArray* switches = g_ptr_array_new_with_free_func(g_free);
for (const auto& env_switch : flutter::GetSwitchesFromEnvironment()) {
g_ptr_array_add(switches, g_strdup(env_switch.c_str()));
}
return switches;
}
| engine/shell/platform/linux/fl_engine.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_engine.cc",
"repo_id": "engine",
"token_count": 14167
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_EMBEDDER_RESPONDER_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_EMBEDDER_RESPONDER_H_
#include <gdk/gdk.h>
#include <functional>
#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"
constexpr int kMaxConvertedKeyData = 3;
// The signature of a function that FlKeyEmbedderResponder calls on every key
// event.
//
// The `user_data` is opaque data managed by the object that creates
// FlKeyEmbedderResponder, and is registered along with this callback
// via `fl_key_embedder_responder_new`.
//
// The `callback_user_data` is opaque data managed by FlKeyEmbedderResponder.
// Instances of the EmbedderSendKeyEvent callback are required to invoke
// `callback` with the `callback_user_data` parameter after the `event` has been
// processed.
typedef void (*EmbedderSendKeyEvent)(const FlutterKeyEvent* event,
FlutterKeyEventCallback callback,
void* callback_user_data,
void* send_key_event_user_data);
G_BEGIN_DECLS
#define FL_TYPE_KEY_EMBEDDER_RESPONDER fl_key_embedder_responder_get_type()
G_DECLARE_FINAL_TYPE(FlKeyEmbedderResponder,
fl_key_embedder_responder,
FL,
KEY_EMBEDDER_RESPONDER,
GObject);
/**
* FlKeyEmbedderResponder:
*
* A #FlKeyResponder that handles events by sending the converted events
* through the embedder API.
*
* This class communicates with the HardwareKeyboard API in the framework.
*/
/**
* fl_key_embedder_responder_new:
* @engine: The #FlEngine, whose the embedder API will be used to send
* the event.
*
* Creates a new #FlKeyEmbedderResponder.
* @send_key_event: a function that is called on every key event.
* @send_key_event_user_data: an opaque pointer that will be sent back as the
* last argument of send_key_event, created and managed by the object that holds
* FlKeyEmbedderResponder.
*
* Returns: a new #FlKeyEmbedderResponder.
*/
FlKeyEmbedderResponder* fl_key_embedder_responder_new(
EmbedderSendKeyEvent send_key_event,
void* send_key_event_user_data);
/**
* fl_key_embedder_responder_sync_modifiers_if_needed:
* @responder: the #FlKeyEmbedderResponder self.
* @state: the state of the modifiers mask.
* @event_time: the time attribute of the incoming GDK event.
*
* If needed, synthesize modifier keys up and down event by comparing their
* current pressing states with the given modifiers mask.
*/
void fl_key_embedder_responder_sync_modifiers_if_needed(
FlKeyEmbedderResponder* responder,
guint state,
double event_time);
/**
* fl_key_embedder_responder_get_pressed_state:
* @responder: the #FlKeyEmbedderResponder self.
*
* Returns the keyboard pressed state. The hash table contains one entry per
* pressed keys, mapping from the logical key to the physical key.
*/
GHashTable* fl_key_embedder_responder_get_pressed_state(
FlKeyEmbedderResponder* responder);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_EMBEDDER_RESPONDER_H_
| engine/shell/platform/linux/fl_key_embedder_responder.h/0 | {
"file_path": "engine/shell/platform/linux/fl_key_embedder_responder.h",
"repo_id": "engine",
"token_count": 1285
} | 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.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h"
#include <gmodule.h>
#include "flutter/shell/platform/linux/fl_method_call_private.h"
#include "flutter/shell/platform/linux/fl_method_channel_private.h"
#include "flutter/shell/platform/linux/fl_method_codec_private.h"
struct _FlMethodChannel {
GObject parent_instance;
// Messenger to communicate on.
FlBinaryMessenger* messenger;
// TRUE if the channel has been closed.
gboolean channel_closed;
// Channel name.
gchar* name;
// Codec to en/decode messages.
FlMethodCodec* codec;
// Function called when a method call is received.
FlMethodChannelMethodCallHandler method_call_handler;
gpointer method_call_handler_data;
GDestroyNotify method_call_handler_destroy_notify;
};
G_DEFINE_TYPE(FlMethodChannel, fl_method_channel, G_TYPE_OBJECT)
// Called when a binary message is received on this channel.
static void message_cb(FlBinaryMessenger* messenger,
const gchar* channel,
GBytes* message,
FlBinaryMessengerResponseHandle* response_handle,
gpointer user_data) {
FlMethodChannel* self = FL_METHOD_CHANNEL(user_data);
if (self->method_call_handler == nullptr) {
return;
}
g_autofree gchar* method = nullptr;
g_autoptr(FlValue) args = nullptr;
g_autoptr(GError) error = nullptr;
if (!fl_method_codec_decode_method_call(self->codec, message, &method, &args,
&error)) {
g_warning("Failed to decode method call: %s", error->message);
return;
}
g_autoptr(FlMethodCall) method_call =
fl_method_call_new(method, args, self, response_handle);
self->method_call_handler(self, method_call, self->method_call_handler_data);
}
// Called when a response is received to a sent message.
static void message_response_cb(GObject* object,
GAsyncResult* result,
gpointer user_data) {
GTask* task = G_TASK(user_data);
g_task_return_pointer(task, result, g_object_unref);
}
// Called when the channel handler is closed.
static void channel_closed_cb(gpointer user_data) {
g_autoptr(FlMethodChannel) self = FL_METHOD_CHANNEL(user_data);
self->channel_closed = TRUE;
// Disconnect handler.
if (self->method_call_handler_destroy_notify != nullptr) {
self->method_call_handler_destroy_notify(self->method_call_handler_data);
}
self->method_call_handler = nullptr;
self->method_call_handler_data = nullptr;
self->method_call_handler_destroy_notify = nullptr;
}
static void fl_method_channel_dispose(GObject* object) {
FlMethodChannel* self = FL_METHOD_CHANNEL(object);
// Note we don't have to clear the handler in messenger as it holds
// a reference to this object so the following code is only run after
// the messenger has closed the channel already.
g_clear_object(&self->messenger);
g_clear_pointer(&self->name, g_free);
g_clear_object(&self->codec);
if (self->method_call_handler_destroy_notify != nullptr) {
self->method_call_handler_destroy_notify(self->method_call_handler_data);
}
self->method_call_handler = nullptr;
self->method_call_handler_data = nullptr;
self->method_call_handler_destroy_notify = nullptr;
G_OBJECT_CLASS(fl_method_channel_parent_class)->dispose(object);
}
static void fl_method_channel_class_init(FlMethodChannelClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_method_channel_dispose;
}
static void fl_method_channel_init(FlMethodChannel* self) {}
G_MODULE_EXPORT FlMethodChannel* fl_method_channel_new(
FlBinaryMessenger* messenger,
const gchar* name,
FlMethodCodec* codec) {
g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr);
g_return_val_if_fail(name != nullptr, nullptr);
g_return_val_if_fail(FL_IS_METHOD_CODEC(codec), nullptr);
FlMethodChannel* self =
FL_METHOD_CHANNEL(g_object_new(fl_method_channel_get_type(), nullptr));
self->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger));
self->name = g_strdup(name);
self->codec = FL_METHOD_CODEC(g_object_ref(codec));
fl_binary_messenger_set_message_handler_on_channel(
self->messenger, self->name, message_cb, g_object_ref(self),
channel_closed_cb);
return self;
}
G_MODULE_EXPORT void fl_method_channel_set_method_call_handler(
FlMethodChannel* self,
FlMethodChannelMethodCallHandler handler,
gpointer user_data,
GDestroyNotify destroy_notify) {
g_return_if_fail(FL_IS_METHOD_CHANNEL(self));
// Don't set handler if channel closed.
if (self->channel_closed) {
if (handler != nullptr) {
g_warning(
"Attempted to set method call handler on a closed FlMethodChannel");
}
if (destroy_notify != nullptr) {
destroy_notify(user_data);
}
return;
}
if (self->method_call_handler_destroy_notify != nullptr) {
self->method_call_handler_destroy_notify(self->method_call_handler_data);
}
self->method_call_handler = handler;
self->method_call_handler_data = user_data;
self->method_call_handler_destroy_notify = destroy_notify;
}
G_MODULE_EXPORT void fl_method_channel_invoke_method(
FlMethodChannel* self,
const gchar* method,
FlValue* args,
GCancellable* cancellable,
GAsyncReadyCallback callback,
gpointer user_data) {
g_return_if_fail(FL_IS_METHOD_CHANNEL(self));
g_return_if_fail(method != nullptr);
g_autoptr(GTask) task =
callback != nullptr ? g_task_new(self, cancellable, callback, user_data)
: nullptr;
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message =
fl_method_codec_encode_method_call(self->codec, method, args, &error);
if (message == nullptr) {
if (task != nullptr) {
g_task_return_error(task, error);
}
return;
}
fl_binary_messenger_send_on_channel(
self->messenger, self->name, message, cancellable,
callback != nullptr ? message_response_cb : nullptr,
g_steal_pointer(&task));
}
G_MODULE_EXPORT FlMethodResponse* fl_method_channel_invoke_method_finish(
FlMethodChannel* self,
GAsyncResult* result,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CHANNEL(self), nullptr);
g_return_val_if_fail(g_task_is_valid(result, self), nullptr);
g_autoptr(GTask) task = G_TASK(result);
GAsyncResult* r = G_ASYNC_RESULT(g_task_propagate_pointer(task, nullptr));
g_autoptr(GBytes) response =
fl_binary_messenger_send_on_channel_finish(self->messenger, r, error);
if (response == nullptr) {
return nullptr;
}
return fl_method_codec_decode_response(self->codec, response, error);
}
gboolean fl_method_channel_respond(
FlMethodChannel* self,
FlBinaryMessengerResponseHandle* response_handle,
FlMethodResponse* response,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CHANNEL(self), FALSE);
g_return_val_if_fail(FL_IS_BINARY_MESSENGER_RESPONSE_HANDLE(response_handle),
FALSE);
g_return_val_if_fail(FL_IS_METHOD_SUCCESS_RESPONSE(response) ||
FL_IS_METHOD_ERROR_RESPONSE(response) ||
FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(response),
FALSE);
g_autoptr(GBytes) message = nullptr;
if (FL_IS_METHOD_SUCCESS_RESPONSE(response)) {
FlMethodSuccessResponse* r = FL_METHOD_SUCCESS_RESPONSE(response);
message = fl_method_codec_encode_success_envelope(
self->codec, fl_method_success_response_get_result(r), error);
if (message == nullptr) {
return FALSE;
}
} else if (FL_IS_METHOD_ERROR_RESPONSE(response)) {
FlMethodErrorResponse* r = FL_METHOD_ERROR_RESPONSE(response);
message = fl_method_codec_encode_error_envelope(
self->codec, fl_method_error_response_get_code(r),
fl_method_error_response_get_message(r),
fl_method_error_response_get_details(r), error);
if (message == nullptr) {
return FALSE;
}
} else if (FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(response)) {
message = nullptr;
} else {
g_assert_not_reached();
}
return fl_binary_messenger_send_response(self->messenger, response_handle,
message, error);
}
| engine/shell/platform/linux/fl_method_channel.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_method_channel.cc",
"repo_id": "engine",
"token_count": 3347
} | 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_plugin_registrar.h"
#include "flutter/shell/platform/linux/fl_plugin_registrar_private.h"
#include <gmodule.h>
G_DECLARE_FINAL_TYPE(FlPluginRegistrarImpl,
fl_plugin_registrar_impl,
FL,
PLUGIN_REGISTRAR_IMPL,
GObject)
struct _FlPluginRegistrarImpl {
GObject parent_instance;
// View that plugin is controlling.
FlView* view;
// Messenger to communicate on.
FlBinaryMessenger* messenger;
// Texture registrar in use.
FlTextureRegistrar* texture_registrar;
};
static void fl_plugin_registrar_impl_iface_init(
FlPluginRegistrarInterface* iface);
G_DEFINE_INTERFACE(FlPluginRegistrar, fl_plugin_registrar, G_TYPE_OBJECT)
G_DEFINE_TYPE_WITH_CODE(
FlPluginRegistrarImpl,
fl_plugin_registrar_impl,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_plugin_registrar_get_type(),
fl_plugin_registrar_impl_iface_init))
static void fl_plugin_registrar_default_init(
FlPluginRegistrarInterface* iface) {}
static void fl_plugin_registrar_impl_dispose(GObject* object) {
FlPluginRegistrarImpl* self = FL_PLUGIN_REGISTRAR_IMPL(object);
if (self->view != nullptr) {
g_object_remove_weak_pointer(G_OBJECT(self->view),
reinterpret_cast<gpointer*>(&(self->view)));
self->view = nullptr;
}
g_clear_object(&self->messenger);
g_clear_object(&self->texture_registrar);
G_OBJECT_CLASS(fl_plugin_registrar_impl_parent_class)->dispose(object);
}
static void fl_plugin_registrar_impl_class_init(
FlPluginRegistrarImplClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_plugin_registrar_impl_dispose;
}
static FlBinaryMessenger* get_messenger(FlPluginRegistrar* registrar) {
FlPluginRegistrarImpl* self = FL_PLUGIN_REGISTRAR_IMPL(registrar);
return self->messenger;
}
static FlTextureRegistrar* get_texture_registrar(FlPluginRegistrar* registrar) {
FlPluginRegistrarImpl* self = FL_PLUGIN_REGISTRAR_IMPL(registrar);
return self->texture_registrar;
}
static FlView* get_view(FlPluginRegistrar* registrar) {
FlPluginRegistrarImpl* self = FL_PLUGIN_REGISTRAR_IMPL(registrar);
return self->view;
}
static void fl_plugin_registrar_impl_iface_init(
FlPluginRegistrarInterface* iface) {
iface->get_messenger = get_messenger;
iface->get_texture_registrar = get_texture_registrar;
iface->get_view = get_view;
}
static void fl_plugin_registrar_impl_init(FlPluginRegistrarImpl* self) {}
FlPluginRegistrar* fl_plugin_registrar_new(
FlView* view,
FlBinaryMessenger* messenger,
FlTextureRegistrar* texture_registrar) {
g_return_val_if_fail(view == nullptr || FL_IS_VIEW(view), nullptr);
g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr);
g_return_val_if_fail(FL_IS_TEXTURE_REGISTRAR(texture_registrar), nullptr);
FlPluginRegistrarImpl* self = FL_PLUGIN_REGISTRAR_IMPL(
g_object_new(fl_plugin_registrar_impl_get_type(), nullptr));
// Added to stop compiler complaining about an unused function.
FL_IS_PLUGIN_REGISTRAR_IMPL(self);
self->view = view;
if (view != nullptr) {
g_object_add_weak_pointer(G_OBJECT(view),
reinterpret_cast<gpointer*>(&(self->view)));
}
self->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger));
self->texture_registrar =
FL_TEXTURE_REGISTRAR(g_object_ref(texture_registrar));
return FL_PLUGIN_REGISTRAR(self);
}
G_MODULE_EXPORT FlBinaryMessenger* fl_plugin_registrar_get_messenger(
FlPluginRegistrar* self) {
g_return_val_if_fail(FL_IS_PLUGIN_REGISTRAR(self), nullptr);
return FL_PLUGIN_REGISTRAR_GET_IFACE(self)->get_messenger(self);
}
G_MODULE_EXPORT FlTextureRegistrar* fl_plugin_registrar_get_texture_registrar(
FlPluginRegistrar* self) {
g_return_val_if_fail(FL_IS_PLUGIN_REGISTRAR(self), nullptr);
return FL_PLUGIN_REGISTRAR_GET_IFACE(self)->get_texture_registrar(self);
}
G_MODULE_EXPORT FlView* fl_plugin_registrar_get_view(FlPluginRegistrar* self) {
g_return_val_if_fail(FL_IS_PLUGIN_REGISTRAR(self), nullptr);
return FL_PLUGIN_REGISTRAR_GET_IFACE(self)->get_view(self);
}
| engine/shell/platform/linux/fl_plugin_registrar.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_plugin_registrar.cc",
"repo_id": "engine",
"token_count": 1809
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_SETTINGS_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_SETTINGS_H_
#include <glib-object.h>
G_BEGIN_DECLS
G_DECLARE_INTERFACE(FlSettings, fl_settings, FL, SETTINGS, GObject)
/**
* FlClockFormat:
* @FL_CLOCK_FORMAT_12H: 12-hour clock format.
* @FL_CLOCK_FORMAT_24H: 24-hour clock format.
*
* Available clock formats.
*/
typedef enum {
// NOLINTBEGIN(readability-identifier-naming)
FL_CLOCK_FORMAT_12H,
FL_CLOCK_FORMAT_24H,
// NOLINTEND(readability-identifier-naming)
} FlClockFormat;
/**
* FlColorScheme:
* @FL_COLOR_SCHEME_LIGHT: Prefer light theme.
* @FL_COLOR_SCHEME_DARK: Prefer dark theme.
*
* Available color schemes.
*/
typedef enum {
// NOLINTBEGIN(readability-identifier-naming)
FL_COLOR_SCHEME_LIGHT,
FL_COLOR_SCHEME_DARK,
// NOLINTEND(readability-identifier-naming)
} FlColorScheme;
/**
* FlSettings:
* #FlSettings is and object that provides desktop settings.
*/
struct _FlSettingsInterface {
GTypeInterface parent;
FlClockFormat (*get_clock_format)(FlSettings* settings);
FlColorScheme (*get_color_scheme)(FlSettings* settings);
gboolean (*get_enable_animations)(FlSettings* settings);
gboolean (*get_high_contrast)(FlSettings* settings);
gdouble (*get_text_scaling_factor)(FlSettings* settings);
};
/**
* fl_settings_new:
*
* Creates a new settings instance.
*
* Returns: a new #FlSettings.
*/
FlSettings* fl_settings_new();
/**
* fl_settings_get_clock_format:
* @settings: an #FlSettings.
*
* Whether the clock displays in 24-hour or 12-hour format.
*
* This corresponds to `org.gnome.desktop.interface.clock-format` in GNOME.
*
* Returns: an #FlClockFormat.
*/
FlClockFormat fl_settings_get_clock_format(FlSettings* settings);
/**
* fl_settings_get_color_scheme:
* @settings: an #FlSettings.
*
* The preferred color scheme for the user interface.
*
* This corresponds to `org.gnome.desktop.interface.color-scheme` in GNOME.
*
* Returns: an #FlColorScheme.
*/
FlColorScheme fl_settings_get_color_scheme(FlSettings* settings);
/**
* fl_settings_get_enable_animations:
* @settings: an #FlSettings.
*
* Whether animations should be enabled.
*
* This corresponds to `org.gnome.desktop.interface.enable-animations` in GNOME.
*
* Returns: %TRUE if animations are enabled.
*/
gboolean fl_settings_get_enable_animations(FlSettings* settings);
/**
* fl_settings_get_high_contrast:
* @settings: an #FlSettings.
*
* Whether to use high contrast theme.
*
* This corresponds to `org.gnome.desktop.a11y.interface.high-contrast` in
* GNOME.
*
* Returns: %TRUE if high contrast is used.
*/
gboolean fl_settings_get_high_contrast(FlSettings* settings);
/**
* fl_settings_get_text_scaling_factor:
* @settings: an #FlSettings.
*
* Factor used to enlarge or reduce text display, without changing font size.
*
* This corresponds to `org.gnome.desktop.interface.text-scaling-factor` in
* GNOME.
*
* Returns: a floating point number.
*/
gdouble fl_settings_get_text_scaling_factor(FlSettings* settings);
/**
* fl_settings_emit_changed:
* @settings: an #FlSettings.
*
* Emits the "changed" signal. Used by FlSettings implementations to notify when
* the desktop settings have changed.
*/
void fl_settings_emit_changed(FlSettings* settings);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_SETTINGS_H_
| engine/shell/platform/linux/fl_settings.h/0 | {
"file_path": "engine/shell/platform/linux/fl_settings.h",
"repo_id": "engine",
"token_count": 1203
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXT_INPUT_PLUGIN_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXT_INPUT_PLUGIN_H_
#include <gtk/gtk.h>
#include "flutter/shell/platform/linux/fl_key_event.h"
#include "flutter/shell/platform/linux/fl_text_input_view_delegate.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h"
G_BEGIN_DECLS
G_DECLARE_DERIVABLE_TYPE(FlTextInputPlugin,
fl_text_input_plugin,
FL,
TEXT_INPUT_PLUGIN,
GObject);
/**
* FlTextInputPlugin:
*
* #FlTextInputPlugin is a plugin that implements the shell side
* of SystemChannels.textInput from the Flutter services library.
*/
struct _FlTextInputPluginClass {
GObjectClass parent_class;
/**
* Virtual method called to filter a keypress.
*/
gboolean (*filter_keypress)(FlTextInputPlugin* self, FlKeyEvent* event);
};
/**
* fl_text_input_plugin_new:
* @messenger: an #FlBinaryMessenger.
* @im_context: (allow-none): a #GtkIMContext.
* @view_delegate: an #FlTextInputViewDelegate.
*
* Creates a new plugin that implements SystemChannels.textInput from the
* Flutter services library.
*
* Returns: a new #FlTextInputPlugin.
*/
FlTextInputPlugin* fl_text_input_plugin_new(
FlBinaryMessenger* messenger,
GtkIMContext* im_context,
FlTextInputViewDelegate* view_delegate);
/**
* fl_text_input_plugin_filter_keypress
* @plugin: an #FlTextInputPlugin.
* @event: a #FlKeyEvent
*
* Process a Gdk key event.
*
* Returns: %TRUE if the event was used.
*/
gboolean fl_text_input_plugin_filter_keypress(FlTextInputPlugin* plugin,
FlKeyEvent* event);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXT_INPUT_PLUGIN_H_
| engine/shell/platform/linux/fl_text_input_plugin.h/0 | {
"file_path": "engine/shell/platform/linux/fl_text_input_plugin.h",
"repo_id": "engine",
"token_count": 802
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_VIEW_ACCESSIBLE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_VIEW_ACCESSIBLE_H_
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
#include <gtk/gtk-a11y.h>
#include "flutter/shell/platform/embedder/embedder.h"
G_BEGIN_DECLS
G_DECLARE_FINAL_TYPE(FlViewAccessible,
fl_view_accessible,
FL,
VIEW_ACCESSIBLE,
GtkContainerAccessible)
/**
* FlViewAccessible:
*
* #FlViewAccessible is an object that exposes accessibility information for an
* #FlView.
*/
/**
* fl_view_accessible_handle_update_semantics:
* @accessible: an #FlViewAccessible.
* @update: semantic update information.
*
* Handle a semantics update from Flutter.
*/
void fl_view_accessible_handle_update_semantics(
FlViewAccessible* accessible,
const FlutterSemanticsUpdate2* update);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_VIEW_ACCESSIBLE_H_
| engine/shell/platform/linux/fl_view_accessible.h/0 | {
"file_path": "engine/shell/platform/linux/fl_view_accessible.h",
"repo_id": "engine",
"token_count": 494
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CALL_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CALL_H_
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
#include <glib-object.h>
#include <gmodule.h>
#include "fl_method_response.h"
#include "fl_value.h"
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_FINAL_TYPE(FlMethodCall, fl_method_call, FL, METHOD_CALL, GObject)
/**
* FlMethodCall:
*
* #FlMethodCall represents and incoming method call as returned by an
* #FlMethodChannel.
*/
/**
* fl_method_call_get_name:
* @method_call: an #FlMethodCall.
*
* Gets the name of the method call.
*
* Returns: a method name.
*/
const gchar* fl_method_call_get_name(FlMethodCall* method_call);
/**
* fl_method_call_get_args:
* @method_call: an #FlMethodCall.
*
* Gets the arguments passed to the method.
*
* Returns: an #FlValue.
*/
FlValue* fl_method_call_get_args(FlMethodCall* method_call);
/**
* fl_method_call_respond:
* @method_call: an #FlMethodCall.
* @response: an #FlMethodResponse.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Responds to a method call.
*
* Returns: %TRUE on success.
*/
gboolean fl_method_call_respond(FlMethodCall* method_call,
FlMethodResponse* response,
GError** error);
/**
* fl_method_call_respond_success:
* @method_call: an #FlMethodCall.
* @result: (allow-none): value to respond with, must match what the
* #FlMethodCodec supports.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Convenience method that responds to method call with
* #FlMethodSuccessResponse.
*
* Returns: %TRUE on success.
*/
gboolean fl_method_call_respond_success(FlMethodCall* method_call,
FlValue* result,
GError** error);
/**
* fl_method_call_respond_error:
* @method_call: an #FlMethodCall.
* @code: error code.
* @message: (allow-none): error message.
* @details: (allow-none): details for the error.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Convenience method that responds to method call with #FlMethodErrorResponse.
*
* Returns: %TRUE on success.
*/
gboolean fl_method_call_respond_error(FlMethodCall* method_call,
const gchar* code,
const gchar* message,
FlValue* details,
GError** error);
/**
* fl_method_call_respond_not_implemented:
* @method_call: an #FlMethodCall.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Convenience method that responds to method call with
* #FlMethodNotImplementedResponse.
*
* Returns: %TRUE on success.
*/
gboolean fl_method_call_respond_not_implemented(FlMethodCall* method_call,
GError** error);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CALL_H_
| engine/shell/platform/linux/public/flutter_linux/fl_method_call.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_method_call.h",
"repo_id": "engine",
"token_count": 1425
} | 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.
#include "gtest/gtest.h"
#include "flutter/shell/platform/linux/testing/fl_test.h"
#include "flutter/shell/platform/linux/fl_engine_private.h"
#include "flutter/shell/platform/linux/testing/mock_renderer.h"
namespace {
class ImModuleEnv : public ::testing::Environment {
public:
void SetUp() override {
setenv("GTK_IM_MODULE", "gtk-im-context-simple", true);
}
};
testing::Environment* const kEnv =
testing::AddGlobalTestEnvironment(new ImModuleEnv);
} // namespace
static uint8_t hex_digit_to_int(char value) {
if (value >= '0' && value <= '9') {
return value - '0';
} else if (value >= 'a' && value <= 'f') {
return value - 'a' + 10;
} else if (value >= 'F' && value <= 'F') {
return value - 'A' + 10;
} else {
return 0;
}
}
static uint8_t parse_hex8(const gchar* hex_string) {
if (hex_string[0] == '\0') {
return 0x00;
}
return hex_digit_to_int(hex_string[0]) << 4 | hex_digit_to_int(hex_string[1]);
}
GBytes* hex_string_to_bytes(const gchar* hex_string) {
GByteArray* buffer = g_byte_array_new();
for (int i = 0; hex_string[i] != '\0' && hex_string[i + 1] != '\0'; i += 2) {
uint8_t value = parse_hex8(hex_string + i);
g_byte_array_append(buffer, &value, 1);
}
return g_byte_array_free_to_bytes(buffer);
}
gchar* bytes_to_hex_string(GBytes* bytes) {
GString* hex_string = g_string_new("");
size_t data_length;
const uint8_t* data =
static_cast<const uint8_t*>(g_bytes_get_data(bytes, &data_length));
for (size_t i = 0; i < data_length; i++) {
g_string_append_printf(hex_string, "%02x", data[i]);
}
return g_string_free(hex_string, FALSE);
}
FlEngine* make_mock_engine() {
g_autoptr(FlDartProject) project = fl_dart_project_new();
return make_mock_engine_with_project(project);
}
FlEngine* make_mock_engine_with_project(FlDartProject* project) {
g_autoptr(FlMockRenderer) renderer = fl_mock_renderer_new();
g_autoptr(FlEngine) engine = fl_engine_new(project, FL_RENDERER(renderer));
g_autoptr(GError) engine_error = nullptr;
EXPECT_TRUE(fl_engine_start(engine, &engine_error));
EXPECT_EQ(engine_error, nullptr);
return static_cast<FlEngine*>(g_object_ref(engine));
}
void PrintTo(FlValue* v, std::ostream* os) {
g_autofree gchar* s = fl_value_to_string(v);
*os << s;
}
| engine/shell/platform/linux/testing/fl_test.cc/0 | {
"file_path": "engine/shell/platform/linux/testing/fl_test.cc",
"repo_id": "engine",
"token_count": 977
} | 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.
#include "flutter/shell/platform/linux/testing/mock_renderer.h"
struct _FlMockRenderer {
FlRenderer parent_instance;
};
G_DEFINE_TYPE(FlMockRenderer, fl_mock_renderer, fl_renderer_get_type())
// Implements FlRenderer::make_current.
static void fl_mock_renderer_make_current(FlRenderer* renderer) {}
// Implements FlRenderer::make_resource_current.
static void fl_mock_renderer_make_resource_current(FlRenderer* renderer) {}
// Implements FlRenderer::clear_current.
static void fl_mock_renderer_clear_current(FlRenderer* renderer) {}
static void fl_mock_renderer_class_init(FlMockRendererClass* klass) {
FL_RENDERER_CLASS(klass)->make_current = fl_mock_renderer_make_current;
FL_RENDERER_CLASS(klass)->make_resource_current =
fl_mock_renderer_make_resource_current;
FL_RENDERER_CLASS(klass)->clear_current = fl_mock_renderer_clear_current;
}
static void fl_mock_renderer_init(FlMockRenderer* self) {}
// Creates a stub renderer
FlMockRenderer* fl_mock_renderer_new() {
return FL_MOCK_RENDERER(g_object_new(fl_mock_renderer_get_type(), nullptr));
}
| engine/shell/platform/linux/testing/mock_renderer.cc/0 | {
"file_path": "engine/shell/platform/linux/testing/mock_renderer.cc",
"repo_id": "engine",
"token_count": 463
} | 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.
#include "flutter/shell/platform/windows/accessibility_bridge_windows.h"
#include <comdef.h>
#include <comutil.h>
#include <oleacc.h>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
#include "flutter/shell/platform/windows/flutter_platform_node_delegate_windows.h"
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h"
#include "flutter/shell/platform/windows/testing/test_keyboard.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
using ::testing::NiceMock;
// A structure representing a Win32 MSAA event targeting a specified node.
struct MsaaEvent {
std::shared_ptr<FlutterPlatformNodeDelegateWindows> node_delegate;
ax::mojom::Event event_type;
};
// Accessibility bridge delegate that captures events dispatched to the OS.
class AccessibilityBridgeWindowsSpy : public AccessibilityBridgeWindows {
public:
using AccessibilityBridgeWindows::OnAccessibilityEvent;
explicit AccessibilityBridgeWindowsSpy(FlutterWindowsEngine* engine,
FlutterWindowsView* view)
: AccessibilityBridgeWindows(view) {}
void DispatchWinAccessibilityEvent(
std::shared_ptr<FlutterPlatformNodeDelegateWindows> node_delegate,
ax::mojom::Event event_type) override {
dispatched_events_.push_back({node_delegate, event_type});
}
void SetFocus(std::shared_ptr<FlutterPlatformNodeDelegateWindows>
node_delegate) override {
focused_nodes_.push_back(std::move(node_delegate));
}
void ResetRecords() {
dispatched_events_.clear();
focused_nodes_.clear();
}
const std::vector<MsaaEvent>& dispatched_events() const {
return dispatched_events_;
}
const std::vector<int32_t> focused_nodes() const {
std::vector<int32_t> ids;
std::transform(focused_nodes_.begin(), focused_nodes_.end(),
std::back_inserter(ids),
[](std::shared_ptr<FlutterPlatformNodeDelegate> node) {
return node->GetAXNode()->id();
});
return ids;
}
protected:
std::weak_ptr<FlutterPlatformNodeDelegate> GetFocusedNode() override {
return focused_nodes_.back();
}
private:
std::vector<MsaaEvent> dispatched_events_;
std::vector<std::shared_ptr<FlutterPlatformNodeDelegate>> focused_nodes_;
FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridgeWindowsSpy);
};
// A FlutterWindowsView whose accessibility bridge is an
// AccessibilityBridgeWindowsSpy.
class FlutterWindowsViewSpy : public FlutterWindowsView {
public:
FlutterWindowsViewSpy(FlutterWindowsEngine* engine,
std::unique_ptr<WindowBindingHandler> handler)
: FlutterWindowsView(kImplicitViewId, engine, std::move(handler)) {}
protected:
virtual std::shared_ptr<AccessibilityBridgeWindows>
CreateAccessibilityBridge() override {
return std::make_shared<AccessibilityBridgeWindowsSpy>(GetEngine(), this);
}
private:
FML_DISALLOW_COPY_AND_ASSIGN(FlutterWindowsViewSpy);
};
// Returns an engine instance configured with dummy project path values, and
// overridden methods for sending platform messages, so that the engine can
// respond as if the framework were connected.
std::unique_ptr<FlutterWindowsEngine> GetTestEngine() {
FlutterDesktopEngineProperties properties = {};
properties.assets_path = L"C:\\foo\\flutter_assets";
properties.icu_data_path = L"C:\\foo\\icudtl.dat";
properties.aot_library_path = L"C:\\foo\\aot.so";
FlutterProjectBundle project(properties);
auto engine = std::make_unique<FlutterWindowsEngine>(project);
EngineModifier modifier(engine.get());
modifier.embedder_api().UpdateSemanticsEnabled =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) {
return kSuccess;
};
MockEmbedderApiForKeyboard(modifier,
std::make_shared<MockKeyResponseController>());
engine->Run();
return engine;
}
// Populates the AXTree associated with the specified bridge with test data.
//
// node0
// / \
// node1 node2
// / \
// node3 node4
//
// node0 and node2 are grouping nodes. node1 and node2 are static text nodes.
// node4 is a static text node with no text, and hence has the "ignored" state.
void PopulateAXTree(std::shared_ptr<AccessibilityBridge> bridge) {
// Add node 0: root.
FlutterSemanticsNode2 node0{sizeof(FlutterSemanticsNode2), 0};
std::vector<int32_t> node0_children{1, 2};
node0.child_count = node0_children.size();
node0.children_in_traversal_order = node0_children.data();
node0.children_in_hit_test_order = node0_children.data();
// Add node 1: text child of node 0.
FlutterSemanticsNode2 node1{sizeof(FlutterSemanticsNode2), 1};
node1.label = "prefecture";
node1.value = "Kyoto";
// Add node 2: subtree child of node 0.
FlutterSemanticsNode2 node2{sizeof(FlutterSemanticsNode2), 2};
std::vector<int32_t> node2_children{3, 4};
node2.child_count = node2_children.size();
node2.children_in_traversal_order = node2_children.data();
node2.children_in_hit_test_order = node2_children.data();
// Add node 3: text child of node 2.
FlutterSemanticsNode2 node3{sizeof(FlutterSemanticsNode2), 3};
node3.label = "city";
node3.value = "Uji";
// Add node 4: text child (with no text) of node 2.
FlutterSemanticsNode2 node4{sizeof(FlutterSemanticsNode2), 4};
bridge->AddFlutterSemanticsNodeUpdate(node0);
bridge->AddFlutterSemanticsNodeUpdate(node1);
bridge->AddFlutterSemanticsNodeUpdate(node2);
bridge->AddFlutterSemanticsNodeUpdate(node3);
bridge->AddFlutterSemanticsNodeUpdate(node4);
bridge->CommitUpdates();
}
ui::AXNode* AXNodeFromID(std::shared_ptr<AccessibilityBridge> bridge,
int32_t id) {
auto node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(id).lock();
return node_delegate ? node_delegate->GetAXNode() : nullptr;
}
std::shared_ptr<AccessibilityBridgeWindowsSpy> GetAccessibilityBridgeSpy(
FlutterWindowsView& view) {
return std::static_pointer_cast<AccessibilityBridgeWindowsSpy>(
view.accessibility_bridge().lock());
}
void ExpectWinEventFromAXEvent(int32_t node_id,
ui::AXEventGenerator::Event ax_event,
ax::mojom::Event expected_event) {
auto engine = GetTestEngine();
FlutterWindowsViewSpy view{
engine.get(), std::make_unique<NiceMock<MockWindowBindingHandler>>()};
EngineModifier modifier{engine.get()};
modifier.SetImplicitView(&view);
view.OnUpdateSemanticsEnabled(true);
auto bridge = GetAccessibilityBridgeSpy(view);
PopulateAXTree(bridge);
bridge->ResetRecords();
bridge->OnAccessibilityEvent({AXNodeFromID(bridge, node_id),
{ax_event, ax::mojom::EventFrom::kNone, {}}});
ASSERT_EQ(bridge->dispatched_events().size(), 1);
EXPECT_EQ(bridge->dispatched_events()[0].event_type, expected_event);
}
void ExpectWinEventFromAXEventOnFocusNode(int32_t node_id,
ui::AXEventGenerator::Event ax_event,
ax::mojom::Event expected_event,
int32_t focus_id) {
auto engine = GetTestEngine();
FlutterWindowsViewSpy view{
engine.get(), std::make_unique<NiceMock<MockWindowBindingHandler>>()};
EngineModifier modifier{engine.get()};
modifier.SetImplicitView(&view);
view.OnUpdateSemanticsEnabled(true);
auto bridge = GetAccessibilityBridgeSpy(view);
PopulateAXTree(bridge);
bridge->ResetRecords();
auto focus_delegate =
bridge->GetFlutterPlatformNodeDelegateFromID(focus_id).lock();
bridge->SetFocus(std::static_pointer_cast<FlutterPlatformNodeDelegateWindows>(
focus_delegate));
bridge->OnAccessibilityEvent({AXNodeFromID(bridge, node_id),
{ax_event, ax::mojom::EventFrom::kNone, {}}});
ASSERT_EQ(bridge->dispatched_events().size(), 1);
EXPECT_EQ(bridge->dispatched_events()[0].event_type, expected_event);
EXPECT_EQ(bridge->dispatched_events()[0].node_delegate->GetAXNode()->id(),
focus_id);
}
} // namespace
TEST(AccessibilityBridgeWindows, GetParent) {
auto engine = GetTestEngine();
FlutterWindowsViewSpy view{
engine.get(), std::make_unique<NiceMock<MockWindowBindingHandler>>()};
EngineModifier modifier{engine.get()};
modifier.SetImplicitView(&view);
view.OnUpdateSemanticsEnabled(true);
auto bridge = view.accessibility_bridge().lock();
PopulateAXTree(bridge);
auto node0_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
auto node1_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock();
EXPECT_EQ(node0_delegate->GetNativeViewAccessible(),
node1_delegate->GetParent());
}
TEST(AccessibilityBridgeWindows, GetParentOnRootRetunsNullptr) {
auto engine = GetTestEngine();
FlutterWindowsViewSpy view{
engine.get(), std::make_unique<NiceMock<MockWindowBindingHandler>>()};
EngineModifier modifier{engine.get()};
modifier.SetImplicitView(&view);
view.OnUpdateSemanticsEnabled(true);
auto bridge = view.accessibility_bridge().lock();
PopulateAXTree(bridge);
auto node0_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
ASSERT_TRUE(node0_delegate->GetParent() == nullptr);
}
TEST(AccessibilityBridgeWindows, DispatchAccessibilityAction) {
auto engine = GetTestEngine();
FlutterWindowsViewSpy view{
engine.get(), std::make_unique<NiceMock<MockWindowBindingHandler>>()};
EngineModifier modifier{engine.get()};
modifier.SetImplicitView(&view);
view.OnUpdateSemanticsEnabled(true);
auto bridge = view.accessibility_bridge().lock();
PopulateAXTree(bridge);
FlutterSemanticsAction actual_action = kFlutterSemanticsActionTap;
modifier.embedder_api().DispatchSemanticsAction = MOCK_ENGINE_PROC(
DispatchSemanticsAction,
([&actual_action](FLUTTER_API_SYMBOL(FlutterEngine) engine, uint64_t id,
FlutterSemanticsAction action, const uint8_t* data,
size_t data_length) {
actual_action = action;
return kSuccess;
}));
AccessibilityBridgeWindows delegate(&view);
delegate.DispatchAccessibilityAction(1, kFlutterSemanticsActionCopy, {});
EXPECT_EQ(actual_action, kFlutterSemanticsActionCopy);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityEventAlert) {
ExpectWinEventFromAXEvent(0, ui::AXEventGenerator::Event::ALERT,
ax::mojom::Event::kAlert);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityEventChildrenChanged) {
ExpectWinEventFromAXEvent(0, ui::AXEventGenerator::Event::CHILDREN_CHANGED,
ax::mojom::Event::kChildrenChanged);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityEventFocusChanged) {
auto engine = GetTestEngine();
FlutterWindowsViewSpy view{
engine.get(), std::make_unique<NiceMock<MockWindowBindingHandler>>()};
EngineModifier modifier{engine.get()};
modifier.SetImplicitView(&view);
view.OnUpdateSemanticsEnabled(true);
auto bridge = GetAccessibilityBridgeSpy(view);
PopulateAXTree(bridge);
bridge->ResetRecords();
bridge->OnAccessibilityEvent({AXNodeFromID(bridge, 1),
{ui::AXEventGenerator::Event::FOCUS_CHANGED,
ax::mojom::EventFrom::kNone,
{}}});
ASSERT_EQ(bridge->dispatched_events().size(), 1);
EXPECT_EQ(bridge->dispatched_events()[0].event_type,
ax::mojom::Event::kFocus);
ASSERT_EQ(bridge->focused_nodes().size(), 1);
EXPECT_EQ(bridge->focused_nodes()[0], 1);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityEventIgnoredChanged) {
// Static test nodes with no text, hint, or scrollability are ignored.
ExpectWinEventFromAXEvent(4, ui::AXEventGenerator::Event::IGNORED_CHANGED,
ax::mojom::Event::kHide);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityImageAnnotationChanged) {
ExpectWinEventFromAXEvent(
1, ui::AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED,
ax::mojom::Event::kTextChanged);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityLiveRegionChanged) {
ExpectWinEventFromAXEvent(1, ui::AXEventGenerator::Event::LIVE_REGION_CHANGED,
ax::mojom::Event::kLiveRegionChanged);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityNameChanged) {
ExpectWinEventFromAXEvent(1, ui::AXEventGenerator::Event::NAME_CHANGED,
ax::mojom::Event::kTextChanged);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityHScrollPosChanged) {
ExpectWinEventFromAXEvent(
1, ui::AXEventGenerator::Event::SCROLL_HORIZONTAL_POSITION_CHANGED,
ax::mojom::Event::kScrollPositionChanged);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityVScrollPosChanged) {
ExpectWinEventFromAXEvent(
1, ui::AXEventGenerator::Event::SCROLL_VERTICAL_POSITION_CHANGED,
ax::mojom::Event::kScrollPositionChanged);
}
TEST(AccessibilityBridgeWindows, OnAccessibilitySelectedChanged) {
ExpectWinEventFromAXEvent(1, ui::AXEventGenerator::Event::SELECTED_CHANGED,
ax::mojom::Event::kValueChanged);
}
TEST(AccessibilityBridgeWindows, OnAccessibilitySelectedChildrenChanged) {
ExpectWinEventFromAXEvent(
2, ui::AXEventGenerator::Event::SELECTED_CHILDREN_CHANGED,
ax::mojom::Event::kSelectedChildrenChanged);
}
TEST(AccessibilityBridgeWindows, OnAccessibilitySubtreeCreated) {
ExpectWinEventFromAXEvent(0, ui::AXEventGenerator::Event::SUBTREE_CREATED,
ax::mojom::Event::kShow);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityValueChanged) {
ExpectWinEventFromAXEvent(1, ui::AXEventGenerator::Event::VALUE_CHANGED,
ax::mojom::Event::kValueChanged);
}
TEST(AccessibilityBridgeWindows, OnAccessibilityStateChanged) {
ExpectWinEventFromAXEvent(
1, ui::AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED,
ax::mojom::Event::kStateChanged);
}
TEST(AccessibilityBridgeWindows, OnDocumentSelectionChanged) {
ExpectWinEventFromAXEventOnFocusNode(
1, ui::AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED,
ax::mojom::Event::kDocumentSelectionChanged, 2);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/accessibility_bridge_windows_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/accessibility_bridge_windows_unittests.cc",
"repo_id": "engine",
"token_count": 5588
} | 366 |
// 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/client_wrapper/testing/stub_flutter_windows_api.h"
static flutter::testing::StubFlutterWindowsApi* s_stub_implementation;
namespace flutter {
namespace testing {
// static
void StubFlutterWindowsApi::SetTestStub(StubFlutterWindowsApi* stub) {
s_stub_implementation = stub;
}
// static
StubFlutterWindowsApi* StubFlutterWindowsApi::GetTestStub() {
return s_stub_implementation;
}
ScopedStubFlutterWindowsApi::ScopedStubFlutterWindowsApi(
std::unique_ptr<StubFlutterWindowsApi> stub)
: stub_(std::move(stub)) {
previous_stub_ = StubFlutterWindowsApi::GetTestStub();
StubFlutterWindowsApi::SetTestStub(stub_.get());
}
ScopedStubFlutterWindowsApi::~ScopedStubFlutterWindowsApi() {
StubFlutterWindowsApi::SetTestStub(previous_stub_);
}
} // namespace testing
} // namespace flutter
// Forwarding dummy implementations of the C API.
FlutterDesktopViewControllerRef FlutterDesktopViewControllerCreate(
int width,
int height,
FlutterDesktopEngineRef engine) {
if (s_stub_implementation) {
return s_stub_implementation->ViewControllerCreate(width, height, engine);
}
return nullptr;
}
void FlutterDesktopViewControllerDestroy(
FlutterDesktopViewControllerRef controller) {
if (s_stub_implementation) {
s_stub_implementation->ViewControllerDestroy();
}
}
FlutterDesktopViewId FlutterDesktopViewControllerGetViewId(
FlutterDesktopViewControllerRef controller) {
// The stub ignores this, so just return an arbitrary non-zero value.
return static_cast<FlutterDesktopViewId>(1);
}
FlutterDesktopEngineRef FlutterDesktopViewControllerGetEngine(
FlutterDesktopViewControllerRef controller) {
// The stub ignores this, so just return an arbitrary non-zero value.
return reinterpret_cast<FlutterDesktopEngineRef>(1);
}
FlutterDesktopViewRef FlutterDesktopViewControllerGetView(
FlutterDesktopViewControllerRef controller) {
// The stub ignores this, so just return an arbitrary non-zero value.
return reinterpret_cast<FlutterDesktopViewRef>(1);
}
void FlutterDesktopViewControllerForceRedraw(
FlutterDesktopViewControllerRef controller) {
if (s_stub_implementation) {
s_stub_implementation->ViewControllerForceRedraw();
}
}
bool FlutterDesktopViewControllerHandleTopLevelWindowProc(
FlutterDesktopViewControllerRef controller,
HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam,
LRESULT* result) {
if (s_stub_implementation) {
return s_stub_implementation->ViewControllerHandleTopLevelWindowProc(
hwnd, message, wparam, lparam, result);
}
return false;
}
FlutterDesktopEngineRef FlutterDesktopEngineCreate(
const FlutterDesktopEngineProperties* engine_properties) {
if (s_stub_implementation) {
return s_stub_implementation->EngineCreate(*engine_properties);
}
return nullptr;
}
bool FlutterDesktopEngineDestroy(FlutterDesktopEngineRef engine_ref) {
if (s_stub_implementation) {
return s_stub_implementation->EngineDestroy();
}
return true;
}
bool FlutterDesktopEngineRun(FlutterDesktopEngineRef engine,
const char* entry_point) {
if (s_stub_implementation) {
return s_stub_implementation->EngineRun(entry_point);
}
return true;
}
uint64_t FlutterDesktopEngineProcessMessages(FlutterDesktopEngineRef engine) {
if (s_stub_implementation) {
return s_stub_implementation->EngineProcessMessages();
}
return 0;
}
void FlutterDesktopEngineSetNextFrameCallback(FlutterDesktopEngineRef engine,
VoidCallback callback,
void* user_data) {
if (s_stub_implementation) {
s_stub_implementation->EngineSetNextFrameCallback(callback, user_data);
}
}
void FlutterDesktopEngineReloadSystemFonts(FlutterDesktopEngineRef engine) {
if (s_stub_implementation) {
s_stub_implementation->EngineReloadSystemFonts();
}
}
FlutterDesktopPluginRegistrarRef FlutterDesktopEngineGetPluginRegistrar(
FlutterDesktopEngineRef engine,
const char* plugin_name) {
// The stub ignores this, so just return an arbitrary non-zero value.
return reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1);
}
FlutterDesktopMessengerRef FlutterDesktopEngineGetMessenger(
FlutterDesktopEngineRef engine) {
// The stub ignores this, so just return an arbitrary non-zero value.
return reinterpret_cast<FlutterDesktopMessengerRef>(2);
}
FlutterDesktopTextureRegistrarRef FlutterDesktopEngineGetTextureRegistrar(
FlutterDesktopEngineRef engine) {
// The stub ignores this, so just return an arbitrary non-zero value.
return reinterpret_cast<FlutterDesktopTextureRegistrarRef>(3);
}
HWND FlutterDesktopViewGetHWND(FlutterDesktopViewRef controller) {
if (s_stub_implementation) {
return s_stub_implementation->ViewGetHWND();
}
return reinterpret_cast<HWND>(-1);
}
IDXGIAdapter* FlutterDesktopViewGetGraphicsAdapter(FlutterDesktopViewRef view) {
if (s_stub_implementation) {
return s_stub_implementation->ViewGetGraphicsAdapter();
}
return nullptr;
}
bool FlutterDesktopEngineProcessExternalWindowMessage(
FlutterDesktopEngineRef engine,
HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam,
LRESULT* result) {
if (s_stub_implementation) {
return s_stub_implementation->EngineProcessExternalWindowMessage(
engine, hwnd, message, wparam, lparam, result);
}
return false;
}
void FlutterDesktopEngineRegisterPlatformViewType(
FlutterDesktopEngineRef engine,
const char* view_type_name,
FlutterPlatformViewTypeEntry view_type) {
if (s_stub_implementation) {
s_stub_implementation->EngineRegisterPlatformViewType(view_type_name,
view_type);
}
}
FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetView(
FlutterDesktopPluginRegistrarRef controller) {
if (s_stub_implementation) {
return s_stub_implementation->PluginRegistrarGetView();
}
return nullptr;
}
FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetViewById(
FlutterDesktopPluginRegistrarRef controller,
FlutterDesktopViewId view_id) {
if (s_stub_implementation) {
return s_stub_implementation->PluginRegistrarGetViewById(view_id);
}
return nullptr;
}
void FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopWindowProcCallback delegate,
void* user_data) {
if (s_stub_implementation) {
return s_stub_implementation
->PluginRegistrarRegisterTopLevelWindowProcDelegate(delegate,
user_data);
}
}
void FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopWindowProcCallback delegate) {
if (s_stub_implementation) {
return s_stub_implementation
->PluginRegistrarUnregisterTopLevelWindowProcDelegate(delegate);
}
}
| engine/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.cc/0 | {
"file_path": "engine/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.cc",
"repo_id": "engine",
"token_count": 2519
} | 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.
#include "Windows.h"
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_DPI_UTILS_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_DPI_UTILS_H_
namespace flutter {
/// Returns the DPI for |hwnd|. Supports all DPI awareness modes, and is
/// backward compatible down to Windows Vista. If |hwnd| is nullptr, returns the
/// DPI for the primary monitor. If Per-Monitor DPI awareness is not available,
/// returns the system's DPI.
UINT GetDpiForHWND(HWND hwnd);
/// Returns the DPI of a given monitor. Defaults to 96 if the API is not
/// available.
UINT GetDpiForMonitor(HMONITOR monitor);
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_DPI_UTILS_H_
| engine/shell/platform/windows/dpi_utils.h/0 | {
"file_path": "engine/shell/platform/windows/dpi_utils.h",
"repo_id": "engine",
"token_count": 272
} | 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_EXTERNAL_TEXTURE_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_EXTERNAL_TEXTURE_H_
#include "flutter/shell/platform/embedder/embedder.h"
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
namespace flutter {
// Abstract external texture.
class ExternalTexture {
public:
virtual ~ExternalTexture() = default;
// Returns the unique id of this texture.
int64_t texture_id() const { return reinterpret_cast<int64_t>(this); };
// Attempts to populate the specified |opengl_texture| with texture details
// such as the name, width, height and the pixel format.
// Returns true on success.
virtual bool PopulateTexture(size_t width,
size_t height,
FlutterOpenGLTexture* opengl_texture) = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EXTERNAL_TEXTURE_H_
| engine/shell/platform/windows/external_texture.h/0 | {
"file_path": "engine/shell/platform/windows/external_texture.h",
"repo_id": "engine",
"token_count": 383
} | 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.
#include "flutter/shell/platform/windows/public/flutter_windows.h"
#include <io.h>
#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <filesystem>
#include <memory>
#include <vector>
#include "flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h"
#include "flutter/shell/platform/common/incoming_message_dispatcher.h"
#include "flutter/shell/platform/common/path_utils.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/windows/dpi_utils.h"
#include "flutter/shell/platform/windows/flutter_project_bundle.h"
#include "flutter/shell/platform/windows/flutter_window.h"
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
#include "flutter/shell/platform/windows/flutter_windows_view_controller.h"
#include "flutter/shell/platform/windows/window_binding_handler.h"
#include "flutter/shell/platform/windows/window_state.h"
static_assert(FLUTTER_ENGINE_VERSION == 1, "");
// Returns the engine corresponding to the given opaque API handle.
static flutter::FlutterWindowsEngine* EngineFromHandle(
FlutterDesktopEngineRef ref) {
return reinterpret_cast<flutter::FlutterWindowsEngine*>(ref);
}
// Returns the opaque API handle for the given engine instance.
static FlutterDesktopEngineRef HandleForEngine(
flutter::FlutterWindowsEngine* engine) {
return reinterpret_cast<FlutterDesktopEngineRef>(engine);
}
static flutter::FlutterWindowsViewController* ViewControllerFromHandle(
FlutterDesktopViewControllerRef ref) {
return reinterpret_cast<flutter::FlutterWindowsViewController*>(ref);
}
static FlutterDesktopViewControllerRef HandleForViewController(
flutter::FlutterWindowsViewController* view_controller) {
return reinterpret_cast<FlutterDesktopViewControllerRef>(view_controller);
}
// Returns the view corresponding to the given opaque API handle.
static flutter::FlutterWindowsView* ViewFromHandle(FlutterDesktopViewRef ref) {
return reinterpret_cast<flutter::FlutterWindowsView*>(ref);
}
// Returns the opaque API handle for the given view instance.
static FlutterDesktopViewRef HandleForView(flutter::FlutterWindowsView* view) {
return reinterpret_cast<FlutterDesktopViewRef>(view);
}
// Returns the texture registrar corresponding to the given opaque API handle.
static flutter::FlutterWindowsTextureRegistrar* TextureRegistrarFromHandle(
FlutterDesktopTextureRegistrarRef ref) {
return reinterpret_cast<flutter::FlutterWindowsTextureRegistrar*>(ref);
}
// Returns the opaque API handle for the given texture registrar instance.
static FlutterDesktopTextureRegistrarRef HandleForTextureRegistrar(
flutter::FlutterWindowsTextureRegistrar* registrar) {
return reinterpret_cast<FlutterDesktopTextureRegistrarRef>(registrar);
}
FlutterDesktopViewControllerRef FlutterDesktopViewControllerCreate(
int width,
int height,
FlutterDesktopEngineRef engine_ref) {
flutter::FlutterWindowsEngine* engine_ptr = EngineFromHandle(engine_ref);
std::unique_ptr<flutter::WindowBindingHandler> window_wrapper =
std::make_unique<flutter::FlutterWindow>(
width, height, engine_ptr->windows_proc_table());
auto engine = std::unique_ptr<flutter::FlutterWindowsEngine>(engine_ptr);
std::unique_ptr<flutter::FlutterWindowsView> view =
engine->CreateView(std::move(window_wrapper));
auto controller = std::make_unique<flutter::FlutterWindowsViewController>(
std::move(engine), std::move(view));
controller->view()->CreateRenderSurface();
if (!controller->engine()->running()) {
if (!controller->engine()->Run()) {
return nullptr;
}
}
// Must happen after engine is running.
controller->view()->SendInitialBounds();
// The Windows embedder listens to accessibility updates using the
// view's HWND. The embedder's accessibility features may be stale if
// the app was in headless mode.
controller->engine()->UpdateAccessibilityFeatures();
return HandleForViewController(controller.release());
}
void FlutterDesktopViewControllerDestroy(FlutterDesktopViewControllerRef ref) {
auto controller = ViewControllerFromHandle(ref);
delete controller;
}
FlutterDesktopViewId FlutterDesktopViewControllerGetViewId(
FlutterDesktopViewControllerRef ref) {
auto controller = ViewControllerFromHandle(ref);
return static_cast<FlutterDesktopViewId>(controller->view()->view_id());
}
FlutterDesktopEngineRef FlutterDesktopViewControllerGetEngine(
FlutterDesktopViewControllerRef ref) {
auto controller = ViewControllerFromHandle(ref);
return HandleForEngine(controller->engine());
}
FlutterDesktopViewRef FlutterDesktopViewControllerGetView(
FlutterDesktopViewControllerRef ref) {
auto controller = ViewControllerFromHandle(ref);
return HandleForView(controller->view());
}
void FlutterDesktopViewControllerForceRedraw(
FlutterDesktopViewControllerRef ref) {
auto controller = ViewControllerFromHandle(ref);
controller->view()->ForceRedraw();
}
bool FlutterDesktopViewControllerHandleTopLevelWindowProc(
FlutterDesktopViewControllerRef ref,
HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam,
LRESULT* result) {
auto controller = ViewControllerFromHandle(ref);
std::optional<LRESULT> delegate_result =
controller->engine()
->window_proc_delegate_manager()
->OnTopLevelWindowProc(hwnd, message, wparam, lparam);
if (delegate_result) {
*result = *delegate_result;
}
return delegate_result.has_value();
}
FlutterDesktopEngineRef FlutterDesktopEngineCreate(
const FlutterDesktopEngineProperties* engine_properties) {
flutter::FlutterProjectBundle project(*engine_properties);
auto engine = std::make_unique<flutter::FlutterWindowsEngine>(project);
return HandleForEngine(engine.release());
}
bool FlutterDesktopEngineDestroy(FlutterDesktopEngineRef engine_ref) {
flutter::FlutterWindowsEngine* engine = EngineFromHandle(engine_ref);
bool result = true;
if (engine->running()) {
result = engine->Stop();
}
delete engine;
return result;
}
bool FlutterDesktopEngineRun(FlutterDesktopEngineRef engine,
const char* entry_point) {
std::string_view entry_point_view{""};
if (entry_point != nullptr) {
entry_point_view = entry_point;
}
return EngineFromHandle(engine)->Run(entry_point_view);
}
uint64_t FlutterDesktopEngineProcessMessages(FlutterDesktopEngineRef engine) {
return std::chrono::nanoseconds::max().count();
}
void FlutterDesktopEngineReloadSystemFonts(FlutterDesktopEngineRef engine) {
EngineFromHandle(engine)->ReloadSystemFonts();
}
FlutterDesktopPluginRegistrarRef FlutterDesktopEngineGetPluginRegistrar(
FlutterDesktopEngineRef engine,
const char* plugin_name) {
// Currently, one registrar acts as the registrar for all plugins, so the
// name is ignored. It is part of the API to reduce churn in the future when
// aligning more closely with the Flutter registrar system.
return EngineFromHandle(engine)->GetRegistrar();
}
FlutterDesktopMessengerRef FlutterDesktopEngineGetMessenger(
FlutterDesktopEngineRef engine) {
return EngineFromHandle(engine)->messenger();
}
FlutterDesktopTextureRegistrarRef FlutterDesktopEngineGetTextureRegistrar(
FlutterDesktopEngineRef engine) {
return HandleForTextureRegistrar(
EngineFromHandle(engine)->texture_registrar());
}
void FlutterDesktopEngineSetNextFrameCallback(FlutterDesktopEngineRef engine,
VoidCallback callback,
void* user_data) {
EngineFromHandle(engine)->SetNextFrameCallback(
[callback, user_data]() { callback(user_data); });
}
HWND FlutterDesktopViewGetHWND(FlutterDesktopViewRef view) {
return ViewFromHandle(view)->GetWindowHandle();
}
IDXGIAdapter* FlutterDesktopViewGetGraphicsAdapter(FlutterDesktopViewRef view) {
auto egl_manager = ViewFromHandle(view)->GetEngine()->egl_manager();
if (egl_manager) {
Microsoft::WRL::ComPtr<ID3D11Device> d3d_device;
Microsoft::WRL::ComPtr<IDXGIDevice> dxgi_device;
if (egl_manager->GetDevice(d3d_device.GetAddressOf()) &&
SUCCEEDED(d3d_device.As(&dxgi_device))) {
IDXGIAdapter* adapter;
if (SUCCEEDED(dxgi_device->GetAdapter(&adapter))) {
return adapter;
}
}
}
return nullptr;
}
bool FlutterDesktopEngineProcessExternalWindowMessage(
FlutterDesktopEngineRef engine,
HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam,
LRESULT* result) {
std::optional<LRESULT> lresult =
EngineFromHandle(engine)->ProcessExternalWindowMessage(hwnd, message,
wparam, lparam);
if (result && lresult.has_value()) {
*result = lresult.value();
}
return lresult.has_value();
}
void FlutterDesktopEngineRegisterPlatformViewType(
FlutterDesktopEngineRef engine,
const char* view_type_name,
FlutterPlatformViewTypeEntry view_type) {
// TODO(schectman): forward to platform view manager.
// https://github.com/flutter/flutter/issues/143375
}
FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetView(
FlutterDesktopPluginRegistrarRef registrar) {
return HandleForView(registrar->engine->view(flutter::kImplicitViewId));
}
FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetViewById(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopViewId view_id) {
return HandleForView(registrar->engine->view(view_id));
}
void FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopWindowProcCallback delegate,
void* user_data) {
registrar->engine->window_proc_delegate_manager()
->RegisterTopLevelWindowProcDelegate(delegate, user_data);
}
void FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopWindowProcCallback delegate) {
registrar->engine->window_proc_delegate_manager()
->UnregisterTopLevelWindowProcDelegate(delegate);
}
UINT FlutterDesktopGetDpiForHWND(HWND hwnd) {
return flutter::GetDpiForHWND(hwnd);
}
UINT FlutterDesktopGetDpiForMonitor(HMONITOR monitor) {
return flutter::GetDpiForMonitor(monitor);
}
void FlutterDesktopResyncOutputStreams() {
FILE* unused;
if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
_dup2(_fileno(stdout), 1);
}
if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
_dup2(_fileno(stdout), 2);
}
std::ios::sync_with_stdio();
}
// Implementations of common/ API methods.
FlutterDesktopMessengerRef FlutterDesktopPluginRegistrarGetMessenger(
FlutterDesktopPluginRegistrarRef registrar) {
return registrar->engine->messenger();
}
void FlutterDesktopPluginRegistrarSetDestructionHandler(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopOnPluginRegistrarDestroyed callback) {
registrar->engine->AddPluginRegistrarDestructionCallback(callback, registrar);
}
bool FlutterDesktopMessengerSendWithReply(FlutterDesktopMessengerRef messenger,
const char* channel,
const uint8_t* message,
const size_t message_size,
const FlutterDesktopBinaryReply reply,
void* user_data) {
FML_DCHECK(FlutterDesktopMessengerIsAvailable(messenger))
<< "Messenger must reference a running engine to send a message";
return flutter::FlutterDesktopMessenger::FromRef(messenger)
->GetEngine()
->SendPlatformMessage(channel, message, message_size, reply, user_data);
}
bool FlutterDesktopMessengerSend(FlutterDesktopMessengerRef messenger,
const char* channel,
const uint8_t* message,
const size_t message_size) {
return FlutterDesktopMessengerSendWithReply(messenger, channel, message,
message_size, nullptr, nullptr);
}
void FlutterDesktopMessengerSendResponse(
FlutterDesktopMessengerRef messenger,
const FlutterDesktopMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length) {
FML_DCHECK(FlutterDesktopMessengerIsAvailable(messenger))
<< "Messenger must reference a running engine to send a response";
flutter::FlutterDesktopMessenger::FromRef(messenger)
->GetEngine()
->SendPlatformMessageResponse(handle, data, data_length);
}
void FlutterDesktopMessengerSetCallback(FlutterDesktopMessengerRef messenger,
const char* channel,
FlutterDesktopMessageCallback callback,
void* user_data) {
FML_DCHECK(FlutterDesktopMessengerIsAvailable(messenger))
<< "Messenger must reference a running engine to set a callback";
flutter::FlutterDesktopMessenger::FromRef(messenger)
->GetEngine()
->message_dispatcher()
->SetMessageCallback(channel, callback, user_data);
}
FlutterDesktopMessengerRef FlutterDesktopMessengerAddRef(
FlutterDesktopMessengerRef messenger) {
return flutter::FlutterDesktopMessenger::FromRef(messenger)
->AddRef()
->ToRef();
}
void FlutterDesktopMessengerRelease(FlutterDesktopMessengerRef messenger) {
flutter::FlutterDesktopMessenger::FromRef(messenger)->Release();
}
bool FlutterDesktopMessengerIsAvailable(FlutterDesktopMessengerRef messenger) {
return flutter::FlutterDesktopMessenger::FromRef(messenger)->GetEngine() !=
nullptr;
}
FlutterDesktopMessengerRef FlutterDesktopMessengerLock(
FlutterDesktopMessengerRef messenger) {
flutter::FlutterDesktopMessenger::FromRef(messenger)->GetMutex().lock();
return messenger;
}
void FlutterDesktopMessengerUnlock(FlutterDesktopMessengerRef messenger) {
flutter::FlutterDesktopMessenger::FromRef(messenger)->GetMutex().unlock();
}
FlutterDesktopTextureRegistrarRef FlutterDesktopRegistrarGetTextureRegistrar(
FlutterDesktopPluginRegistrarRef registrar) {
return HandleForTextureRegistrar(registrar->engine->texture_registrar());
}
int64_t FlutterDesktopTextureRegistrarRegisterExternalTexture(
FlutterDesktopTextureRegistrarRef texture_registrar,
const FlutterDesktopTextureInfo* texture_info) {
return TextureRegistrarFromHandle(texture_registrar)
->RegisterTexture(texture_info);
}
void FlutterDesktopTextureRegistrarUnregisterExternalTexture(
FlutterDesktopTextureRegistrarRef texture_registrar,
int64_t texture_id,
void (*callback)(void* user_data),
void* user_data) {
auto registrar = TextureRegistrarFromHandle(texture_registrar);
if (callback) {
registrar->UnregisterTexture(
texture_id, [callback, user_data]() { callback(user_data); });
return;
}
registrar->UnregisterTexture(texture_id);
}
bool FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable(
FlutterDesktopTextureRegistrarRef texture_registrar,
int64_t texture_id) {
return TextureRegistrarFromHandle(texture_registrar)
->MarkTextureFrameAvailable(texture_id);
}
| engine/shell/platform/windows/flutter_windows.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_windows.cc",
"repo_id": "engine",
"token_count": 5304
} | 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/keyboard_key_channel_handler.h"
#include <memory>
#include "flutter/shell/platform/common/json_message_codec.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
#include "flutter/shell/platform/windows/testing/test_binary_messenger.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
static constexpr char kScanCodeKey[] = "scanCode";
static constexpr char kCharacterCodePointKey[] = "characterCodePoint";
static constexpr int kHandledScanCode = 0x14;
static constexpr int kUnhandledScanCode = 0x15;
static constexpr int kUnhandledScanCodeExtended = 0xe015;
static std::unique_ptr<std::vector<uint8_t>> CreateResponse(bool handled) {
auto response_doc =
std::make_unique<rapidjson::Document>(rapidjson::kObjectType);
auto& allocator = response_doc->GetAllocator();
response_doc->AddMember("handled", handled, allocator);
return JsonMessageCodec::GetInstance().EncodeMessage(*response_doc);
}
} // namespace
TEST(KeyboardKeyChannelHandlerTest, KeyboardHookHandling) {
auto handled_message = CreateResponse(true);
auto unhandled_message = CreateResponse(false);
int received_scancode = 0;
TestBinaryMessenger messenger(
[&received_scancode, &handled_message, &unhandled_message](
const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
if (channel == "flutter/keyevent") {
auto message_doc = JsonMessageCodec::GetInstance().DecodeMessage(
message, message_size);
received_scancode = (*message_doc)[kScanCodeKey].GetInt();
if (received_scancode == kHandledScanCode) {
reply(handled_message->data(), handled_message->size());
} else {
reply(unhandled_message->data(), unhandled_message->size());
}
}
});
KeyboardKeyChannelHandler handler(&messenger);
bool last_handled = false;
handler.KeyboardHook(
64, kHandledScanCode, WM_KEYDOWN, L'a', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(received_scancode, kHandledScanCode);
EXPECT_EQ(last_handled, true);
received_scancode = 0;
handler.KeyboardHook(
64, kUnhandledScanCode, WM_KEYDOWN, L'b', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(received_scancode, kUnhandledScanCode);
EXPECT_EQ(last_handled, false);
received_scancode = 0;
handler.KeyboardHook(
64, kHandledScanCode, WM_SYSKEYDOWN, L'a', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(received_scancode, kHandledScanCode);
EXPECT_EQ(last_handled, true);
received_scancode = 0;
handler.KeyboardHook(
64, kUnhandledScanCode, WM_SYSKEYDOWN, L'c', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(received_scancode, kUnhandledScanCode);
EXPECT_EQ(last_handled, false);
}
TEST(KeyboardKeyChannelHandlerTest, ExtendedKeysAreSentToRedispatch) {
auto handled_message = CreateResponse(true);
auto unhandled_message = CreateResponse(false);
int received_scancode = 0;
TestBinaryMessenger messenger(
[&received_scancode, &handled_message, &unhandled_message](
const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
if (channel == "flutter/keyevent") {
auto message_doc = JsonMessageCodec::GetInstance().DecodeMessage(
message, message_size);
received_scancode = (*message_doc)[kScanCodeKey].GetInt();
if (received_scancode == kHandledScanCode) {
reply(handled_message->data(), handled_message->size());
} else {
reply(unhandled_message->data(), unhandled_message->size());
}
}
});
KeyboardKeyChannelHandler handler(&messenger);
bool last_handled = true;
// Extended key flag is passed to redispatched events if set.
handler.KeyboardHook(
64, kUnhandledScanCode, WM_KEYDOWN, L'b', true, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(received_scancode, kUnhandledScanCodeExtended);
last_handled = true;
// Extended key flag is not passed to redispatched events if not set.
handler.KeyboardHook(
64, kUnhandledScanCode, WM_KEYDOWN, L'b', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(received_scancode, kUnhandledScanCode);
}
TEST(KeyboardKeyChannelHandlerTest, DeadKeysDoNotCrash) {
bool received = false;
TestBinaryMessenger messenger(
[&received](const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
if (channel == "flutter/keyevent") {
auto message_doc = JsonMessageCodec::GetInstance().DecodeMessage(
message, message_size);
uint32_t character = (*message_doc)[kCharacterCodePointKey].GetUint();
EXPECT_EQ(character, (uint32_t)'^');
received = true;
}
return true;
});
KeyboardKeyChannelHandler handler(&messenger);
// Extended key flag is passed to redispatched events if set.
handler.KeyboardHook(0xDD, 0x1a, WM_KEYDOWN, 0x8000005E, false, false,
[](bool handled) {});
// EXPECT is done during the callback above.
EXPECT_TRUE(received);
}
TEST(KeyboardKeyChannelHandlerTest, EmptyResponsesDoNotCrash) {
bool received = false;
TestBinaryMessenger messenger(
[&received](const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
if (channel == "flutter/keyevent") {
std::string empty_message = "";
std::vector<uint8_t> empty_response(empty_message.begin(),
empty_message.end());
reply(empty_response.data(), empty_response.size());
received = true;
}
return true;
});
KeyboardKeyChannelHandler handler(&messenger);
handler.KeyboardHook(64, kUnhandledScanCode, WM_KEYDOWN, L'b', false, false,
[](bool handled) {});
// Passes if it does not crash.
EXPECT_TRUE(received);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/keyboard_key_channel_handler_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/keyboard_key_channel_handler_unittests.cc",
"repo_id": "engine",
"token_count": 2514
} | 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.
#include "flutter/shell/platform/windows/platform_view_manager.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h"
namespace flutter {
namespace {
constexpr char kChannelName[] = "flutter/platform_views";
constexpr char kCreateMethod[] = "create";
constexpr char kFocusMethod[] = "focus";
constexpr char kViewTypeParameter[] = "viewType";
constexpr char kIdParameter[] = "id";
constexpr char kDirectionParameter[] = "direction";
constexpr char kFocusParameter[] = "focus";
} // namespace
PlatformViewManager::PlatformViewManager(BinaryMessenger* binary_messenger)
: channel_(std::make_unique<MethodChannel<EncodableValue>>(
binary_messenger,
kChannelName,
&StandardMethodCodec::GetInstance())) {
channel_->SetMethodCallHandler(
[this](const MethodCall<EncodableValue>& call,
std::unique_ptr<MethodResult<EncodableValue>> result) {
const auto& args = std::get<EncodableMap>(*call.arguments());
if (call.method_name() == kCreateMethod) {
const auto& type_itr = args.find(EncodableValue(kViewTypeParameter));
const auto& id_itr = args.find(EncodableValue(kIdParameter));
if (type_itr == args.end()) {
result->Error("AddPlatformView", "Parameter viewType is required");
return;
}
if (id_itr == args.end()) {
result->Error("AddPlatformView", "Parameter id is required");
return;
}
const auto& type = std::get<std::string>(type_itr->second);
const auto& id = std::get<std::int32_t>(id_itr->second);
if (AddPlatformView(id, type)) {
result->Success();
} else {
result->Error("AddPlatformView", "Failed to add platform view");
}
return;
} else if (call.method_name() == kFocusMethod) {
const auto& id_itr = args.find(EncodableValue(kIdParameter));
const auto& direction_itr =
args.find(EncodableValue(kDirectionParameter));
const auto& focus_itr = args.find(EncodableValue(kFocusParameter));
if (id_itr == args.end()) {
result->Error("FocusPlatformView", "Parameter id is required");
return;
}
if (direction_itr == args.end()) {
result->Error("FocusPlatformView",
"Parameter direction is required");
return;
}
if (focus_itr == args.end()) {
result->Error("FocusPlatformView", "Parameter focus is required");
return;
}
const auto& id = std::get<std::int32_t>(id_itr->second);
const auto& direction = std::get<std::int32_t>(direction_itr->second);
const auto& focus = std::get<bool>(focus_itr->second);
if (FocusPlatformView(
id, static_cast<FocusChangeDirection>(direction), focus)) {
result->Success();
} else {
result->Error("FocusPlatformView", "Failed to focus platform view");
}
return;
}
result->NotImplemented();
});
}
PlatformViewManager::~PlatformViewManager() {}
} // namespace flutter
| engine/shell/platform/windows/platform_view_manager.cc/0 | {
"file_path": "engine/shell/platform/windows/platform_view_manager.cc",
"repo_id": "engine",
"token_count": 1435
} | 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/task_runner.h"
#include "flutter/fml/macros.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
class MockTaskRunner : public TaskRunner {
public:
MockTaskRunner(CurrentTimeProc get_current_time,
const TaskExpiredCallback& on_task_expired)
: TaskRunner(get_current_time, on_task_expired) {}
virtual bool RunsTasksOnCurrentThread() const override { return true; }
void SimulateTimerAwake() { ProcessTasks(); }
protected:
virtual void WakeUp() override {
// Do nothing to avoid processing tasks immediately after the tasks is
// posted.
}
virtual TaskTimePoint GetCurrentTimeForTask() const override {
return TaskTimePoint(
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::nanoseconds(10000)));
}
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockTaskRunner);
};
uint64_t MockGetCurrentTime() {
return 10000;
}
} // namespace
TEST(TaskRunnerTest, MaybeExecuteTaskWithExactOrder) {
std::vector<uint64_t> executed_task_order;
auto runner =
MockTaskRunner(MockGetCurrentTime,
[&executed_task_order](const FlutterTask* expired_task) {
executed_task_order.push_back(expired_task->task);
});
uint64_t time_now = MockGetCurrentTime();
runner.PostFlutterTask(FlutterTask{nullptr, 1}, time_now);
runner.PostFlutterTask(FlutterTask{nullptr, 2}, time_now);
runner.PostTask(
[&executed_task_order]() { executed_task_order.push_back(3); });
runner.PostTask(
[&executed_task_order]() { executed_task_order.push_back(4); });
runner.SimulateTimerAwake();
std::vector<uint64_t> posted_task_order{1, 2, 3, 4};
EXPECT_EQ(executed_task_order, posted_task_order);
}
TEST(TaskRunnerTest, MaybeExecuteTaskOnlyExpired) {
std::set<uint64_t> executed_task;
auto runner = MockTaskRunner(
MockGetCurrentTime, [&executed_task](const FlutterTask* expired_task) {
executed_task.insert(expired_task->task);
});
uint64_t task_expired_before_now = 1;
uint64_t time_before_now = 0;
runner.PostFlutterTask(FlutterTask{nullptr, task_expired_before_now},
time_before_now);
uint64_t task_expired_after_now = 2;
uint64_t time_after_now = MockGetCurrentTime() * 2;
runner.PostFlutterTask(FlutterTask{nullptr, task_expired_after_now},
time_after_now);
runner.SimulateTimerAwake();
std::set<uint64_t> only_task_expired_before_now{task_expired_before_now};
EXPECT_EQ(executed_task, only_task_expired_before_now);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/task_runner_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/task_runner_unittests.cc",
"repo_id": "engine",
"token_count": 1096
} | 373 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WM_BUILDERS_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WM_BUILDERS_H_
#include <stdint.h>
#include <windows.h>
namespace flutter {
namespace testing {
constexpr LRESULT kWmResultZero = 0;
constexpr LRESULT kWmResultDefault = 0xDEADC0DE;
constexpr LRESULT kWmResultDontCheck = 0xFFFF1234;
// A struct to hold simulated events that will be delivered after the framework
// response is handled.
struct Win32Message {
UINT message;
WPARAM wParam;
LPARAM lParam;
LRESULT expected_result;
};
typedef enum WmFieldExtended {
kNotExtended = 0,
kExtended = 1,
} WmFieldExtended;
typedef enum WmFieldContext {
kNoContext = 0,
kAltHeld = 1,
} WmFieldContext;
typedef enum WmFieldPrevState {
kWasUp = 0,
kWasDown = 1,
} WmFieldPrevState;
typedef enum WmFieldTransitionState {
kBeingReleased = 0,
kBeingPressed = 1,
} WmFieldTransitionState;
// WM_KEYDOWN messages.
//
// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keydown.
typedef struct WmKeyDownInfo {
uint32_t key;
uint8_t scan_code;
WmFieldExtended extended;
WmFieldPrevState prev_state;
// WmFieldTransitionState transition; // Always 0.
// WmFieldContext context; // Always 0.
uint16_t repeat_count = 1;
Win32Message Build(LRESULT expected_result = kWmResultDontCheck);
} WmKeyDownInfo;
// WM_KEYUP messages.
//
// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keyup.
typedef struct WmKeyUpInfo {
uint32_t key;
uint8_t scan_code;
WmFieldExtended extended;
// WmFieldPrevState prev_state; // Always 1.
// WmFieldTransitionState transition; // Always 1.
// WmFieldContext context; // Always 0.
// uint16_t repeat_count; // Always 1.
// Set this flag to enforce prev_state to be 0.
//
// This occurs in rare cases when the message is synthesized.
bool overwrite_prev_state_0;
Win32Message Build(LRESULT expected_result = kWmResultDontCheck);
} WmKeyUpInfo;
// WM_CHAR messages.
//
// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-char.
typedef struct WmCharInfo {
uint32_t char_code;
uint8_t scan_code;
WmFieldExtended extended;
WmFieldPrevState prev_state;
WmFieldTransitionState transition;
WmFieldContext context;
uint16_t repeat_count = 1;
// The 25th bit of the LParam.
//
// Some messages are sent with bit25 set. Its meaning is yet unknown.
bool bit25 = 0;
Win32Message Build(LRESULT expected_result = kWmResultDontCheck);
} WmCharInfo;
// WM_SYSKEYDOWN messages.
//
// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-syskeydown.
typedef struct WmSysKeyDownInfo {
uint32_t key;
uint8_t scan_code;
WmFieldExtended extended;
WmFieldPrevState prev_state;
// WmFieldTransitionState transition; // Always 0.
WmFieldContext context;
uint16_t repeat_count = 1;
Win32Message Build(LRESULT expected_result = kWmResultDontCheck);
} WmSysKeyDownInfo;
// WM_SYSKEYUP messages.
//
// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-syskeyup.
typedef struct WmSysKeyUpInfo {
uint32_t key;
uint8_t scan_code;
WmFieldExtended extended;
// WmFieldPrevState prev_state; // Always 1.
// WmFieldTransitionState transition; // Always 1.
WmFieldContext context;
// uint16_t repeat_count; // Always 1.
Win32Message Build(LRESULT expected_result = kWmResultDontCheck);
} WmSysKeyUpInfo;
// WM_DEADCHAR messages.
//
// See https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-deadchar.
typedef struct WmDeadCharInfo {
uint32_t char_code;
uint8_t scan_code;
WmFieldExtended extended;
WmFieldPrevState prev_state;
WmFieldTransitionState transition;
WmFieldContext context;
uint16_t repeat_count = 1;
Win32Message Build(LRESULT expected_result = kWmResultDontCheck);
} WmDeadCharInfo;
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WM_BUILDERS_H_
| engine/shell/platform/windows/testing/wm_builders.h/0 | {
"file_path": "engine/shell/platform/windows/testing/wm_builders.h",
"repo_id": "engine",
"token_count": 1465
} | 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.
#include "flutter/shell/platform/windows/windows_proc_table.h"
#include <WinUser.h>
#include <dwmapi.h>
namespace flutter {
WindowsProcTable::WindowsProcTable() {
user32_ = fml::NativeLibrary::Create("user32.dll");
get_pointer_type_ =
user32_->ResolveFunction<GetPointerType_*>("GetPointerType");
}
WindowsProcTable::~WindowsProcTable() {
user32_ = nullptr;
}
BOOL WindowsProcTable::GetPointerType(UINT32 pointer_id,
POINTER_INPUT_TYPE* pointer_type) const {
if (!get_pointer_type_.has_value()) {
return FALSE;
}
return get_pointer_type_.value()(pointer_id, pointer_type);
}
LRESULT WindowsProcTable::GetThreadPreferredUILanguages(DWORD flags,
PULONG count,
PZZWSTR languages,
PULONG length) const {
return ::GetThreadPreferredUILanguages(flags, count, languages, length);
}
bool WindowsProcTable::GetHighContrastEnabled() const {
HIGHCONTRAST high_contrast = {.cbSize = sizeof(HIGHCONTRAST)};
if (!::SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(HIGHCONTRAST),
&high_contrast, 0)) {
return false;
}
return high_contrast.dwFlags & HCF_HIGHCONTRASTON;
}
bool WindowsProcTable::DwmIsCompositionEnabled() const {
BOOL composition_enabled;
if (SUCCEEDED(::DwmIsCompositionEnabled(&composition_enabled))) {
return composition_enabled;
}
return true;
}
HRESULT WindowsProcTable::DwmFlush() const {
return ::DwmFlush();
}
} // namespace flutter
| engine/shell/platform/windows/windows_proc_table.cc/0 | {
"file_path": "engine/shell/platform/windows/windows_proc_table.cc",
"repo_id": "engine",
"token_count": 782
} | 375 |
python_version: "3.8"
# Used by:
# auth.py
# gerrit_util.py
# git_cl.py
# my_activity.py
# TODO(crbug.com/1002153): Add ninjalog_uploader.py
wheel: <
name: "infra/python/wheels/httplib2-py3"
version: "version:0.13.1"
>
# Used by:
# my_activity.py
wheel: <
name: "infra/python/wheels/python-dateutil-py2_py3"
version: "version:2.7.3"
>
wheel: <
name: "infra/python/wheels/six-py2_py3"
version: "version:1.10.0"
>
| engine/testing/.vpython3/0 | {
"file_path": "engine/testing/.vpython3",
"repo_id": "engine",
"token_count": 214
} | 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.
import("//flutter/build/dart/rules.gni")
import("//flutter/testing/rules/runtime_mode.gni")
assert(is_android)
flutter_snapshot("android_background_image_snapshot") {
main_dart = "lib/main.dart"
package_config = ".dart_tool/package_config.json"
}
if (!is_aot) {
copy("copy_jit_assets") {
visibility = [ ":*" ]
sources = [
"$target_gen_dir/isolate_snapshot_data",
"$target_gen_dir/isolate_snapshot_instr",
"$target_gen_dir/kernel_blob.bin",
]
outputs = [ "$root_out_dir/android_background_image/app/assets/flutter_assets/{{source_file_part}}" ]
deps = [ ":android_background_image_snapshot" ]
}
}
group("android_background_image") {
deps = [
":android_background_image_snapshot",
"android",
]
if (!is_aot) {
deps += [ ":copy_jit_assets" ]
}
}
| engine/testing/android_background_image/BUILD.gn/0 | {
"file_path": "engine/testing/android_background_image/BUILD.gn",
"repo_id": "engine",
"token_count": 383
} | 377 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/testing/assertions_skia.h"
namespace std {
std::ostream& operator<<(std::ostream& os, const SkClipOp& o) {
switch (o) {
case SkClipOp::kDifference:
os << "ClipOpDifference";
break;
case SkClipOp::kIntersect:
os << "ClipOpIntersect";
break;
default:
os << "ClipOpUnknown" << static_cast<int>(o);
break;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const SkMatrix& m) {
os << std::endl;
os << "Scale X: " << m[SkMatrix::kMScaleX] << ", ";
os << "Skew X: " << m[SkMatrix::kMSkewX] << ", ";
os << "Trans X: " << m[SkMatrix::kMTransX] << std::endl;
os << "Skew Y: " << m[SkMatrix::kMSkewY] << ", ";
os << "Scale Y: " << m[SkMatrix::kMScaleY] << ", ";
os << "Trans Y: " << m[SkMatrix::kMTransY] << std::endl;
os << "Persp X: " << m[SkMatrix::kMPersp0] << ", ";
os << "Persp Y: " << m[SkMatrix::kMPersp1] << ", ";
os << "Persp Z: " << m[SkMatrix::kMPersp2];
os << std::endl;
return os;
}
std::ostream& operator<<(std::ostream& os, const SkM44& m) {
os << m.rc(0, 0) << ", " << m.rc(0, 1) << ", " << m.rc(0, 2) << ", "
<< m.rc(0, 3) << std::endl;
os << m.rc(1, 0) << ", " << m.rc(1, 1) << ", " << m.rc(1, 2) << ", "
<< m.rc(1, 3) << std::endl;
os << m.rc(2, 0) << ", " << m.rc(2, 1) << ", " << m.rc(2, 2) << ", "
<< m.rc(2, 3) << std::endl;
os << m.rc(3, 0) << ", " << m.rc(3, 1) << ", " << m.rc(3, 2) << ", "
<< m.rc(3, 3);
return os;
}
std::ostream& operator<<(std::ostream& os, const SkVector3& v) {
return os << v.x() << ", " << v.y() << ", " << v.z();
}
std::ostream& operator<<(std::ostream& os, const SkIRect& r) {
return os << "LTRB: " << r.fLeft << ", " << r.fTop << ", " << r.fRight << ", "
<< r.fBottom;
}
std::ostream& operator<<(std::ostream& os, const SkRect& r) {
return os << "LTRB: " << r.fLeft << ", " << r.fTop << ", " << r.fRight << ", "
<< r.fBottom;
}
std::ostream& operator<<(std::ostream& os, const SkRRect& r) {
return os << "LTRB: " << r.rect().fLeft << ", " << r.rect().fTop << ", "
<< r.rect().fRight << ", " << r.rect().fBottom;
}
std::ostream& operator<<(std::ostream& os, const SkPath& r) {
return os << "Valid: " << r.isValid()
<< ", FillType: " << static_cast<int>(r.getFillType())
<< ", Bounds: " << r.getBounds();
}
std::ostream& operator<<(std::ostream& os, const SkPoint& r) {
return os << "XY: " << r.fX << ", " << r.fY;
}
std::ostream& operator<<(std::ostream& os, const SkISize& size) {
return os << size.width() << ", " << size.height();
}
std::ostream& operator<<(std::ostream& os, const SkColor4f& r) {
return os << r.fR << ", " << r.fG << ", " << r.fB << ", " << r.fA;
}
std::ostream& operator<<(std::ostream& os, const SkPaint& r) {
return os << "Color: " << r.getColor4f() << ", Style: " << r.getStyle()
<< ", AA: " << r.isAntiAlias() << ", Shader: " << r.getShader();
}
std::ostream& operator<<(std::ostream& os, const SkSamplingOptions& s) {
if (s.useCubic) {
return os << "CubicResampler: " << s.cubic.B << ", " << s.cubic.C;
} else {
return os << "Filter: " << static_cast<int>(s.filter)
<< ", Mipmap: " << static_cast<int>(s.mipmap);
}
}
} // namespace std
| engine/testing/assertions_skia.cc/0 | {
"file_path": "engine/testing/assertions_skia.cc",
"repo_id": "engine",
"token_count": 1548
} | 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.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('Loading an asset that does not exist returns null', () async {
Object? error;
try {
await ImmutableBuffer.fromAsset('ThisDoesNotExist');
} catch (err) {
error = err;
}
expect(error, isNotNull);
expect(error is Exception, true);
});
test('Loading a file that does not exist returns null', () async {
Object? error;
try {
await ImmutableBuffer.fromFilePath('ThisDoesNotExist');
} catch (err) {
error = err;
}
expect(error, isNotNull);
expect(error is Exception, true);
});
test('returns the bytes of a bundled asset', () async {
final ImmutableBuffer buffer = await ImmutableBuffer.fromAsset('DashInNooglerHat.jpg');
expect(buffer.length == 354679, true);
});
test('returns the bytes of a file', () async {
final ImmutableBuffer buffer = await ImmutableBuffer.fromFilePath('flutter/lib/ui/fixtures/DashInNooglerHat.jpg');
expect(buffer.length == 354679, true);
});
test('Can load an asset with a space in the key', () async {
// This assets actual path is "fixtures/DashInNooglerHat%20WithSpace.jpg"
final ImmutableBuffer buffer = await ImmutableBuffer.fromAsset('DashInNooglerHat WithSpace.jpg');
expect(buffer.length == 354679, true);
});
test('can dispose immutable buffer', () async {
final ImmutableBuffer buffer = await ImmutableBuffer.fromAsset('DashInNooglerHat.jpg');
buffer.dispose();
});
test('Tester can disable loading fonts from an asset bundle', () async {
final List<int> ahemImage = await _createPictureFromFont('Ahem');
// Font that is bundled in the asset directory of the test runner.
final List<int> bundledFontImage = await _createPictureFromFont('Roboto');
// Bundling fonts is disabled, so the font selected in both cases should be ahem.
// Therefore each buffer will contain identical contents.
expect(ahemImage, equals(bundledFontImage));
});
test('Tester can still load through dart:ui', () async {
/// Manually load font asset through dart.
final Uint8List encoded = utf8.encode(Uri(path: Uri.encodeFull('Roboto-Medium.ttf')).path);
final Completer<Uint8List> result = Completer<Uint8List>();
PlatformDispatcher.instance.sendPlatformMessage('flutter/assets', encoded.buffer.asByteData(), (ByteData? data) {
result.complete(data!.buffer.asUint8List());
});
await loadFontFromList(await result.future, fontFamily: 'Roboto2');
final List<int> ahemImage = await _createPictureFromFont('Ahem');
// Font that is bundled in the asset directory of the test runner.
final List<int> bundledFontImage = await _createPictureFromFont('Roboto2');
// Bundling fonts is disabled, so the font selected in both cases should be ahem.
// Therefore each buffer will contain identical contents.
expect(ahemImage, notEquals(bundledFontImage));
});
}
Future<List<int>> _createPictureFromFont(String fontFamily) async {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: fontFamily,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: 20,
));
builder.addText('Test');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 20 * 5.0));
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawParagraph(paragraph, Offset.zero);
final Picture picture = recorder.endRecording();
final Image image = await picture.toImage(100, 100);
final ByteData? data = await image.toByteData();
return data!.buffer.asUint8List().toList();
}
| engine/testing/dart/assets_test.dart/0 | {
"file_path": "engine/testing/dart/assets_test.dart",
"repo_id": "engine",
"token_count": 1256
} | 379 |
// Copyright 2021 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.
// FlutterTesterOptions=--disallow-insecure-connections
import 'dart:async';
import 'dart:io';
import 'package:litetest/litetest.dart';
typedef FutureFunction = Future<Object?> Function();
/// Asserts that `callback` throws an exception of type `T`.
Future<void> asyncExpectThrows<T>(FutureFunction callback) async {
bool threw = false;
try {
await callback();
} catch (e) {
expect(e is T, true);
threw = true;
}
expect(threw, true);
}
Future<String> getLocalHostIP() async {
final List<NetworkInterface> interfaces = await NetworkInterface.list(
type: InternetAddressType.IPv4);
return interfaces.first.addresses.first.address;
}
Future<void> bindServerAndTest(String serverHost,
Future<void> Function(HttpClient client, Uri uri) testCode) async {
final HttpClient httpClient = HttpClient();
final HttpServer server = await HttpServer.bind(serverHost, 0);
final Uri uri = Uri(scheme: 'http', host: serverHost, port: server.port);
try {
await testCode(httpClient, uri);
} finally {
httpClient.close(force: true);
await server.close();
}
}
/// Answers the question whether this computer supports binding to IPv6 addresses.
Future<bool> _supportsIPv6() async {
try {
final ServerSocket socket = await ServerSocket.bind(InternetAddress.loopbackIPv6, 0);
await socket.close();
return true;
} on SocketException catch (_) {
return false;
}
}
void main() {
test('testWithLocalIP', () async {
await bindServerAndTest(await getLocalHostIP(), (HttpClient httpClient, Uri httpUri) async {
asyncExpectThrows<UnsupportedError>(
() async => httpClient.getUrl(httpUri));
asyncExpectThrows<UnsupportedError>(
() async => runZoned(() => httpClient.getUrl(httpUri),
zoneValues: <dynamic, dynamic>{#flutter.io.allow_http: 'foo'}));
asyncExpectThrows<UnsupportedError>(
() async => runZoned(() => httpClient.getUrl(httpUri),
zoneValues: <dynamic, dynamic>{#flutter.io.allow_http: false}));
await runZoned(() => httpClient.getUrl(httpUri),
zoneValues: <dynamic, dynamic>{#flutter.io.allow_http: true});
});
});
test('testWithHostname', () async {
await bindServerAndTest(Platform.localHostname, (HttpClient httpClient, Uri httpUri) async {
asyncExpectThrows<UnsupportedError>(
() async => httpClient.getUrl(httpUri));
final _MockZoneValue mockFoo = _MockZoneValue('foo');
asyncExpectThrows<UnsupportedError>(
() async => runZoned(() => httpClient.getUrl(httpUri),
zoneValues: <dynamic, dynamic>{#flutter.io.allow_http: mockFoo}));
expect(mockFoo.checked, isTrue);
final _MockZoneValue mockFalse = _MockZoneValue(false);
asyncExpectThrows<UnsupportedError>(
() async => runZoned(() => httpClient.getUrl(httpUri),
zoneValues: <dynamic, dynamic>{#flutter.io.allow_http: mockFalse}));
expect(mockFalse.checked, isTrue);
final _MockZoneValue mockTrue = _MockZoneValue(true);
await runZoned(() => httpClient.getUrl(httpUri),
zoneValues: <dynamic, dynamic>{#flutter.io.allow_http: mockTrue});
expect(mockFalse.checked, isTrue);
});
}, skip: Platform.isMacOS); // https://github.com/flutter/flutter/issues/141149
test('testWithLoopback', () async {
await bindServerAndTest('127.0.0.1', (HttpClient httpClient, Uri uri) async {
await httpClient.getUrl(Uri.parse('http://localhost:${uri.port}'));
await httpClient.getUrl(Uri.parse('http://127.0.0.1:${uri.port}'));
});
});
test('testWithIPV6', () async {
if (await _supportsIPv6()) {
await bindServerAndTest('::1', (HttpClient httpClient, Uri uri) async {
await httpClient.getUrl(uri);
});
}
});
}
class _MockZoneValue {
_MockZoneValue(this._value);
final Object? _value;
bool _falseChecked = false;
bool _trueChecked = false;
@override
bool operator ==(Object o) {
if(o == true) {
_trueChecked = true;
}
if(o == false) {
_falseChecked = true;
}
return _value == o;
}
bool get checked => _falseChecked && _trueChecked;
@override
int get hashCode => _value.hashCode;
}
| engine/testing/dart/http_disallow_http_connections_test.dart/0 | {
"file_path": "engine/testing/dart/http_disallow_http_connections_test.dart",
"repo_id": "engine",
"token_count": 1652
} | 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.
import 'dart:developer' as developer;
import 'dart:ui';
import 'package:litetest/litetest.dart';
import 'package:vm_service/vm_service.dart' as vms;
import 'package:vm_service/vm_service_io.dart';
import '../impeller_enabled.dart';
void main() {
test('simple iplr shader can be re-initialized', () async {
if (impellerEnabled) {
// Needs https://github.com/flutter/flutter/issues/129659
return;
}
vms.VmService? vmService;
FragmentShader? shader;
try {
final FragmentProgram program = await FragmentProgram.fromAsset(
'functions.frag.iplr',
);
shader = program.fragmentShader()..setFloat(0, 1.0);
_use(shader);
final developer.ServiceProtocolInfo info = await developer.Service.getInfo();
if (info.serverUri == null) {
fail('This test must not be run with --disable-vm-service.');
}
vmService = await vmServiceConnectUri(
'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws',
);
final vms.VM vm = await vmService.getVM();
expect(vm.isolates!.isNotEmpty, true);
for (final vms.IsolateRef isolateRef in vm.isolates!) {
final vms.Response response = await vmService.callServiceExtension(
'ext.ui.window.reinitializeShader',
isolateId: isolateRef.id,
args: <String, Object>{
'assetKey': 'functions.frag.iplr',
},
);
expect(response.type == 'Success', true);
}
} finally {
await vmService?.dispose();
shader?.dispose();
}
});
}
void _use(Shader shader) {
}
| engine/testing/dart/observatory/shader_reload_test.dart/0 | {
"file_path": "engine/testing/dart/observatory/shader_reload_test.dart",
"repo_id": "engine",
"token_count": 722
} | 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.
// FlutterTesterOptions=--enable-serial-gc
import 'package:litetest/litetest.dart';
int use(List<int> a) {
return a[0];
}
void main() {
test('Serial GC option test ', () async {
const bool threw = false;
for (int i = 0; i < 100; i++) {
final List<int> a = <int>[100];
use(a);
}
expect(threw, false);
});
}
| engine/testing/dart/serial_gc_test.dart/0 | {
"file_path": "engine/testing/dart/serial_gc_test.dart",
"repo_id": "engine",
"token_count": 189
} | 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.
#include "flutter/testing/elf_loader.h"
#include <utility>
#include "flutter/fml/file.h"
#include "flutter/fml/paths.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/testing/testing.h"
namespace flutter {
namespace testing {
ELFAOTSymbols LoadELFSymbolFromFixturesIfNeccessary(std::string elf_filename) {
if (!DartVM::IsRunningPrecompiledCode()) {
return {};
}
const auto elf_path =
fml::paths::JoinPaths({GetFixturesPath(), std::move(elf_filename)});
if (!fml::IsFile(elf_path)) {
FML_LOG(ERROR) << "App AOT file does not exist for this fixture. Attempts "
"to launch the Dart VM with these AOT symbols will fail.";
return {};
}
ELFAOTSymbols symbols;
#if OS_FUCHSIA
// TODO(gw280): https://github.com/flutter/flutter/issues/50285
// Dart doesn't implement Dart_LoadELF on Fuchsia
FML_LOG(ERROR) << "Dart doesn't implement Dart_LoadELF on Fuchsia";
return {};
#else
// Must not be freed.
const char* error = nullptr;
auto loaded_elf =
Dart_LoadELF(elf_path.c_str(), // file path
0, // file offset
&error, // error (out)
&symbols.vm_snapshot_data, // vm snapshot data (out)
&symbols.vm_snapshot_instrs, // vm snapshot instrs (out)
&symbols.vm_isolate_data, // vm isolate data (out)
&symbols.vm_isolate_instrs // vm isolate instr (out)
);
if (loaded_elf == nullptr) {
FML_LOG(ERROR)
<< "Could not fetch AOT symbols from loaded ELF. Attempts "
"to launch the Dart VM with these AOT symbols will fail. Error: "
<< error;
return {};
}
symbols.loaded_elf.reset(loaded_elf);
return symbols;
#endif // OS_FUCHSIA
}
ELFAOTSymbols LoadELFSplitSymbolFromFixturesIfNeccessary(
std::string elf_split_filename) {
if (!DartVM::IsRunningPrecompiledCode()) {
return {};
}
const auto elf_path =
fml::paths::JoinPaths({GetFixturesPath(), std::move(elf_split_filename)});
if (!fml::IsFile(elf_path)) {
// We do not log here, as there is no expectation for a split library to
// exist.
return {};
}
ELFAOTSymbols symbols;
#if OS_FUCHSIA
// TODO(gw280): https://github.com/flutter/flutter/issues/50285
// Dart doesn't implement Dart_LoadELF on Fuchsia
FML_LOG(ERROR) << "Dart doesn't implement Dart_LoadELF on Fuchsia";
return {};
#else
// Must not be freed.
const char* error = nullptr;
auto loaded_elf =
Dart_LoadELF(elf_path.c_str(), // file path
0, // file offset
&error, // error (out)
&symbols.vm_snapshot_data, // vm snapshot data (out)
&symbols.vm_snapshot_instrs, // vm snapshot instrs (out)
&symbols.vm_isolate_data, // vm isolate data (out)
&symbols.vm_isolate_instrs // vm isolate instr (out)
);
if (loaded_elf == nullptr) {
FML_LOG(ERROR)
<< "Could not fetch AOT symbols from loaded ELF. Attempts "
"to launch the Dart VM with these AOT symbols will fail. Error: "
<< error;
return {};
}
symbols.loaded_elf.reset(loaded_elf);
return symbols;
#endif
}
bool PrepareSettingsForAOTWithSymbols(Settings& settings,
const ELFAOTSymbols& symbols) {
if (!DartVM::IsRunningPrecompiledCode()) {
return false;
}
settings.vm_snapshot_data = [&]() {
return std::make_unique<fml::NonOwnedMapping>(symbols.vm_snapshot_data, 0u);
};
settings.isolate_snapshot_data = [&]() {
return std::make_unique<fml::NonOwnedMapping>(symbols.vm_isolate_data, 0u);
};
settings.vm_snapshot_instr = [&]() {
return std::make_unique<fml::NonOwnedMapping>(symbols.vm_snapshot_instrs,
0u);
};
settings.isolate_snapshot_instr = [&]() {
return std::make_unique<fml::NonOwnedMapping>(symbols.vm_isolate_instrs,
0u);
};
return true;
}
} // namespace testing
} // namespace flutter
| engine/testing/elf_loader.cc/0 | {
"file_path": "engine/testing/elf_loader.cc",
"repo_id": "engine",
"token_count": 1994
} | 383 |
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="19529" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="19519"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="132" y="86"/>
</scene>
</scenes>
<resources>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
| engine/testing/ios/IosBenchmarks/IosBenchmarks/Base.lproj/Main.storyboard/0 | {
"file_path": "engine/testing/ios/IosBenchmarks/IosBenchmarks/Base.lproj/Main.storyboard",
"repo_id": "engine",
"token_count": 826
} | 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.
#include "flutter/testing/mock_canvas.h"
#include "flutter/testing/canvas_test.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
using MockCanvasTest = CanvasTest;
#ifndef NDEBUG
TEST_F(MockCanvasTest, DrawRRectDies) {
EXPECT_DEATH_IF_SUPPORTED(mock_canvas().DrawRRect(SkRRect(), DlPaint()), "");
}
#endif
TEST_F(MockCanvasTest, DrawCalls) {
const SkRect rect = SkRect::MakeWH(5.0f, 5.0f);
const DlPaint paint = DlPaint(DlColor::kGreen());
const auto expected_draw_calls = std::vector{
MockCanvas::DrawCall{0, MockCanvas::DrawRectData{rect, paint}}};
mock_canvas().DrawRect(rect, paint);
EXPECT_EQ(mock_canvas().draw_calls(), expected_draw_calls);
}
} // namespace testing
} // namespace flutter
| engine/testing/mock_canvas_unittests.cc/0 | {
"file_path": "engine/testing/mock_canvas_unittests.cc",
"repo_id": "engine",
"token_count": 341
} | 385 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/common/config.gni")
assert(is_android || is_ios)
is_aot = flutter_runtime_mode == "profile" || flutter_runtime_mode == "release"
| engine/testing/rules/runtime_mode.gni/0 | {
"file_path": "engine/testing/rules/runtime_mode.gni",
"repo_id": "engine",
"token_count": 96
} | 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.scenarios;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("dev.flutter.scenarios", appContext.getPackageName());
}
}
| engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenarios/ExampleInstrumentedTest.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenarios/ExampleInstrumentedTest.java",
"repo_id": "engine",
"token_count": 261
} | 387 |
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.facebook.testing.screenshot:plugin:0.12.0'
// leakcanary uses Kotlin. This app does not, but the plugin is
// needed to specify language version options.
// Gradle 8.0 requires minimum kotlin 1.6.10
// https://docs.gradle.org/current/userguide/upgrading_version_7.html#legacy_incrementaltaskinputs_api
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'
// Requries Minimum AGP 7.3.
// https://docs.gradle.org/current/userguide/upgrading_version_7.html#legacy_incrementaltaskinputs_api
classpath 'com.android.tools.build:gradle:7.4.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
configurations.classpath {
resolutionStrategy.activateDependencyLocking()
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = project.hasProperty('out_dir')
? project.property('out_dir')
: '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
project.evaluationDependsOn(':app')
dependencyLocking {
lockAllConfigurations()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| engine/testing/scenario_app/android/build.gradle/0 | {
"file_path": "engine/testing/scenario_app/android/build.gradle",
"repo_id": "engine",
"token_count": 580
} | 388 |
<!--Dummy plist file to make the impeller version of scenario test happy-->
<?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>
<!--This flag does not do anything, it only makes the xcodebuild command happy-->
<key>FLTEnableImpeller</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>SceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
</dict>
</plist>
| engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/Scenarios/Info_Impeller.plist/0 | {
"file_path": "engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/Scenarios/Info_Impeller.plist",
"repo_id": "engine",
"token_count": 366
} | 389 |
// 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.
#import <Flutter/Flutter.h>
#import <XCTest/XCTest.h>
#import "ScreenBeforeFlutter.h"
FLUTTER_ASSERT_ARC
@interface XCAppLifecycleTestExpectation : XCTestExpectation
- (instancetype)initForLifecycle:(NSString*)expectedLifecycle forStep:(NSString*)step;
@property(nonatomic, readonly, copy) NSString* expectedLifecycle;
@end
@implementation XCAppLifecycleTestExpectation
@synthesize expectedLifecycle = _expectedLifecycle;
- (instancetype)initForLifecycle:(NSString*)expectedLifecycle forStep:(NSString*)step {
// The step is here because the callbacks into the handler which checks these expectations isn't
// synchronous with the executions in the test, so it's hard to find the cause in the test
// otherwise.
self = [super initWithDescription:[NSString stringWithFormat:@"Expected state %@ during step %@",
expectedLifecycle, step]];
_expectedLifecycle = [expectedLifecycle copy];
return self;
}
@end
@interface AppLifecycleTests : XCTestCase
@end
@implementation AppLifecycleTests
- (void)setUp {
[super setUp];
self.continueAfterFailure = NO;
}
- (NSArray*)initialPresentLifecycles {
NSMutableArray* expectations =
[NSMutableArray arrayWithObject:[[XCAppLifecycleTestExpectation alloc]
initForLifecycle:@"AppLifecycleState.inactive"
forStep:@"showing a FlutterViewController"]];
// If the test is the very first test to run in the test target, the UIApplication may
// be in inactive state. Haven't found a good way to force it to go to active state.
// So just account for it in the initial lifecycle events with an extra resumed since
// the FlutterViewController tracks all view controller and application lifecycle events.
if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
[expectations addObject:[[XCAppLifecycleTestExpectation alloc]
initForLifecycle:@"AppLifecycleState.resumed"
forStep:@"showing a FlutterViewController"]];
}
[expectations addObject:[[XCAppLifecycleTestExpectation alloc]
initForLifecycle:@"AppLifecycleState.resumed"
forStep:@"showing a FlutterViewController"]];
return expectations;
}
- (void)skip_testDismissedFlutterViewControllerNotRespondingToApplicationLifecycle {
XCTestExpectation* engineStartedExpectation = [self expectationWithDescription:@"Engine started"];
// Let the engine finish booting (at the end of which the channels are properly set-up) before
// moving onto the next step of showing the next view controller.
ScreenBeforeFlutter* rootVC = [[ScreenBeforeFlutter alloc] initWithEngineRunCompletion:^void() {
[engineStartedExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5 handler:nil];
UIApplication* application = UIApplication.sharedApplication;
application.delegate.window.rootViewController = rootVC;
FlutterEngine* engine = rootVC.engine;
NSMutableArray* lifecycleExpectations = [NSMutableArray arrayWithCapacity:10];
// Expected sequence from showing the FlutterViewController is inactive and resumed.
[lifecycleExpectations addObjectsFromArray:[self initialPresentLifecycles]];
[engine.lifecycleChannel setMessageHandler:^(id message, FlutterReply callback) {
if (lifecycleExpectations.count == 0) {
XCTFail(@"Unexpected lifecycle transition: %@", message);
return;
}
XCAppLifecycleTestExpectation* nextExpectation = [lifecycleExpectations objectAtIndex:0];
if (![[nextExpectation expectedLifecycle] isEqualToString:message]) {
XCTFail(@"Expected lifecycle %@ but instead received %@", [nextExpectation expectedLifecycle],
message);
return;
}
[nextExpectation fulfill];
[lifecycleExpectations removeObjectAtIndex:0];
}];
FlutterViewController* flutterVC;
@autoreleasepool {
// Holding onto this FlutterViewController is consequential here. Since a released
// FlutterViewController wouldn't keep listening to the application lifecycle events and produce
// false positives for the application lifecycle tests further below.
XCTestExpectation* vcShown = [self expectationWithDescription:@"present"];
flutterVC = [rootVC showFlutter:^{
[vcShown fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
// The expectations list isn't dequeued by the message handler yet.
[self waitForExpectations:lifecycleExpectations timeout:5 enforceOrder:YES];
// Now dismiss the FlutterViewController again and expect another inactive and paused.
[lifecycleExpectations addObjectsFromArray:@[
[[XCAppLifecycleTestExpectation alloc]
initForLifecycle:@"AppLifecycleState.inactive"
forStep:@"dismissing a FlutterViewController"],
[[XCAppLifecycleTestExpectation alloc]
initForLifecycle:@"AppLifecycleState.paused"
forStep:@"dismissing a FlutterViewController"]
]];
XCTestExpectation* vcDismissed = [self expectationWithDescription:@"dismiss"];
[flutterVC dismissViewControllerAnimated:NO
completion:^{
[vcDismissed fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
[self waitForExpectations:lifecycleExpectations timeout:5 enforceOrder:YES];
// Now put the app in the background (while the engine is still running) and bring it back to
// the foreground. Granted, we're not winning any awards for hyper-realism but at least we're
// checking that we aren't observing the UIApplication notifications and double registering
// for AppLifecycleState events.
// These operations are synchronous so if they trigger any lifecycle events, they should trigger
// failures in the message handler immediately.
[[NSNotificationCenter defaultCenter]
postNotificationName:UIApplicationWillResignActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:UIApplicationWillEnterForegroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:UIApplicationDidBecomeActiveNotification
object:nil];
flutterVC = nil;
[engine setViewController:nil];
}
// There's no timing latch for our semi-fake background-foreground cycle so launch the
// FlutterViewController again to check the complete event list again.
// Expect only lifecycle events from showing the FlutterViewController again, not from any
// backgrounding/foregrounding.
[lifecycleExpectations addObjectsFromArray:@[
[[XCAppLifecycleTestExpectation alloc]
initForLifecycle:@"AppLifecycleState.inactive"
forStep:@"showing a FlutterViewController a second time after backgrounding"],
[[XCAppLifecycleTestExpectation alloc]
initForLifecycle:@"AppLifecycleState.resumed"
forStep:@"showing a FlutterViewController a second time after backgrounding"]
]];
@autoreleasepool {
XCTestExpectation* vcShown = [self expectationWithDescription:@"present"];
flutterVC = [rootVC showFlutter:^{
[vcShown fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
NSLog(@"FlutterViewController instance %@ created", flutterVC);
[self waitForExpectations:lifecycleExpectations timeout:5 enforceOrder:YES];
// The final dismissal cycles through inactive and paused again.
[lifecycleExpectations addObjectsFromArray:@[
[[XCAppLifecycleTestExpectation alloc] initForLifecycle:@"AppLifecycleState.inactive"
forStep:@"popping the FlutterViewController"],
[[XCAppLifecycleTestExpectation alloc]
initForLifecycle:@"AppLifecycleState.paused"
forStep:@"popping the FlutterViewController"]
]];
XCTestExpectation* vcDismissed = [self expectationWithDescription:@"dismiss"];
[flutterVC dismissViewControllerAnimated:NO
completion:^{
[vcDismissed fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
flutterVC = nil;
[engine setViewController:nil];
}
// Dismantle.
[engine.lifecycleChannel setMessageHandler:nil];
[rootVC dismissViewControllerAnimated:NO completion:nil];
[engine destroyContext];
}
- (void)skip_testFlutterViewControllerDetachingSendsApplicationLifecycle {
XCTestExpectation* engineStartedExpectation = [self expectationWithDescription:@"Engine started"];
// Let the engine finish booting (at the end of which the channels are properly set-up) before
// moving onto the next step of showing the next view controller.
ScreenBeforeFlutter* rootVC = [[ScreenBeforeFlutter alloc] initWithEngineRunCompletion:^void() {
[engineStartedExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5 handler:nil];
UIApplication* application = UIApplication.sharedApplication;
application.delegate.window.rootViewController = rootVC;
FlutterEngine* engine = rootVC.engine;
NSMutableArray* lifecycleExpectations = [NSMutableArray arrayWithCapacity:10];
// Expected sequence from showing the FlutterViewController is inactive and resumed.
[lifecycleExpectations addObjectsFromArray:[self initialPresentLifecycles]];
[engine.lifecycleChannel setMessageHandler:^(id message, FlutterReply callback) {
if (lifecycleExpectations.count == 0) {
XCTFail(@"Unexpected lifecycle transition: %@", message);
return;
}
XCAppLifecycleTestExpectation* nextExpectation = [lifecycleExpectations objectAtIndex:0];
if (![[nextExpectation expectedLifecycle] isEqualToString:message]) {
XCTFail(@"Expected lifecycle %@ but instead received %@", [nextExpectation expectedLifecycle],
message);
return;
}
[nextExpectation fulfill];
[lifecycleExpectations removeObjectAtIndex:0];
}];
// At the end of Flutter VC, we want to make sure it deallocs and sends detached signal.
// Using autoreleasepool will guarantee that.
FlutterViewController* flutterVC;
@autoreleasepool {
XCTestExpectation* vcShown = [self expectationWithDescription:@"present"];
flutterVC = [rootVC showFlutter:^{
[vcShown fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
[self waitForExpectations:lifecycleExpectations timeout:5];
// Starts dealloc flutter VC.
[lifecycleExpectations addObjectsFromArray:@[
[[XCAppLifecycleTestExpectation alloc] initForLifecycle:@"AppLifecycleState.inactive"
forStep:@"detaching a FlutterViewController"],
[[XCAppLifecycleTestExpectation alloc] initForLifecycle:@"AppLifecycleState.paused"
forStep:@"detaching a FlutterViewController"],
[[XCAppLifecycleTestExpectation alloc]
initForLifecycle:@"AppLifecycleState.detached"
forStep:@"detaching a FlutterViewController"]
]];
[flutterVC dismissViewControllerAnimated:NO completion:nil];
flutterVC = nil;
}
[self waitForExpectations:lifecycleExpectations timeout:5];
// Dismantle.
[engine setViewController:nil];
[engine.lifecycleChannel setMessageHandler:nil];
[rootVC dismissViewControllerAnimated:NO completion:nil];
[engine destroyContext];
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosTests/AppLifecycleTests.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosTests/AppLifecycleTests.m",
"repo_id": "engine",
"token_count": 4439
} | 390 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Flutter/Flutter.h>
#import <XCTest/XCTest.h>
FLUTTER_ASSERT_ARC
@interface LocalizationInitializationTest : XCTestCase
@property(nonatomic, strong) XCUIApplication* application;
@end
@implementation LocalizationInitializationTest
- (void)setUp {
[super setUp];
self.continueAfterFailure = NO;
self.application = [[XCUIApplication alloc] init];
self.application.launchArguments = @[ @"--locale-initialization" ];
[self.application launch];
}
- (void)testNoLocalePrepend {
NSTimeInterval timeout = 10.0;
// The locales received by dart:ui are exposed onBeginFrame via semantics label.
// There should only be one locale. The list should consist of the default
// locale provided by the iOS app.
NSArray<NSString*>* preferredLocales = [NSLocale preferredLanguages];
XCTAssertEqual(preferredLocales.count, 1);
// Dart connects the locale parts with `_` while iOS connects them with `-`.
// Converts to dart format before comparing.
NSString* localeDart = [preferredLocales.firstObject stringByReplacingOccurrencesOfString:@"-"
withString:@"_"];
NSString* expectedIdentifier = [NSString stringWithFormat:@"[%@]", localeDart];
XCUIElement* textInputSemanticsObject =
[self.application.textFields matchingIdentifier:expectedIdentifier].element;
XCTAssertTrue([textInputSemanticsObject waitForExistenceWithTimeout:timeout]);
[textInputSemanticsObject tap];
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/LocalizationInitializationTest.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/LocalizationInitializationTest.m",
"repo_id": "engine",
"token_count": 560
} | 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 'dart:typed_data';
import 'dart:ui';
import 'channel_util.dart';
import 'scenario.dart';
/// A blank page with a button that pops the page when tapped.
class PoppableScreenScenario extends Scenario {
/// Creates the PoppableScreenScenario.
PoppableScreenScenario(super.view) {
channelBuffers.setListener('flutter/platform', _onHandlePlatformMessage);
}
// Rect for the pop button. Only defined once onMetricsChanged is called.
Rect? _buttonRect;
@override
void onBeginFrame(Duration duration) {
final SceneBuilder builder = SceneBuilder();
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawPaint(Paint()..color = const Color.fromARGB(255, 255, 255, 255));
if (_buttonRect != null) {
canvas.drawRect(
_buttonRect!,
Paint()..color = const Color.fromARGB(255, 255, 0, 0),
);
}
final Picture picture = recorder.endRecording();
builder.pushOffset(0, 0);
builder.addPicture(Offset.zero, picture);
final Scene scene = builder.build();
view.render(scene);
scene.dispose();
}
@override
void onDrawFrame() {
// Just draw once since the content never changes.
}
@override
void onMetricsChanged() {
_buttonRect = Rect.fromLTRB(
view.physicalSize.width / 4,
view.physicalSize.height * 2 / 5,
view.physicalSize.width * 3 / 4,
view.physicalSize.height * 3 / 5,
);
view.platformDispatcher.scheduleFrame();
}
@override
void onPointerDataPacket(PointerDataPacket packet) {
for (final PointerData data in packet.data) {
if (data.change == PointerChange.up &&
(_buttonRect?.contains(Offset(data.physicalX, data.physicalY)) ?? false)
) {
_pop();
}
}
}
void _pop() {
sendJsonMethodCall(
dispatcher: view.platformDispatcher,
// 'flutter/platform' is the hardcoded name of the 'platform'
// `SystemChannel` from the `SystemNavigator` API.
// https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/services/system_navigator.dart.
channel: 'flutter/platform',
method: 'SystemNavigator.pop',
// Don't care about the response. If it doesn't go through, the test
// will fail.
);
}
void _onHandlePlatformMessage(ByteData? data, PlatformMessageResponseCallback callback) {
view.platformDispatcher.sendPlatformMessage('flutter/platform', data, null);
}
@override
void unmount() {
channelBuffers.clearListener('flutter/platform');
super.unmount();
}
}
| engine/testing/scenario_app/lib/src/poppable_screen.dart/0 | {
"file_path": "engine/testing/scenario_app/lib/src/poppable_screen.dart",
"repo_id": "engine",
"token_count": 979
} | 392 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_TESTING_TEST_ARGS_H_
#define FLUTTER_TESTING_TEST_ARGS_H_
#include "flutter/fml/command_line.h"
namespace flutter {
namespace testing {
const fml::CommandLine& GetArgsForProcess();
void SetArgsForProcess(int argc, char** argv);
} // namespace testing
} // namespace flutter
#endif // FLUTTER_TESTING_TEST_ARGS_H_
| engine/testing/test_args.h/0 | {
"file_path": "engine/testing/test_args.h",
"repo_id": "engine",
"token_count": 177
} | 393 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/testing/test_vulkan_image.h"
#include "flutter/testing/test_vulkan_context.h"
namespace flutter {
namespace testing {
TestVulkanImage::TestVulkanImage() = default;
TestVulkanImage::TestVulkanImage(TestVulkanImage&& other) = default;
TestVulkanImage& TestVulkanImage::operator=(TestVulkanImage&& other) = default;
TestVulkanImage::~TestVulkanImage() = default;
VkImage TestVulkanImage::GetImage() {
return image_;
}
} // namespace testing
} // namespace flutter
| engine/testing/test_vulkan_image.cc/0 | {
"file_path": "engine/testing/test_vulkan_image.cc",
"repo_id": "engine",
"token_count": 203
} | 394 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_ENUM_UTIL_H_
#define UI_ACCESSIBILITY_AX_ENUM_UTIL_H_
#include <string>
#include "ax_base_export.h"
#include "ax_enums.h"
namespace ui {
// ax::mojom::Event
AX_BASE_EXPORT const char* ToString(ax::mojom::Event event);
AX_BASE_EXPORT ax::mojom::Event ParseEvent(const char* event);
// ax::mojom::Role
AX_BASE_EXPORT const char* ToString(ax::mojom::Role role);
AX_BASE_EXPORT ax::mojom::Role ParseRole(const char* role);
// ax::mojom::State
AX_BASE_EXPORT const char* ToString(ax::mojom::State state);
AX_BASE_EXPORT ax::mojom::State ParseState(const char* state);
// ax::mojom::Action
AX_BASE_EXPORT const char* ToString(ax::mojom::Action action);
AX_BASE_EXPORT ax::mojom::Action ParseAction(const char* action);
// ax::mojom::ActionFlags
AX_BASE_EXPORT const char* ToString(ax::mojom::ActionFlags action_flags);
AX_BASE_EXPORT ax::mojom::ActionFlags ParseActionFlags(
const char* action_flags);
// ax::mojom::DefaultActionVerb
AX_BASE_EXPORT const char* ToString(
ax::mojom::DefaultActionVerb default_action_verb);
// Returns a localized string that corresponds to the name of the given action.
AX_BASE_EXPORT std::string ToLocalizedString(
ax::mojom::DefaultActionVerb action_verb);
AX_BASE_EXPORT ax::mojom::DefaultActionVerb ParseDefaultActionVerb(
const char* default_action_verb);
// ax::mojom::Mutation
AX_BASE_EXPORT const char* ToString(ax::mojom::Mutation mutation);
AX_BASE_EXPORT ax::mojom::Mutation ParseMutation(const char* mutation);
// ax::mojom::StringAttribute
AX_BASE_EXPORT const char* ToString(
ax::mojom::StringAttribute string_attribute);
AX_BASE_EXPORT ax::mojom::StringAttribute ParseStringAttribute(
const char* string_attribute);
// ax::mojom::IntAttribute
AX_BASE_EXPORT const char* ToString(ax::mojom::IntAttribute int_attribute);
AX_BASE_EXPORT ax::mojom::IntAttribute ParseIntAttribute(
const char* int_attribute);
// ax::mojom::FloatAttribute
AX_BASE_EXPORT const char* ToString(ax::mojom::FloatAttribute float_attribute);
AX_BASE_EXPORT ax::mojom::FloatAttribute ParseFloatAttribute(
const char* float_attribute);
// ax::mojom::BoolAttribute
AX_BASE_EXPORT const char* ToString(ax::mojom::BoolAttribute bool_attribute);
AX_BASE_EXPORT ax::mojom::BoolAttribute ParseBoolAttribute(
const char* bool_attribute);
// ax::mojom::IntListAttribute
AX_BASE_EXPORT const char* ToString(
ax::mojom::IntListAttribute int_list_attribute);
AX_BASE_EXPORT ax::mojom::IntListAttribute ParseIntListAttribute(
const char* int_list_attribute);
// ax::mojom::StringListAttribute
AX_BASE_EXPORT const char* ToString(
ax::mojom::StringListAttribute string_list_attribute);
AX_BASE_EXPORT ax::mojom::StringListAttribute ParseStringListAttribute(
const char* string_list_attribute);
// ax::mojom::ListStyle
AX_BASE_EXPORT const char* ToString(ax::mojom::ListStyle list_style);
AX_BASE_EXPORT ax::mojom::ListStyle ParseListStyle(const char* list_style);
// ax::mojom::MarkerType
AX_BASE_EXPORT const char* ToString(ax::mojom::MarkerType marker_type);
AX_BASE_EXPORT ax::mojom::MarkerType ParseMarkerType(const char* marker_type);
// ax::mojom::MoveDirection
AX_BASE_EXPORT const char* ToString(ax::mojom::MoveDirection move_direction);
AX_BASE_EXPORT ax::mojom::MoveDirection ParseMoveDirection(
const char* move_direction);
// ax::mojom::Command
AX_BASE_EXPORT const char* ToString(ax::mojom::Command command);
AX_BASE_EXPORT ax::mojom::Command ParseCommand(const char* command);
// ax::mojom::TextBoundary
AX_BASE_EXPORT const char* ToString(ax::mojom::TextBoundary text_boundary);
AX_BASE_EXPORT ax::mojom::TextBoundary ParseTextBoundary(
const char* text_boundary);
// ax:mojom::TextDecorationStyle
AX_BASE_EXPORT const char* ToString(
ax::mojom::TextDecorationStyle text_decoration_style);
AX_BASE_EXPORT ax::mojom::TextDecorationStyle ParseTextDecorationStyle(
const char* text_decoration_style);
// ax::mojom::TextAlign
AX_BASE_EXPORT const char* ToString(ax::mojom::TextAlign text_align);
AX_BASE_EXPORT ax::mojom::TextAlign ParseTextAlign(const char* text_align);
// ax::mojom::WritingDirection
AX_BASE_EXPORT const char* ToString(ax::mojom::WritingDirection text_direction);
AX_BASE_EXPORT ax::mojom::WritingDirection ParseTextDirection(
const char* text_direction);
// ax::mojom::TextPosition
AX_BASE_EXPORT const char* ToString(ax::mojom::TextPosition text_position);
AX_BASE_EXPORT ax::mojom::TextPosition ParseTextPosition(
const char* text_position);
// ax::mojom::TextStyle
AX_BASE_EXPORT const char* ToString(ax::mojom::TextStyle text_style);
AX_BASE_EXPORT ax::mojom::TextStyle ParseTextStyle(const char* text_style);
// ax::mojom::AriaCurrentState
AX_BASE_EXPORT const char* ToString(
ax::mojom::AriaCurrentState aria_current_state);
AX_BASE_EXPORT ax::mojom::AriaCurrentState ParseAriaCurrentState(
const char* aria_current_state);
// ax::mojom::HasPopup
AX_BASE_EXPORT const char* ToString(ax::mojom::HasPopup has_popup);
AX_BASE_EXPORT ax::mojom::HasPopup ParseHasPopup(const char* has_popup);
// ax::mojom::InvalidState
AX_BASE_EXPORT const char* ToString(ax::mojom::InvalidState invalid_state);
AX_BASE_EXPORT ax::mojom::InvalidState ParseInvalidState(
const char* invalid_state);
// ax::mojom::Restriction
AX_BASE_EXPORT const char* ToString(ax::mojom::Restriction restriction);
AX_BASE_EXPORT ax::mojom::Restriction ParseRestriction(const char* restriction);
// ax::mojom::CheckedState
AX_BASE_EXPORT const char* ToString(ax::mojom::CheckedState checked_state);
AX_BASE_EXPORT ax::mojom::CheckedState ParseCheckedState(
const char* checked_state);
// ax::mojom::SortDirection
AX_BASE_EXPORT const char* ToString(ax::mojom::SortDirection sort_direction);
AX_BASE_EXPORT ax::mojom::SortDirection ParseSortDirection(
const char* sort_direction);
// ax::mojom::NameFrom
AX_BASE_EXPORT const char* ToString(ax::mojom::NameFrom name_from);
AX_BASE_EXPORT ax::mojom::NameFrom ParseNameFrom(const char* name_from);
// ax::mojom::DescriptionFrom
AX_BASE_EXPORT const char* ToString(
ax::mojom::DescriptionFrom description_from);
AX_BASE_EXPORT ax::mojom::DescriptionFrom ParseDescriptionFrom(
const char* description_from);
// ax::mojom::EventFrom
AX_BASE_EXPORT const char* ToString(ax::mojom::EventFrom event_from);
AX_BASE_EXPORT ax::mojom::EventFrom ParseEventFrom(const char* event_from);
// ax::mojom::Gesture
AX_BASE_EXPORT const char* ToString(ax::mojom::Gesture gesture);
AX_BASE_EXPORT ax::mojom::Gesture ParseGesture(const char* gesture);
// ax::mojom::TextAffinity
AX_BASE_EXPORT const char* ToString(ax::mojom::TextAffinity text_affinity);
AX_BASE_EXPORT ax::mojom::TextAffinity ParseTextAffinity(
const char* text_affinity);
// ax::mojom::TreeOrder
AX_BASE_EXPORT const char* ToString(ax::mojom::TreeOrder tree_order);
AX_BASE_EXPORT ax::mojom::TreeOrder ParseTreeOrder(const char* tree_order);
// ax::mojom::ImageAnnotationStatus
AX_BASE_EXPORT const char* ToString(ax::mojom::ImageAnnotationStatus status);
AX_BASE_EXPORT ax::mojom::ImageAnnotationStatus ParseImageAnnotationStatus(
const char* status);
// ax::mojom::Dropeffect
AX_BASE_EXPORT const char* ToString(ax::mojom::Dropeffect dropeffect);
AX_BASE_EXPORT ax::mojom::Dropeffect ParseDropeffect(const char* dropeffect);
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_ENUM_UTIL_H_
| engine/third_party/accessibility/ax/ax_enum_util.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_enum_util.h",
"repo_id": "engine",
"token_count": 2780
} | 395 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax_node_data.h"
#include <set>
#include <unordered_set>
#include "gtest/gtest.h"
#include "ax_enum_util.h"
#include "ax_enums.h"
#include "ax_role_properties.h"
#include "base/container_utils.h"
namespace ui {
TEST(AXNodeDataTest, GetAndSetCheckedState) {
AXNodeData root;
EXPECT_EQ(ax::mojom::CheckedState::kNone, root.GetCheckedState());
EXPECT_FALSE(root.HasIntAttribute(ax::mojom::IntAttribute::kCheckedState));
root.SetCheckedState(ax::mojom::CheckedState::kMixed);
EXPECT_EQ(ax::mojom::CheckedState::kMixed, root.GetCheckedState());
EXPECT_TRUE(root.HasIntAttribute(ax::mojom::IntAttribute::kCheckedState));
root.SetCheckedState(ax::mojom::CheckedState::kFalse);
EXPECT_EQ(ax::mojom::CheckedState::kFalse, root.GetCheckedState());
EXPECT_TRUE(root.HasIntAttribute(ax::mojom::IntAttribute::kCheckedState));
root.SetCheckedState(ax::mojom::CheckedState::kNone);
EXPECT_EQ(ax::mojom::CheckedState::kNone, root.GetCheckedState());
EXPECT_FALSE(root.HasIntAttribute(ax::mojom::IntAttribute::kCheckedState));
}
TEST(AXNodeDataTest, TextAttributes) {
AXNodeData node_1;
node_1.AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize, 1.5);
AXNodeData node_2;
node_2.AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize, 1.5);
EXPECT_TRUE(node_1.GetTextStyles() == node_2.GetTextStyles());
node_2.AddIntAttribute(ax::mojom::IntAttribute::kColor, 100);
EXPECT_TRUE(node_1.GetTextStyles() != node_2.GetTextStyles());
node_1.AddIntAttribute(ax::mojom::IntAttribute::kColor, 100);
EXPECT_TRUE(node_1.GetTextStyles() == node_2.GetTextStyles());
node_2.RemoveIntAttribute(ax::mojom::IntAttribute::kColor);
EXPECT_TRUE(node_1.GetTextStyles() != node_2.GetTextStyles());
node_2.AddIntAttribute(ax::mojom::IntAttribute::kColor, 100);
EXPECT_TRUE(node_1.GetTextStyles() == node_2.GetTextStyles());
node_1.AddStringAttribute(ax::mojom::StringAttribute::kFontFamily,
"test font");
EXPECT_TRUE(node_1.GetTextStyles() != node_2.GetTextStyles());
node_2.AddStringAttribute(ax::mojom::StringAttribute::kFontFamily,
"test font");
EXPECT_TRUE(node_1.GetTextStyles() == node_2.GetTextStyles());
node_2.RemoveStringAttribute(ax::mojom::StringAttribute::kFontFamily);
EXPECT_TRUE(node_1.GetTextStyles() != node_2.GetTextStyles());
node_2.AddStringAttribute(ax::mojom::StringAttribute::kFontFamily,
"test font");
EXPECT_TRUE(node_1.GetTextStyles() == node_2.GetTextStyles());
node_2.AddStringAttribute(ax::mojom::StringAttribute::kFontFamily,
"different font");
EXPECT_TRUE(node_1.GetTextStyles() != node_2.GetTextStyles());
std::string tooltip;
node_2.AddStringAttribute(ax::mojom::StringAttribute::kTooltip,
"test tooltip");
EXPECT_TRUE(node_2.GetStringAttribute(ax::mojom::StringAttribute::kTooltip,
&tooltip));
EXPECT_EQ(tooltip, "test tooltip");
AXNodeTextStyles node1_styles = node_1.GetTextStyles();
AXNodeTextStyles moved_styles = std::move(node1_styles);
EXPECT_TRUE(node1_styles != moved_styles);
EXPECT_TRUE(moved_styles == node_1.GetTextStyles());
}
TEST(AXNodeDataTest, IsButtonPressed) {
// A non-button element with CheckedState::kTrue should not return true for
// IsButtonPressed.
AXNodeData non_button_pressed;
non_button_pressed.role = ax::mojom::Role::kGenericContainer;
non_button_pressed.SetCheckedState(ax::mojom::CheckedState::kTrue);
EXPECT_FALSE(IsButton(non_button_pressed.role));
EXPECT_FALSE(non_button_pressed.IsButtonPressed());
// A button element with CheckedState::kTrue should return true for
// IsButtonPressed.
AXNodeData button_pressed;
button_pressed.role = ax::mojom::Role::kButton;
button_pressed.SetCheckedState(ax::mojom::CheckedState::kTrue);
EXPECT_TRUE(IsButton(button_pressed.role));
EXPECT_TRUE(button_pressed.IsButtonPressed());
button_pressed.role = ax::mojom::Role::kPopUpButton;
EXPECT_TRUE(IsButton(button_pressed.role));
EXPECT_TRUE(button_pressed.IsButtonPressed());
button_pressed.role = ax::mojom::Role::kToggleButton;
EXPECT_TRUE(IsButton(button_pressed.role));
EXPECT_TRUE(button_pressed.IsButtonPressed());
// A button element does not have CheckedState::kTrue should return false for
// IsButtonPressed.
AXNodeData button_not_pressed;
button_not_pressed.role = ax::mojom::Role::kButton;
button_not_pressed.SetCheckedState(ax::mojom::CheckedState::kNone);
EXPECT_TRUE(IsButton(button_not_pressed.role));
EXPECT_FALSE(button_not_pressed.IsButtonPressed());
button_not_pressed.role = ax::mojom::Role::kPopUpButton;
button_not_pressed.SetCheckedState(ax::mojom::CheckedState::kFalse);
EXPECT_TRUE(IsButton(button_not_pressed.role));
EXPECT_FALSE(button_not_pressed.IsButtonPressed());
button_not_pressed.role = ax::mojom::Role::kToggleButton;
button_not_pressed.SetCheckedState(ax::mojom::CheckedState::kMixed);
EXPECT_TRUE(IsButton(button_not_pressed.role));
EXPECT_FALSE(button_not_pressed.IsButtonPressed());
}
TEST(AXNodeDataTest, IsClickable) {
// Test for ax node data attribute with a custom default action verb.
AXNodeData data_default_action_verb;
for (int action_verb_idx =
static_cast<int>(ax::mojom::DefaultActionVerb::kMinValue);
action_verb_idx <=
static_cast<int>(ax::mojom::DefaultActionVerb::kMaxValue);
action_verb_idx++) {
data_default_action_verb.SetDefaultActionVerb(
static_cast<ax::mojom::DefaultActionVerb>(action_verb_idx));
bool is_clickable = data_default_action_verb.IsClickable();
SCOPED_TRACE(testing::Message()
<< "ax::mojom::DefaultActionVerb="
<< ToString(data_default_action_verb.GetDefaultActionVerb())
<< ", Actual: isClickable=" << is_clickable
<< ", Expected: isClickable=" << !is_clickable);
if (data_default_action_verb.GetDefaultActionVerb() ==
ax::mojom::DefaultActionVerb::kClickAncestor ||
data_default_action_verb.GetDefaultActionVerb() ==
ax::mojom::DefaultActionVerb::kNone)
EXPECT_FALSE(is_clickable);
else
EXPECT_TRUE(is_clickable);
}
// Test for iterating through all roles and validate if a role is clickable.
std::set<ax::mojom::Role> roles_expected_is_clickable = {
ax::mojom::Role::kButton,
ax::mojom::Role::kCheckBox,
ax::mojom::Role::kColorWell,
ax::mojom::Role::kComboBoxMenuButton,
ax::mojom::Role::kDate,
ax::mojom::Role::kDateTime,
ax::mojom::Role::kDisclosureTriangle,
ax::mojom::Role::kDocBackLink,
ax::mojom::Role::kDocBiblioRef,
ax::mojom::Role::kDocGlossRef,
ax::mojom::Role::kDocNoteRef,
ax::mojom::Role::kImeCandidate,
ax::mojom::Role::kInputTime,
ax::mojom::Role::kLink,
ax::mojom::Role::kListBox,
ax::mojom::Role::kListBoxOption,
ax::mojom::Role::kMenuItem,
ax::mojom::Role::kMenuItemCheckBox,
ax::mojom::Role::kMenuItemRadio,
ax::mojom::Role::kMenuListOption,
ax::mojom::Role::kPdfActionableHighlight,
ax::mojom::Role::kPopUpButton,
ax::mojom::Role::kPortal,
ax::mojom::Role::kRadioButton,
ax::mojom::Role::kSearchBox,
ax::mojom::Role::kSpinButton,
ax::mojom::Role::kSwitch,
ax::mojom::Role::kTab,
ax::mojom::Role::kTextField,
ax::mojom::Role::kTextFieldWithComboBox,
ax::mojom::Role::kToggleButton};
AXNodeData data;
for (int role_idx = static_cast<int>(ax::mojom::Role::kMinValue);
role_idx <= static_cast<int>(ax::mojom::Role::kMaxValue); role_idx++) {
data.role = static_cast<ax::mojom::Role>(role_idx);
bool is_clickable = data.IsClickable();
SCOPED_TRACE(testing::Message()
<< "ax::mojom::Role=" << ToString(data.role)
<< ", Actual: isClickable=" << is_clickable
<< ", Expected: isClickable=" << !is_clickable);
EXPECT_EQ(base::Contains(roles_expected_is_clickable, data.role),
is_clickable);
}
}
TEST(AXNodeDataTest, IsInvocable) {
// Test for iterating through all roles and validate if a role is invocable.
// A role is invocable if it is clickable and supports neither expand collapse
// nor toggle.
AXNodeData data;
for (int role_idx = static_cast<int>(ax::mojom::Role::kMinValue);
role_idx <= static_cast<int>(ax::mojom::Role::kMaxValue); role_idx++) {
data.role = static_cast<ax::mojom::Role>(role_idx);
bool is_activatable = data.IsActivatable();
const bool supports_expand_collapse = data.SupportsExpandCollapse();
const bool supports_toggle = ui::SupportsToggle(data.role);
const bool is_clickable = data.IsClickable();
const bool is_invocable = data.IsInvocable();
SCOPED_TRACE(testing::Message()
<< "ax::mojom::Role=" << ToString(data.role)
<< ", isClickable=" << is_clickable << ", isActivatable="
<< is_activatable << ", supportsToggle=" << supports_toggle
<< ", supportsExpandCollapse=" << supports_expand_collapse
<< ", Actual: isInvocable=" << is_invocable
<< ", Expected: isInvocable=" << !is_invocable);
if (is_clickable && !is_activatable && !supports_toggle &&
!supports_expand_collapse)
EXPECT_TRUE(is_invocable);
else
EXPECT_FALSE(is_invocable);
}
}
TEST(AXNodeDataTest, IsMenuButton) {
// A non button element should return false for IsMenuButton.
AXNodeData non_button;
non_button.role = ax::mojom::Role::kGenericContainer;
EXPECT_FALSE(IsButton(non_button.role));
EXPECT_FALSE(non_button.IsMenuButton());
// Only button element with HasPopup::kMenu should return true for
// IsMenuButton. All other ax::mojom::HasPopup types should return false.
AXNodeData button_with_popup;
button_with_popup.role = ax::mojom::Role::kButton;
for (int has_popup_idx = static_cast<int>(ax::mojom::HasPopup::kMinValue);
has_popup_idx <= static_cast<int>(ax::mojom::HasPopup::kMaxValue);
has_popup_idx++) {
button_with_popup.SetHasPopup(
static_cast<ax::mojom::HasPopup>(has_popup_idx));
bool is_menu_button = button_with_popup.IsMenuButton();
SCOPED_TRACE(testing::Message()
<< "ax::mojom::Role=" << ToString(button_with_popup.role)
<< ", hasPopup=" << ToString(button_with_popup.GetHasPopup())
<< ", Actual: isMenuButton=" << is_menu_button
<< ", Expected: isMenuButton=" << !is_menu_button);
if (IsButton(button_with_popup.role) &&
button_with_popup.GetHasPopup() == ax::mojom::HasPopup::kMenu)
EXPECT_TRUE(is_menu_button);
else
EXPECT_FALSE(is_menu_button);
}
}
TEST(AXNodeDataTest, SupportsExpandCollapse) {
// Test for iterating through all hasPopup attributes and validate if a
// hasPopup attribute supports expand collapse.
AXNodeData data_has_popup;
for (int has_popup_idx = static_cast<int>(ax::mojom::HasPopup::kMinValue);
has_popup_idx <= static_cast<int>(ax::mojom::HasPopup::kMaxValue);
has_popup_idx++) {
data_has_popup.SetHasPopup(static_cast<ax::mojom::HasPopup>(has_popup_idx));
bool supports_expand_collapse = data_has_popup.SupportsExpandCollapse();
SCOPED_TRACE(testing::Message() << "ax::mojom::HasPopup="
<< ToString(data_has_popup.GetHasPopup())
<< ", Actual: supportsExpandCollapse="
<< supports_expand_collapse
<< ", Expected: supportsExpandCollapse="
<< !supports_expand_collapse);
if (data_has_popup.GetHasPopup() == ax::mojom::HasPopup::kFalse)
EXPECT_FALSE(supports_expand_collapse);
else
EXPECT_TRUE(supports_expand_collapse);
}
// Test for iterating through all states and validate if a state supports
// expand collapse.
AXNodeData data_state;
for (int state_idx = static_cast<int>(ax::mojom::State::kMinValue);
state_idx <= static_cast<int>(ax::mojom::State::kMaxValue);
state_idx++) {
ax::mojom::State state = static_cast<ax::mojom::State>(state_idx);
// skipping kNone here because AXNodeData::AddState, RemoveState forbids
// kNone to be added/removed and would fail DCHECK.
if (state == ax::mojom::State::kNone)
continue;
data_state.AddState(state);
bool supports_expand_collapse = data_state.SupportsExpandCollapse();
SCOPED_TRACE(testing::Message() << "ax::mojom::State=" << ToString(state)
<< ", Actual: supportsExpandCollapse="
<< supports_expand_collapse
<< ", Expected: supportsExpandCollapse="
<< !supports_expand_collapse);
if (data_state.HasState(ax::mojom::State::kExpanded) ||
data_state.HasState(ax::mojom::State::kCollapsed))
EXPECT_TRUE(supports_expand_collapse);
else
EXPECT_FALSE(supports_expand_collapse);
data_state.RemoveState(state);
}
// Test for iterating through all roles and validate if a role supports expand
// collapse.
AXNodeData data;
std::unordered_set<ax::mojom::Role> roles_expected_supports_expand_collapse =
{ax::mojom::Role::kComboBoxGrouping, ax::mojom::Role::kComboBoxMenuButton,
ax::mojom::Role::kDisclosureTriangle,
ax::mojom::Role::kTextFieldWithComboBox, ax::mojom::Role::kTreeItem};
for (int role_idx = static_cast<int>(ax::mojom::Role::kMinValue);
role_idx <= static_cast<int>(ax::mojom::Role::kMaxValue); role_idx++) {
data.role = static_cast<ax::mojom::Role>(role_idx);
bool supports_expand_collapse = data.SupportsExpandCollapse();
SCOPED_TRACE(testing::Message() << "ax::mojom::Role=" << ToString(data.role)
<< ", Actual: supportsExpandCollapse="
<< supports_expand_collapse
<< ", Expected: supportsExpandCollapse="
<< !supports_expand_collapse);
if (roles_expected_supports_expand_collapse.find(data.role) !=
roles_expected_supports_expand_collapse.end())
EXPECT_TRUE(supports_expand_collapse);
else
EXPECT_FALSE(supports_expand_collapse);
}
}
TEST(AXNodeDataTest, BitFieldsSanityCheck) {
EXPECT_LT(static_cast<size_t>(ax::mojom::State::kMaxValue),
sizeof(AXNodeData::state) * 8);
EXPECT_LT(static_cast<size_t>(ax::mojom::Action::kMaxValue),
sizeof(AXNodeData::actions) * 8);
}
} // namespace ui
| engine/third_party/accessibility/ax/ax_node_data_unittest.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_node_data_unittest.cc",
"repo_id": "engine",
"token_count": 6405
} | 396 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_TABLE_INFO_H_
#define UI_ACCESSIBILITY_AX_TABLE_INFO_H_
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "ax_export.h"
namespace ui {
class AXTree;
class AXNode;
// This helper class computes info about tables and grids in AXTrees.
class AX_EXPORT AXTableInfo {
public:
struct CellData {
AXNode* cell;
int32_t cell_id;
size_t col_index;
size_t row_index;
size_t col_span;
size_t row_span;
size_t aria_col_index;
size_t aria_row_index;
};
// Returns nullptr if the node is not a valid table or grid node.
static AXTableInfo* Create(AXTree* tree, AXNode* table_node);
~AXTableInfo();
// Called automatically on Create(), but must be called again any time
// the table is invalidated. Returns true if this is still a table.
bool Update();
// Whether the data is valid. Whenever the tree is updated in any way,
// every AXTableInfo is invalidated and needs to be recomputed, just
// to be safe.
bool valid() const { return valid_; }
void Invalidate();
// The real row count, guaranteed to be at least as large as the
// maximum row index of any cell.
size_t row_count = 0;
// The real column count, guaranteed to be at least as large as the
// maximum column index of any cell.
size_t col_count = 0;
// List of column header nodes IDs for each column index.
std::vector<std::vector<int32_t>> col_headers;
// List of row header node IDs for each row index.
std::vector<std::vector<int32_t>> row_headers;
// All header cells.
std::vector<int32_t> all_headers;
// The id of the element with the caption tag or ARIA role.
int32_t caption_id;
// 2-D array of [row][column] -> cell node ID.
// This may contain duplicates if there is a rowspan or
// colspan. The entry is empty (zero) only if the cell
// really is missing from the table.
std::vector<std::vector<int32_t>> cell_ids;
// Array of cell data for every unique cell in the table.
std::vector<CellData> cell_data_vector;
// Set of all unique cell node IDs in the table.
std::vector<int32_t> unique_cell_ids;
// Extra computed nodes for the accessibility tree for macOS:
// one column node for each table column, followed by one
// table header container node.
std::vector<AXNode*> extra_mac_nodes;
// Map from each cell's node ID to its index in unique_cell_ids.
std::unordered_map<int32_t, size_t> cell_id_to_index;
// Map from each row's node ID to its row index.
std::unordered_map<int32_t, size_t> row_id_to_index;
// List of ax nodes that represent the rows of the table.
std::vector<AXNode*> row_nodes;
// The ARIA row count and column count, if any ARIA table or grid
// attributes are used in the table at all.
int aria_row_count = 0;
int aria_col_count = 0;
std::string ToString() const;
private:
AXTableInfo(AXTree* tree, AXNode* table_node);
void ClearVectors();
void BuildCellDataVectorFromRowAndCellNodes(
const std::vector<AXNode*>& row_node_list,
const std::vector<std::vector<AXNode*>>& cell_nodes_per_row);
void BuildCellAndHeaderVectorsFromCellData();
void UpdateExtraMacNodes();
void ClearExtraMacNodes();
AXNode* CreateExtraMacColumnNode(size_t col_index);
AXNode* CreateExtraMacTableHeaderNode();
void UpdateExtraMacColumnNodeAttributes(size_t col_index);
AXTree* tree_ = nullptr;
AXNode* table_node_ = nullptr;
bool valid_ = false;
std::map<int, std::map<int, CellData>> incremental_row_col_map_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_TABLE_INFO
| engine/third_party/accessibility/ax/ax_table_info.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_table_info.h",
"repo_id": "engine",
"token_count": 1248
} | 397 |
// 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_TREE_UPDATE_H_
#define UI_ACCESSIBILITY_AX_TREE_UPDATE_H_
#include <cstddef>
#include <cstdint>
#include <string>
#include <unordered_map>
#include <vector>
#include "ax_enum_util.h"
#include "ax_enums.h"
#include "ax_event_intent.h"
#include "ax_node_data.h"
#include "ax_tree_data.h"
#include "base/string_utils.h"
namespace ui {
// An AXTreeUpdate is a serialized representation of an atomic change
// to an AXTree. The sender and receiver must be in sync; the update
// is only meant to bring the tree from a specific previous state into
// its next state. Trying to apply it to the wrong tree should immediately
// die with a fatal assertion.
//
// An AXTreeUpdate consists of an optional node id to clear (meaning
// that all of that node's children and their descendants are deleted),
// followed by an ordered vector of zero or more AXNodeData structures to
// be applied to the tree in order. An update may also include an optional
// update to the AXTreeData structure that applies to the tree as a whole.
//
// Suppose that the next AXNodeData to be applied is |node|. The following
// invariants must hold:
// 1. Either
// a) |node.id| is already in the tree, or
// b) the tree is empty, and
// |node| is the new root of the tree, and
// |node.role| == WebAXRoleRootWebArea.
// 2. Every child id in |node.child_ids| must either be already a child
// of this node, or a new id not previously in the tree. It is not
// allowed to "reparent" a child to this node without first removing
// that child from its previous parent.
// 3. When a new id appears in |node.child_ids|, the tree should create a
// new uninitialized placeholder node for it immediately. That
// placeholder must be updated within the same AXTreeUpdate, otherwise
// it's a fatal error. This guarantees the tree is always complete
// before or after an AXTreeUpdate.
template <typename AXNodeData, typename AXTreeData>
struct AXTreeUpdateBase {
// If |has_tree_data| is true, the value of |tree_data| should be used
// to update the tree data, otherwise it should be ignored.
bool has_tree_data = false;
AXTreeData tree_data;
// The id of a node to clear, before applying any updates,
// or AXNode::kInvalidAXID if no nodes should be cleared. Clearing a node
// means deleting all of its children and their descendants, but leaving that
// node in the tree. It's an error to clear a node but not subsequently update
// it as part of the tree update.
int node_id_to_clear = AXNode::kInvalidAXID;
// The id of the root of the tree, if the root is changing. This is
// required to be set if the root of the tree is changing or Unserialize
// will fail. If the root of the tree is not changing this is optional
// and it is allowed to pass 0.
int root_id = 0;
// A vector of nodes to update, according to the rules above.
std::vector<AXNodeData> nodes;
// The source of the event which generated this tree update.
ax::mojom::EventFrom event_from = ax::mojom::EventFrom::kNone;
// The event intents associated with this tree update.
std::vector<AXEventIntent> event_intents;
// Return a multi-line indented string representation, for logging.
std::string ToString() const;
// TODO(dmazzoni): location changes
};
using AXTreeUpdate = AXTreeUpdateBase<AXNodeData, AXTreeData>;
template <typename AXNodeData, typename AXTreeData>
std::string AXTreeUpdateBase<AXNodeData, AXTreeData>::ToString() const {
std::string result;
if (has_tree_data) {
result += "AXTreeUpdate tree data:" + tree_data.ToString() + "\n";
}
if (node_id_to_clear != AXNode::kInvalidAXID) {
result += "AXTreeUpdate: clear node " +
base::NumberToString(node_id_to_clear) + "\n";
}
if (root_id != AXNode::kInvalidAXID) {
result += "AXTreeUpdate: root id " + base::NumberToString(root_id) + "\n";
}
if (event_from != ax::mojom::EventFrom::kNone)
result += "event_from=" + std::string(ui::ToString(event_from)) + "\n";
if (!event_intents.empty()) {
result += "event_intents=[\n";
for (const auto& event_intent : event_intents)
result += " " + event_intent.ToString() + "\n";
result += "]\n";
}
// The challenge here is that we want to indent the nodes being updated
// so that parent/child relationships are clear, but we don't have access
// to the rest of the tree for context, so we have to try to show the
// relative indentation of child nodes in this update relative to their
// parents.
std::unordered_map<int32_t, int> id_to_indentation;
for (size_t i = 0; i < nodes.size(); ++i) {
int indent = id_to_indentation[nodes[i].id];
result += std::string(2 * indent, ' ');
result += nodes[i].ToString() + "\n";
for (size_t j = 0; j < nodes[i].child_ids.size(); ++j)
id_to_indentation[nodes[i].child_ids[j]] = indent + 1;
}
return result;
}
// Two tree updates can be merged into one if the second one
// doesn't clear a subtree, doesn't have new tree data, and
// doesn't have a new root id - in other words the second tree
// update consists of only changes to nodes.
template <typename AXNodeData, typename AXTreeData>
bool TreeUpdatesCanBeMerged(
const AXTreeUpdateBase<AXNodeData, AXTreeData>& u1,
const AXTreeUpdateBase<AXNodeData, AXTreeData>& u2) {
if (u2.node_id_to_clear != AXNode::kInvalidAXID)
return false;
if (u2.has_tree_data && u2.tree_data != u1.tree_data)
return false;
if (u2.root_id != u1.root_id)
return false;
return true;
}
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_TREE_UPDATE_H_
| engine/third_party/accessibility/ax/ax_tree_update.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_tree_update.h",
"repo_id": "engine",
"token_count": 1927
} | 398 |
// 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.
#import "ax_platform_node_mac.h"
#import <Cocoa/Cocoa.h>
#include <cstddef>
#include "ax/ax_action_data.h"
#include "ax/ax_node_data.h"
#include "ax/ax_role_properties.h"
#include "ax_platform_node.h"
#include "ax_platform_node_delegate.h"
#include "base/no_destructor.h"
#import "gfx/mac/coordinate_conversion.h"
namespace {
NSString* const NSAccessibilityScrollToVisibleAction = @"AXScrollToVisible";
// Same length as web content/WebKit.
static int kLiveRegionDebounceMillis = 20;
using RoleMap = std::map<ax::mojom::Role, NSString*>;
using EventMap = std::map<ax::mojom::Event, NSString*>;
using ActionList = std::vector<std::pair<ax::mojom::Action, NSString*>>;
struct AnnouncementSpec {
base::scoped_nsobject<NSString> announcement;
base::scoped_nsobject<NSWindow> window;
bool is_polite;
};
RoleMap BuildRoleMap() {
const RoleMap::value_type roles[] = {
{ax::mojom::Role::kAbbr, NSAccessibilityGroupRole},
{ax::mojom::Role::kAlert, NSAccessibilityGroupRole},
{ax::mojom::Role::kAlertDialog, NSAccessibilityGroupRole},
{ax::mojom::Role::kAnchor, NSAccessibilityGroupRole},
{ax::mojom::Role::kApplication, NSAccessibilityGroupRole},
{ax::mojom::Role::kArticle, NSAccessibilityGroupRole},
{ax::mojom::Role::kAudio, NSAccessibilityGroupRole},
{ax::mojom::Role::kBanner, NSAccessibilityGroupRole},
{ax::mojom::Role::kBlockquote, NSAccessibilityGroupRole},
{ax::mojom::Role::kButton, NSAccessibilityButtonRole},
{ax::mojom::Role::kCanvas, NSAccessibilityImageRole},
{ax::mojom::Role::kCaption, NSAccessibilityGroupRole},
{ax::mojom::Role::kCell, @"AXCell"},
{ax::mojom::Role::kCheckBox, NSAccessibilityCheckBoxRole},
{ax::mojom::Role::kCode, NSAccessibilityGroupRole},
{ax::mojom::Role::kColorWell, NSAccessibilityColorWellRole},
{ax::mojom::Role::kColumn, NSAccessibilityColumnRole},
{ax::mojom::Role::kColumnHeader, @"AXCell"},
{ax::mojom::Role::kComboBoxGrouping, NSAccessibilityGroupRole},
{ax::mojom::Role::kComboBoxMenuButton, NSAccessibilityPopUpButtonRole},
{ax::mojom::Role::kComment, NSAccessibilityGroupRole},
{ax::mojom::Role::kComplementary, NSAccessibilityGroupRole},
{ax::mojom::Role::kContentDeletion, NSAccessibilityGroupRole},
{ax::mojom::Role::kContentInsertion, NSAccessibilityGroupRole},
{ax::mojom::Role::kContentInfo, NSAccessibilityGroupRole},
{ax::mojom::Role::kDate, @"AXDateField"},
{ax::mojom::Role::kDateTime, @"AXDateField"},
{ax::mojom::Role::kDefinition, NSAccessibilityGroupRole},
{ax::mojom::Role::kDescriptionListDetail, NSAccessibilityGroupRole},
{ax::mojom::Role::kDescriptionList, NSAccessibilityListRole},
{ax::mojom::Role::kDescriptionListTerm, NSAccessibilityGroupRole},
{ax::mojom::Role::kDialog, NSAccessibilityGroupRole},
{ax::mojom::Role::kDetails, NSAccessibilityGroupRole},
{ax::mojom::Role::kDirectory, NSAccessibilityListRole},
// If Mac supports AXExpandedChanged event with
// NSAccessibilityDisclosureTriangleRole, We should update
// ax::mojom::Role::kDisclosureTriangle mapping to
// NSAccessibilityDisclosureTriangleRole. http://crbug.com/558324
{ax::mojom::Role::kDisclosureTriangle, NSAccessibilityButtonRole},
{ax::mojom::Role::kDocAbstract, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocAcknowledgments, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocAfterword, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocAppendix, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocBackLink, NSAccessibilityLinkRole},
{ax::mojom::Role::kDocBiblioEntry, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocBibliography, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocBiblioRef, NSAccessibilityLinkRole},
{ax::mojom::Role::kDocChapter, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocColophon, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocConclusion, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocCover, NSAccessibilityImageRole},
{ax::mojom::Role::kDocCredit, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocCredits, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocDedication, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocEndnote, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocEndnotes, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocEpigraph, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocEpilogue, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocErrata, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocExample, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocFootnote, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocForeword, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocGlossary, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocGlossRef, NSAccessibilityLinkRole},
{ax::mojom::Role::kDocIndex, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocIntroduction, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocNoteRef, NSAccessibilityLinkRole},
{ax::mojom::Role::kDocNotice, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocPageBreak, NSAccessibilitySplitterRole},
{ax::mojom::Role::kDocPageList, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocPart, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocPreface, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocPrologue, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocPullquote, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocQna, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocSubtitle, @"AXHeading"},
{ax::mojom::Role::kDocTip, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocToc, NSAccessibilityGroupRole},
{ax::mojom::Role::kDocument, NSAccessibilityGroupRole},
{ax::mojom::Role::kEmbeddedObject, NSAccessibilityGroupRole},
{ax::mojom::Role::kEmphasis, NSAccessibilityGroupRole},
{ax::mojom::Role::kFigcaption, NSAccessibilityGroupRole},
{ax::mojom::Role::kFigure, NSAccessibilityGroupRole},
{ax::mojom::Role::kFooter, NSAccessibilityGroupRole},
{ax::mojom::Role::kFooterAsNonLandmark, NSAccessibilityGroupRole},
{ax::mojom::Role::kForm, NSAccessibilityGroupRole},
{ax::mojom::Role::kGenericContainer, NSAccessibilityGroupRole},
{ax::mojom::Role::kGraphicsDocument, NSAccessibilityGroupRole},
{ax::mojom::Role::kGraphicsObject, NSAccessibilityGroupRole},
{ax::mojom::Role::kGraphicsSymbol, NSAccessibilityImageRole},
// Should be NSAccessibilityGridRole but VoiceOver treating it like
// a list as of 10.12.6, so following WebKit and using table role:
{ax::mojom::Role::kGrid, NSAccessibilityTableRole}, // crbug.com/753925
{ax::mojom::Role::kGroup, NSAccessibilityGroupRole},
{ax::mojom::Role::kHeader, NSAccessibilityGroupRole},
{ax::mojom::Role::kHeaderAsNonLandmark, NSAccessibilityGroupRole},
{ax::mojom::Role::kHeading, @"AXHeading"},
{ax::mojom::Role::kIframe, NSAccessibilityGroupRole},
{ax::mojom::Role::kIframePresentational, NSAccessibilityGroupRole},
{ax::mojom::Role::kIgnored, NSAccessibilityUnknownRole},
{ax::mojom::Role::kImage, NSAccessibilityImageRole},
{ax::mojom::Role::kImageMap, NSAccessibilityGroupRole},
{ax::mojom::Role::kInputTime, @"AXTimeField"},
{ax::mojom::Role::kLabelText, NSAccessibilityGroupRole},
{ax::mojom::Role::kLayoutTable, NSAccessibilityGroupRole},
{ax::mojom::Role::kLayoutTableCell, NSAccessibilityGroupRole},
{ax::mojom::Role::kLayoutTableRow, NSAccessibilityGroupRole},
{ax::mojom::Role::kLegend, NSAccessibilityGroupRole},
{ax::mojom::Role::kLineBreak, NSAccessibilityGroupRole},
{ax::mojom::Role::kLink, NSAccessibilityLinkRole},
{ax::mojom::Role::kList, NSAccessibilityListRole},
{ax::mojom::Role::kListBox, NSAccessibilityListRole},
{ax::mojom::Role::kListBoxOption, NSAccessibilityStaticTextRole},
{ax::mojom::Role::kListItem, NSAccessibilityGroupRole},
{ax::mojom::Role::kListMarker, @"AXListMarker"},
{ax::mojom::Role::kLog, NSAccessibilityGroupRole},
{ax::mojom::Role::kMain, NSAccessibilityGroupRole},
{ax::mojom::Role::kMark, NSAccessibilityGroupRole},
{ax::mojom::Role::kMarquee, NSAccessibilityGroupRole},
{ax::mojom::Role::kMath, NSAccessibilityGroupRole},
{ax::mojom::Role::kMenu, NSAccessibilityMenuRole},
{ax::mojom::Role::kMenuBar, NSAccessibilityMenuBarRole},
{ax::mojom::Role::kMenuItem, NSAccessibilityMenuItemRole},
{ax::mojom::Role::kMenuItemCheckBox, NSAccessibilityMenuItemRole},
{ax::mojom::Role::kMenuItemRadio, NSAccessibilityMenuItemRole},
{ax::mojom::Role::kMenuListOption, NSAccessibilityMenuItemRole},
{ax::mojom::Role::kMenuListPopup, NSAccessibilityMenuRole},
{ax::mojom::Role::kMeter, NSAccessibilityLevelIndicatorRole},
{ax::mojom::Role::kNavigation, NSAccessibilityGroupRole},
{ax::mojom::Role::kNone, NSAccessibilityGroupRole},
{ax::mojom::Role::kNote, NSAccessibilityGroupRole},
{ax::mojom::Role::kParagraph, NSAccessibilityGroupRole},
{ax::mojom::Role::kPdfActionableHighlight, NSAccessibilityButtonRole},
{ax::mojom::Role::kPluginObject, NSAccessibilityGroupRole},
{ax::mojom::Role::kPopUpButton, NSAccessibilityPopUpButtonRole},
{ax::mojom::Role::kPortal, NSAccessibilityButtonRole},
{ax::mojom::Role::kPre, NSAccessibilityGroupRole},
{ax::mojom::Role::kPresentational, NSAccessibilityGroupRole},
{ax::mojom::Role::kProgressIndicator, NSAccessibilityProgressIndicatorRole},
{ax::mojom::Role::kRadioButton, NSAccessibilityRadioButtonRole},
{ax::mojom::Role::kRadioGroup, NSAccessibilityRadioGroupRole},
{ax::mojom::Role::kRegion, NSAccessibilityGroupRole},
{ax::mojom::Role::kRootWebArea, @"AXWebArea"},
{ax::mojom::Role::kRow, NSAccessibilityRowRole},
{ax::mojom::Role::kRowGroup, NSAccessibilityGroupRole},
{ax::mojom::Role::kRowHeader, @"AXCell"},
// TODO(accessibility) What should kRuby be? It's not listed? Any others
// missing? Maybe use switch statement so that compiler doesn't allow us
// to miss any.
{ax::mojom::Role::kRubyAnnotation, NSAccessibilityUnknownRole},
{ax::mojom::Role::kScrollBar, NSAccessibilityScrollBarRole},
{ax::mojom::Role::kSearch, NSAccessibilityGroupRole},
{ax::mojom::Role::kSearchBox, NSAccessibilityTextFieldRole},
{ax::mojom::Role::kSection, NSAccessibilityGroupRole},
{ax::mojom::Role::kSlider, NSAccessibilitySliderRole},
{ax::mojom::Role::kSliderThumb, NSAccessibilityValueIndicatorRole},
{ax::mojom::Role::kSpinButton, NSAccessibilityIncrementorRole},
{ax::mojom::Role::kSplitter, NSAccessibilitySplitterRole},
{ax::mojom::Role::kStaticText, NSAccessibilityStaticTextRole},
{ax::mojom::Role::kStatus, NSAccessibilityGroupRole},
{ax::mojom::Role::kSuggestion, NSAccessibilityGroupRole},
{ax::mojom::Role::kSvgRoot, NSAccessibilityGroupRole},
{ax::mojom::Role::kSwitch, NSAccessibilityCheckBoxRole},
{ax::mojom::Role::kStrong, NSAccessibilityGroupRole},
{ax::mojom::Role::kTab, NSAccessibilityRadioButtonRole},
{ax::mojom::Role::kTable, NSAccessibilityTableRole},
{ax::mojom::Role::kTableHeaderContainer, NSAccessibilityGroupRole},
{ax::mojom::Role::kTabList, NSAccessibilityTabGroupRole},
{ax::mojom::Role::kTabPanel, NSAccessibilityGroupRole},
{ax::mojom::Role::kTerm, NSAccessibilityGroupRole},
{ax::mojom::Role::kTextField, NSAccessibilityTextFieldRole},
{ax::mojom::Role::kTextFieldWithComboBox, NSAccessibilityComboBoxRole},
{ax::mojom::Role::kTime, NSAccessibilityGroupRole},
{ax::mojom::Role::kTimer, NSAccessibilityGroupRole},
{ax::mojom::Role::kTitleBar, NSAccessibilityStaticTextRole},
{ax::mojom::Role::kToggleButton, NSAccessibilityCheckBoxRole},
{ax::mojom::Role::kToolbar, NSAccessibilityToolbarRole},
{ax::mojom::Role::kTooltip, NSAccessibilityGroupRole},
{ax::mojom::Role::kTree, NSAccessibilityOutlineRole},
{ax::mojom::Role::kTreeGrid, NSAccessibilityTableRole},
{ax::mojom::Role::kTreeItem, NSAccessibilityRowRole},
{ax::mojom::Role::kVideo, NSAccessibilityGroupRole},
{ax::mojom::Role::kWebArea, @"AXWebArea"},
// Use the group role as the BrowserNativeWidgetWindow already provides
// a kWindow role, and having extra window roles, which are treated
// specially by screen readers, can break their ability to find the
// content window. See http://crbug.com/875843 for more information.
{ax::mojom::Role::kWindow, NSAccessibilityGroupRole},
};
return RoleMap(begin(roles), end(roles));
}
RoleMap BuildSubroleMap() {
const RoleMap::value_type subroles[] = {
{ax::mojom::Role::kAlert, @"AXApplicationAlert"},
{ax::mojom::Role::kAlertDialog, @"AXApplicationAlertDialog"},
{ax::mojom::Role::kApplication, @"AXLandmarkApplication"},
{ax::mojom::Role::kArticle, @"AXDocumentArticle"},
{ax::mojom::Role::kBanner, @"AXLandmarkBanner"},
{ax::mojom::Role::kCode, @"AXCodeStyleGroup"},
{ax::mojom::Role::kComplementary, @"AXLandmarkComplementary"},
{ax::mojom::Role::kContentDeletion, @"AXDeleteStyleGroup"},
{ax::mojom::Role::kContentInsertion, @"AXInsertStyleGroup"},
{ax::mojom::Role::kContentInfo, @"AXLandmarkContentInfo"},
{ax::mojom::Role::kDefinition, @"AXDefinition"},
{ax::mojom::Role::kDescriptionListDetail, @"AXDefinition"},
{ax::mojom::Role::kDescriptionListTerm, @"AXTerm"},
{ax::mojom::Role::kDialog, @"AXApplicationDialog"},
{ax::mojom::Role::kDocument, @"AXDocument"},
{ax::mojom::Role::kEmphasis, @"AXEmphasisStyleGroup"},
{ax::mojom::Role::kFooter, @"AXLandmarkContentInfo"},
{ax::mojom::Role::kForm, @"AXLandmarkForm"},
{ax::mojom::Role::kGraphicsDocument, @"AXDocument"},
{ax::mojom::Role::kHeader, @"AXLandmarkBanner"},
{ax::mojom::Role::kLog, @"AXApplicationLog"},
{ax::mojom::Role::kMain, @"AXLandmarkMain"},
{ax::mojom::Role::kMarquee, @"AXApplicationMarquee"},
{ax::mojom::Role::kMath, @"AXDocumentMath"},
{ax::mojom::Role::kNavigation, @"AXLandmarkNavigation"},
{ax::mojom::Role::kNote, @"AXDocumentNote"},
{ax::mojom::Role::kRegion, @"AXLandmarkRegion"},
{ax::mojom::Role::kSearch, @"AXLandmarkSearch"},
{ax::mojom::Role::kSearchBox, @"AXSearchField"},
{ax::mojom::Role::kSection, @"AXLandmarkRegion"},
{ax::mojom::Role::kStatus, @"AXApplicationStatus"},
{ax::mojom::Role::kStrong, @"AXStrongStyleGroup"},
{ax::mojom::Role::kSwitch, @"AXSwitch"},
{ax::mojom::Role::kTabPanel, @"AXTabPanel"},
{ax::mojom::Role::kTerm, @"AXTerm"},
{ax::mojom::Role::kTime, @"AXTimeGroup"},
{ax::mojom::Role::kTimer, @"AXApplicationTimer"},
{ax::mojom::Role::kToggleButton, @"AXToggleButton"},
{ax::mojom::Role::kTooltip, @"AXUserInterfaceTooltip"},
{ax::mojom::Role::kTreeItem, NSAccessibilityOutlineRowSubrole},
};
return RoleMap(begin(subroles), end(subroles));
}
EventMap BuildEventMap() {
const EventMap::value_type events[] = {
{ax::mojom::Event::kCheckedStateChanged, NSAccessibilityValueChangedNotification},
{ax::mojom::Event::kFocus, NSAccessibilityFocusedUIElementChangedNotification},
{ax::mojom::Event::kFocusContext, NSAccessibilityFocusedUIElementChangedNotification},
{ax::mojom::Event::kTextChanged, NSAccessibilityTitleChangedNotification},
{ax::mojom::Event::kValueChanged, NSAccessibilityValueChangedNotification},
{ax::mojom::Event::kTextSelectionChanged, NSAccessibilitySelectedTextChangedNotification},
// TODO(patricialor): Add more events.
};
return EventMap(begin(events), end(events));
}
ActionList BuildActionList() {
const ActionList::value_type entries[] = {
// NSAccessibilityPressAction must come first in this list.
{ax::mojom::Action::kDoDefault, NSAccessibilityPressAction},
{ax::mojom::Action::kScrollToMakeVisible, NSAccessibilityScrollToVisibleAction},
{ax::mojom::Action::kDecrement, NSAccessibilityDecrementAction},
{ax::mojom::Action::kIncrement, NSAccessibilityIncrementAction},
{ax::mojom::Action::kShowContextMenu, NSAccessibilityShowMenuAction},
};
return ActionList(begin(entries), end(entries));
}
const ActionList& GetActionList() {
static const base::NoDestructor<ActionList> action_map(BuildActionList());
return *action_map;
}
void PostAnnouncementNotification(NSString* announcement, NSWindow* window, bool is_polite) {
NSAccessibilityPriorityLevel priority =
is_polite ? NSAccessibilityPriorityMedium : NSAccessibilityPriorityHigh;
NSDictionary* notification_info =
@{NSAccessibilityAnnouncementKey : announcement,
NSAccessibilityPriorityKey : @(priority)};
// On Mojave, announcements from an inactive window aren't spoken.
NSAccessibilityPostNotificationWithUserInfo(
window, NSAccessibilityAnnouncementRequestedNotification, notification_info);
}
void NotifyMacEvent(AXPlatformNodeCocoa* target, ax::mojom::Event event_type) {
NSString* notification = [AXPlatformNodeCocoa nativeNotificationFromAXEvent:event_type];
if (notification)
NSAccessibilityPostNotification(target, notification);
}
// Returns true if |action| should be added implicitly for |data|.
bool HasImplicitAction(const ui::AXNodeData& data, ax::mojom::Action action) {
return action == ax::mojom::Action::kDoDefault && data.IsClickable();
}
// For roles that show a menu for the default action, ensure "show menu" also
// appears in available actions, but only if that's not already used for a
// context menu. It will be mapped back to the default action when performed.
bool AlsoUseShowMenuActionForDefaultAction(const ui::AXNodeData& data) {
return HasImplicitAction(data, ax::mojom::Action::kDoDefault) &&
!data.HasAction(ax::mojom::Action::kShowContextMenu) &&
data.role == ax::mojom::Role::kPopUpButton;
}
} // namespace
@interface AXPlatformNodeCocoa (Private)
// Helper function for string attributes that don't require extra processing.
- (NSString*)getStringAttribute:(ax::mojom::StringAttribute)attribute;
// Returns AXValue, or nil if AXValue isn't an NSString.
- (NSString*)getAXValueAsString;
// Returns the data necessary to queue an NSAccessibility announcement if
// |eventType| should be announced, or nullptr otherwise.
- (std::unique_ptr<AnnouncementSpec>)announcementForEvent:(ax::mojom::Event)eventType;
// Ask the system to announce |announcementText|. This is debounced to happen
// at most every |kLiveRegionDebounceMillis| per node, with only the most
// recent announcement text read, to account for situations with multiple
// notifications happening one after another (for example, results for
// find-in-page updating rapidly as they come in from subframes).
- (void)scheduleLiveRegionAnnouncement:(std::unique_ptr<AnnouncementSpec>)announcement;
@end
@implementation AXPlatformNodeCocoa {
ui::AXPlatformNodeBase* _node; // Weak. Retains us.
std::unique_ptr<AnnouncementSpec> _pendingAnnouncement;
}
@synthesize node = _node;
+ (NSString*)nativeRoleFromAXRole:(ax::mojom::Role)role {
static const base::NoDestructor<RoleMap> role_map(BuildRoleMap());
RoleMap::const_iterator it = role_map->find(role);
return it != role_map->end() ? it->second : NSAccessibilityUnknownRole;
}
+ (NSString*)nativeSubroleFromAXRole:(ax::mojom::Role)role {
static const base::NoDestructor<RoleMap> subrole_map(BuildSubroleMap());
RoleMap::const_iterator it = subrole_map->find(role);
return it != subrole_map->end() ? it->second : nil;
}
+ (NSString*)nativeNotificationFromAXEvent:(ax::mojom::Event)event {
static const base::NoDestructor<EventMap> event_map(BuildEventMap());
EventMap::const_iterator it = event_map->find(event);
return it != event_map->end() ? it->second : nil;
}
- (instancetype)initWithNode:(ui::AXPlatformNodeBase*)node {
if ((self = [super init])) {
_node = node;
}
return self;
}
- (void)detach {
if (!_node)
return;
_node = nil;
NSAccessibilityPostNotification(self, NSAccessibilityUIElementDestroyedNotification);
}
- (NSRect)boundsInScreen {
if (!_node || !_node->GetDelegate())
return NSZeroRect;
return gfx::ScreenRectToNSRect(_node->GetDelegate()->GetBoundsRect(
ui::AXCoordinateSystem::kScreenDIPs, ui::AXClippingBehavior::kClipped));
}
- (NSString*)getStringAttribute:(ax::mojom::StringAttribute)attribute {
std::string attributeValue;
if (_node->GetStringAttribute(attribute, &attributeValue))
return @(attributeValue.data());
return nil;
}
- (NSString*)getAXValueAsString {
id value = [self AXValueInternal];
return [value isKindOfClass:[NSString class]] ? value : nil;
}
- (NSString*)getName {
return @(_node->GetName().data());
}
- (std::unique_ptr<AnnouncementSpec>)announcementForEvent:(ax::mojom::Event)eventType {
// Only alerts and live region changes should be announced.
BASE_DCHECK(eventType == ax::mojom::Event::kAlert ||
eventType == ax::mojom::Event::kLiveRegionChanged);
std::string liveStatus = _node->GetStringAttribute(ax::mojom::StringAttribute::kLiveStatus);
// If live status is explicitly set to off, don't announce.
if (liveStatus == "off")
return nullptr;
NSString* name = [self getName];
NSString* announcementText = name;
if ([announcementText length] <= 0) {
announcementText = @(base::UTF16ToUTF8(_node->GetInnerText()).data());
}
if ([announcementText length] == 0)
return nullptr;
auto announcement = std::make_unique<AnnouncementSpec>();
announcement->announcement = base::scoped_nsobject<NSString>([announcementText retain]);
announcement->window = base::scoped_nsobject<NSWindow>([[self AXWindowInternal] retain]);
announcement->is_polite = liveStatus != "assertive";
return announcement;
}
- (void)scheduleLiveRegionAnnouncement:(std::unique_ptr<AnnouncementSpec>)announcement {
if (_pendingAnnouncement) {
// An announcement is already in flight, so just reset the contents. This is
// threadsafe because the dispatch is on the main queue.
_pendingAnnouncement = std::move(announcement);
return;
}
_pendingAnnouncement = std::move(announcement);
dispatch_after(kLiveRegionDebounceMillis * NSEC_PER_MSEC, dispatch_get_main_queue(), ^{
if (!_pendingAnnouncement) {
return;
}
PostAnnouncementNotification(_pendingAnnouncement->announcement, _pendingAnnouncement->window,
_pendingAnnouncement->is_polite);
_pendingAnnouncement.reset();
});
}
// NSAccessibility informal protocol implementation.
- (BOOL)accessibilityIsIgnored {
if (!_node)
return YES;
return [[self AXRoleInternal] isEqualToString:NSAccessibilityUnknownRole] ||
_node->GetData().HasState(ax::mojom::State::kInvisible);
}
- (id)accessibilityHitTest:(NSPoint)point {
if (!NSPointInRect(point, [self boundsInScreen]))
return nil;
for (id child in [[self AXChildrenInternal] reverseObjectEnumerator]) {
if (!NSPointInRect(point, [child accessibilityFrame]))
continue;
if (id foundChild = [child accessibilityHitTest:point])
return foundChild;
}
// Hit self, but not any child.
return NSAccessibilityUnignoredAncestor(self);
}
- (BOOL)accessibilityNotifiesWhenDestroyed {
return YES;
}
- (id)accessibilityFocusedUIElement {
return _node ? _node->GetDelegate()->GetFocus() : nil;
}
// This function and accessibilityPerformAction:, while deprecated, are a) still
// called by AppKit internally and b) not implemented by NSAccessibilityElement,
// so this class needs its own implementations.
- (NSArray*)accessibilityActionNames {
if (!_node)
return @[];
base::scoped_nsobject<NSMutableArray> axActions([[NSMutableArray alloc] init]);
const ui::AXNodeData& data = _node->GetData();
const ActionList& action_list = GetActionList();
// VoiceOver expects the "press" action to be first. Note that some roles
// should be given a press action implicitly.
BASE_DCHECK([action_list[0].second isEqualToString:NSAccessibilityPressAction]);
for (const auto& item : action_list) {
if (data.HasAction(item.first) || HasImplicitAction(data, item.first))
[axActions addObject:item.second];
}
if (AlsoUseShowMenuActionForDefaultAction(data))
[axActions addObject:NSAccessibilityShowMenuAction];
return axActions.autorelease();
}
- (void)accessibilityPerformAction:(NSString*)action {
// Actions are performed asynchronously, so it's always possible for an object
// to change its mind after previously reporting an action as available.
if (![[self accessibilityActionNames] containsObject:action])
return;
ui::AXActionData data;
if ([action isEqualToString:NSAccessibilityShowMenuAction] &&
AlsoUseShowMenuActionForDefaultAction(_node->GetData())) {
data.action = ax::mojom::Action::kDoDefault;
} else {
for (const ActionList::value_type& entry : GetActionList()) {
if ([action isEqualToString:entry.second]) {
data.action = entry.first;
break;
}
}
}
// Note ui::AX_ACTIONs which are just overwriting an accessibility attribute
// are already implemented in -accessibilitySetValue:forAttribute:, so ignore
// those here.
if (data.action != ax::mojom::Action::kNone)
_node->GetDelegate()->AccessibilityPerformAction(data);
}
- (NSString*)AXRoleInternal {
if (!_node)
return nil;
return [[self class] nativeRoleFromAXRole:_node->GetData().role];
}
- (NSString*)AXRoleDescriptionInternal {
switch (_node->GetData().role) {
case ax::mojom::Role::kTab:
// There is no NSAccessibilityTabRole or similar (AXRadioButton is used
// instead). Do the same as NSTabView and put "tab" in the description.
// return [l10n_util::GetNSStringWithFixup(IDS_ACCNAME_TAB_ROLE_DESCRIPTION)
// lowercaseString];
return nil;
case ax::mojom::Role::kDisclosureTriangle:
// return [l10n_util::GetNSStringWithFixup(
// IDS_ACCNAME_DISCLOSURE_TRIANGLE_ROLE_DESCRIPTION) lowercaseString];
return nil;
default:
break;
}
return NSAccessibilityRoleDescription([self AXRoleInternal], [self AXSubroleInternal]);
}
- (NSString*)AXSubroleInternal {
ax::mojom::Role role = _node->GetData().role;
switch (role) {
case ax::mojom::Role::kTextField:
if (_node->GetData().HasState(ax::mojom::State::kProtected))
return NSAccessibilitySecureTextFieldSubrole;
break;
default:
break;
}
return [AXPlatformNodeCocoa nativeSubroleFromAXRole:role];
}
- (NSString*)AXHelpInternal {
// TODO(aleventhal) Key shortcuts attribute should eventually get
// its own field. Follow what WebKit does for aria-keyshortcuts, see
// https://bugs.webkit.org/show_bug.cgi?id=159215 (WebKit bug).
NSString* desc = [self getStringAttribute:ax::mojom::StringAttribute::kDescription];
NSString* key = [self getStringAttribute:ax::mojom::StringAttribute::kKeyShortcuts];
if (!desc.length)
return key.length ? key : @"";
if (!key.length)
return desc;
return [NSString stringWithFormat:@"%@ %@", desc, key];
}
- (id)AXValueInternal {
ax::mojom::Role role = _node->GetData().role;
if (role == ax::mojom::Role::kTab)
return [self AXSelectedInternal];
if (ui::IsNameExposedInAXValueForRole(role)) {
if (role == ax::mojom::Role::kStaticText) {
// Static texts may store their texts in the value attributes. For
// example, the selectable text stores its text in value instead of
// name.
NSString* value = [self getName];
if (value.length == 0) {
value = [self getStringAttribute:ax::mojom::StringAttribute::kValue];
}
return value;
}
return [self getName];
}
if (_node->IsPlatformCheckable()) {
// Mixed checkbox state not currently supported in views, but could be.
// See browser_accessibility_cocoa.mm for details.
const auto checkedState = static_cast<ax::mojom::CheckedState>(
_node->GetIntAttribute(ax::mojom::IntAttribute::kCheckedState));
return checkedState == ax::mojom::CheckedState::kTrue ? @1 : @0;
}
return [self getStringAttribute:ax::mojom::StringAttribute::kValue];
}
- (NSNumber*)AXEnabledInternal {
return @(_node->GetData().GetRestriction() != ax::mojom::Restriction::kDisabled);
}
- (NSNumber*)AXFocusedInternal {
if (_node->GetData().HasState(ax::mojom::State::kFocusable))
return @(_node->GetDelegate()->GetFocus() == _node->GetNativeViewAccessible());
return @NO;
}
- (id)AXParentInternal {
if (!_node)
return nil;
return NSAccessibilityUnignoredAncestor(_node->GetParent());
}
- (NSArray*)AXChildrenInternal {
if (!_node)
return @[];
int count = _node->GetChildCount();
NSMutableArray* children = [NSMutableArray arrayWithCapacity:count];
for (auto child_iterator_ptr = _node->GetDelegate()->ChildrenBegin();
*child_iterator_ptr != *_node->GetDelegate()->ChildrenEnd(); ++(*child_iterator_ptr)) {
[children addObject:child_iterator_ptr->GetNativeViewAccessible()];
}
return NSAccessibilityUnignoredChildren(children);
}
- (id)AXWindowInternal {
return _node->GetDelegate()->GetNSWindow();
}
- (id)AXTopLevelUIElementInternal {
return [self AXWindowInternal];
}
- (NSValue*)AXPositionInternal {
return [NSValue valueWithPoint:self.boundsInScreen.origin];
}
- (NSValue*)AXSizeInternal {
return [NSValue valueWithSize:self.boundsInScreen.size];
}
- (NSString*)AXTitleInternal {
if (ui::IsNameExposedInAXValueForRole(_node->GetData().role))
return @"";
return [self getName];
}
- (NSNumber*)AXSelectedInternal {
return @(_node->GetData().GetBoolAttribute(ax::mojom::BoolAttribute::kSelected));
}
- (NSString*)AXPlaceholderValueInternal {
return [self getStringAttribute:ax::mojom::StringAttribute::kPlaceholder];
}
- (NSString*)AXMenuItemMarkChar {
if (!ui::IsMenuItem(_node->GetData().role))
return nil;
const auto checkedState = static_cast<ax::mojom::CheckedState>(
_node->GetIntAttribute(ax::mojom::IntAttribute::kCheckedState));
if (checkedState == ax::mojom::CheckedState::kTrue) {
return @"\xE2\x9C\x93"; // UTF-8 for unicode 0x2713, "check mark"
}
return @"";
}
- (NSString*)AXSelectedTextInternal {
NSRange selectedTextRange;
[[self AXSelectedTextRangeInternal] getValue:&selectedTextRange];
return [[self getAXValueAsString] substringWithRange:selectedTextRange];
}
- (NSValue*)AXSelectedTextRangeInternal {
int start = _node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart);
int end = _node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd);
NSAssert((start >= 0 && end >= 0) || (start == -1 && end == -1), @"selection is invalid");
if (start == -1 && end == -1) {
return [NSValue valueWithRange:{NSNotFound, 0}];
}
// NSRange cannot represent the direction the text was selected in.
return [NSValue valueWithRange:{static_cast<NSUInteger>(std::min(start, end)),
static_cast<NSUInteger>(abs(end - start))}];
}
- (NSNumber*)AXNumberOfCharactersInternal {
return @([[self getAXValueAsString] length]);
}
- (NSValue*)AXVisibleCharacterRangeInternal {
return [NSValue valueWithRange:{0, [[self getAXValueAsString] length]}];
}
- (NSNumber*)AXInsertionPointLineNumberInternal {
// Multiline is not supported on views.
return @0;
}
// Method based accessibility APIs.
- (NSString*)description {
return [NSString stringWithFormat:@"%@ - %@ (%@)", [super description], [self AXTitleInternal],
[self AXRoleInternal]];
}
// The methods below implement the NSAccessibility protocol. These methods
// appear to be the minimum needed to avoid AppKit refusing to handle the
// element or crashing internally. Most of the remaining old API methods (the
// ones from NSObject) are implemented in terms of the new NSAccessibility
// methods.
//
// TODO(https://crbug.com/386671): Does this class need to implement the various
// accessibilityPerformFoo methods, or are the stub implementations from
// NSAccessibilityElement sufficient?
- (NSArray*)accessibilityChildren {
return [self AXChildrenInternal];
}
- (BOOL)isAccessibilityElement {
if (!_node)
return NO;
return (![[self AXRoleInternal] isEqualToString:NSAccessibilityUnknownRole] &&
!_node->GetData().HasState(ax::mojom::State::kInvisible));
}
- (BOOL)isAccessibilityEnabled {
return [[self AXEnabledInternal] boolValue];
}
- (NSRect)accessibilityFrame {
return [self boundsInScreen];
}
- (NSString*)accessibilityLabel {
// accessibilityLabel is "a short description of the accessibility element",
// and accessibilityTitle is "the title of the accessibility element"; at
// least in Chromium, the title usually is a short description of the element,
// so it also functions as a label.
return [self AXTitleInternal];
}
- (NSString*)accessibilityTitle {
return [self AXTitleInternal];
}
- (id)accessibilityValue {
return [self AXValueInternal];
}
- (NSAccessibilityRole)accessibilityRole {
return [self AXRoleInternal];
}
- (NSString*)accessibilityRoleDescription {
return [self AXRoleDescriptionInternal];
}
- (NSAccessibilitySubrole)accessibilitySubrole {
return [self AXSubroleInternal];
}
- (NSString*)accessibilityHelp {
return [self AXHelpInternal];
}
- (id)accessibilityParent {
return [self AXParentInternal];
}
- (id)accessibilityWindow {
return [self AXWindowInternal];
}
- (id)accessibilityTopLevelUIElement {
return [self AXTopLevelUIElementInternal];
}
- (BOOL)accessibilitySelected {
return [[self AXSelectedInternal] boolValue];
}
- (BOOL)isAccessibilitySelectorAllowed:(SEL)selector {
if (!_node)
return NO;
const ax::mojom::Restriction restriction = _node->GetData().GetRestriction();
if (restriction == ax::mojom::Restriction::kDisabled)
return NO;
if (selector == @selector(setAccessibilityValue:)) {
// Tabs use the radio button role on Mac, so they are selected by calling
// setSelected on an individual tab, rather than by setting the selected
// element on the tabstrip as a whole.
if (_node->GetData().role == ax::mojom::Role::kTab) {
return !_node->GetData().GetBoolAttribute(ax::mojom::BoolAttribute::kSelected);
}
return restriction != ax::mojom::Restriction::kReadOnly;
}
// TODO(https://crbug.com/692362): Once the underlying bug in
// views::Textfield::SetSelectionRange() described in that bug is fixed,
// remove the check here; right now, this check serves to prevent
// accessibility clients from trying to set the selection range, which won't
// work because of 692362.
if (selector == @selector(setAccessibilitySelectedText:) ||
selector == @selector(setAccessibilitySelectedTextRange:) ||
selector == @selector(setAccessibilitySelectedTextMarkerRange:)) {
return restriction != ax::mojom::Restriction::kReadOnly;
}
if (selector == @selector(setAccessibilityFocused:))
return _node->GetData().HasState(ax::mojom::State::kFocusable);
// TODO(https://crbug.com/386671): What about role-specific selectors?
return [super isAccessibilitySelectorAllowed:selector];
}
- (void)setAccessibilityValue:(id)value {
if (!_node)
return;
ui::AXActionData data;
data.action = _node->GetData().role == ax::mojom::Role::kTab ? ax::mojom::Action::kSetSelection
: ax::mojom::Action::kSetValue;
if ([value isKindOfClass:[NSString class]]) {
data.value = std::string([value UTF8String]);
} else if ([value isKindOfClass:[NSValue class]]) {
// TODO(https://crbug.com/386671): Is this case actually needed? The
// NSObject accessibility implementation supported this, but can it actually
// occur?
NSRange range = [value rangeValue];
data.anchor_offset = range.location;
data.focus_offset = NSMaxRange(range);
}
_node->GetDelegate()->AccessibilityPerformAction(data);
}
- (void)setAccessibilityFocused:(BOOL)isFocused {
if (!_node)
return;
ui::AXActionData data;
data.action = isFocused ? ax::mojom::Action::kFocus : ax::mojom::Action::kBlur;
_node->GetDelegate()->AccessibilityPerformAction(data);
}
- (void)setAccessibilitySelectedText:(NSString*)text {
if (!_node)
return;
ui::AXActionData data;
data.action = ax::mojom::Action::kReplaceSelectedText;
data.value = std::string([text UTF8String]);
_node->GetDelegate()->AccessibilityPerformAction(data);
}
- (void)setAccessibilitySelectedTextRange:(NSRange)range {
if (!_node)
return;
ui::AXActionData data;
data.action = ax::mojom::Action::kSetSelection;
data.anchor_offset = range.location;
data.focus_offset = NSMaxRange(range);
_node->GetDelegate()->AccessibilityPerformAction(data);
}
// "Configuring Text Elements" section of the NSAccessibility formal protocol.
// These are all "required" methods, although in practice the ones that are left
// BASE_UNREACHABLE() seem to not be called anywhere (and were BASE_DCHECK false in
// the old API as well).
- (NSInteger)accessibilityInsertionPointLineNumber {
return [[self AXInsertionPointLineNumberInternal] integerValue];
}
- (NSInteger)accessibilityNumberOfCharacters {
if (!_node)
return 0;
return [[self AXNumberOfCharactersInternal] integerValue];
}
- (NSString*)accessibilityPlaceholderValue {
if (!_node)
return nil;
return [self AXPlaceholderValueInternal];
}
- (NSString*)accessibilitySelectedText {
if (!_node)
return nil;
return [self AXSelectedTextInternal];
}
- (NSRange)accessibilitySelectedTextRange {
if (!_node)
return NSMakeRange(0, 0);
NSRange r;
[[self AXSelectedTextRangeInternal] getValue:&r];
return r;
}
- (NSArray*)accessibilitySelectedTextRanges {
if (!_node)
return nil;
return @[ [self AXSelectedTextRangeInternal] ];
}
- (NSRange)accessibilitySharedCharacterRange {
if (!_node)
return NSMakeRange(0, 0);
NSRange r;
[[self AXSelectedTextRangeInternal] getValue:&r];
return r;
}
- (NSArray*)accessibilitySharedTextUIElements {
if (!_node)
return nil;
return @[ self ];
}
- (NSRange)accessibilityVisibleCharacterRange {
if (!_node)
return NSMakeRange(0, 0);
return [[self AXVisibleCharacterRangeInternal] rangeValue];
}
- (NSString*)accessibilityStringForRange:(NSRange)range {
if (!_node)
return nil;
return [[self getAXValueAsString] substringWithRange:range];
}
- (NSAttributedString*)accessibilityAttributedStringForRange:(NSRange)range {
if (!_node)
return nil;
// TODO(https://crbug.com/958811): Implement this for real.
base::scoped_nsobject<NSAttributedString> attributedString(
[[NSAttributedString alloc] initWithString:[self accessibilityStringForRange:range]]);
return attributedString.autorelease();
}
- (NSData*)accessibilityRTFForRange:(NSRange)range {
return nil;
}
- (NSRect)accessibilityFrameForRange:(NSRange)range {
return NSZeroRect;
}
- (NSInteger)accessibilityLineForIndex:(NSInteger)index {
// Views textfields are single-line.
return 0;
}
- (NSRange)accessibilityRangeForIndex:(NSInteger)index {
BASE_UNREACHABLE();
return NSMakeRange(0, 0);
}
- (NSRange)accessibilityStyleRangeForIndex:(NSInteger)index {
if (!_node)
return NSMakeRange(0, 0);
// TODO(https://crbug.com/958811): Implement this for real.
return NSMakeRange(0, [self accessibilityNumberOfCharacters]);
}
- (NSRange)accessibilityRangeForLine:(NSInteger)line {
if (!_node)
return NSMakeRange(0, 0);
if (line != 0) {
BASE_LOG() << "Views textfields are single-line.";
BASE_UNREACHABLE();
}
return NSMakeRange(0, [self accessibilityNumberOfCharacters]);
}
- (NSRange)accessibilityRangeForPosition:(NSPoint)point {
// TODO(a-wallen): Framework needs to send Text Metrics
// to the AXTree in order for a NSPoint (x, y) to be
// translated to the appropriate range of UTF-16 chars.
return NSMakeRange(0, 0);
}
// "Setting the Focus" section of the NSAccessibility formal protocol.
// These are all "required" methods.
- (NSArray*)accessibilitySharedFocusElements {
if (![[self AXFocusedInternal] boolValue])
return nil;
return @[ self ];
}
- (id)accessibilityFocusedWindow {
if (![[self AXFocusedInternal] boolValue])
return nil;
return self;
}
- (id)accessibilityApplicationFocusedUIElement {
if (![[self AXFocusedInternal] boolValue])
return nil;
return self;
}
- (BOOL)isAccessibilityFocused {
return [[self AXFocusedInternal] boolValue];
}
@end
namespace ui {
// static
AXPlatformNode* AXPlatformNode::Create(AXPlatformNodeDelegate* delegate) {
AXPlatformNodeBase* node = new AXPlatformNodeMac();
node->Init(delegate);
return node;
}
// static
AXPlatformNode* AXPlatformNode::FromNativeViewAccessible(gfx::NativeViewAccessible accessible) {
if ([accessible isKindOfClass:[AXPlatformNodeCocoa class]])
return [accessible node];
return nullptr;
}
AXPlatformNodeMac::AXPlatformNodeMac() {}
AXPlatformNodeMac::~AXPlatformNodeMac() {}
void AXPlatformNodeMac::Destroy() {
if (native_node_)
[native_node_ detach];
AXPlatformNodeBase::Destroy();
}
// On Mac, the checked state is mapped to AXValue.
bool AXPlatformNodeMac::IsPlatformCheckable() const {
if (GetData().role == ax::mojom::Role::kTab) {
// On Mac, tabs are exposed as radio buttons, and are treated as checkable.
// Also, the internal State::kSelected is be mapped to checked via AXValue.
return true;
}
return AXPlatformNodeBase::IsPlatformCheckable();
}
gfx::NativeViewAccessible AXPlatformNodeMac::GetNativeViewAccessible() {
if (!native_node_)
native_node_.reset([[AXPlatformNodeCocoa alloc] initWithNode:this]);
return native_node_.get();
}
void AXPlatformNodeMac::NotifyAccessibilityEvent(ax::mojom::Event event_type) {
AXPlatformNodeBase::NotifyAccessibilityEvent(event_type);
GetNativeViewAccessible();
// Handle special cases.
// Alerts and live regions go through the announcement API instead of the
// regular NSAccessibility notification system.
if (event_type == ax::mojom::Event::kAlert ||
event_type == ax::mojom::Event::kLiveRegionChanged) {
if (auto announcement = [native_node_ announcementForEvent:event_type]) {
[native_node_ scheduleLiveRegionAnnouncement:std::move(announcement)];
}
return;
}
if (event_type == ax::mojom::Event::kSelection) {
ax::mojom::Role role = GetData().role;
if (ui::IsMenuItem(role)) {
// On Mac, map menu item selection to a focus event.
NotifyMacEvent(native_node_, ax::mojom::Event::kFocus);
return;
} else if (ui::IsListItem(role)) {
if (AXPlatformNodeBase* container = GetSelectionContainer()) {
const ui::AXNodeData& data = container->GetData();
if (data.role == ax::mojom::Role::kListBox &&
!data.HasState(ax::mojom::State::kMultiselectable) &&
GetDelegate()->GetFocus() == GetNativeViewAccessible()) {
NotifyMacEvent(native_node_, ax::mojom::Event::kFocus);
return;
}
}
}
}
// Otherwise, use mappings between ax::mojom::Event and NSAccessibility
// notifications from the EventMap above.
NotifyMacEvent(native_node_, event_type);
}
void AXPlatformNodeMac::AnnounceText(const std::u16string& text) {
PostAnnouncementNotification(@(base::UTF16ToUTF8(text).data()), [native_node_ AXWindowInternal],
false);
}
bool IsNameExposedInAXValueForRole(ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kListBoxOption:
case ax::mojom::Role::kListMarker:
case ax::mojom::Role::kMenuListOption:
case ax::mojom::Role::kStaticText:
case ax::mojom::Role::kTitleBar:
return true;
default:
return false;
}
}
void AXPlatformNodeMac::AddAttributeToList(const char* name,
const char* value,
PlatformAttributeList* attributes) {
BASE_UNREACHABLE();
}
} // namespace ui
| engine/third_party/accessibility/ax/platform/ax_platform_node_mac.mm/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_mac.mm",
"repo_id": "engine",
"token_count": 16095
} | 399 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_RELATION_WIN_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_RELATION_WIN_H_
#include <oleacc.h>
#include <wrl/client.h>
#include <set>
#include <vector>
#include "base/compiler_specific.h"
#include "base/metrics/histogram_macros.h"
#include "base/observer_list.h"
#include "base/win/atl.h"
#include "third_party/iaccessible2/ia2_api_all.h"
#include "ui/accessibility/ax_export.h"
#include "ui/accessibility/ax_text_utils.h"
#include "ui/accessibility/platform/ax_platform_node_win.h"
namespace ui {
//
// AXPlatformRelationWin
//
// A simple implementation of IAccessibleRelation, used to represent a
// relationship between one accessible node in the tree and
// potentially multiple target nodes. Also contains a utility function
// to compute all of the possible IAccessible2 relations and reverse
// relations given the internal relation id attributes.
class AXPlatformRelationWin : public CComObjectRootEx<CComMultiThreadModel>,
public IAccessibleRelation {
public:
BEGIN_COM_MAP(AXPlatformRelationWin)
COM_INTERFACE_ENTRY(IAccessibleRelation)
END_COM_MAP()
AXPlatformRelationWin();
virtual ~AXPlatformRelationWin();
// This is the main utility function that enumerates all of the possible
// IAccessible2 relations between one node and any other node in the tree.
// Forward relations come from the int_attributes and intlist_attributes
// in node_data. Reverse relations come from querying |delegate| for the
// reverse relations given |node_data.id|.
//
// If you pass -1 for |desired_index| and "" for |desired_ia2_relation|,
// it will return a count of all relations.
//
// If you pass either an index in |desired_index| or a specific relation
// in |desired_ia2_relation|, the first matching relation will be returned in
// |out_ia2_relation| and |out_targets| (both of which must not be null),
// and it will return 1 on success, and 0 if none were found matching that
// criteria.
static int EnumerateRelationships(AXPlatformNodeBase* node,
int desired_index,
const base::string16& desired_ia2_relation,
base::string16* out_ia2_relation,
std::set<AXPlatformNode*>* out_targets);
void Initialize(const base::string16& type);
void Invalidate();
void AddTarget(AXPlatformNodeWin* target);
// IAccessibleRelation methods.
IFACEMETHODIMP get_relationType(BSTR* relation_type) override;
IFACEMETHODIMP get_nTargets(LONG* n_targets) override;
IFACEMETHODIMP get_target(LONG target_index, IUnknown** target) override;
IFACEMETHODIMP get_targets(LONG max_targets,
IUnknown** targets,
LONG* n_targets) override;
IFACEMETHODIMP get_localizedRelationType(BSTR* relation_type) override;
private:
base::string16 type_;
std::vector<Microsoft::WRL::ComPtr<AXPlatformNodeWin>> targets_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_RELATION_WIN_H_
| engine/third_party/accessibility/ax/platform/ax_platform_relation_win.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_relation_win.h",
"repo_id": "engine",
"token_count": 1207
} | 400 |
// 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.
// This file adds defines about the platform we're currently building on.
//
// Operating System:
// OS_AIX / OS_ANDROID / OS_ASMJS / OS_FREEBSD / OS_FUCHSIA / OS_IOS /
// OS_LINUX / OS_MAC / OS_NACL (SFI or NONSFI) / OS_NETBSD / OS_OPENBSD /
// OS_QNX / OS_SOLARIS / OS_WIN
// Operating System family:
// OS_APPLE: IOS or MAC
// OS_BSD: FREEBSD or NETBSD or OPENBSD
// OS_POSIX: AIX or ANDROID or ASMJS or CHROMEOS or FREEBSD or IOS or LINUX
// or MAC or NACL or NETBSD or OPENBSD or QNX or SOLARIS
//
// /!\ Note: OS_CHROMEOS is set by the build system, not this file
//
// Compiler:
// COMPILER_MSVC / COMPILER_GCC
//
// Processor:
// ARCH_CPU_ARM64 / ARCH_CPU_ARMEL / ARCH_CPU_MIPS / ARCH_CPU_MIPS64 /
// ARCH_CPU_MIPS64EL / ARCH_CPU_MIPSEL / ARCH_CPU_PPC64 / ARCH_CPU_S390 /
// ARCH_CPU_S390X / ARCH_CPU_X86 / ARCH_CPU_X86_64
// Processor family:
// ARCH_CPU_ARM_FAMILY: ARMEL or ARM64
// ARCH_CPU_MIPS_FAMILY: MIPS64EL or MIPSEL or MIPS64 or MIPS
// ARCH_CPU_PPC64_FAMILY: PPC64
// ARCH_CPU_S390_FAMILY: S390 or S390X
// ARCH_CPU_X86_FAMILY: X86 or X86_64
// Processor features:
// ARCH_CPU_31_BITS / ARCH_CPU_32_BITS / ARCH_CPU_64_BITS
// ARCH_CPU_BIG_ENDIAN / ARCH_CPU_LITTLE_ENDIAN
#ifndef UI_ACCESSIBILITY_BUILD_BUILD_CONFIG_H_
#define UI_ACCESSIBILITY_BUILD_BUILD_CONFIG_H_
// A set of macros to use for platform detection.
#if defined(__native_client__)
// __native_client__ must be first, so that other OS_ defines are not set.
#define OS_NACL 1
// OS_NACL comes in two sandboxing technology flavors, SFI or Non-SFI.
// PNaCl toolchain defines __native_client_nonsfi__ macro in Non-SFI build
// mode, while it does not in SFI build mode.
#if defined(__native_client_nonsfi__)
#define OS_NACL_NONSFI
#else
#define OS_NACL_SFI
#endif
#elif defined(ANDROID)
#define OS_ANDROID 1
#elif defined(__APPLE__)
// Only include TargetConditionals after testing ANDROID as some Android builds
// on the Mac have this header available and it's not needed unless the target
// is really an Apple platform.
#include <TargetConditionals.h>
#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
#define OS_IOS 1
#else
#define OS_MAC 1
#endif // defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
#elif defined(__linux__)
#define OS_LINUX 1
// Include a system header to pull in features.h for glibc/uclibc macros.
#include <unistd.h>
#if defined(__GLIBC__) && !defined(__UCLIBC__)
// We really are using glibc, not uClibc pretending to be glibc.
#define LIBC_GLIBC 1
#endif
#elif defined(_WIN32)
#define OS_WIN 1
#elif defined(__Fuchsia__)
#define OS_FUCHSIA 1
#elif defined(__FreeBSD__)
#define OS_FREEBSD 1
#elif defined(__NetBSD__)
#define OS_NETBSD 1
#elif defined(__OpenBSD__)
#define OS_OPENBSD 1
#elif defined(__sun)
#define OS_SOLARIS 1
#elif defined(__QNXNTO__)
#define OS_QNX 1
#elif defined(_AIX)
#define OS_AIX 1
#elif defined(__asmjs__) || defined(__wasm__)
#define OS_ASMJS 1
#else
#error Please add support for your platform in build/build_config.h
#endif
// NOTE: Adding a new port? Please follow
// https://chromium.googlesource.com/chromium/src/+/master/docs/new_port_policy.md
#if defined(OS_MAC) || defined(OS_IOS)
#define OS_APPLE 1
#endif
// For access to standard BSD features, use OS_BSD instead of a
// more specific macro.
#if defined(OS_FREEBSD) || defined(OS_NETBSD) || defined(OS_OPENBSD)
#define OS_BSD 1
#endif
// For access to standard POSIXish features, use OS_POSIX instead of a
// more specific macro.
#if defined(OS_AIX) || defined(OS_ANDROID) || defined(OS_ASMJS) || \
defined(OS_FREEBSD) || defined(OS_IOS) || defined(OS_LINUX) || \
defined(OS_CHROMEOS) || defined(OS_MAC) || defined(OS_NACL) || \
defined(OS_NETBSD) || defined(OS_OPENBSD) || defined(OS_QNX) || \
defined(OS_SOLARIS)
#define OS_POSIX 1
#endif
// Compiler detection. Note: clang masquerades as GCC on POSIX and as MSVC on
// Windows.
#if defined(__GNUC__)
#define COMPILER_GCC 1
#elif defined(_MSC_VER)
#define COMPILER_MSVC 1
#else
#error Please add support for your compiler in build/build_config.h
#endif
// Processor architecture detection. For more info on what's defined, see:
// http://msdn.microsoft.com/en-us/library/b0084kay.aspx
// http://www.agner.org/optimize/calling_conventions.pdf
// or with gcc, run: "echo | gcc -E -dM -"
#if defined(_M_X64) || defined(__x86_64__)
#define ARCH_CPU_X86_FAMILY 1
#define ARCH_CPU_X86_64 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(_M_IX86) || defined(__i386__)
#define ARCH_CPU_X86_FAMILY 1
#define ARCH_CPU_X86 1
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(__s390x__)
#define ARCH_CPU_S390_FAMILY 1
#define ARCH_CPU_S390X 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_BIG_ENDIAN 1
#elif defined(__s390__)
#define ARCH_CPU_S390_FAMILY 1
#define ARCH_CPU_S390 1
#define ARCH_CPU_31_BITS 1
#define ARCH_CPU_BIG_ENDIAN 1
#elif (defined(__PPC64__) || defined(__PPC__)) && defined(__BIG_ENDIAN__)
#define ARCH_CPU_PPC64_FAMILY 1
#define ARCH_CPU_PPC64 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_BIG_ENDIAN 1
#elif defined(__PPC64__)
#define ARCH_CPU_PPC64_FAMILY 1
#define ARCH_CPU_PPC64 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(__ARMEL__)
#define ARCH_CPU_ARM_FAMILY 1
#define ARCH_CPU_ARMEL 1
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(__aarch64__) || defined(_M_ARM64)
#define ARCH_CPU_ARM_FAMILY 1
#define ARCH_CPU_ARM64 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(__pnacl__) || defined(__asmjs__) || defined(__wasm__)
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(__MIPSEL__)
#if defined(__LP64__)
#define ARCH_CPU_MIPS_FAMILY 1
#define ARCH_CPU_MIPS64EL 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#else
#define ARCH_CPU_MIPS_FAMILY 1
#define ARCH_CPU_MIPSEL 1
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#endif
#elif defined(__MIPSEB__)
#if defined(__LP64__)
#define ARCH_CPU_MIPS_FAMILY 1
#define ARCH_CPU_MIPS64 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_BIG_ENDIAN 1
#else
#define ARCH_CPU_MIPS_FAMILY 1
#define ARCH_CPU_MIPS 1
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_BIG_ENDIAN 1
#endif
#else
#error Please add support for your architecture in build/build_config.h
#endif
// Type detection for wchar_t.
#if defined(OS_WIN)
#define WCHAR_T_IS_UTF16
#elif defined(OS_FUCHSIA)
#define WCHAR_T_IS_UTF32
#elif defined(OS_POSIX) && defined(COMPILER_GCC) && defined(__WCHAR_MAX__) && \
(__WCHAR_MAX__ == 0x7fffffff || __WCHAR_MAX__ == 0xffffffff)
#define WCHAR_T_IS_UTF32
#elif defined(OS_POSIX) && defined(COMPILER_GCC) && defined(__WCHAR_MAX__) && \
(__WCHAR_MAX__ == 0x7fff || __WCHAR_MAX__ == 0xffff)
// On Posix, we'll detect short wchar_t, but projects aren't guaranteed to
// compile in this mode (in particular, Chrome doesn't). This is intended for
// other projects using base who manage their own dependencies and make sure
// short wchar works for them.
#define WCHAR_T_IS_UTF16
#else
#error Please add support for your compiler in build/build_config.h
#endif
#if defined(OS_ANDROID)
// The compiler thinks std::string::const_iterator and "const char*" are
// equivalent types.
#define STD_STRING_ITERATOR_IS_CHAR_POINTER
// The compiler thinks std::u16string::const_iterator and "char16*" are
// equivalent types.
#define BASE_STRING16_ITERATOR_IS_CHAR16_POINTER
#endif
#endif // UI_ACCESSIBILITY_BUILD_BUILD_CONFIG_H_
| engine/third_party/accessibility/ax_build/build_config.h/0 | {
"file_path": "engine/third_party/accessibility/ax_build/build_config.h",
"repo_id": "engine",
"token_count": 3124
} | 401 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_NUMERICS_CLAMPED_MATH_H_
#define BASE_NUMERICS_CLAMPED_MATH_H_
#include <cstddef>
#include <limits>
#include <type_traits>
#include "base/numerics/clamped_math_impl.h"
namespace base {
namespace internal {
template <typename T>
class ClampedNumeric {
static_assert(std::is_arithmetic<T>::value,
"ClampedNumeric<T>: T must be a numeric type.");
public:
using type = T;
constexpr ClampedNumeric() : value_(0) {}
// Copy constructor.
template <typename Src>
constexpr ClampedNumeric(const ClampedNumeric<Src>& rhs)
: value_(saturated_cast<T>(rhs.value_)) {}
template <typename Src>
friend class ClampedNumeric;
// This is not an explicit constructor because we implicitly upgrade regular
// numerics to ClampedNumerics to make them easier to use.
template <typename Src>
constexpr ClampedNumeric(Src value) // NOLINT(runtime/explicit)
: value_(saturated_cast<T>(value)) {
static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric.");
}
// This is not an explicit constructor because we want a seamless conversion
// from StrictNumeric types.
template <typename Src>
constexpr ClampedNumeric(
StrictNumeric<Src> value) // NOLINT(runtime/explicit)
: value_(saturated_cast<T>(static_cast<Src>(value))) {}
// Returns a ClampedNumeric of the specified type, cast from the current
// ClampedNumeric, and saturated to the destination type.
template <typename Dst>
constexpr ClampedNumeric<typename UnderlyingType<Dst>::type> Cast() const {
return *this;
}
// Prototypes for the supported arithmetic operator overloads.
template <typename Src>
constexpr ClampedNumeric& operator+=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator-=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator*=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator/=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator%=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator<<=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator>>=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator&=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator|=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator^=(const Src rhs);
constexpr ClampedNumeric operator-() const {
// The negation of two's complement int min is int min, so that's the
// only overflow case where we will saturate.
return ClampedNumeric<T>(SaturatedNegWrapper(value_));
}
constexpr ClampedNumeric operator~() const {
return ClampedNumeric<decltype(InvertWrapper(T()))>(InvertWrapper(value_));
}
constexpr ClampedNumeric Abs() const {
// The negation of two's complement int min is int min, so that's the
// only overflow case where we will saturate.
return ClampedNumeric<T>(SaturatedAbsWrapper(value_));
}
template <typename U>
constexpr ClampedNumeric<typename MathWrapper<ClampedMaxOp, T, U>::type> Max(
const U rhs) const {
using result_type = typename MathWrapper<ClampedMaxOp, T, U>::type;
return ClampedNumeric<result_type>(
ClampedMaxOp<T, U>::Do(value_, Wrapper<U>::value(rhs)));
}
template <typename U>
constexpr ClampedNumeric<typename MathWrapper<ClampedMinOp, T, U>::type> Min(
const U rhs) const {
using result_type = typename MathWrapper<ClampedMinOp, T, U>::type;
return ClampedNumeric<result_type>(
ClampedMinOp<T, U>::Do(value_, Wrapper<U>::value(rhs)));
}
// This function is available only for integral types. It returns an unsigned
// integer of the same width as the source type, containing the absolute value
// of the source, and properly handling signed min.
constexpr ClampedNumeric<typename UnsignedOrFloatForSize<T>::type>
UnsignedAbs() const {
return ClampedNumeric<typename UnsignedOrFloatForSize<T>::type>(
SafeUnsignedAbs(value_));
}
constexpr ClampedNumeric& operator++() {
*this += 1;
return *this;
}
constexpr ClampedNumeric operator++(int) {
ClampedNumeric value = *this;
*this += 1;
return value;
}
constexpr ClampedNumeric& operator--() {
*this -= 1;
return *this;
}
constexpr ClampedNumeric operator--(int) {
ClampedNumeric value = *this;
*this -= 1;
return value;
}
// These perform the actual math operations on the ClampedNumerics.
// Binary arithmetic operations.
template <template <typename, typename, typename> class M,
typename L,
typename R>
static constexpr ClampedNumeric MathOp(const L lhs, const R rhs) {
using Math = typename MathWrapper<M, L, R>::math;
return ClampedNumeric<T>(
Math::template Do<T>(Wrapper<L>::value(lhs), Wrapper<R>::value(rhs)));
}
// Assignment arithmetic operations.
template <template <typename, typename, typename> class M, typename R>
constexpr ClampedNumeric& MathOp(const R rhs) {
using Math = typename MathWrapper<M, T, R>::math;
*this =
ClampedNumeric<T>(Math::template Do<T>(value_, Wrapper<R>::value(rhs)));
return *this;
}
template <typename Dst>
constexpr operator Dst() const {
return saturated_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(
value_);
}
// This method extracts the raw integer value without saturating it to the
// destination type as the conversion operator does. This is useful when
// e.g. assigning to an auto type or passing as a deduced template parameter.
constexpr T RawValue() const { return value_; }
private:
T value_;
// These wrappers allow us to handle state the same way for both
// ClampedNumeric and POD arithmetic types.
template <typename Src>
struct Wrapper {
static constexpr Src value(Src value) {
return static_cast<typename UnderlyingType<Src>::type>(value);
}
};
};
// Convience wrapper to return a new ClampedNumeric from the provided arithmetic
// or ClampedNumericType.
template <typename T>
constexpr ClampedNumeric<typename UnderlyingType<T>::type> MakeClampedNum(
const T value) {
return value;
}
#if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS
// Overload the ostream output operator to make logging work nicely.
template <typename T>
std::ostream& operator<<(std::ostream& os, const ClampedNumeric<T>& value) {
os << static_cast<T>(value);
return os;
}
#endif
// These implement the variadic wrapper for the math operations.
template <template <typename, typename, typename> class M,
typename L,
typename R>
constexpr ClampedNumeric<typename MathWrapper<M, L, R>::type> ClampMathOp(
const L lhs,
const R rhs) {
using Math = typename MathWrapper<M, L, R>::math;
return ClampedNumeric<typename Math::result_type>::template MathOp<M>(lhs,
rhs);
}
// General purpose wrapper template for arithmetic operations.
template <template <typename, typename, typename> class M,
typename L,
typename R,
typename... Args>
constexpr ClampedNumeric<typename ResultType<M, L, R, Args...>::type>
ClampMathOp(const L lhs, const R rhs, const Args... args) {
return ClampMathOp<M>(ClampMathOp<M>(lhs, rhs), args...);
}
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Add, +, +=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Sub, -, -=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Mul, *, *=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Div, /, /=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Mod, %, %=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Lsh, <<, <<=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Rsh, >>, >>=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, And, &, &=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Or, |, |=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Xor, ^, ^=)
BASE_NUMERIC_ARITHMETIC_VARIADIC(Clamped, Clamp, Max)
BASE_NUMERIC_ARITHMETIC_VARIADIC(Clamped, Clamp, Min)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsLess, <)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsLessOrEqual, <=)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsGreater, >)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsGreaterOrEqual, >=)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsEqual, ==)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsNotEqual, !=)
} // namespace internal
using internal::ClampAdd;
using internal::ClampAnd;
using internal::ClampDiv;
using internal::ClampedNumeric;
using internal::ClampLsh;
using internal::ClampMax;
using internal::ClampMin;
using internal::ClampMod;
using internal::ClampMul;
using internal::ClampOr;
using internal::ClampRsh;
using internal::ClampSub;
using internal::ClampXor;
using internal::MakeClampedNum;
} // namespace base
#endif // BASE_NUMERICS_CLAMPED_MATH_H_
| engine/third_party/accessibility/base/numerics/clamped_math.h/0 | {
"file_path": "engine/third_party/accessibility/base/numerics/clamped_math.h",
"repo_id": "engine",
"token_count": 3374
} | 402 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_STRING_UTILS_H_
#define BASE_STRING_UTILS_H_
#include <memory>
#include <string>
#include <vector>
namespace base {
constexpr char16_t kWhitespaceUTF16 = u' ';
// Return a C++ string given printf-like input.
template <typename... Args>
std::string StringPrintf(const std::string& format, Args... args) {
// Calculate the buffer size.
int size = snprintf(nullptr, 0, format.c_str(), args...) + 1;
std::unique_ptr<char[]> buf = std::make_unique<char[]>(size);
snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), buf.get() + size - 1);
}
std::u16string ASCIIToUTF16(std::string src);
std::u16string UTF8ToUTF16(std::string src);
std::string UTF16ToUTF8(std::u16string src);
std::u16string NumberToString16(unsigned int number);
std::u16string NumberToString16(int32_t number);
std::u16string NumberToString16(float number);
std::u16string NumberToString16(double number);
std::string NumberToString(unsigned int number);
std::string NumberToString(int32_t number);
std::string NumberToString(float number);
std::string NumberToString(double number);
std::string ToUpperASCII(std::string str);
std::string ToLowerASCII(std::string str);
std::string JoinString(std::vector<std::string> tokens, std::string delimiter);
std::u16string JoinString(std::vector<std::u16string> tokens,
std::u16string delimiter);
void ReplaceChars(std::string in,
std::string from,
std::string to,
std::string* out);
void ReplaceChars(std::u16string in,
std::u16string from,
std::u16string to,
std::u16string* out);
bool LowerCaseEqualsASCII(std::string a, std::string b);
bool ContainsOnlyChars(std::u16string str, char16_t ch);
const std::string& EmptyString();
} // namespace base
#endif // BASE_STRING_UTILS_H_
| engine/third_party/accessibility/base/string_utils.h/0 | {
"file_path": "engine/third_party/accessibility/base/string_utils.h",
"repo_id": "engine",
"token_count": 772
} | 403 |
// 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 BASE_WIN_SCOPED_SAFEARRAY_H_
#define BASE_WIN_SCOPED_SAFEARRAY_H_
#include <objbase.h>
#include <optional>
#include "base/base_export.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/win/variant_util.h"
namespace base {
namespace win {
// Manages a Windows SAFEARRAY. This is a minimal wrapper that simply provides
// RAII semantics and does not duplicate the extensive functionality that
// CComSafeArray offers.
class BASE_EXPORT ScopedSafearray {
public:
// LockScope<VARTYPE> class for automatically managing the lifetime of a
// SAFEARRAY lock, and granting easy access to the underlying data either
// through random access or as an iterator.
// It is undefined behavior if the underlying SAFEARRAY is destroyed
// before the LockScope.
// LockScope implements std::iterator_traits as a random access iterator, so
// that LockScope is compatible with STL methods that require these traits.
template <VARTYPE ElementVartype>
class BASE_EXPORT LockScope final {
public:
// Type declarations to support std::iterator_traits
using iterator_category = std::random_access_iterator_tag;
using value_type = typename internal::VariantUtil<ElementVartype>::Type;
using difference_type = ptrdiff_t;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
LockScope()
: safearray_(nullptr),
vartype_(VT_EMPTY),
array_(nullptr),
array_size_(0U) {}
LockScope(LockScope<ElementVartype>&& other)
: safearray_(std::exchange(other.safearray_, nullptr)),
vartype_(std::exchange(other.vartype_, VT_EMPTY)),
array_(std::exchange(other.array_, nullptr)),
array_size_(std::exchange(other.array_size_, 0U)) {}
LockScope<ElementVartype>& operator=(LockScope<ElementVartype>&& other) {
BASE_DCHECK(this != &other);
Reset();
safearray_ = std::exchange(other.safearray_, nullptr);
vartype_ = std::exchange(other.vartype_, VT_EMPTY);
array_ = std::exchange(other.array_, nullptr);
array_size_ = std::exchange(other.array_size_, 0U);
return *this;
}
~LockScope() { Reset(); }
VARTYPE Type() const { return vartype_; }
size_t size() const { return array_size_; }
pointer begin() { return array_; }
pointer end() { return array_ + array_size_; }
const_pointer begin() const { return array_; }
const_pointer end() const { return array_ + array_size_; }
pointer data() { return array_; }
const_pointer data() const { return array_; }
reference operator[](int index) { return at(index); }
const_reference operator[](int index) const { return at(index); }
reference at(size_t index) {
BASE_DCHECK(array_ != nullptr);
BASE_DCHECK(index < array_size_);
return array_[index];
}
const_reference at(size_t index) const {
return const_cast<LockScope<ElementVartype>*>(this)->at(index);
}
private:
LockScope(SAFEARRAY* safearray,
VARTYPE vartype,
pointer array,
size_t array_size)
: safearray_(safearray),
vartype_(vartype),
array_(array),
array_size_(array_size) {}
void Reset() {
if (safearray_)
SafeArrayUnaccessData(safearray_);
safearray_ = nullptr;
vartype_ = VT_EMPTY;
array_ = nullptr;
array_size_ = 0U;
}
SAFEARRAY* safearray_;
VARTYPE vartype_;
pointer array_;
size_t array_size_;
friend class ScopedSafearray;
BASE_DISALLOW_COPY_AND_ASSIGN(LockScope);
};
explicit ScopedSafearray(SAFEARRAY* safearray = nullptr)
: safearray_(safearray) {}
// Move constructor
ScopedSafearray(ScopedSafearray&& r) noexcept : safearray_(r.safearray_) {
r.safearray_ = nullptr;
}
// Move operator=. Allows assignment from a ScopedSafearray rvalue.
ScopedSafearray& operator=(ScopedSafearray&& rvalue) {
Reset(rvalue.Release());
return *this;
}
~ScopedSafearray() { Destroy(); }
// Creates a LockScope for accessing the contents of a
// single-dimensional SAFEARRAYs.
template <VARTYPE ElementVartype>
std::optional<LockScope<ElementVartype>> CreateLockScope() const {
if (!safearray_ || SafeArrayGetDim(safearray_) != 1)
return std::nullopt;
VARTYPE vartype;
HRESULT hr = SafeArrayGetVartype(safearray_, &vartype);
if (FAILED(hr) ||
!internal::VariantUtil<ElementVartype>::IsConvertibleTo(vartype)) {
return std::nullopt;
}
typename LockScope<ElementVartype>::pointer array = nullptr;
hr = SafeArrayAccessData(safearray_, reinterpret_cast<void**>(&array));
if (FAILED(hr))
return std::nullopt;
const size_t array_size = GetCount();
return LockScope<ElementVartype>(safearray_, vartype, array, array_size);
}
void Destroy() {
if (safearray_) {
HRESULT hr = SafeArrayDestroy(safearray_);
BASE_DCHECK(S_OK == hr);
safearray_ = nullptr;
}
}
// Give ScopedSafearray ownership over an already allocated SAFEARRAY or
// nullptr.
void Reset(SAFEARRAY* safearray = nullptr) {
if (safearray != safearray_) {
Destroy();
safearray_ = safearray;
}
}
// Releases ownership of the SAFEARRAY to the caller.
SAFEARRAY* Release() {
SAFEARRAY* safearray = safearray_;
safearray_ = nullptr;
return safearray;
}
// Retrieves the pointer address.
// Used to receive SAFEARRAYs as out arguments (and take ownership).
// This function releases any existing references because it will leak
// the existing ref otherwise.
// Usage: GetSafearray(safearray.Receive());
SAFEARRAY** Receive() {
Destroy();
return &safearray_;
}
// Returns the number of elements in a dimension of the array.
size_t GetCount(UINT dimension = 0) const {
BASE_DCHECK(safearray_);
// Initialize |lower| and |upper| so this method will return zero if either
// SafeArrayGetLBound or SafeArrayGetUBound returns failure because they
// only write to the output parameter when successful.
LONG lower = 0;
LONG upper = -1;
BASE_DCHECK(dimension < SafeArrayGetDim(safearray_));
HRESULT hr = SafeArrayGetLBound(safearray_, dimension + 1, &lower);
BASE_DCHECK(SUCCEEDED(hr));
hr = SafeArrayGetUBound(safearray_, dimension + 1, &upper);
BASE_DCHECK(SUCCEEDED(hr));
return (upper - lower + 1);
}
// Returns the internal pointer.
SAFEARRAY* Get() const { return safearray_; }
// Forbid comparison of ScopedSafearray types. You should never have the same
// SAFEARRAY owned by two different scoped_ptrs.
bool operator==(const ScopedSafearray& safearray2) const = delete;
bool operator!=(const ScopedSafearray& safearray2) const = delete;
private:
SAFEARRAY* safearray_;
BASE_DISALLOW_COPY_AND_ASSIGN(ScopedSafearray);
};
} // namespace win
} // namespace base
#endif // BASE_WIN_SCOPED_SAFEARRAY_H_
| engine/third_party/accessibility/base/win/scoped_safearray.h/0 | {
"file_path": "engine/third_party/accessibility/base/win/scoped_safearray.h",
"repo_id": "engine",
"token_count": 2717
} | 404 |
// 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 "point.h"
#include "ax_build/build_config.h"
#include "base/string_utils.h"
#include "point_conversions.h"
#include "point_f.h"
#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_IOS)
#include <CoreGraphics/CoreGraphics.h>
#elif defined(OS_APPLE)
#include <ApplicationServices/ApplicationServices.h>
#endif
namespace gfx {
#if defined(OS_WIN)
Point::Point(DWORD point) {
POINTS points = MAKEPOINTS(point);
x_ = points.x;
y_ = points.y;
}
Point::Point(const POINT& point) : x_(point.x), y_(point.y) {}
Point& Point::operator=(const POINT& point) {
x_ = point.x;
y_ = point.y;
return *this;
}
#elif defined(OS_APPLE)
Point::Point(const CGPoint& point) : x_(point.x), y_(point.y) {}
#endif
#if defined(OS_WIN)
POINT Point::ToPOINT() const {
POINT p;
p.x = x();
p.y = y();
return p;
}
#elif defined(OS_APPLE)
CGPoint Point::ToCGPoint() const {
return CGPointMake(x(), y());
}
#endif
void Point::SetToMin(const Point& other) {
x_ = x_ <= other.x_ ? x_ : other.x_;
y_ = y_ <= other.y_ ? y_ : other.y_;
}
void Point::SetToMax(const Point& other) {
x_ = x_ >= other.x_ ? x_ : other.x_;
y_ = y_ >= other.y_ ? y_ : other.y_;
}
std::string Point::ToString() const {
return base::StringPrintf("%d,%d", x(), y());
}
Point ScaleToCeiledPoint(const Point& point, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return point;
return ToCeiledPoint(ScalePoint(gfx::PointF(point), x_scale, y_scale));
}
Point ScaleToCeiledPoint(const Point& point, float scale) {
if (scale == 1.f)
return point;
return ToCeiledPoint(ScalePoint(gfx::PointF(point), scale, scale));
}
Point ScaleToFlooredPoint(const Point& point, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return point;
return ToFlooredPoint(ScalePoint(gfx::PointF(point), x_scale, y_scale));
}
Point ScaleToFlooredPoint(const Point& point, float scale) {
if (scale == 1.f)
return point;
return ToFlooredPoint(ScalePoint(gfx::PointF(point), scale, scale));
}
Point ScaleToRoundedPoint(const Point& point, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return point;
return ToRoundedPoint(ScalePoint(gfx::PointF(point), x_scale, y_scale));
}
Point ScaleToRoundedPoint(const Point& point, float scale) {
if (scale == 1.f)
return point;
return ToRoundedPoint(ScalePoint(gfx::PointF(point), scale, scale));
}
} // namespace gfx
| engine/third_party/accessibility/gfx/geometry/point.cc/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/point.cc",
"repo_id": "engine",
"token_count": 1009
} | 405 |
// 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 "size_conversions.h"
#include "base/numerics/safe_conversions.h"
namespace gfx {
Size ToFlooredSize(const SizeF& size) {
return Size(base::ClampFloor(size.width()), base::ClampFloor(size.height()));
}
Size ToCeiledSize(const SizeF& size) {
return Size(base::ClampCeil(size.width()), base::ClampCeil(size.height()));
}
Size ToRoundedSize(const SizeF& size) {
return Size(base::ClampRound(size.width()), base::ClampRound(size.height()));
}
} // namespace gfx
| engine/third_party/accessibility/gfx/geometry/size_conversions.cc/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/size_conversions.cc",
"repo_id": "engine",
"token_count": 228
} | 406 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GFX_RANGE_EXPORT_H_
#define GFX_RANGE_EXPORT_H_
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(GFX_RANGE_IMPLEMENTATION)
#define GFX_RANGE_EXPORT __declspec(dllexport)
#else
#define GFX_RANGE_EXPORT __declspec(dllimport)
#endif // defined(GFX_RANGE_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(GFX_RANGE_IMPLEMENTATION)
#define GFX_RANGE_EXPORT __attribute__((visibility("default")))
#else
#define GFX_RANGE_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define GFX_RANGE_EXPORT
#endif
#endif // GFX_RANGE_EXPORT_H_
| engine/third_party/accessibility/gfx/range/gfx_range_export.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/range/gfx_range_export.h",
"repo_id": "engine",
"token_count": 284
} | 407 |
//
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//
// @flow
// @format
//
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SPRING_ANIMATION_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SPRING_ANIMATION_H_
#include <Foundation/NSObject.h>
// This simplified spring model is based off of a damped harmonic oscillator.
// See:
// https://en.wikipedia.org/wiki/Harmonic_oscillator#Damped_harmonic_oscillator
//
// This models the closed form of the second order differential equation which
// happens to match the algorithm used by CASpringAnimation, a QuartzCore (iOS)
// API that creates spring animations.
@interface SpringAnimation : NSObject
- (instancetype)initWithStiffness:(double)stiffness
damping:(double)damping
mass:(double)mass
initialVelocity:(double)initialVelocity
fromValue:(double)fromValue
toValue:(double)toValue;
- (double)curveFunction:(double)t;
@property(nonatomic, assign, readonly) double stiffness;
@property(nonatomic, assign, readonly) double damping;
@property(nonatomic, assign, readonly) double mass;
@property(nonatomic, assign, readonly) double initialVelocity;
@property(nonatomic, assign) double fromValue;
@property(nonatomic, assign) double toValue;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SPRING_ANIMATION_H_
| engine/third_party/spring_animation/spring_animation.h/0 | {
"file_path": "engine/third_party/spring_animation/spring_animation.h",
"repo_id": "engine",
"token_count": 581
} | 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.
#ifndef LIB_TONIC_DART_ARGS_H_
#define LIB_TONIC_DART_ARGS_H_
#include <iostream>
#include <sstream>
#include <type_traits>
#include <utility>
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/converter/dart_converter.h"
#include "tonic/dart_wrappable.h"
namespace tonic {
class DartArgIterator {
public:
explicit DartArgIterator(Dart_NativeArguments args, int start_index = 1)
: args_(args), index_(start_index), had_exception_(false) {}
template <typename T>
T GetNext() {
if (had_exception_)
return T();
Dart_Handle exception = nullptr;
T arg = DartConverter<T>::FromArguments(args_, index_++, exception);
if (exception) {
had_exception_ = true;
Dart_ThrowException(exception);
}
return arg;
}
bool had_exception() const { return had_exception_; }
Dart_NativeArguments args() const { return args_; }
private:
Dart_NativeArguments args_;
int index_;
bool had_exception_;
TONIC_DISALLOW_COPY_AND_ASSIGN(DartArgIterator);
};
// Classes for generating and storing an argument pack of integer indices
// (based on well-known "indices trick", see: http://goo.gl/bKKojn):
template <size_t... indices>
struct IndicesHolder {};
template <size_t requested_index, size_t... indices>
struct IndicesGenerator {
using type = typename IndicesGenerator<requested_index - 1,
requested_index - 1,
indices...>::type;
};
template <size_t... indices>
struct IndicesGenerator<0, indices...> {
using type = IndicesHolder<indices...>;
};
template <typename T>
class IndicesForSignature {};
template <typename ResultType, typename... ArgTypes>
struct IndicesForSignature<ResultType (*)(ArgTypes...)> {
static const size_t count = sizeof...(ArgTypes);
using type = typename IndicesGenerator<count>::type;
};
template <typename C, typename ResultType, typename... ArgTypes>
struct IndicesForSignature<ResultType (C::*)(ArgTypes...)> {
static const size_t count = sizeof...(ArgTypes);
using type = typename IndicesGenerator<count>::type;
};
template <typename C, typename ResultType, typename... ArgTypes>
struct IndicesForSignature<ResultType (C::*)(ArgTypes...) const> {
static const size_t count = sizeof...(ArgTypes);
using type = typename IndicesGenerator<count>::type;
};
template <size_t index, typename ArgType>
struct DartArgHolder {
using ValueType = typename std::remove_const<
typename std::remove_reference<ArgType>::type>::type;
ValueType value;
explicit DartArgHolder(DartArgIterator* it)
: value(it->GetNext<ValueType>()) {}
};
template <typename T>
void DartReturn(T result, Dart_NativeArguments args) {
DartConverter<T>::SetReturnValue(args, std::move(result));
}
template <typename IndicesType, typename T>
class DartDispatcher {};
// Match functions on the form:
// `void f(ArgTypes...)`
template <size_t... indices, typename... ArgTypes>
struct DartDispatcher<IndicesHolder<indices...>, void (*)(ArgTypes...)>
: public DartArgHolder<indices, ArgTypes>... {
using FunctionPtr = void (*)(ArgTypes...);
DartArgIterator* it_;
explicit DartDispatcher(DartArgIterator* it)
: DartArgHolder<indices, ArgTypes>(it)..., it_(it) {}
void Dispatch(FunctionPtr func) {
(*func)(DartArgHolder<indices, ArgTypes>::value...);
}
};
// Match functions on the form:
// `ResultType f(ArgTypes...)`
template <size_t... indices, typename ResultType, typename... ArgTypes>
struct DartDispatcher<IndicesHolder<indices...>, ResultType (*)(ArgTypes...)>
: public DartArgHolder<indices, ArgTypes>... {
using FunctionPtr = ResultType (*)(ArgTypes...);
using CtorResultType = ResultType;
DartArgIterator* it_;
explicit DartDispatcher(DartArgIterator* it)
: DartArgHolder<indices, ArgTypes>(it)..., it_(it) {}
void Dispatch(FunctionPtr func) {
DartReturn((*func)(DartArgHolder<indices, ArgTypes>::value...),
it_->args());
}
ResultType DispatchCtor(FunctionPtr func) {
return (*func)(DartArgHolder<indices, ArgTypes>::value...);
}
};
// Match instance methods on the form:
// `void C::m(ArgTypes...)`
template <size_t... indices, typename C, typename... ArgTypes>
struct DartDispatcher<IndicesHolder<indices...>, void (C::*)(ArgTypes...)>
: public DartArgHolder<indices, ArgTypes>... {
using FunctionPtr = void (C::*)(ArgTypes...);
DartArgIterator* it_;
explicit DartDispatcher(DartArgIterator* it)
: DartArgHolder<indices, ArgTypes>(it)..., it_(it) {}
void Dispatch(FunctionPtr func) {
(GetReceiver<C>(it_->args())->*func)(
DartArgHolder<indices, ArgTypes>::value...);
}
};
// Match instance methods on the form:
// `ReturnType (C::m)(ArgTypes...) const`
template <size_t... indices,
typename C,
typename ReturnType,
typename... ArgTypes>
struct DartDispatcher<IndicesHolder<indices...>,
ReturnType (C::*)(ArgTypes...) const>
: public DartArgHolder<indices, ArgTypes>... {
using FunctionPtr = ReturnType (C::*)(ArgTypes...) const;
DartArgIterator* it_;
explicit DartDispatcher(DartArgIterator* it)
: DartArgHolder<indices, ArgTypes>(it)..., it_(it) {}
void Dispatch(FunctionPtr func) {
DartReturn((GetReceiver<C>(it_->args())->*func)(
DartArgHolder<indices, ArgTypes>::value...),
it_->args());
}
};
// Match instance methods on the form:
// `ReturnType (C::m)(ArgTypes...)`
template <size_t... indices,
typename C,
typename ResultType,
typename... ArgTypes>
struct DartDispatcher<IndicesHolder<indices...>, ResultType (C::*)(ArgTypes...)>
: public DartArgHolder<indices, ArgTypes>... {
using FunctionPtr = ResultType (C::*)(ArgTypes...);
DartArgIterator* it_;
explicit DartDispatcher(DartArgIterator* it)
: DartArgHolder<indices, ArgTypes>(it)..., it_(it) {}
void Dispatch(FunctionPtr func) {
DartReturn((GetReceiver<C>(it_->args())->*func)(
DartArgHolder<indices, ArgTypes>::value...),
it_->args());
}
};
template <typename Sig>
void DartCall(Sig func, Dart_NativeArguments args) {
DartArgIterator it(args);
using Indices = typename IndicesForSignature<Sig>::type;
DartDispatcher<Indices, Sig> decoder(&it);
if (it.had_exception())
return;
decoder.Dispatch(func);
}
template <typename Sig>
void DartCallStatic(Sig func, Dart_NativeArguments args) {
DartArgIterator it(args, 0);
using Indices = typename IndicesForSignature<Sig>::type;
DartDispatcher<Indices, Sig> decoder(&it);
if (it.had_exception())
return;
decoder.Dispatch(func);
}
template <typename Sig>
void DartCallConstructor(Sig func, Dart_NativeArguments args) {
DartArgIterator it(args);
using Indices = typename IndicesForSignature<Sig>::type;
using Wrappable = typename DartDispatcher<Indices, Sig>::CtorResultType;
Wrappable wrappable;
{
DartDispatcher<Indices, Sig> decoder(&it);
if (it.had_exception())
return;
wrappable = decoder.DispatchCtor(func);
}
Dart_Handle wrapper = Dart_GetNativeArgument(args, 0);
TONIC_CHECK(!CheckAndHandleError(wrapper));
intptr_t native_fields[DartWrappable::kNumberOfNativeFields];
TONIC_CHECK(!CheckAndHandleError(Dart_GetNativeFieldsOfArgument(
args, 0, DartWrappable::kNumberOfNativeFields, native_fields)));
TONIC_CHECK(!native_fields[DartWrappable::kPeerIndex]);
wrappable->AssociateWithDartWrapper(wrapper);
}
// Templates to automatically setup static entry points for FFI Native
// functions.
// Entry points for instance methods take the instance as the first argument and
// call the given method with the remaining arguments.
// Arguments will automatically get converted to and from their FFI
// representations with the DartConverter templates.
//
// @tparam C The type of the receiver. Or `void` if there is no receiver.
// @tparam Signature The signature of the function being dispatched to.
// @tparam function The function pointer being dispatched to.
template <typename C, typename Signature, Signature function>
struct FfiDispatcher;
// Concatenate the FFI representation of each argument to the stream,
// serialising them into a comma separated list.
// Example: "Handle, Bool, Uint64"
template <typename Arg, typename... Args>
void WriteFfiArguments(std::ostringstream* stream) {
*stream << tonic::DartConverter<typename std::remove_const<
typename std::remove_reference<Arg>::type>::type>::GetFfiRepresentation();
if constexpr (sizeof...(Args) > 0) {
*stream << ", ";
WriteFfiArguments<Args...>(stream);
}
}
// Concatenate the Dart representation of each argument to the stream,
// serialising them into a comma separated list.
// Example: "Object, bool, int"
template <typename Arg, typename... Args>
void WriteDartArguments(std::ostringstream* stream) {
*stream << tonic::DartConverter<
typename std::remove_const<typename std::remove_reference<Arg>::type>::
type>::GetDartRepresentation();
if constexpr (sizeof...(Args) > 0) {
*stream << ", ";
WriteDartArguments<Args...>(stream);
}
}
// Logical 'and' together whether each argument is allowed in a leaf call.
template <typename Arg, typename... Args>
bool AllowedInLeafCall() {
bool result = tonic::DartConverter<typename std::remove_const<
typename std::remove_reference<Arg>::type>::type>::AllowedInLeafCall();
if constexpr (sizeof...(Args) > 0) {
result &= AllowedInLeafCall<Args...>();
}
return result;
}
// Match `Return function(...)`.
template <typename Return, typename... Args, Return (*function)(Args...)>
struct FfiDispatcher<void, Return (*)(Args...), function> {
using FfiReturn = typename DartConverter<Return>::FfiType;
static const size_t n_args = sizeof...(Args);
// Static C entry-point with Dart FFI signature.
static FfiReturn Call(
typename DartConverter<typename std::remove_const<
typename std::remove_reference<Args>::type>::type>::FfiType... args) {
// Call C++ function, forwarding converted native arguments.
return DartConverter<Return>::ToFfi(function(
DartConverter<typename std::remove_const<typename std::remove_reference<
Args>::type>::type>::FromFfi(args)...));
}
static bool AllowedAsLeafCall() {
if constexpr (sizeof...(Args) > 0) {
return AllowedInLeafCall<Return>() && AllowedInLeafCall<Args...>();
}
return AllowedInLeafCall<Return>();
}
static const char* GetReturnFfiRepresentation() {
return tonic::DartConverter<Return>::GetFfiRepresentation();
}
static const char* GetReturnDartRepresentation() {
return tonic::DartConverter<Return>::GetDartRepresentation();
}
static void WriteFfiArguments(std::ostringstream* stream) {
if constexpr (sizeof...(Args) > 0) {
::tonic::WriteFfiArguments<Args...>(stream);
}
}
static void WriteDartArguments(std::ostringstream* stream) {
if constexpr (sizeof...(Args) > 0) {
::tonic::WriteDartArguments<Args...>(stream);
}
}
};
// Match `Return C::method(...)`.
template <typename C,
typename Return,
typename... Args,
Return (C::*method)(Args...)>
struct FfiDispatcher<C, Return (C::*)(Args...), method> {
using FfiReturn = typename DartConverter<Return>::FfiType;
static const size_t n_args = sizeof...(Args);
// Static C entry-point with Dart FFI signature.
static FfiReturn Call(
DartWrappable* receiver,
typename DartConverter<typename std::remove_const<
typename std::remove_reference<Args>::type>::type>::FfiType... args) {
// Call C++ method on receiver, forwarding converted native arguments.
return DartConverter<Return>::ToFfi((static_cast<C*>(receiver)->*method)(
DartConverter<typename std::remove_const<typename std::remove_reference<
Args>::type>::type>::FromFfi(args)...));
}
static bool AllowedAsLeafCall() {
if constexpr (sizeof...(Args) > 0) {
return AllowedInLeafCall<Return>() && AllowedInLeafCall<Args...>();
}
return AllowedInLeafCall<Return>();
}
static const char* GetReturnFfiRepresentation() {
return tonic::DartConverter<Return>::GetFfiRepresentation();
}
static const char* GetReturnDartRepresentation() {
return tonic::DartConverter<Return>::GetDartRepresentation();
}
static void WriteFfiArguments(std::ostringstream* stream) {
*stream << tonic::DartConverter<C*>::GetFfiRepresentation();
if constexpr (sizeof...(Args) > 0) {
*stream << ", ";
::tonic::WriteFfiArguments<Args...>(stream);
}
}
static void WriteDartArguments(std::ostringstream* stream) {
*stream << tonic::DartConverter<C*>::GetDartRepresentation();
if constexpr (sizeof...(Args) > 0) {
*stream << ", ";
::tonic::WriteDartArguments<Args...>(stream);
}
}
};
// Match `Return C::method(...) const`.
template <typename C,
typename Return,
typename... Args,
Return (C::*method)(Args...) const>
struct FfiDispatcher<C, Return (C::*)(Args...) const, method> {
using FfiReturn = typename DartConverter<Return>::FfiType;
static const size_t n_args = sizeof...(Args);
// Static C entry-point with Dart FFI signature.
static FfiReturn Call(
DartWrappable* receiver,
typename DartConverter<typename std::remove_const<
typename std::remove_reference<Args>::type>::type>::FfiType... args) {
// Call C++ method on receiver, forwarding converted native arguments.
return DartConverter<Return>::ToFfi((static_cast<C*>(receiver)->*method)(
DartConverter<typename std::remove_const<typename std::remove_reference<
Args>::type>::type>::FromFfi(args)...));
}
static bool AllowedAsLeafCall() {
if constexpr (sizeof...(Args) > 0) {
return AllowedInLeafCall<Return>() && AllowedInLeafCall<Args...>();
}
return AllowedInLeafCall<Return>();
}
static const char* GetReturnFfiRepresentation() {
return tonic::DartConverter<Return>::GetFfiRepresentation();
}
static const char* GetReturnDartRepresentation() {
return tonic::DartConverter<Return>::GetDartRepresentation();
}
static void WriteFfiArguments(std::ostringstream* stream) {
*stream << tonic::DartConverter<C*>::GetFfiRepresentation();
if constexpr (sizeof...(Args) > 0) {
*stream << ", ";
::tonic::WriteFfiArguments<Args...>(stream);
}
}
static void WriteDartArguments(std::ostringstream* stream) {
*stream << tonic::DartConverter<C*>::GetDartRepresentation();
if constexpr (sizeof...(Args) > 0) {
*stream << ", ";
::tonic::WriteDartArguments<Args...>(stream);
}
}
};
// `void` specialisation since we can't declare `ToFfi` to take void rvalues.
// Match `void function(...)`.
template <typename... Args, void (*function)(Args...)>
struct FfiDispatcher<void, void (*)(Args...), function> {
static const size_t n_args = sizeof...(Args);
// Static C entry-point with Dart FFI signature.
static void Call(
typename DartConverter<typename std::remove_const<
typename std::remove_reference<Args>::type>::type>::FfiType... args) {
// Call C++ function, forwarding converted native arguments.
function(
DartConverter<typename std::remove_const<typename std::remove_reference<
Args>::type>::type>::FromFfi(args)...);
}
static bool AllowedAsLeafCall() {
if constexpr (sizeof...(Args) > 0) {
return AllowedInLeafCall<Args...>();
}
return true;
}
static const char* GetReturnFfiRepresentation() {
return tonic::DartConverter<void>::GetFfiRepresentation();
}
static const char* GetReturnDartRepresentation() {
return tonic::DartConverter<void>::GetDartRepresentation();
}
static void WriteFfiArguments(std::ostringstream* stream) {
if constexpr (sizeof...(Args) > 0) {
::tonic::WriteFfiArguments<Args...>(stream);
}
}
static void WriteDartArguments(std::ostringstream* stream) {
if constexpr (sizeof...(Args) > 0) {
::tonic::WriteDartArguments<Args...>(stream);
}
}
};
// `void` specialisation since we can't declare `ToFfi` to take void rvalues.
// Match `void C::method(...)`.
template <typename C, typename... Args, void (C::*method)(Args...)>
struct FfiDispatcher<C, void (C::*)(Args...), method> {
static const size_t n_args = sizeof...(Args);
// Static C entry-point with Dart FFI signature.
static void Call(
DartWrappable* receiver,
typename DartConverter<typename std::remove_const<
typename std::remove_reference<Args>::type>::type>::FfiType... args) {
// Call C++ method on receiver, forwarding converted native arguments.
(static_cast<C*>(receiver)->*method)(
DartConverter<typename std::remove_const<typename std::remove_reference<
Args>::type>::type>::FromFfi(args)...);
}
static bool AllowedAsLeafCall() {
if constexpr (sizeof...(Args) > 0) {
return AllowedInLeafCall<Args...>();
}
return true;
}
static const char* GetReturnFfiRepresentation() {
return tonic::DartConverter<void>::GetFfiRepresentation();
}
static const char* GetReturnDartRepresentation() {
return tonic::DartConverter<void>::GetDartRepresentation();
}
static void WriteFfiArguments(std::ostringstream* stream) {
*stream << tonic::DartConverter<C*>::GetFfiRepresentation();
if constexpr (sizeof...(Args) > 0) {
*stream << ", ";
::tonic::WriteFfiArguments<Args...>(stream);
}
}
static void WriteDartArguments(std::ostringstream* stream) {
*stream << tonic::DartConverter<C*>::GetDartRepresentation();
if constexpr (sizeof...(Args) > 0) {
*stream << ", ";
::tonic::WriteDartArguments<Args...>(stream);
}
}
};
} // namespace tonic
#endif // LIB_TONIC_DART_ARGS_H_
| engine/third_party/tonic/dart_args.h/0 | {
"file_path": "engine/third_party/tonic/dart_args.h",
"repo_id": "engine",
"token_count": 6623
} | 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.
#include "tonic/dart_state.h"
#include "tonic/converter/dart_converter.h"
#include "tonic/dart_class_library.h"
#include "tonic/dart_message_handler.h"
#include "tonic/file_loader/file_loader.h"
namespace tonic {
DartState::Scope::Scope(DartState* dart_state)
: scope_(dart_state->isolate()) {}
DartState::Scope::Scope(std::shared_ptr<DartState> dart_state)
: scope_(dart_state->isolate()) {}
DartState::Scope::~Scope() {}
DartState::DartState(int dirfd,
std::function<void(Dart_Handle)> message_epilogue)
: isolate_(nullptr),
private_constructor_name_(),
class_library_(new DartClassLibrary),
message_handler_(new DartMessageHandler()),
file_loader_(new FileLoader(dirfd)),
message_epilogue_(message_epilogue),
has_set_return_code_(false),
is_shutting_down_(false) {}
DartState::~DartState() {}
void DartState::SetIsolate(Dart_Isolate isolate) {
isolate_ = isolate;
if (!isolate_)
return;
private_constructor_name_.Clear();
Dart_EnterScope();
private_constructor_name_.Set(
this, Dart_NewPersistentHandle(Dart_NewStringFromCString("_")));
Dart_ExitScope();
DidSetIsolate();
}
DartState* DartState::From(Dart_Isolate isolate) {
auto isolate_data =
static_cast<std::shared_ptr<DartState>*>(Dart_IsolateData(isolate));
return isolate_data->get();
}
DartState* DartState::Current() {
auto isolate_data =
static_cast<std::shared_ptr<DartState>*>(Dart_CurrentIsolateData());
return isolate_data ? isolate_data->get() : nullptr;
}
std::weak_ptr<DartState> DartState::GetWeakPtr() {
return shared_from_this();
}
void DartState::SetReturnCode(uint32_t return_code) {
if (set_return_code_callback_) {
set_return_code_callback_(return_code);
}
has_set_return_code_ = true;
}
void DartState::SetReturnCodeCallback(std::function<void(uint32_t)> callback) {
set_return_code_callback_ = callback;
}
void DartState::DidSetIsolate() {}
Dart_Handle DartState::HandleLibraryTag(Dart_LibraryTag tag,
Dart_Handle library,
Dart_Handle url) {
return Current()->file_loader().HandleLibraryTag(tag, library, url);
}
} // namespace tonic
| engine/third_party/tonic/dart_state.cc/0 | {
"file_path": "engine/third_party/tonic/dart_state.cc",
"repo_id": "engine",
"token_count": 946
} | 410 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tonic/filesystem/filesystem/file.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <climits>
#include <cstdint>
#include "tonic/common/build_config.h"
#if defined(OS_WIN)
#define BINARY_MODE _O_BINARY
#else
#define BINARY_MODE 0
#endif
#if defined(OS_WIN)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
#include "tonic/filesystem/filesystem/eintr_wrapper.h"
#include "tonic/filesystem/filesystem/portable_unistd.h"
namespace filesystem {
namespace {
template <typename T>
bool ReadFileDescriptor(int fd, T* result) {
if (!result) {
return false;
}
result->clear();
if (fd < 0)
return false;
constexpr size_t kBufferSize = 1 << 16;
size_t offset = 0;
ssize_t bytes_read = 0;
do {
offset += bytes_read;
result->resize(offset + kBufferSize);
bytes_read = HANDLE_EINTR(read(fd, &(*result)[offset], kBufferSize));
} while (bytes_read > 0);
if (bytes_read < 0) {
result->clear();
return false;
}
result->resize(offset + bytes_read);
return true;
}
} // namespace
std::pair<uint8_t*, intptr_t> ReadFileDescriptorToBytes(int fd) {
std::pair<uint8_t*, intptr_t> failure_pair{nullptr, -1};
struct stat st;
if (fstat(fd, &st) != 0) {
return failure_pair;
}
intptr_t file_size = st.st_size;
uint8_t* ptr = (uint8_t*)malloc(file_size);
size_t bytes_left = file_size;
size_t offset = 0;
while (bytes_left > 0) {
ssize_t bytes_read = HANDLE_EINTR(read(fd, &ptr[offset], bytes_left));
if (bytes_read < 0) {
return failure_pair;
}
offset += bytes_read;
bytes_left -= bytes_read;
}
return std::pair<uint8_t*, intptr_t>(ptr, file_size);
}
bool ReadFileToString(const std::string& path, std::string* result) {
Descriptor fd(open(path.c_str(), O_RDONLY));
return ReadFileDescriptor(fd.get(), result);
}
bool ReadFileDescriptorToString(int fd, std::string* result) {
return ReadFileDescriptor(fd, result);
}
std::pair<uint8_t*, intptr_t> ReadFileToBytes(const std::string& path) {
std::pair<uint8_t*, intptr_t> failure_pair{nullptr, -1};
Descriptor fd(open(path.c_str(), O_RDONLY | BINARY_MODE));
if (!fd.is_valid())
return failure_pair;
return ReadFileDescriptorToBytes(fd.get());
}
} // namespace filesystem
| engine/third_party/tonic/filesystem/filesystem/file.cc/0 | {
"file_path": "engine/third_party/tonic/filesystem/filesystem/file.cc",
"repo_id": "engine",
"token_count": 963
} | 411 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef LIB_TONIC_LOGGING_DART_INVOKE_H_
#define LIB_TONIC_LOGGING_DART_INVOKE_H_
#include <initializer_list>
#include "third_party/dart/runtime/include/dart_api.h"
namespace tonic {
Dart_Handle DartInvokeField(Dart_Handle target,
const char* name,
std::initializer_list<Dart_Handle> args);
Dart_Handle DartInvoke(Dart_Handle closure,
std::initializer_list<Dart_Handle> args);
Dart_Handle DartInvokeVoid(Dart_Handle closure);
} // namespace tonic
#endif // LIB_TONIC_LOGGING_DART_INVOKE_H_
| engine/third_party/tonic/logging/dart_invoke.h/0 | {
"file_path": "engine/third_party/tonic/logging/dart_invoke.h",
"repo_id": "engine",
"token_count": 320
} | 412 |
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TXT_ASSET_FONT_MANAGER_H_
#define TXT_ASSET_FONT_MANAGER_H_
#include <memory>
#include <utility>
#include "flutter/fml/macros.h"
#include "third_party/skia/include/core/SkFontMgr.h"
#include "third_party/skia/include/core/SkStream.h"
#include "txt/font_asset_provider.h"
#include "txt/typeface_font_asset_provider.h"
namespace txt {
class AssetFontManager : public SkFontMgr {
public:
explicit AssetFontManager(std::unique_ptr<FontAssetProvider> font_provider);
~AssetFontManager() override;
protected:
// |SkFontMgr|
sk_sp<SkFontStyleSet> onMatchFamily(const char familyName[]) const override;
std::unique_ptr<FontAssetProvider> font_provider_;
private:
// |SkFontMgr|
int onCountFamilies() const override;
// |SkFontMgr|
void onGetFamilyName(int index, SkString* familyName) const override;
// |SkFontMgr|
sk_sp<SkFontStyleSet> onCreateStyleSet(int index) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onMatchFamilyStyle(const char familyName[],
const SkFontStyle&) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onMatchFamilyStyleCharacter(
const char familyName[],
const SkFontStyle&,
const char* bcp47[],
int bcp47Count,
SkUnichar character) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData>, int ttcIndex) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset>,
int ttcIndex) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset>,
const SkFontArguments&) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onMakeFromFile(const char path[],
int ttcIndex) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onLegacyMakeTypeface(const char familyName[],
SkFontStyle) const override;
FML_DISALLOW_COPY_AND_ASSIGN(AssetFontManager);
};
class DynamicFontManager : public AssetFontManager {
public:
DynamicFontManager()
: AssetFontManager(std::make_unique<TypefaceFontAssetProvider>()) {}
TypefaceFontAssetProvider& font_provider() const {
return static_cast<TypefaceFontAssetProvider&>(*font_provider_);
}
};
} // namespace txt
#endif // TXT_ASSET_FONT_MANAGER_H_
| engine/third_party/txt/src/txt/asset_font_manager.h/0 | {
"file_path": "engine/third_party/txt/src/txt/asset_font_manager.h",
"repo_id": "engine",
"token_count": 1162
} | 413 |
/*
* 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.
*/
#ifndef LIB_TXT_SRC_PLACEHOLDER_RUN_H_
#define LIB_TXT_SRC_PLACEHOLDER_RUN_H_
#include "text_baseline.h"
namespace txt {
/// Where to vertically align the placeholder relative to the surrounding text.
enum class PlaceholderAlignment {
/// Match the baseline of the placeholder with the baseline.
kBaseline,
/// Align the bottom edge of the placeholder with the baseline such that the
/// placeholder sits on top of the baseline.
kAboveBaseline,
/// Align the top edge of the placeholder with the baseline specified in
/// such that the placeholder hangs below the baseline.
kBelowBaseline,
/// Align the top edge of the placeholder with the top edge of the font.
/// When the placeholder is very tall, the extra space will hang from
/// the top and extend through the bottom of the line.
kTop,
/// Align the bottom edge of the placeholder with the top edge of the font.
/// When the placeholder is very tall, the extra space will rise from
/// the bottom and extend through the top of the line.
kBottom,
/// Align the middle of the placeholder with the middle of the text. When the
/// placeholder is very tall, the extra space will grow equally from
/// the top and bottom of the line.
kMiddle,
};
// Represents the metrics required to fully define a rect that will fit a
// placeholder.
//
// LibTxt will leave an empty space in the layout of the text of the size
// defined by this class. After layout, the framework will draw placeholders
// into the reserved space.
class PlaceholderRun {
public:
double width = 0;
double height = 0;
PlaceholderAlignment alignment;
TextBaseline baseline;
// Distance from the top edge of the rect to the baseline position. This
// baseline will be aligned against the alphabetic baseline of the surrounding
// text.
//
// Positive values drop the baseline lower (positions the rect higher) and
// small or negative values will cause the rect to be positioned underneath
// the line. When baseline == height, the bottom edge of the rect will rest on
// the alphabetic baseline.
double baseline_offset = 0;
PlaceholderRun();
PlaceholderRun(double width,
double height,
PlaceholderAlignment alignment,
TextBaseline baseline,
double baseline_offset);
};
} // namespace txt
#endif // LIB_TXT_SRC_PLACEHOLDER_RUN_H_
| engine/third_party/txt/src/txt/placeholder_run.h/0 | {
"file_path": "engine/third_party/txt/src/txt/placeholder_run.h",
"repo_id": "engine",
"token_count": 843
} | 414 |
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIB_TXT_SRC_TEXT_SHADOW_H_
#define LIB_TXT_SRC_TEXT_SHADOW_H_
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkPoint.h"
namespace txt {
class TextShadow {
public:
SkColor color = SK_ColorBLACK;
SkPoint offset;
double blur_sigma = 0.0;
TextShadow();
TextShadow(SkColor color, SkPoint offset, double blur_sigma);
bool operator==(const TextShadow& other) const;
bool operator!=(const TextShadow& other) const;
bool hasShadow() const;
};
} // namespace txt
#endif // LIB_TXT_SRC_TEXT_SHADOW_H_
| engine/third_party/txt/src/txt/text_shadow.h/0 | {
"file_path": "engine/third_party/txt/src/txt/text_shadow.h",
"repo_id": "engine",
"token_count": 374
} | 415 |
UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
See Terms of Use <https://www.unicode.org/copyright.html>
for definitions of Unicode Inc.’s Data Files and Software.
NOTICE TO USER: Carefully read the following legal agreement.
BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S
DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"),
YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
TERMS AND CONDITIONS OF THIS AGREEMENT.
IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE
THE DATA FILES OR SOFTWARE.
COPYRIGHT AND PERMISSION NOTICE
Copyright © 1991-2022 Unicode, Inc. All rights reserved.
Distributed under the Terms of Use in https://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Unicode data files and any associated documentation
(the "Data Files") or Unicode software and any associated documentation
(the "Software") to deal in the Data Files or Software
without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, and/or sell copies of
the Data Files or Software, and to permit persons to whom the Data Files
or Software are furnished to do so, provided that either
(a) this copyright and permission notice appear with all copies
of the Data Files or Software, or
(b) this copyright and permission notice appear in associated
Documentation.
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THE DATA FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale,
use or other dealings in these Data Files or Software without prior
written authorization of the copyright holder.
| engine/third_party/web_unicode/LICENSE/0 | {
"file_path": "engine/third_party/web_unicode/LICENSE",
"repo_id": "engine",
"token_count": 627
} | 416 |
# Updating the Embedding Dependencies
The instructions in this README explain how to create a CIPD package that
contains the build-time dependencies of the Android embedding of the Engine,
and the dependencies of the in-tree testing framework. The Android embedder is
shipped to Flutter end-users, but these build-time dependencies are not.
Therefore, the license script can skip over the destination of the CIPD package
in an Engine checkout at `src/third_party/android_embedding_dependencies`.
Even so, the CIPD package should contain a LICENSE file, and the instructions
below explain how to fetch the license information for the dependencies.
## Requirements
1. If you have a flutter/engine checkout, then you should already have
[Depot tools](http://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/depot_tools_tutorial.html#_setting_up) on your path.
1. You should have a copy of `gradle` in a flutter/engine checkout under
`src/third_party/gradle/bin/gradle`.
## Steps
1. Update `src/flutter/tools/androidx/files.json`. (This file includes the Maven
dependencies used to build Flutter apps).
1. `cd` into this directory: `src/flutter/tools/cipd/android_embedding_bundle`.
1. Run `gradle downloadLicenses`
1. Run `gradle updateDependencies`
1. Examine the file `./build/reports/license/license-dependency.xml`. If it
contains licenses other than "The Apache License, Version 2.0" or something
very similar, STOP. Ask Hixie for adivce on how to proceed.
1. Copy or move the `lib/` directory to `src/third_party/android_embedding_dependencies/`,
overwriting its contents, and ensure the Android build still works.
1. Run `cipd create --pkg-def cipd.yaml -tag last_updated:"$version_tag"` where
`$version_tag` is the output of `date +%Y-%m-%dT%T%z`.
1. Update the `DEPS` file entry for `android_embedding_dependencies` with the
new tag: `last_updated:"$version_tag"`.
1. Update the GN list `embedding_dependencies_jars` in
`src/flutter/shell/platform/android/BUILD.gn`.
| engine/tools/cipd/android_embedding_bundle/README.md/0 | {
"file_path": "engine/tools/cipd/android_embedding_bundle/README.md",
"repo_id": "engine",
"token_count": 614
} | 417 |
#!/bin/bash
set -e
set -x
if [[ "$CIRRUS_CI" = false || -z $CIRRUS_CI ]]
then
echo "Cloning Flutter repo to local machine."
fi
if [[ -z $ENGINE_PATH ]]
then
echo "Please set ENGINE_PATH environment variable."
exit 1
fi
# Go to the engine git repo to get the date of the latest commit.
cd $ENGINE_PATH/src/flutter
# Special handling of release branches.
ENGINE_BRANCH_NAME=$CIRRUS_BASE_BRANCH
versionregex="^v[[:digit:]]+\."
releasecandidateregex="^flutter-[[:digit:]]+\.[[:digit:]]+-candidate\.[[:digit:]]+$"
ON_RELEASE_BRANCH=false
echo "Engine on branch $ENGINE_BRANCH_NAME"
if [[ $ENGINE_BRANCH_NAME =~ $versionregex || $ENGINE_BRANCH_NAME =~ $releasecandidateregex ]]
then
echo "release branch $ENGINE_BRANCH_NAME"
ON_RELEASE_BRANCH=true
fi
# Get latest commit's time for the engine repo.
# Use date based on local time otherwise timezones might get mixed.
LATEST_COMMIT_TIME_ENGINE=`git log -1 --date=local --format="%cd"`
echo "Latest commit time on engine found as $LATEST_COMMIT_TIME_ENGINE"
# Check if there is an argument added for repo location.
# If not use the location that should be set by Cirrus/LUCI.
FLUTTER_CLONE_REPO_PATH=$1
if [[ -z $FLUTTER_CLONE_REPO_PATH ]]
then
if [[ -z $FRAMEWORK_PATH ]]
then
echo "Framework path should be set to run the script."
exit 1
fi
# Do rest of the task in the root directory
cd ~
mkdir -p $FRAMEWORK_PATH
cd $FRAMEWORK_PATH
else
cd $FLUTTER_CLONE_REPO_PATH
fi
# Clone the Flutter Framework.
git clone https://github.com/flutter/flutter.git
cd flutter
FRAMEWORK_BRANCH_NAME=`git branch | grep '*' | cut -d ' ' -f2`
if [[ "$ON_RELEASE_BRANCH" = true && ENGINE_BRANCH_NAME != FRAMEWORK_BRANCH_NAME ]]
then
echo "For a release framework and engine should be on the same version."
echo "Switching branches on Framework to from $FRAMEWORK_BRANCH_NAME to $ENGINE_BRANCH_NAME"
# Switch to the same version branch with the engine.
# If same version branch does not exits, fail.
SWITCH_RESULT=`git checkout $ENGINE_BRANCH_NAME` || true
if [[ -z "$SWITCH_RESULT" ]]
then
echo "$ENGINE_BRANCH_NAME Branch not found on framework. Quit."
exit 1
fi
fi
# Get the time of the youngest commit older than engine commit.
# Git log uses commit date not the author date.
# Before makes the comparison considering the timezone as well.
COMMIT_NO=`git log --before="$LATEST_COMMIT_TIME_ENGINE" -n 1 | grep commit | cut -d ' ' -f2`
echo "Using the flutter/flutter commit $COMMIT_NO";
git reset --hard $COMMIT_NO
| engine/tools/clone_flutter.sh/0 | {
"file_path": "engine/tools/clone_flutter.sh",
"repo_id": "engine",
"token_count": 910
} | 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.
// ignore_for_file: prefer_const_constructors, unused_local_variable, depend_on_referenced_packages
import 'dart:core';
import 'package:const_finder_fixtures_package/package.dart';
import 'target.dart';
void main() {
const Target target1 = Target('1', 1, null);
const Target target2 = Target('2', 2, Target('4', 4, null));
const Target target3 = Target('3', 3, Target('5', 5, null)); // should be tree shaken out.
target1.hit();
target2.hit();
blah(const Target('6', 6, null));
const IgnoreMe ignoreMe = IgnoreMe(Target('7', 7, null)); // IgnoreMe is ignored but 7 is not.
final IgnoreMe ignoreMe2 = IgnoreMe(const Target('8', 8, null));
final IgnoreMe ignoreMe3 = IgnoreMe(const Target('9', 9, Target('10', 10, null)));
print(ignoreMe);
print(ignoreMe2);
print(ignoreMe3);
createTargetInPackage();
final StaticConstInitializer staticConstMap = StaticConstInitializer();
staticConstMap.useOne(1);
const ExtendsTarget extendsTarget = ExtendsTarget('11', 11, null);
extendsTarget.hit();
const ImplementsTarget implementsTarget = ImplementsTarget('12', 12, null);
implementsTarget.hit();
const MixedInTarget mixedInTraget = MixedInTarget('13');
mixedInTraget.hit();
}
class IgnoreMe {
const IgnoreMe(this.target);
final Target target;
@override
String toString() => target.toString();
}
class StaticConstInitializer {
static const List<Target> targets = <Target>[
Target('100', 100, null),
Target('101', 101, Target('102', 102, null)),
];
static const Set<Target> targetSet = <Target>{
Target('103', 103, null),
Target('104', 104, Target('105', 105, null)),
};
static const Map<int, Target> targetMap = <int, Target>{
0: Target('106', 106, null),
1: Target('107', 107, Target('108', 108, null)),
};
void useOne(int index) {
targets[index].hit();
targetSet.skip(index).first.hit();
targetMap[index]!.hit();
}
}
void blah(Target target) {
print(target);
}
| engine/tools/const_finder/test/fixtures/lib/consts.dart/0 | {
"file_path": "engine/tools/const_finder/test/fixtures/lib/consts.dart",
"repo_id": "engine",
"token_count": 694
} | 419 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:path/path.dart' as p;
import 'environment.dart';
/// Returns a dart-sdk/bin directory path that is compatible with the host.
String findDartBinDirectory(Environment env) {
return p.dirname(env.platform.resolvedExecutable);
}
/// Returns a dart-sdk/bin/dart file pthat that is executable on the host.
String findDartBinary(Environment env) {
return p.join(findDartBinDirectory(env), 'dart');
}
| engine/tools/engine_tool/lib/src/dart_utils.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/dart_utils.dart",
"repo_id": "engine",
"token_count": 175
} | 420 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ffi' as ffi show Abi;
import 'dart:io' as io;
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:engine_tool/src/environment.dart';
import 'package:engine_tool/src/logger.dart';
import 'package:engine_tool/src/proc_utils.dart';
import 'package:engine_tool/src/worker_pool.dart';
import 'package:litetest/litetest.dart';
import 'package:platform/platform.dart';
import 'package:process_fakes/process_fakes.dart';
import 'package:process_runner/process_runner.dart';
void main() {
final Engine engine;
try {
engine = Engine.findWithin();
} catch (e) {
io.stderr.writeln(e);
io.exitCode = 1;
return;
}
(Environment, List<List<String>>) macEnv(Logger logger) {
final List<List<String>> runHistory = <List<String>>[];
return (
Environment(
abi: ffi.Abi.macosArm64,
engine: engine,
platform: FakePlatform(
operatingSystem: Platform.macOS,
resolvedExecutable: io.Platform.resolvedExecutable),
processRunner: ProcessRunner(
processManager: FakeProcessManager(onStart: (List<String> command) {
runHistory.add(command);
switch (command) {
case ['success']:
return FakeProcess(stdout: 'stdout success');
case ['failure']:
return FakeProcess(exitCode: 1, stdout: 'stdout failure');
default:
return FakeProcess();
}
}, onRun: (List<String> command) {
// Should not be executed.
assert(false);
return io.ProcessResult(81, 1, '', '');
})),
logger: logger,
),
runHistory
);
}
test('process queue success', () async {
final Logger logger = Logger.test();
final (Environment env, _) = macEnv(logger);
final WorkerPool wp = WorkerPool(env, NoopWorkerPoolProgressReporter());
final ProcessTask task =
ProcessTask('S', env, io.Directory.current, <String>['success']);
final bool r = await wp.run(<WorkerTask>{task});
expect(r, equals(true));
expect(task.processArtifacts.exitCode, equals(0));
final ProcessArtifacts loaded =
ProcessArtifacts.fromFile(io.File(task.processArtifactsPath));
expect(loaded.stdout, equals('stdout success'));
});
test('process queue failure', () async {
final Logger logger = Logger.test();
final (Environment env, _) = macEnv(logger);
final WorkerPool wp = WorkerPool(env, NoopWorkerPoolProgressReporter());
final ProcessTask task =
ProcessTask('F', env, io.Directory.current, <String>['failure']);
final bool r = await wp.run(<WorkerTask>{task});
expect(r, equals(false));
expect(task.processArtifacts.exitCode, notEquals(0));
final ProcessArtifacts loaded =
ProcessArtifacts.fromFile(io.File(task.processArtifactsPath));
expect(loaded.stdout, equals('stdout failure'));
});
}
| engine/tools/engine_tool/test/proc_utils_test.dart/0 | {
"file_path": "engine/tools/engine_tool/test/proc_utils_test.dart",
"repo_id": "engine",
"token_count": 1206
} | 421 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_TOOLS_FONT_SUBSET_HB_WRAPPERS_H_
#define FLUTTER_TOOLS_FONT_SUBSET_HB_WRAPPERS_H_
#include <hb-subset.h>
#include <memory>
namespace HarfbuzzWrappers {
struct hb_blob_deleter {
void operator()(hb_blob_t* ptr) { hb_blob_destroy(ptr); }
};
struct hb_face_deleter {
void operator()(hb_face_t* ptr) { hb_face_destroy(ptr); }
};
struct hb_subset_input_deleter {
void operator()(hb_subset_input_t* ptr) { hb_subset_input_destroy(ptr); }
};
struct hb_set_deleter {
void operator()(hb_set_t* ptr) { hb_set_destroy(ptr); }
};
using HbBlobPtr = std::unique_ptr<hb_blob_t, hb_blob_deleter>;
using HbFacePtr = std::unique_ptr<hb_face_t, hb_face_deleter>;
using HbSubsetInputPtr =
std::unique_ptr<hb_subset_input_t, hb_subset_input_deleter>;
using HbSetPtr = std::unique_ptr<hb_set_t, hb_set_deleter>;
}; // namespace HarfbuzzWrappers
#endif // FLUTTER_TOOLS_FONT_SUBSET_HB_WRAPPERS_H_
| engine/tools/font_subset/hb_wrappers.h/0 | {
"file_path": "engine/tools/font_subset/hb_wrappers.h",
"repo_id": "engine",
"token_count": 473
} | 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.
# Generates a package_config.json file containing all of the packages used
# to generate a kernel file.
#
# Package configs are files which describe metadata about a dart package.
# This includes information like the name, dart language version, where to
# find the files, etc. The file is required by the dart kernel compiler.
#
# Parameters
#
# deps, public_deps (optional)
# [list of labels] The targets to generate a manifest for.
# See `gn help` for more details.
#
# testonly, visibility, metadata (optional)
# See `gn help`.
#
# outputs (optional)
# Singleton list containing the path to the package_config file.
# Defaults to `[ "$target_gen_dir/${target_name}_package_config.json" ]`.
template("dart_package_config") {
main_target = target_name
generate_target = "${target_name}_generate"
# Build the name of the output file.
if (defined(invoker.outputs)) {
_outputs = invoker.outputs
assert(_outputs != [] && _outputs == [ _outputs[0] ],
"Outputs list must have exactly one element.")
package_config_file = _outputs[0]
} else {
package_config_file = "$target_gen_dir/${target_name}_package_config.json"
}
intermediate_file = "$package_config_file.partial"
# Gather metadata about runtime objects.
generated_file(generate_target) {
forward_variables_from(invoker,
[
"deps",
"public_deps",
"testonly",
])
visibility = [ ":$main_target" ]
data_keys = [
# A list of package configuration entries
#
# Each entry must contain these values:
# - `name`: The name of the package;
# - `root_uri`: Path to the package root relative to root_build_dir;
# - `package_uri`: The path in which the source lives
#
# The following entries may optionally be specified
# - `language_version`: The dart language version.
# - `pubspec_path`: The path to the pubspec file to find the language version
"package_config_entries",
]
walk_keys = [ "package_config_entry_barrier" ]
outputs = [ intermediate_file ]
output_conversion = "json"
}
# Converts the intermediate to a real package_config.json file.
action(main_target) {
forward_variables_from(invoker,
[
"deps",
"public_deps",
"testonly",
"visibility",
])
script = "//flutter/tools/fuchsia/dart/gen_dart_package_config.py"
inputs = [ intermediate_file ]
outputs = [ package_config_file ]
depfile = "${target_gen_dir}/${target_name}.d"
args = [
"--input",
rebase_path(intermediate_file, root_build_dir),
"--output",
rebase_path(package_config_file, root_build_dir),
"--root",
rebase_path("//", root_build_dir),
"--depfile",
rebase_path(depfile, root_build_dir),
]
if (!defined(deps)) {
deps = []
}
deps += [ ":$generate_target" ]
metadata = {
# Add a barrier here to avoid double of inclusion of elements listed in
# the generated package config.
package_config_entry_barrier = []
if (defined(invoker.metadata)) {
forward_variables_from(invoker.metadata, "*")
}
}
}
}
| engine/tools/fuchsia/dart/dart_package_config.gni/0 | {
"file_path": "engine/tools/fuchsia/dart/dart_package_config.gni",
"repo_id": "engine",
"token_count": 1503
} | 423 |
#!/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.
if [[ -n "${ZSH_VERSION:-}" ]]; then
devshell_lib_dir=${${(%):-%x}:a:h}
else
devshell_lib_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
fi
# Note: if this file location changes this path needs to change
FLUTTER_ENGINE_SRC_DIR="$(dirname "$(dirname "$(dirname "$(dirname "$(dirname "${devshell_lib_dir}")")")")")"
export FLUTTER_ENGINE_SRC_DIR
unset devshell_lib_dir
# Find the fuchsia sdk location
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
export FLUTTER_ENGINE_FUCHSIA_SDK_DIR="${FLUTTER_ENGINE_SRC_DIR}/fuchsia/sdk/linux"
elif [[ "$OSTYPE" == "darwin"* ]]; then
export FLUTTER_ENGINE_FUCHSIA_SDK_DIR="${FLUTTER_ENGINE_SRC_DIR}/fuchsia/sdk/mac"
else
echo "We only support linux/mac"
exit 1
fi
function engine-is-stderr-tty {
[[ -t 2 ]]
}
# engine-debug prints a line to stderr with a cyan DEBUG: prefix.
function engine-debug {
if engine-is-stderr-tty; then
echo -e >&2 "\033[1;36mDEBUG:\033[0m $*"
else
echo -e >&2 "DEBUG: $*"
fi
}
# engine-info prints a line to stderr with a green INFO: prefix.
function engine-info {
if engine-is-stderr-tty; then
echo -e >&2 "\033[1;32mINFO:\033[0m $*"
else
echo -e >&2 "INFO: $*"
fi
}
# engine-error prints a line to stderr with a red ERROR: prefix.
function engine-error {
if engine-is-stderr-tty; then
echo -e >&2 "\033[1;31mERROR:\033[0m $*"
else
echo -e >&2 "ERROR: $*"
fi
}
# engine-warning prints a line to stderr with a yellow WARNING: prefix.
function engine-warning {
if engine-is-stderr-tty; then
echo -e >&2 "\033[1;33mWARNING:\033[0m $*"
else
echo -e >&2 "WARNING: $*"
fi
}
function ensure_fuchsia_dir() {
if [[ -z "${FUCHSIA_DIR}" ]]; then
engine-error "A valid fuchsia.git checkout is required." \
"Make sure you have a valid FUCHSIA_DIR."
exit 1
fi
}
function ensure_engine_dir() {
if [[ -z "${ENGINE_DIR}" ]]; then
engine-error "ENGINE_DIR must be set to the src folder of your Flutter Engine checkout."
exit 1
fi
}
function ensure_ninja() {
if ! [ -x "$(command -v ninja)" ]; then
engine-error '`ninja` is not in your $PATH. Do you have depot_tools installed and in your $PATH? https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/depot_tools_tutorial.html#_setting_up'
exit 1
fi
}
function ensure_autoninja() {
if ! [ -x "$(command -v autoninja)" ]; then
engine-error '`autoninja` is not in your $PATH. Do you have depot_tools installed and in your $PATH? https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/depot_tools_tutorial.html#_setting_up'
exit 1
fi
}
| engine/tools/fuchsia/devshell/lib/vars.sh/0 | {
"file_path": "engine/tools/fuchsia/devshell/lib/vars.sh",
"repo_id": "engine",
"token_count": 1131
} | 424 |
#!/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.
""" Generate a Fuchsia repo capable of serving Fuchsia archives over the
network.
"""
import argparse
import collections
import json
import os
import subprocess
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--pm-bin', dest='pm_bin', action='store', required=True)
parser.add_argument('--repo-dir', dest='repo_dir', action='store', required=True)
parser.add_argument('--archive', dest='archives', action='append', required=True)
args = parser.parse_args()
assert os.path.exists(args.pm_bin)
if not os.path.exists(args.repo_dir):
pm_newrepo_command = [args.pm_bin, 'newrepo', '-repo', args.repo_dir]
subprocess.check_call(pm_newrepo_command)
pm_publish_command = [
args.pm_bin,
'publish',
'-C', # Remove all previous registrations.
'-a', # Publish archives from an archive (mode).
'-repo',
args.repo_dir
]
for archive in args.archives:
pm_publish_command.append('-f')
pm_publish_command.append(archive)
subprocess.check_call(pm_publish_command)
return 0
if __name__ == '__main__':
sys.exit(main())
| engine/tools/fuchsia/gen_repo.py/0 | {
"file_path": "engine/tools/fuchsia/gen_repo.py",
"repo_id": "engine",
"token_count": 467
} | 425 |
// Copyright 2014 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:args/args.dart';
import 'package:gen_web_keyboard_keymap/benchmark_planner.dart';
import 'package:gen_web_keyboard_keymap/common.dart';
import 'package:gen_web_keyboard_keymap/github.dart';
import 'package:gen_web_keyboard_keymap/layout_types.dart';
import 'package:path/path.dart' as path;
const String kEnvGithubToken = 'GITHUB_TOKEN';
String _renderTemplate(String template, Map<String, String> dictionary) {
String result = template;
dictionary.forEach((String key, String value) {
final String localResult = result.replaceAll('@@@$key@@@', value);
if (localResult == result) {
print('Template key $key is not used.');
}
result = localResult;
});
return result;
}
void _writeFileTo(String outputDir, String outputFileName, String body) {
final String outputPath = path.join(outputDir, outputFileName);
Directory(outputDir).createSync(recursive: true);
File(outputPath).writeAsStringSync(body);
}
String _readSharedSegment(String path) {
const String kSegmentStartMark = '/*@@@ SHARED SEGMENT START @@@*/';
const String kSegmentEndMark = '/*@@@ SHARED SEGMENT END @@@*/';
final List<String> lines = File(path).readAsStringSync().split('\n');
// Defining the two variables as `late final` ensures that each mark is found
// once and only once, otherwise assertion errors will be thrown.
late final int startLine;
late final int endLine;
for (int lineNo = 0; lineNo < lines.length; lineNo += 1) {
if (lines[lineNo] == kSegmentStartMark) {
startLine = lineNo;
} else if (lines[lineNo] == kSegmentEndMark) {
endLine = lineNo;
}
}
assert(startLine < endLine);
return lines.sublist(startLine + 1, endLine).join('\n').trimRight();
}
typedef _ForEachAction<V> = void Function(String key, V value);
void _sortedForEach<V>(Map<String, V> map, _ForEachAction<V> action) {
map
.entries
.toList()
..sort((MapEntry<String, V> a, MapEntry<String, V> b) => a.key.compareTo(b.key))
..forEach((MapEntry<String, V> entry) {
action(entry.key, entry.value);
});
}
String _escapeStringToDart(String origin) {
// If there is no `'`, we can use the raw string surrounded by `'`.
if (!origin.contains("'")) {
return "r'$origin'";
} else {
// If there is no `"`, we can use the raw string surrounded by `"`.
if (!origin.contains('"')) {
return 'r"$origin"';
} else {
// If there are both kinds of quotes, we have to use non-raw string
// and escape necessary characters.
final String beforeQuote = origin
.replaceAll(r'\', r'\\')
.replaceAll(r'$', r'\$')
.replaceAll("'", r"\'");
return "'$beforeQuote'";
}
}
}
typedef _ValueCompare<T> = void Function(T?, T?, String path);
void _mapForEachEqual<T>(Map<String, T> a, Map<String, T> b, _ValueCompare<T> body, String path) {
assert(a.length == b.length, '$path.length: ${a.length} vs ${b.length}');
for (final String key in a.keys) {
body(a[key], b[key], key);
}
}
// Ensure that two maps are deeply equal.
//
// Differences will be thrown as assertion.
bool _verifyMap(Map<String, Map<String, int>> a, Map<String, Map<String, int>> b) {
_mapForEachEqual(a, b, (Map<String, int>? aMap, Map<String, int>? bMap, String path) {
_mapForEachEqual(aMap!, bMap!, (int? aValue, int? bValue, String path) {
assert(aValue == bValue && aValue != null, '$path: $aValue vs $bValue');
}, path);
}, '');
return true;
}
String _buildMapString(Iterable<Layout> layouts) {
final Map<String, Map<String, int>> originalMap = combineLayouts(layouts);
final List<String> compressed = marshallMappingData(originalMap);
final Map<String, Map<String, int>> uncompressed = unmarshallMappingData(compressed.join());
assert(_verifyMap(originalMap, uncompressed));
return ' return unmarshallMappingData(\n'
'${compressed.map((String line) => ' ${_escapeStringToDart(line)}\n').join()}'
' ); // ${compressed.join().length} characters';
}
String _buildTestCasesString(List<Layout> layouts) {
final List<String> layoutsString = <String>[];
for (final Layout layout in layouts) {
final List<String> layoutEntries = <String>[];
_sortedForEach(planLayout(layout.entries), (String eventCode, int logicalKey) {
final LayoutEntry entry = layout.entries[eventCode]!;
layoutEntries.add(" verifyEntry(mapping, '$eventCode', <String>["
'${entry.printables.map(_escapeStringToDart).join(', ')}'
"], '${String.fromCharCode(logicalKey)}');");
});
layoutsString.add('''
group('${layout.language}', () {
${layoutEntries.join('\n')}
});
''');
}
return layoutsString.join('\n').trimRight();
}
Future<void> main(List<String> rawArguments) async {
final Map<String, String> env = Platform.environment;
final ArgParser argParser = ArgParser();
argParser.addFlag(
'force',
abbr: 'f',
negatable: false,
help: 'Make a new request to GitHub even if a cache is detected',
);
argParser.addFlag(
'help',
abbr: 'h',
negatable: false,
help: 'Print help for this command.',
);
final ArgResults parsedArguments = argParser.parse(rawArguments);
if (parsedArguments['help'] as bool) {
print(argParser.usage);
exit(0);
}
bool enabledAssert = false;
assert(() {
enabledAssert = true;
return true;
}());
if (!enabledAssert) {
print('Error: This script must be run with assert enabled. Please rerun with --enable-asserts.');
exit(1);
}
final String? envGithubToken = env[kEnvGithubToken];
if (envGithubToken == null) {
print('Error: Environment variable $kEnvGithubToken not found.\n\n'
'Set the environment variable $kEnvGithubToken as a GitHub personal access\n'
'token for authentication. This token is only used for quota controlling\n'
'and does not need any scopes. Create one at\n'
'https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token.',
);
exit(1);
}
// The root of this package. The folder that is called
// 'gen_web_locale_keymap' and contains 'pubspec.yaml'.
final Directory packageRoot = Directory(path.dirname(Platform.script.toFilePath())).parent;
// The root of the output package. The folder that is called
// 'web_locale_keymap' and contains 'pubspec.yaml'.
final String outputRoot = path.join(packageRoot.parent.parent.path,
'third_party', 'web_locale_keymap');
final GithubResult githubResult = await fetchFromGithub(
githubToken: envGithubToken,
force: parsedArguments['force'] as bool,
cacheRoot: path.join(packageRoot.path, '.cache'),
);
final List<Layout> winLayouts = githubResult.layouts.where((Layout layout) =>
layout.platform == LayoutPlatform.win).toList();
final List<Layout> linuxLayouts = githubResult.layouts.where((Layout layout) =>
layout.platform == LayoutPlatform.linux).toList();
final List<Layout> darwinLayouts = githubResult.layouts.where((Layout layout) =>
layout.platform == LayoutPlatform.darwin).toList();
// Generate the definition file.
_writeFileTo(
path.join(outputRoot, 'lib', 'web_locale_keymap'),
'key_mappings.g.dart',
_renderTemplate(
File(path.join(packageRoot.path, 'data', 'key_mappings.dart.tmpl')).readAsStringSync(),
<String, String>{
'COMMIT_URL': githubResult.url,
'WIN_MAPPING': _buildMapString(winLayouts),
'LINUX_MAPPING': _buildMapString(linuxLayouts),
'DARWIN_MAPPING': _buildMapString(darwinLayouts),
'COMMON': _readSharedSegment(path.join(packageRoot.path, 'lib', 'common.dart')),
},
),
);
// Generate the test cases.
_writeFileTo(
path.join(outputRoot, 'test'),
'test_cases.g.dart',
_renderTemplate(
File(path.join(packageRoot.path, 'data', 'test_cases.dart.tmpl')).readAsStringSync(),
<String, String>{
'WIN_CASES': _buildTestCasesString(winLayouts),
'LINUX_CASES': _buildTestCasesString(linuxLayouts),
'DARWIN_CASES': _buildTestCasesString(darwinLayouts),
},
),
);
}
| engine/tools/gen_web_locale_keymap/bin/gen_web_locale_keymap.dart/0 | {
"file_path": "engine/tools/gen_web_locale_keymap/bin/gen_web_locale_keymap.dart",
"repo_id": "engine",
"token_count": 3074
} | 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 'package:args/command_runner.dart';
import 'messages.dart';
/// The command that implements the pre-rebase githook
class PreRebaseCommand extends Command<bool> {
@override
final String name = 'pre-rebase';
@override
final String description = 'Checks to run before a "git rebase"';
@override
Future<bool> run() async {
printGclientSyncReminder(name);
// Returning false here will block the rebase.
return true;
}
}
| engine/tools/githooks/lib/src/pre_rebase_command.dart/0 | {
"file_path": "engine/tools/githooks/lib/src/pre_rebase_command.dart",
"repo_id": "engine",
"token_count": 188
} | 427 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:path/path.dart' as p;
import 'package:skia_gold_client/skia_gold_client.dart';
import 'src/digests_json_format.dart';
/// Used by [harvest] to process a directory for Skia Gold upload.
abstract class Harvester {
/// Creates a new [Harvester] from the directory at [workDirectory].
///
/// The directory is expected to match the following structure:
/// ```txt
/// workDirectory/
/// - digest.json
/// - test_name_1.png
/// - test_name_2.png
/// - ...
/// ```
///
/// The format of `digest.json` is expected to match the following:
/// ```jsonc
/// {
/// "dimensions": {
/// // Key-value pairs of dimensions to provide to Skia Gold.
/// // For example:
/// "platform": "linux",
/// },
/// "entries": [
/// // Each entry is a test-run with the following format:
/// {
/// // Path must be a direct sibling of digest.json.
/// "filename": "test_name_1.png",
///
/// // Called `screenshotSize` in Skia Gold (width * height).
/// "width": 100,
/// "height": 100,
///
/// // Called `differentPixelsRate` in Skia Gold.
/// "maxDiffPixelsPercent": 0.01,
///
/// // Called `pixelColorDelta` in Skia Gold.
/// "maxColorDelta": 0
/// }
/// ]
/// }
/// ```
static Future<Harvester> create(
io.Directory workDirectory, StringSink stderr,
{AddImageToSkiaGold? addImageToSkiaGold}) async {
final io.File file = io.File(p.join(workDirectory.path, 'digest.json'));
if (!file.existsSync()) {
// Check if the directory exists or if the file is just missing.
if (!workDirectory.existsSync()) {
throw ArgumentError('Directory not found: ${workDirectory.path}.');
}
// Lookup sibling files to help the user understand what's missing.
final List<io.FileSystemEntity> files = workDirectory.listSync();
throw StateError(
'File "digest.json" not found in ${workDirectory.path}.\n\n'
'Found files: ${files.map((io.FileSystemEntity e) => p.basename(e.path)).join(', ')}',
);
}
final Digests digests = Digests.parse(file.readAsStringSync());
if (addImageToSkiaGold != null) {
return _DryRunHarvester(digests, stderr, workDirectory, addImageToSkiaGold);
} else {
return SkiaGoldHarvester._create(digests, stderr, workDirectory);
}
}
Future<void> _addImg(
String testName,
io.File goldenFile, {
double differentPixelsRate,
int pixelColorDelta,
required int screenshotSize,
});
Future<void> _auth();
Digests get _digests;
StringSink get _stderr;
io.Directory get _workDirectory;
}
/// A [Harvester] that communicates with a real [SkiaGoldClient].
class SkiaGoldHarvester implements Harvester {
SkiaGoldHarvester._init(
this._digests, this._stderr, this._workDirectory, this.client);
@override
final Digests _digests;
@override
final StringSink _stderr;
@override
final io.Directory _workDirectory;
/// The [SkiaGoldClient] that will be used for harvesting.
final SkiaGoldClient client;
static Future<SkiaGoldHarvester> _create(
Digests digests, StringSink stderr, io.Directory workDirectory) async {
final SkiaGoldClient client =
SkiaGoldClient(workDirectory, dimensions: digests.dimensions);
return SkiaGoldHarvester._init(digests, stderr, workDirectory, client);
}
@override
Future<void> _addImg(String testName, io.File goldenFile,
{double differentPixelsRate = 0.01,
int pixelColorDelta = 0,
required int screenshotSize}) async {
return client.addImg(testName, goldenFile,
differentPixelsRate: differentPixelsRate,
pixelColorDelta: pixelColorDelta,
screenshotSize: screenshotSize);
}
@override
Future<void> _auth() {
return client.auth();
}
}
/// A [Harvester] that doesn't harvest, just calls a callback.
class _DryRunHarvester implements Harvester {
_DryRunHarvester(
this._digests, this._stderr, this._workDirectory,
this._addImageToSkiaGold);
@override
final Digests _digests;
@override
final StringSink _stderr;
@override
final io.Directory _workDirectory;
final AddImageToSkiaGold _addImageToSkiaGold;
@override
Future<void> _addImg(String testName, io.File goldenFile,
{double differentPixelsRate = 0.01,
int pixelColorDelta = 0,
required int screenshotSize}) async {
return _addImageToSkiaGold(testName, goldenFile,
differentPixelsRate: differentPixelsRate,
pixelColorDelta: pixelColorDelta,
screenshotSize: screenshotSize);
}
@override
Future<void> _auth() async {
_stderr.writeln('using dimensions: ${_digests.dimensions}');
}
}
/// Uploads the images of digests in [harvester] to Skia Gold.
Future<void> harvest(Harvester harvester) async {
await harvester._auth();
final List<Future<void>> pendingComparisons = <Future<void>>[];
for (final DigestEntry entry in harvester._digests.entries) {
final io.File goldenFile =
io.File(p.join(harvester._workDirectory.path, entry.filename));
final Future<void> future = harvester
._addImg(
entry.filename,
goldenFile,
screenshotSize: entry.width * entry.height,
differentPixelsRate: entry.maxDiffPixelsPercent,
pixelColorDelta: entry.maxColorDelta,
)
.catchError((Object e) {
harvester._stderr.writeln('Failed to add image to Skia Gold: $e');
throw FailedComparisonException(entry.filename);
});
pendingComparisons.add(future);
}
await Future.wait(pendingComparisons);
}
/// An exception thrown when a comparison fails.
final class FailedComparisonException implements Exception {
/// Creates a new instance of [FailedComparisonException].
const FailedComparisonException(this.testName);
/// The test name that failed.
final String testName;
@override
String toString() => 'Failed comparison: $testName';
}
/// A function that uploads an image to Skia Gold.
typedef AddImageToSkiaGold = Future<void> Function(
String testName,
io.File goldenFile, {
double differentPixelsRate,
int pixelColorDelta,
required int screenshotSize,
});
| engine/tools/golden_tests_harvester/lib/golden_tests_harvester.dart/0 | {
"file_path": "engine/tools/golden_tests_harvester/lib/golden_tests_harvester.dart",
"repo_id": "engine",
"token_count": 2300
} | 428 |
include: ../../analysis_options.yaml
linter:
rules:
avoid_print: false
only_throw_errors: false
public_member_api_docs: false
| engine/tools/licenses/analysis_options.yaml/0 | {
"file_path": "engine/tools/licenses/analysis_options.yaml",
"repo_id": "engine",
"token_count": 54
} | 429 |
This license collection script is, fundamentally, one giant pile of
special cases. As such, while there is an attempt to model the rules
that apply to licenses and apply some sort of order to the process,
the code is less than clear. This file attempts to provide an overview.
main.dart is the core of the operation. It first walks the entire
directory tree starting from the root of the repository (which is to
be specified on the command line as the only argument), creating an
in-memory representation of the project (make sure to run this only
after you've run gclient sync, so that all dependencies are on disk).
This is the step that is labeled "Preparing data structures".
Then, it walks this in-memory representation, attempting to assign to
each file one or more licenses. This is the step labeled "Collecting
licenses", which takes a long time.
Finally, it prints out these licenses.
The in-memory representation is a tree of RepositoryEntry objects.
There's three important types of these objects: RepositoryDirectory
objects, which represent directories; RepositoryLicensedFile, which
represents source files and resources that might end up in the binary,
and RepositoryLicenseFile, which represents license files that do not
themselves end up in the binary other than as a side-effect of this
script.
RepositoryDirectory objects contain three lists, the list of
RepositoryDirectory subdirectories, the list of RepositoryLicensedFile
children, and the list of RepositoryLicenseFile children.
RepositoryDirectory objects are the objects that crawl the filesystem.
While the script is pretty conservative (including probably more
licenses than strictly necessary), it tries to avoid including
material that isn't actually used. To do this, RepositoryDirectory
objects only crawl directories and files for which shouldRecurse
returns true. For example, shouldRecurse returns false for ".git"
files. To simplify the configuration of such rules, the default is to
apply the rules in the paths.dart file.
Some directories and files require special handling, and have specific
subclasses of the above classes. To create the appropriate objects,
RepositoryDirectory calls createSubdirectory and createFile to create
the nodes of the tree.
The low-level handling of files is done by classes in filesystem.dart.
This code supports transparently crawling into archives (e.g. .jar
files), as well as handling UTF-8 vs latin1. It contains much magic
and hard-coded file names and so on to handle distinguishing binary
files from text files, and so forth.
This code uses the cache described in cache.dart to try to avoid
having to repeatedly reopen the same file many times in a row.
In the case of a binary file, the license is found by crawling around
the directory structure looking for a "default" license file. In the
case of text files, though, it's often the case that the file itself
mentions the license and therefore the file itself is inspected
looking for copyright or license text. This scanning is done by
determineLicensesFor() in licenses.dart.
This function uses patterns that are themselves in patterns.dart. In
this file we find all manner of long complicated and somewhat crazy
regular expressions. This is where you see quite how absurd this work
can actually be. It is left as an exercise to the reader to look for
the implications of many of the regular expressions; as one example,
though, consider the case of the pattern that matches the AFL/LGPL
dual license statement: there is one file in which the ZIP code for
the Free Software Foundation is off by one, for no clear reason,
leading to the pattern ending with "MA 0211[01]-1307, USA".
The license.dart file also contains the License object, the code that
attempts to determine what copyrights apply to which licenses, and the
code that attempts to identify the licenses themselves (at a high
level), to make sure that appropriate clauses are followed (e.g.
including the copyright with a BSD notice).
In formatter.dart you will find the only part of this codebase that is
actually tested at this time; this is the code that reformats blobs of
text to remove comments and decorations and the like.
The biggest problem with this script right now is that it is absurdly
slow, largely because of the many, many applications of regular
expressions in pattern.dart (especially the ones that use _linebreak).
In regexp_debug.dart we have a wrapper around RegExp that attempts to
quantify this cost, you can see the results if you run the script with
`--verbose`. Long term, the right solution is to change from these
all-in-one patterns to a world where we first tokenize each file, then
apply word-by-word pattern matching to the tokenized input.
| engine/tools/licenses/lib/README/0 | {
"file_path": "engine/tools/licenses/lib/README",
"repo_id": "engine",
"token_count": 1085
} | 430 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
name: path_ops
description: A Dart FFI wrapper for Skia PathKit.
version: 0.0.0
publish_to: none
homepage: https://github.com/flutter/engine/tree/main/tools/path_ops
environment:
sdk: '>=3.2.0-0 <4.0.0'
dev_dependencies:
litetest: any
dependency_overrides:
async_helper:
path: ../../../../third_party/dart/pkg/async_helper
expect:
path: ../../../../third_party/dart/pkg/expect
litetest:
path: ../../../testing/litetest
meta:
path: ../../../../third_party/dart/pkg/meta
smith:
path: ../../../../third_party/dart/pkg/smith
| engine/tools/path_ops/dart/pubspec.yaml/0 | {
"file_path": "engine/tools/path_ops/dart/pubspec.yaml",
"repo_id": "engine",
"token_count": 279
} | 431 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' as convert;
import 'package:engine_build_configs/src/build_config.dart';
import 'package:litetest/litetest.dart';
import 'package:platform/platform.dart';
import 'fixtures.dart' as fixtures;
int main() {
test('BuildConfig parser works', () {
final BuilderConfig buildConfig = BuilderConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(fixtures.buildConfigJson) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.errors, isNull);
expect(buildConfig.builds.length, equals(1));
final Build globalBuild = buildConfig.builds[0];
expect(globalBuild.name, equals('build_name'));
expect(globalBuild.gn.length, equals(4));
expect(globalBuild.gn[0], equals('--gn-arg'));
expect(globalBuild.droneDimensions.length, equals(1));
expect(globalBuild.droneDimensions[0], equals('os=Linux'));
expect(
globalBuild.canRunOn(FakePlatform(operatingSystem: Platform.linux)),
isTrue,
);
expect(
globalBuild.canRunOn(FakePlatform(operatingSystem: Platform.macOS)),
isFalse,
);
final BuildNinja ninja = globalBuild.ninja;
expect(ninja.config, equals('build_name'));
expect(ninja.targets.length, equals(1));
expect(ninja.targets[0], equals('ninja_target'));
expect(globalBuild.archives.length, equals(1));
final BuildArchive buildArchive = globalBuild.archives[0];
expect(buildArchive.name, equals('build_name'));
expect(buildArchive.basePath, equals('base/path'));
expect(buildArchive.type, equals('gcs'));
expect(buildArchive.includePaths.length, equals(1));
expect(buildArchive.includePaths[0], equals('include/path'));
expect(globalBuild.tests.length, equals(1));
final BuildTest tst = globalBuild.tests[0];
expect(tst.name, equals('build_name tests'));
expect(tst.language, equals('python3'));
expect(tst.script, equals('test/script.py'));
expect(tst.parameters.length, equals(1));
expect(tst.parameters[0], equals('--test-params'));
expect(tst.contexts.length, equals(1));
expect(tst.contexts[0], equals('context'));
expect(globalBuild.generators.length, equals(1));
final BuildTask buildTask = globalBuild.generators[0];
expect(buildTask.name, equals('generator_task'));
expect(buildTask.scripts.length, equals(1));
expect(buildTask.scripts[0], equals('gen/script.py'));
expect(buildTask.parameters.length, equals(1));
expect(buildTask.parameters[0], equals('--gen-param'));
expect(buildConfig.generators.length, equals(1));
final TestTask testTask = buildConfig.generators[0];
expect(testTask.name, equals('global generator task'));
expect(testTask.language, equals('dart'));
expect(testTask.script, equals('global/gen_script.dart'));
expect(testTask.parameters.length, equals(1));
expect(testTask.parameters[0], equals('--global-gen-param'));
expect(buildConfig.tests.length, equals(1));
final GlobalTest globalTest = buildConfig.tests[0];
expect(globalTest.name, equals('global test'));
expect(globalTest.recipe, equals('engine_v2/tester_engine'));
expect(globalTest.droneDimensions.length, equals(1));
expect(globalTest.droneDimensions[0], equals('os=Linux'));
expect(
globalTest.canRunOn(FakePlatform(operatingSystem: Platform.linux)),
isTrue,
);
expect(
globalTest.canRunOn(FakePlatform(operatingSystem: Platform.macOS)),
isFalse,
);
expect(globalTest.dependencies.length, equals(1));
expect(globalTest.dependencies[0], equals('dependency'));
expect(globalTest.tasks.length, equals(1));
final TestTask globalTestTask = globalTest.tasks[0];
expect(globalTestTask.name, equals('global test task'));
expect(globalTestTask.script, equals('global/test/script.py'));
expect(globalTestTask.language, equals('<undef>'));
});
test('BuildConfig flags invalid input', () {
const String invalidInput = '''
{
"builds": 5,
"generators": {},
"tests": []
}
''';
final BuilderConfig buildConfig = BuilderConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isFalse);
expect(
buildConfig.errors![0],
equals(
'For field "builds", expected type: list, actual type: int.',
));
});
test('GlobalBuild flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"name": 5
}
],
"generators": {},
"tests": []
}
''';
final BuilderConfig buildConfig = BuilderConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isFalse);
expect(
buildConfig.builds[0].errors![0],
equals(
'For field "name", expected type: string, actual type: int.',
));
});
test('BuildNinja flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"ninja": {
"config": 5
}
}
],
"generators": {},
"tests": []
}
''';
final BuilderConfig buildConfig = BuilderConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isTrue);
expect(buildConfig.builds[0].ninja.valid, isFalse);
expect(
buildConfig.builds[0].ninja.errors![0],
equals(
'For field "config", expected type: string, actual type: int.',
));
});
test('BuildTest flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"tests": [
{
"language": 5
}
]
}
],
"generators": {},
"tests": []
}
''';
final BuilderConfig buildConfig = BuilderConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isTrue);
expect(buildConfig.builds[0].tests[0].valid, isFalse);
expect(
buildConfig.builds[0].tests[0].errors![0],
equals(
'For field "language", expected type: string, actual type: int.',
));
});
test('BuildTask flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"generators": {
"tasks": [
{
"name": 5
}
]
}
}
],
"generators": {},
"tests": []
}
''';
final BuilderConfig buildConfig = BuilderConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isTrue);
expect(buildConfig.builds[0].generators[0].valid, isFalse);
expect(
buildConfig.builds[0].generators[0].errors![0],
equals(
'For field "name", expected type: string, actual type: int.',
));
});
test('BuildArchive flags invalid input', () {
const String invalidInput = '''
{
"builds": [
{
"archives": [
{
"name": 5
}
]
}
],
"generators": {},
"tests": []
}
''';
final BuilderConfig buildConfig = BuilderConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.builds.length, equals(1));
expect(buildConfig.builds[0].valid, isTrue);
expect(buildConfig.builds[0].archives[0].valid, isFalse);
expect(
buildConfig.builds[0].archives[0].errors![0],
equals(
'For field "name", expected type: string, actual type: int.',
));
});
test('GlobalTest flags invalid input', () {
const String invalidInput = '''
{
"tests": [
{
"name": 5
}
]
}
''';
final BuilderConfig buildConfig = BuilderConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.tests.length, equals(1));
expect(buildConfig.tests[0].valid, isFalse);
expect(
buildConfig.tests[0].errors![0],
equals(
'For field "name", expected type: string, actual type: int.',
));
});
test('TestTask flags invalid input', () {
const String invalidInput = '''
{
"tests": [
{
"tasks": [
{
"name": 5
}
]
}
]
}
''';
final BuilderConfig buildConfig = BuilderConfig.fromJson(
path: 'linux_test_config',
map: convert.jsonDecode(invalidInput) as Map<String, Object?>,
);
expect(buildConfig.valid, isTrue);
expect(buildConfig.tests.length, equals(1));
expect(buildConfig.tests[0].tasks[0].valid, isFalse);
expect(
buildConfig.tests[0].tasks[0].errors![0],
contains(
'For field "name", expected type: string, actual type: int.',
));
});
return 0;
}
| engine/tools/pkg/engine_build_configs/test/build_config_test.dart/0 | {
"file_path": "engine/tools/pkg/engine_build_configs/test/build_config_test.dart",
"repo_id": "engine",
"token_count": 3795
} | 432 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//build/compiled_action.gni")
# Inflate the input template file using Inja and the specified values.
template("templater") {
assert(defined(invoker.input), "The input template must be specified.")
assert(defined(invoker.output), "The output location must be defined.")
assert(
defined(invoker.values),
"The values referenced in the template must be specified. Use the --key=value format for each value.")
compiled_action(target_name) {
tool = "//flutter/tools/templater"
inputs = [ invoker.input ]
outputs = [ invoker.output ]
templater_input_path = rebase_path(invoker.input, root_build_dir)
templater_input_flag = "--templater-input=$templater_input_path"
templater_output_path = rebase_path(invoker.output, root_build_dir)
templater_output_flag = "--templater-output=$templater_output_path"
args = [
templater_input_flag,
templater_output_flag,
] + invoker.values
}
}
| engine/tools/templater/templater.gni/0 | {
"file_path": "engine/tools/templater/templater.gni",
"repo_id": "engine",
"token_count": 400
} | 433 |
// 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 "vulkan_backbuffer.h"
#include <limits>
#include "flutter/vulkan/procs/vulkan_proc_table.h"
#include "third_party/skia/include/gpu/vk/GrVkTypes.h"
#include "vulkan/vulkan.h"
namespace vulkan {
VulkanBackbuffer::VulkanBackbuffer(const VulkanProcTable& p_vk,
const VulkanHandle<VkDevice>& device,
const VulkanHandle<VkCommandPool>& pool)
: vk_(p_vk),
device_(device),
usage_command_buffer_(p_vk, device, pool),
render_command_buffer_(p_vk, device, pool),
valid_(false) {
if (!usage_command_buffer_.IsValid() || !render_command_buffer_.IsValid()) {
FML_DLOG(INFO) << "Command buffers were not valid.";
return;
}
if (!CreateSemaphores()) {
FML_DLOG(INFO) << "Could not create semaphores.";
return;
}
if (!CreateFences()) {
FML_DLOG(INFO) << "Could not create fences.";
return;
}
valid_ = true;
}
VulkanBackbuffer::~VulkanBackbuffer() {
FML_ALLOW_UNUSED_LOCAL(WaitFences());
}
bool VulkanBackbuffer::IsValid() const {
return valid_;
}
bool VulkanBackbuffer::CreateSemaphores() {
const VkSemaphoreCreateInfo create_info = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
};
auto semaphore_collect = [this](VkSemaphore semaphore) {
vk_.DestroySemaphore(device_, semaphore, nullptr);
};
for (size_t i = 0; i < semaphores_.size(); i++) {
VkSemaphore semaphore = VK_NULL_HANDLE;
if (VK_CALL_LOG_ERROR(vk_.CreateSemaphore(device_, &create_info, nullptr,
&semaphore)) != VK_SUCCESS) {
return false;
}
semaphores_[i] = VulkanHandle<VkSemaphore>{semaphore, semaphore_collect};
}
return true;
}
bool VulkanBackbuffer::CreateFences() {
const VkFenceCreateInfo create_info = {
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
.pNext = nullptr,
.flags = VK_FENCE_CREATE_SIGNALED_BIT,
};
auto fence_collect = [this](VkFence fence) {
vk_.DestroyFence(device_, fence, nullptr);
};
for (size_t i = 0; i < use_fences_.size(); i++) {
VkFence fence = VK_NULL_HANDLE;
if (VK_CALL_LOG_ERROR(vk_.CreateFence(device_, &create_info, nullptr,
&fence)) != VK_SUCCESS) {
return false;
}
use_fences_[i] = VulkanHandle<VkFence>{fence, fence_collect};
}
return true;
}
bool VulkanBackbuffer::WaitFences() {
VkFence fences[std::tuple_size_v<decltype(use_fences_)>];
for (size_t i = 0; i < use_fences_.size(); i++) {
fences[i] = use_fences_[i];
}
return VK_CALL_LOG_ERROR(vk_.WaitForFences(
device_, static_cast<uint32_t>(use_fences_.size()), fences, true,
std::numeric_limits<uint64_t>::max())) == VK_SUCCESS;
}
bool VulkanBackbuffer::ResetFences() {
VkFence fences[std::tuple_size_v<decltype(use_fences_)>];
for (size_t i = 0; i < use_fences_.size(); i++) {
fences[i] = use_fences_[i];
}
return VK_CALL_LOG_ERROR(vk_.ResetFences(
device_, static_cast<uint32_t>(use_fences_.size()), fences)) ==
VK_SUCCESS;
}
const VulkanHandle<VkFence>& VulkanBackbuffer::GetUsageFence() const {
return use_fences_[0];
}
const VulkanHandle<VkFence>& VulkanBackbuffer::GetRenderFence() const {
return use_fences_[1];
}
const VulkanHandle<VkSemaphore>& VulkanBackbuffer::GetUsageSemaphore() const {
return semaphores_[0];
}
const VulkanHandle<VkSemaphore>& VulkanBackbuffer::GetRenderSemaphore() const {
return semaphores_[1];
}
VulkanCommandBuffer& VulkanBackbuffer::GetUsageCommandBuffer() {
return usage_command_buffer_;
}
VulkanCommandBuffer& VulkanBackbuffer::GetRenderCommandBuffer() {
return render_command_buffer_;
}
} // namespace vulkan
| engine/vulkan/vulkan_backbuffer.cc/0 | {
"file_path": "engine/vulkan/vulkan_backbuffer.cc",
"repo_id": "engine",
"token_count": 1692
} | 434 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/vulkan/vulkan_skia_proc_table.h"
namespace vulkan {
GrVkGetProc CreateSkiaGetProc(const fml::RefPtr<vulkan::VulkanProcTable>& vk) {
if (!vk || !vk->IsValid()) {
return nullptr;
}
return [vk](const char* proc_name, VkInstance instance, VkDevice device) {
if (device != VK_NULL_HANDLE) {
auto result =
vk->AcquireProc(proc_name, VulkanHandle<VkDevice>{device, nullptr});
if (result != nullptr) {
return result;
}
}
return vk->AcquireProc(proc_name,
VulkanHandle<VkInstance>{instance, nullptr});
};
}
} // namespace vulkan
| engine/vulkan/vulkan_skia_proc_table.cc/0 | {
"file_path": "engine/vulkan/vulkan_skia_proc_table.cc",
"repo_id": "engine",
"token_count": 326
} | 435 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:args/args.dart';
import 'package:path/path.dart' as path;
final ArgParser argParser = ArgParser()
..addOption('output-dir')
..addOption('input-dir')
..addFlag('ui')
..addFlag('public')
..addOption('library-name')
..addOption('api-file')
..addMultiOption('source-file')
..addOption('stamp')
..addOption('depfile')
..addOption('exclude-pattern')
..addOption('build-dir');
final List<Replacer> uiPatterns = <Replacer>[
AllReplacer(RegExp(r'library\s+ui;'), 'library dart.ui;'),
AllReplacer(RegExp(r'part\s+of\s+ui;'), 'part of dart.ui;'),
// import 'src/engine.dart' as engine;
AllReplacer(RegExp(r'''
import\s*'src/engine.dart'\s*as\s+engine;
'''), r'''
import 'dart:_engine' as engine;
'''),
// import 'ui_web/src/ui_web.dart' as ui_web;
AllReplacer(RegExp(r'''
import\s*'ui_web/src/ui_web.dart'\s*as\s+ui_web;
'''), r'''
import 'dart:ui_web' as ui_web;
'''),
];
List<Replacer> generateApiFilePatterns(String libraryName, bool isPublic, List<String> extraImports) {
final String libraryPrefix = isPublic ? '' : '_';
return <Replacer>[
AllReplacer(RegExp('library\\s+$libraryName;'), '''
@JS()
library dart.$libraryPrefix$libraryName;
import 'dart:async';
import 'dart:collection';
import 'dart:convert' hide Codec;
import 'dart:developer' as developer;
import 'dart:js_util' as js_util;
import 'dart:_js_annotations';
import 'dart:js_interop' hide JS;
import 'dart:js_interop_unsafe';
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui' as ui;
${extraImports.join('\n')}
'''
),
// Replace exports of engine files with "part" directives.
MappedReplacer(RegExp('''
export\\s*'$libraryName/(.*)';
'''), (Match match) => '''
part '$libraryName/${match.group(1)}';
'''
),
];
}
List<Replacer> generatePartsPatterns(String libraryName, bool isPublic) {
final String libraryPrefix = isPublic ? '' : '_';
return <Replacer>[
AllReplacer(RegExp('part\\s+of\\s+$libraryName;'), 'part of dart.$libraryPrefix$libraryName;'),
// Remove library-level JS annotations.
AllReplacer(RegExp(r'\n@JS(.*)\nlibrary .+;'), ''),
// Remove library directives.
AllReplacer(RegExp(r'\nlibrary .+;'), ''),
// Remove imports/exports from all part files.
AllReplacer(RegExp(r'\nimport\s*.*'), ''),
AllReplacer(RegExp(r'\nexport\s*.*'), ''),
AllReplacer(RegExp(r'\n@DefaultAsset(.*)'), ''),
];
}
final List<Replacer> stripMetaPatterns = <Replacer>[
AllReplacer(RegExp(r"import\s*'package:meta/meta.dart';"), ''),
AllReplacer('@required', ''),
AllReplacer('@protected', ''),
AllReplacer('@mustCallSuper', ''),
AllReplacer('@immutable', ''),
AllReplacer('@visibleForTesting', ''),
];
const Set<String> rootLibraryNames = <String>{
'ui_web',
'engine',
'skwasm_stub',
'skwasm_impl',
};
final Map<Pattern, String> extraImportsMap = <Pattern, String>{
RegExp('skwasm_(stub|impl)'): "import 'dart:_skwasm_stub' if (dart.library.ffi) 'dart:_skwasm_impl';",
'ui_web': "import 'dart:ui_web' as ui_web;",
'engine': "import 'dart:_engine';",
'web_unicode': "import 'dart:_web_unicode';",
'web_test_fonts': "import 'dart:_web_test_fonts';",
'web_locale_keymap': "import 'dart:_web_locale_keymap' as locale_keymap;",
};
// Rewrites the "package"-style web ui library into a dart:ui implementation.
// So far this only requires a replace of the library declarations.
void main(List<String> arguments) {
final ArgResults results = argParser.parse(arguments);
final Directory directory = Directory(results['output-dir'] as String);
final String inputDirectoryPath = results['input-dir'] as String;
final String? excludePattern = results['exclude-pattern'] as String?;
final String stampfilePath = results['stamp'] as String;
final String depfilePath = results['depfile'] as String;
final String buildDirPath = results['build-dir'] as String;
String Function(String source)? preprocessor;
List<Replacer> replacementPatterns;
String? libraryName;
final bool isPublic = results['public'] as bool;
if (results['ui'] as bool) {
replacementPatterns = uiPatterns;
} else {
libraryName = results['library-name'] as String?;
if (libraryName == null) {
throw Exception('library-name must be specified if not rewriting ui');
}
preprocessor = (String source) => preprocessPartFile(source, libraryName!);
replacementPatterns = generatePartsPatterns(libraryName, isPublic);
}
final List<String> inputFiles = <String>[];
final List<FileSystemEntity> entries = Directory(inputDirectoryPath).listSync(
recursive: true, followLinks: false,
);
for (final File inputFile in entries.whereType<File>()) {
if (excludePattern != null && inputFile.path.startsWith(excludePattern)) {
continue;
}
if (!inputFile.path.endsWith('.dart') || inputFile.path.endsWith('_test.dart')) {
continue;
}
inputFiles.add(path.relative(inputFile.path, from: buildDirPath));
String pathSuffix = inputFile.path.substring(inputDirectoryPath.length);
if (libraryName != null) {
pathSuffix = path.join(libraryName, pathSuffix);
}
final String outputFilePath = path.join(directory.path, pathSuffix);
processFile(inputFile.path, outputFilePath, preprocessor, replacementPatterns);
}
if (results['api-file'] != null) {
if (libraryName == null) {
throw Exception('library-name must be specified if api-file is specified');
}
final String inputFilePath = results['api-file'] as String;
final String outputFilePath = path.join(
directory.path, path.basename(inputFilePath));
final List<String> extraImports = getExtraImportsForLibrary(libraryName);
replacementPatterns = generateApiFilePatterns(libraryName, isPublic, extraImports);
processFile(
inputFilePath,
outputFilePath,
(String source) => validateApiFile(inputFilePath, source, libraryName!),
replacementPatterns
);
}
File(stampfilePath).writeAsStringSync('stamp');
writeDepfile(depfilePath, stampfilePath, inputFiles);
}
void writeDepfile(String depfilePath, String stampfilePath, List<String> inputFiles) {
final StringBuffer outBuf = StringBuffer();
outBuf.write('$stampfilePath: ');
outBuf.write(inputFiles.join(' '));
File(depfilePath).writeAsStringSync(outBuf.toString());
}
List<String> getExtraImportsForLibrary(String libraryName) {
// Only our root libraries should have extra imports.
if (!rootLibraryNames.contains(libraryName)) {
return <String>[];
}
final List<String> extraImports = <String>[];
for (final MapEntry<Pattern, String> entry in extraImportsMap.entries) {
// A library shouldn't import itself.
if (entry.key.matchAsPrefix(libraryName) == null) {
extraImports.add(entry.value);
}
}
if (libraryName == 'skwasm_impl') {
extraImports.add("import 'dart:_wasm';");
}
return extraImports;
}
void processFile(String inputFilePath, String outputFilePath, String Function(String source)? preprocessor, List<Replacer> replacementPatterns) {
final File inputFile = File(inputFilePath);
final File outputFile = File(outputFilePath)
..createSync(recursive: true);
outputFile.writeAsStringSync(processSource(
inputFile.readAsStringSync(),
preprocessor,
replacementPatterns));
}
String processSource(String source, String Function(String source)? preprocessor, List<Replacer> replacementPatterns) {
if (preprocessor != null) {
source = preprocessor(source);
}
for (final Replacer replacer in stripMetaPatterns) {
source = replacer.perform(source);
}
for (final Replacer replacer in replacementPatterns) {
source = replacer.perform(source);
}
return source;
}
// Enforces a particular structure in top level api files for sublibraries.
//
// Code in api files must only be made of the library directive, exports,
// and code comments. Imports are disallowed. Instead, the required imports are
// added by this script during the rewrite.
String validateApiFile(String apiFilePath, String apiFileCode, String libraryName) {
final List<String> expectedLines = <String>[
'library $libraryName;',
];
final List<String> lines = apiFileCode.split('\n');
for (int i = 0; i < lines.length; i += 1) {
final int lineNumber = i + 1;
final String line = lines[i].trim();
if (line.isEmpty) {
// Emply lines are OK
continue;
}
if (expectedLines.contains(line)) {
// Expected; let it pass.
continue;
}
if (line.startsWith('//')) {
// Comments are OK
continue;
}
if (line.startsWith('export')) {
// Exports are OK
continue;
}
if (line.startsWith('@DefaultAsset')) {
// Default asset annotations are OK
continue;
}
if (line.startsWith("import 'dart:ffi';")) {
// dart:ffi import is an exception to the import rule, since the
// @DefaultAsset annotation comes from dart:ffi.
continue;
}
throw Exception(
'on line $lineNumber: unexpected code in $apiFilePath. This file '
'may only contain comments and exports. Found:\n'
'$line'
);
}
return apiFileCode;
}
String preprocessPartFile(String source, String libraryName) {
return 'part of $libraryName;\n$source';
}
/// Responsible for performing string replacements.
abstract class Replacer {
/// Performs the replacement in the provided [text].
String perform(String text);
}
/// Replaces all occurrences of a pattern with a fixed string.
class AllReplacer implements Replacer {
/// Creates a new tuple with the given [pattern] and [replacement] string.
AllReplacer(this._pattern, this._replacement);
/// The pattern to be replaced.
final Pattern _pattern;
/// The replacement string.
final String _replacement;
@override
String perform(String text) {
return text.replaceAll(_pattern, _replacement);
}
}
/// Uses a callback to replace each occurrence of a pattern.
class MappedReplacer implements Replacer {
MappedReplacer(this._pattern, this._replace);
/// The pattern to be replaced.
final RegExp _pattern;
/// A callback to replace each occurrence of [_pattern].
final String Function(Match match) _replace;
@override
String perform(String text) {
return text.replaceAllMapped(_pattern, _replace);
}
}
| engine/web_sdk/sdk_rewriter.dart/0 | {
"file_path": "engine/web_sdk/sdk_rewriter.dart",
"repo_id": "engine",
"token_count": 3610
} | 436 |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectCodeStyleSettingsManager">
<option name="PER_PROJECT_SETTINGS">
<value>
<option name="OTHER_INDENT_OPTIONS">
<value>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="8" />
<option name="USE_TAB_CHARACTER" value="false" />
<option name="SMART_TABS" value="false" />
<option name="LABEL_INDENT_SIZE" value="0" />
<option name="LABEL_INDENT_ABSOLUTE" value="false" />
<option name="USE_RELATIVE_INDENTS" value="false" />
</value>
</option>
<option name="LINE_SEPARATOR" value=" " />
<option name="FIELD_NAME_PREFIX" value="my" />
<option name="STATIC_FIELD_NAME_PREFIX" value="our" />
<option name="PREFER_LONGER_NAMES" value="false" />
<option name="PACKAGES_TO_USE_IMPORT_ON_DEMAND">
<value>
<package name="java.awt" withSubpackages="false" static="false" />
<package name="javax.tools" withSubpackages="true" static="false" />
<package name="javax.swing" withSubpackages="false" static="false" />
</value>
</option>
<option name="STATIC_METHODS_ORDER_WEIGHT" value="5" />
<option name="METHODS_ORDER_WEIGHT" value="4" />
<option name="RIGHT_MARGIN" value="140" />
<option name="FORMATTER_TAGS_ENABLED" value="true" />
<option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />
<option name="BLOCK_COMMENT_AT_FIRST_COLUMN" value="false" />
<XML>
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
</XML>
<codeStyleSettings language="CFML">
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_TERNARY_OPERATION" value="true" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="ECMA Script Level 4">
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_TERNARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_EXTENDS_LIST" value="true" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="EXTENDS_LIST_WRAP" value="1" />
<option name="EXTENDS_KEYWORD_WRAP" value="1" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="Groovy">
<option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="0" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_ASSIGNMENT" value="true" />
<option name="ALIGN_MULTILINE_TERNARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_THROWS_LIST" value="true" />
<option name="ALIGN_MULTILINE_EXTENDS_LIST" value="true" />
<option name="SPACE_AFTER_TYPE_CAST" value="false" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="EXTENDS_LIST_WRAP" value="1" />
<option name="THROWS_LIST_WRAP" value="5" />
<option name="EXTENDS_KEYWORD_WRAP" value="1" />
<option name="THROWS_KEYWORD_WRAP" value="1" />
<option name="METHOD_CALL_CHAIN_WRAP" value="1" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="FIELD_ANNOTATION_WRAP" value="0" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="8" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="HTML">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="8" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />
<option name="BLOCK_COMMENT_AT_FIRST_COLUMN" value="false" />
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
<option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="0" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_ASSIGNMENT" value="true" />
<option name="ALIGN_MULTILINE_TERNARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_THROWS_LIST" value="true" />
<option name="ALIGN_MULTILINE_EXTENDS_LIST" value="true" />
<option name="ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION" value="true" />
<option name="SPACE_WITHIN_BRACES" value="true" />
<option name="SPACE_AFTER_TYPE_CAST" value="false" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="EXTENDS_LIST_WRAP" value="1" />
<option name="THROWS_LIST_WRAP" value="5" />
<option name="EXTENDS_KEYWORD_WRAP" value="1" />
<option name="THROWS_KEYWORD_WRAP" value="1" />
<option name="METHOD_CALL_CHAIN_WRAP" value="1" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="FIELD_ANNOTATION_WRAP" value="0" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="8" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JavaScript">
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_TERNARY_OPERATION" value="true" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="PHP">
<option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="0" />
<option name="CLASS_BRACE_STYLE" value="1" />
<option name="METHOD_BRACE_STYLE" value="1" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_TERNARY_OPERATION" value="true" />
<option name="ALIGN_MULTILINE_EXTENDS_LIST" value="true" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="EXTENDS_LIST_WRAP" value="1" />
<option name="EXTENDS_KEYWORD_WRAP" value="1" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="Python">
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="8" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
</value>
</option>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</component>
</project> | flutter-intellij/.idea/codeStyleSettings.xml/0 | {
"file_path": "flutter-intellij/.idea/codeStyleSettings.xml",
"repo_id": "flutter-intellij",
"token_count": 6216
} | 437 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="flutter-intellij [plugin-make]" type="DartCommandLineRunConfigurationType" factoryName="Dart Command Line Application">
<option name="arguments" value="make" />
<option name="filePath" value="$PROJECT_DIR$/tool/plugin/bin/main.dart" />
<option name="workingDirectory" value="$PROJECT_DIR$" />
<method v="2" />
</configuration>
</component> | flutter-intellij/.idea/runConfigurations/flutter_intellij__plugin_make_.xml/0 | {
"file_path": "flutter-intellij/.idea/runConfigurations/flutter_intellij__plugin_make_.xml",
"repo_id": "flutter-intellij",
"token_count": 140
} | 438 |
# Editing Android Native Code
This is a replacement for:
https://flutter.dev/using-ide/#edit-android-code
***
## Getting Started
We recommend using the latest stable version of
Android Studio to edit the native Android
code in your Flutter app. The Flutter project contains a directory
named `android`. This is the root project of the Android code.
If your Flutter app is named `flutter_app` then you would open
Android Studio on the project located at `flutter_app/android`.
You may also use Android Studio to edit your Flutter code.
To do so you must first install the Dart and Flutter plugins
into Android Studio. Then you would open the `flutter_app` in
Android Studio.
It is fine to have both projects open at the same time. The
IDE gives you the option to use separate
windows or to replace the existing window with the new project
when opening a second project. We recommend opening multiple
projects in separate windows in Android Studio.
Why do you need to open Android Studio twice? There are some
technical issues that require the Android project to be opened
as a root project. Doing so provides the best editing
experience for Android code. In the future we hope to allow
Android code to be edited normally by opening the Flutter
project but this requires some changes to Android Studio to
implement.
If you have not run your Flutter app you may see Android Studio
report a build error when you open the `android` project.
Use Build>Make Project to fix it.
## Configuration
Open Android Studio on `flutter_app/android` then check
that a few settings are correct.
1. Open the Project Structure editor using File>Project Structure.
2. Select `SDK Location` in the left-hand list and ensure
that the location of the
Android SDK is correct. If you do not have an Android SDK
installed you can use the SDK Manager in Android Studio
to download one.
3. Select `app` in the left-hand list. In the Properties tab
make sure the Compile Sdk Version matches
the one used by Flutter (as reported by `flutter doctor`).
4. Save your changes and close the editor by clicking `OK`.
## Dependencies
By default Flutter does not add any dependencies to the
Android code. Normally, an Android project includes a
dependency on the appcompat-v7 library. That dependency
enables a lot of nice features, like code completion for
commonly used classes. If you are going to be using those
classes you'll need to add that dependency. You can add it
using the Project Structure editor.
1. Open the Project Structure editor using File>Project Structure.
2. Select `app` in the left-hand list and open the
Dependencies tab.
3. Click the `+` near the bottom of the editor and choose
`Library dependency`.
4. Select the libraries you need and click `OK`.
Caution: adding dependencies also adds code to your app.
This increases the size of the installed binary on user's
devices. The appcompat-v7 library adds almost 7 megabytes.
## Plugins
Editing the native Android code of a Flutter plugin is a bit
more tricky. Let's say we have created a new plugin called `fpl`.
It might have been created using an IDE or perhaps it was made
at the command line:
flutter create --template=plugin fpl
To edit the native Android code you need to follow these steps
the first time, to get dependencies and paths configured.
1. Open `fpl` as the top-level project in Android Studio or IntelliJ.
2. Use the device picker to start the Android emulator.
3. Run the default run configuration, which launches the `example`
app on the emulated device. This causes Flutter to build all
the dependent binaries and get the paths set up correctly,
the Flutter equivalent to doing a Gradle build.
Alternatively, if you have an Android device connected (or
an emulator running) these first three steps could be done
from the command line.
cd fpl/example
flutter run
4. Once the app appears on the emulated device you can terminate
the app and, if desired, close that instance of Android Studio.
5. Open Android Studio on the native code in the example app,
`fpl/example/android`.
6. The Project tool window defaults to the Android view. The list
on the left-hand side of the Android Studio window should have
three items:
* **app**
* **fpl**
* Gradle Scripts
7. The native Android code for your plugin is in **fpl** (or whatever
name you chose for your project). The example app native code is
in **app** and you probably won't need to edit that. You can
ignore Gradle Scripts unless you're doing some advanced
Android programming.
8. Navigate to `fpl/java` to find the Java package for your
new plugin.
Your plugin will probably need to import some dependencies.
You can add dependencies as described in the `Dependencies`
section. Just be sure to select your plugin module (**fpl**
in this example) in the module list.
| flutter-intellij/docs/android.md/0 | {
"file_path": "flutter-intellij/docs/android.md",
"repo_id": "flutter-intellij",
"token_count": 1219
} | 439 |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.tests.gui.fixtures
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.testGuiFramework.fixtures.IdeFrameFixture
import com.intellij.testGuiFramework.fixtures.ToolWindowFixture
import com.intellij.testGuiFramework.framework.Timeouts
import com.intellij.testGuiFramework.impl.GuiTestUtilKt
import com.intellij.testGuiFramework.matcher.ClassNameMatcher
import com.intellij.testGuiFramework.util.step
import io.flutter.inspector.InspectorService
import io.flutter.inspector.InspectorTree
import io.flutter.view.InspectorPanel
import junit.framework.Assert.assertNotNull
import org.fest.swing.core.ComponentFinder
import org.fest.swing.core.Robot
import org.fest.swing.fixture.JTreeFixture
import org.fest.swing.timing.Condition
import org.fest.swing.timing.Pause.pause
import java.awt.Component
import javax.swing.JPanel
import javax.swing.JTree
import javax.swing.tree.TreePath
fun IdeFrameFixture.flutterInspectorFixture(ideFrame: IdeFrameFixture): FlutterInspectorFixture {
return FlutterInspectorFixture(project, robot(), ideFrame)
}
// A fixture for the Inspector top-level view.
class FlutterInspectorFixture(project: Project, robot: Robot, private val ideFrame: IdeFrameFixture)
: ToolWindowFixture("Flutter Inspector", project, robot) {
fun populate() {
step("Populate inspector tree") {
activate()
selectedContent
pause(object : Condition("Initialize inspector") {
override fun test(): Boolean {
return contents[0].displayName != null
}
}, Timeouts.seconds30)
GuiTestUtilKt.waitForBackgroundTasks(myRobot)
}
}
fun widgetsFixture(): InspectorPanelFixture {
showTab(0, contents)
return inspectorPanel(InspectorService.FlutterTreeType.widget)
}
fun renderTreeFixture(): InspectorPanelFixture {
showTab(1, contents)
return inspectorPanel(InspectorService.FlutterTreeType.renderObject)
}
private fun finder(): ComponentFinder {
return ideFrame.robot().finder()
}
private fun <T : Component> classMatcher(name: String, base: Class<T>): ClassNameMatcher<T> {
return ClassNameMatcher.forClass(name, base)
}
private fun inspectorPanel(type: InspectorService.FlutterTreeType): InspectorPanelFixture {
val inspectorPanelRef = Ref<InspectorPanel>()
pause(object : Condition("Inspector with type '$type' shows up") {
override fun test(): Boolean {
val inspectorPanel = findInspectorPanel(type)
inspectorPanelRef.set(inspectorPanel)
return inspectorPanel != null
}
}, Timeouts.seconds10)
val notificationPanel = inspectorPanelRef.get()
assertNotNull(notificationPanel)
return InspectorPanelFixture(notificationPanel, type)
}
private fun findInspectorPanel(type: InspectorService.FlutterTreeType): InspectorPanel? {
val panels = finder().findAll(contents[0].component, classMatcher("io.flutter.view.InspectorPanel", JPanel::class.java))
return panels.firstOrNull { it is InspectorPanel && it.treeType == type && !it.isDetailsSubtree } as InspectorPanel
}
// The InspectorPanel is a little tricky to work with. In order for the tree to have content its view must be made
// visible (either Widgets or Render Tree). However, we don't want to return a reference to an empty tree, because
// of timing issues. We use the fact that the tree has content as a signal to move on to the next step.
inner class InspectorPanelFixture(val inspectorPanel: InspectorPanel, val type: InspectorService.FlutterTreeType) {
fun show() {
showTab(tabIndex(), contents)
}
private fun tabIndex(): Int {
return if (type == InspectorService.FlutterTreeType.widget) 0 else 1
}
fun inspectorTreeFixture(isDetails: Boolean = false): InspectorTreeFixture {
val inspectorTreeRef = Ref<InspectorTree>()
pause(object : Condition("Tree shows up") {
override fun test(): Boolean {
val inspectorTree = findInspectorTree(isDetails)
inspectorTreeRef.set(inspectorTree)
return inspectorTree != null
}
}, Timeouts.seconds10)
val inspectorTree = inspectorTreeRef.get()
assertNotNull(inspectorTree)
return InspectorTreeFixture(inspectorTree)
}
fun findInspectorTree(isDetails: Boolean): InspectorTree? {
val trees = finder().findAll(inspectorPanel, classMatcher("io.flutter.inspector.InspectorTree", JTree::class.java))
val tree = trees.firstOrNull { it is InspectorTree && isDetails == it.detailsSubtree }
if (tree != null) return tree as InspectorTree else return null
}
}
// This fixture is used to access the tree for both Widgets and Render Objects.
inner class InspectorTreeFixture(private val inspectorTree: InspectorTree) {
fun treeFixture(): JTreeFixture {
return JTreeFixture(ideFrame.robot(), inspectorTree)
}
fun selectRow(number: Int, reexpand: Boolean = true) {
waitForContent()
treeFixture().clickRow(number) // This should not collapse the tree, but it does.
if (reexpand) {
pause()
treeFixture().expandRow(number) // TODO(messick) Remove when selection preserves tree expansion.
pause()
}
}
fun selection(): TreePath? {
return inspectorTree.selectionPath
}
fun selectionSync(): TreePath {
waitForContent()
waitForCondition("Selection is set") { inspectorTree.selectionPath != null }
return selection()!!
}
private fun waitForContent() {
waitForCondition("Tree has content") { inspectorTree.rowCount > 1 }
}
private fun waitForCondition(description: String, condition: () -> Boolean): Boolean {
var result: Boolean = false
pause(object : Condition(description) {
override fun test(): Boolean {
result = condition.invoke()
return result
}
}, Timeouts.seconds05)
return result
}
}
}
| flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/fixtures/FlutterInspectorFixture.kt/0 | {
"file_path": "flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/fixtures/FlutterInspectorFixture.kt",
"repo_id": "flutter-intellij",
"token_count": 2061
} | 440 |
package io.flutter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Provides connection settings to an observatory-based debugger, plus a couple of callbacks.
*/
public interface ObservatoryConnector {
/**
* Returns the WebSocket URL used by the observatory, or null if the app didn't connect yet.
*/
@Nullable
String getWebSocketUrl();
/**
* Returns the http URL to open a browser session, if available.
*/
@Nullable
String getBrowserUrl();
@Nullable
String getRemoteBaseUrl();
/**
* Called when the debugger has paused.
*
* <p>The callback can be used to tell the debugger to resume executing the program.
*/
void onDebuggerPaused(@NotNull Runnable resume);
/**
* Called when the debugger has resumed execution.
*/
void onDebuggerResumed();
}
| flutter-intellij/flutter-idea/src/io/flutter/ObservatoryConnector.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/ObservatoryConnector.java",
"repo_id": "flutter-intellij",
"token_count": 252
} | 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.actions;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import icons.FlutterIcons;
import io.flutter.FlutterBundle;
import io.flutter.FlutterConstants;
import io.flutter.FlutterInitializer;
import io.flutter.run.FlutterReloadManager;
import io.flutter.run.daemon.FlutterApp;
import org.jetbrains.annotations.NotNull;
/**
* Action that restarts all running Flutter apps.
*/
@SuppressWarnings("ComponentNotRegistered")
public class RestartAllFlutterApps extends FlutterAppAction {
public static final String ID = "Flutter.RestartAllFlutterApps"; //NON-NLS
public static final String TEXT = FlutterBundle.message("app.restart.all.action.text");
public static final String DESCRIPTION = FlutterBundle.message("app.restart.all.action.description");
public RestartAllFlutterApps(@NotNull FlutterApp app, @NotNull Computable<Boolean> isApplicable) {
super(app, TEXT, DESCRIPTION, FlutterIcons.HotRestart, isApplicable, ID);
// Shortcut is associated with toolbar action.
copyShortcutFrom(ActionManager.getInstance().getAction("Flutter.Toolbar.RestartAllAction"));
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final Project project = getEventProject(e);
if (project == null) {
return;
}
FlutterInitializer.sendAnalyticsAction(this);
FlutterReloadManager.getInstance(project)
.saveAllAndRestartAll(FlutterApp.allFromProjectProcess(project), FlutterConstants.RELOAD_REASON_MANUAL);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/RestartAllFlutterApps.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/RestartAllFlutterApps.java",
"repo_id": "flutter-intellij",
"token_count": 573
} | 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.android;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.ColoredProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.FlutterUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A wrapper around an Android SDK on disk.
*/
public class AndroidSdk {
private static final Logger LOG = Logger.getInstance(AndroidSdk.class);
@Nullable
public static AndroidSdk createFromProject(@NotNull Project project) {
final String sdkPath = IntelliJAndroidSdk.chooseAndroidHome(project, true);
if (sdkPath == null) {
return null;
}
final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(sdkPath);
if (file == null) {
return null;
}
return new AndroidSdk(project, file);
}
@NotNull Project project;
@NotNull
private final VirtualFile home;
AndroidSdk(@NotNull Project project, @NotNull VirtualFile home) {
this.project = project;
this.home = home;
}
/**
* Returns android home directory for this SDK.
*/
@NotNull
public VirtualFile getHome() {
return home;
}
@Nullable
public VirtualFile getEmulatorToolExecutable() {
// Look for $ANDROID_HOME/emulator/emulator.
final VirtualFile file = home.findFileByRelativePath("emulator/" + (SystemInfo.isWindows ? "emulator.exe" : "emulator"));
if (file != null) {
return file;
}
// Look for $ANDROID_HOME/tools/emulator.
return home.findFileByRelativePath("tools/" + (SystemInfo.isWindows ? "emulator.exe" : "emulator"));
}
@NotNull
public List<AndroidEmulator> getEmulators() {
// Execute $ANDROID_HOME/emulator/emulator -list-avds and parse the results.
final VirtualFile emulator = getEmulatorToolExecutable();
if (emulator == null) {
return Collections.emptyList();
}
final String emulatorPath = emulator.getCanonicalPath();
assert (emulatorPath != null);
final GeneralCommandLine cmd = new GeneralCommandLine()
.withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE)
.withWorkDirectory(home.getCanonicalPath())
.withExePath(emulatorPath)
.withParameters("-list-avds");
try {
final StringBuilder stringBuilder = new StringBuilder();
final ColoredProcessHandler process = new ColoredProcessHandler(cmd);
process.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
if (outputType == ProcessOutputTypes.STDOUT) {
stringBuilder.append(event.getText());
}
}
});
process.startNotify();
// We wait a maximum of 10s.
if (!process.waitFor(10000)) {
return Collections.emptyList();
}
final Integer exitCode = process.getExitCode();
if (exitCode == null || process.getExitCode() != 0) {
return Collections.emptyList();
}
// 'emulator -list-avds' results are in the form "foo\nbar\nbaz\n".
final List<AndroidEmulator> emulators = new ArrayList<>();
for (String str : stringBuilder.toString().split("\n")) {
str = str.trim();
if (str.isEmpty()) {
continue;
}
emulators.add(new AndroidEmulator(this, str));
}
return emulators;
}
catch (ExecutionException | RuntimeException e) {
FlutterUtils.warn(LOG, "Error listing android emulators", e);
return Collections.emptyList();
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/android/AndroidSdk.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/android/AndroidSdk.java",
"repo_id": "flutter-intellij",
"token_count": 1517
} | 443 |
/*
* 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.dart;
import org.dartlang.analysis.server.protocol.FlutterOutline;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.EventListener;
public interface FlutterOutlineListener extends EventListener {
void outlineUpdated(@NotNull final String filePath,
@NotNull final FlutterOutline outline,
@Nullable final String instrumentedCode);
}
| flutter-intellij/flutter-idea/src/io/flutter/dart/FlutterOutlineListener.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/dart/FlutterOutlineListener.java",
"repo_id": "flutter-intellij",
"token_count": 206
} | 444 |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.editor;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.inspector.DiagnosticsNode;
import io.flutter.inspector.InspectorService;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
public class PreviewViewController extends PreviewViewControllerBase {
Rectangle screenshotBoundsOverride;
final Component component;
public PreviewViewController(WidgetViewModelData data, boolean drawBackground, Component component, Disposable parentDisposable) {
super(data, drawBackground, parentDisposable);
visible = true;
this.component = component;
}
public void setScreenshotBounds(Rectangle bounds) {
final boolean sizeChanged =
screenshotBounds != null && (screenshotBounds.width != bounds.width || screenshotBounds.height != bounds.height);
screenshotBoundsOverride = bounds;
screenshotBounds = bounds;
if (sizeChanged) {
// Get a new screenshot as the existing screenshot isn't the right resolution.
// TODO(jacobr): only bother if the resolution is sufficiently different.
fetchScreenshot(false);
}
}
@Override
protected Component getComponent() {
return component;
}
@Override
protected VirtualFile getVirtualFile() {
return null;
}
@Override
protected Document getDocument() {
return null;
}
@Override
protected void showPopup(Point location, DiagnosticsNode node) {
popup = PropertyEditorPanel
.showPopup(data.context.inspectorGroupManagerService, data.context.project, getComponent(), node,
node.getCreationLocation().getLocation(), data.context.flutterDartAnalysisService, location);
}
@Override
TextRange getActiveRange() {
return null;
}
@Override
void setCustomCursor(@Nullable Cursor cursor) {
getComponent().setCursor(cursor);
}
@Override
public void computeScreenshotBounds() {
screenshotBounds = screenshotBoundsOverride;
}
@Override
protected Dimension getPreviewSize() {
return screenshotBoundsOverride.getSize();
}
@Override
public void forceRender() {
if (component != null) {
component.revalidate();
component.repaint();
}
}
@Override
InspectorService.Location getLocation() {
return null;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/PreviewViewController.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/PreviewViewController.java",
"repo_id": "flutter-intellij",
"token_count": 791
} | 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.inspections;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInspection.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.jetbrains.lang.dart.psi.DartFile;
import gnu.trove.THashSet;
import io.flutter.FlutterBundle;
import io.flutter.FlutterUtils;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.dart.DartPlugin;
import io.flutter.pub.PubRoot;
import io.flutter.pub.PubRootCache;
import io.flutter.sdk.FlutterSdk;
import io.flutter.utils.FlutterModuleUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
public class FlutterDependencyInspection extends LocalInspectionTool {
private final Set<String> myIgnoredPubspecPaths = new THashSet<>(); // remember for the current session only, do not serialize
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull final PsiFile psiFile, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
if (!isOnTheFly) return null;
if (!(psiFile instanceof DartFile)) return null;
if (DartPlugin.isPubActionInProgress()) return null;
final VirtualFile file = FlutterUtils.getRealVirtualFile(psiFile);
if (file == null || !file.isInLocalFileSystem()) return null;
final Project project = psiFile.getProject();
// If the project should use bazel instead of pub, don't surface this warning.
if (WorkspaceCache.getInstance(project).isBazel()) return null;
if (!ProjectRootManager.getInstance(project).getFileIndex().isInContent(file)) return null;
final Module module = ModuleUtilCore.findModuleForFile(file, project);
if (!FlutterModuleUtils.isFlutterModule(module)) return null;
final PubRoot root = PubRootCache.getInstance(project).getRoot(psiFile);
if (root == null || myIgnoredPubspecPaths.contains(root.getPubspec().getPath())) return null;
if (!root.declaresFlutter()) return null;
// TODO(pq): consider validating package name here (`get` will fail if it's invalid).
if (root.getPackagesFile() == null && root.getPackageConfigFile() == null) {
return createProblemDescriptors(manager, psiFile, root, FlutterBundle.message("pub.get.not.run"));
}
if (!root.hasUpToDatePackages()) {
return createProblemDescriptors(manager, psiFile, root, FlutterBundle.message("pubspec.edited"));
}
return null;
}
@NotNull
private ProblemDescriptor[] createProblemDescriptors(@NotNull final InspectionManager manager,
@NotNull final PsiFile psiFile,
@NotNull final PubRoot root,
@NotNull final String errorMessage) {
final LocalQuickFix[] fixes = new LocalQuickFix[]{
new PackageUpdateFix(FlutterBundle.message("get.dependencies"), FlutterSdk::startPubGet),
new PackageUpdateFix(FlutterBundle.message("upgrade.dependencies"), FlutterSdk::startPubUpgrade),
new IgnoreWarningFix(myIgnoredPubspecPaths, root.getPubspec().getPath())};
return new ProblemDescriptor[]{
manager.createProblemDescriptor(psiFile, errorMessage, true, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING)};
}
private interface SdkAction {
void run(FlutterSdk sdk, @NotNull PubRoot root, @NotNull Project project);
}
private static class PackageUpdateFix extends IntentionAndQuickFixAction {
private final String myFixName;
private final SdkAction mySdkAction;
private PackageUpdateFix(@NotNull final String fixName, @NotNull final SdkAction action) {
myFixName = fixName;
mySdkAction = action;
}
@Override
@NotNull
public String getName() {
return myFixName;
}
@Override
@NotNull
public String getFamilyName() {
return getName();
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void applyFix(@NotNull final Project project, @NotNull final PsiFile psiFile, @Nullable final Editor editor) {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) return;
final PubRoot root = PubRoot.forPsiFile(psiFile);
if (root == null) return;
// TODO(skybrian) analytics?
mySdkAction.run(sdk, root, project);
}
}
private static class IgnoreWarningFix extends IntentionAndQuickFixAction {
@NotNull private final Set<String> myIgnoredPubspecPaths;
@NotNull private final String myPubspecPath;
public IgnoreWarningFix(@NotNull final Set<String> ignoredPubspecPaths, @NotNull final String pubspecPath) {
myIgnoredPubspecPaths = ignoredPubspecPaths;
myPubspecPath = pubspecPath;
}
@Override
@NotNull
public String getName() {
return FlutterBundle.message("ignore.warning");
}
@Override
@NotNull
public String getFamilyName() {
return getName();
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void applyFix(@NotNull final Project project, @NotNull final PsiFile psiFile, @Nullable final Editor editor) {
myIgnoredPubspecPaths.add(myPubspecPath);
DaemonCodeAnalyzer.getInstance(project).restart();
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/inspections/FlutterDependencyInspection.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspections/FlutterDependencyInspection.java",
"repo_id": "flutter-intellij",
"token_count": 2067
} | 446 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.inspector;
import com.google.gson.JsonObject;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.impl.XSourcePositionImpl;
import io.flutter.utils.JsonUtils;
public class InspectorSourceLocation {
private final JsonObject json;
private final InspectorSourceLocation parent;
private final Project project;
public InspectorSourceLocation(JsonObject json, InspectorSourceLocation parent, Project project) {
this.json = json;
this.parent = parent;
this.project = project;
}
public String getFile() {
return JsonUtils.getStringMember(json, "file");
}
public VirtualFile getVirtualFile() {
String fileName = getFile();
if (fileName == null) {
return parent != null ? parent.getVirtualFile() : null;
}
fileName = InspectorService.fromSourceLocationUri(fileName, project);
final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(fileName);
if (virtualFile != null && !virtualFile.exists()) {
return null;
}
return virtualFile;
}
public int getLine() {
return JsonUtils.getIntMember(json, "line");
}
public String getName() {
return JsonUtils.getStringMember(json, "name");
}
public int getColumn() {
return JsonUtils.getIntMember(json, "column");
}
public XSourcePosition getXSourcePosition() {
final VirtualFile file = getVirtualFile();
if (file == null) {
return null;
}
final int line = getLine();
final int column = getColumn();
if (line < 0 || column < 0) {
return null;
}
return XSourcePositionImpl.create(file, line - 1, column - 1);
}
public InspectorService.Location getLocation() {
return new InspectorService.Location(getVirtualFile(), getLine(), getColumn(), getXSourcePosition().getOffset());
}
}
| flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorSourceLocation.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorSourceLocation.java",
"repo_id": "flutter-intellij",
"token_count": 695
} | 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.module.settings;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ItemListener;
/**
* A panel with two radios in a group.
*/
public class RadiosForm {
private JRadioButton radio1;
private JRadioButton radio2;
private JPanel radiosPanel;
private ButtonGroup radioGroup;
public RadiosForm(String label1, String label2) {
radio1.setText(label1);
radio2.setText(label2);
radio2.setSelected(true);
radioGroup = new ButtonGroup();
radioGroup.add(radio1);
radioGroup.add(radio2);
}
@NotNull
public ButtonGroup getGroup() {
return radioGroup;
}
@NotNull
public JComponent getComponent() {
return radiosPanel;
}
public void setToolTipText(String text) {
radiosPanel.setToolTipText(text);
}
public boolean isRadio2Selected() {
return radio2.isSelected();
}
public void addItemListener(ItemListener listener) {
radio1.addItemListener(listener);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/module/settings/RadiosForm.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/settings/RadiosForm.java",
"repo_id": "flutter-intellij",
"token_count": 381
} | 448 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.perf;
/**
* Kinds of performance reports supported by package:flutter.
*/
public enum PerfReportKind {
repaint("repaint"),
rebuild("rebuild");
public final String name;
PerfReportKind(String name) {
this.name = name;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/perf/PerfReportKind.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/PerfReportKind.java",
"repo_id": "flutter-intellij",
"token_count": 130
} | 449 |
/*
* 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.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBPanel;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.vmService.FlutterFramesMonitor;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class PerfFPSPanel extends JBPanel<PerfFPSPanel> {
private static final NumberFormat fpsFormat = new DecimalFormat();
private static final String PERFORMANCE_TAB_LABEL = "Frame rendering times";
static {
fpsFormat.setMinimumFractionDigits(1);
fpsFormat.setMaximumFractionDigits(1);
}
private final Disposable parentDisposable;
private final @NotNull FlutterApp app;
PerfFPSPanel(@NotNull FlutterApp app, @NotNull Disposable parentDisposable) {
this.app = app;
this.parentDisposable = parentDisposable;
buildUI();
}
private void buildUI() {
setLayout(new BorderLayout(0, 3));
setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), PERFORMANCE_TAB_LABEL));
setMinimumSize(new Dimension(0, PerfMemoryPanel.HEIGHT));
setPreferredSize(new Dimension(Short.MAX_VALUE, PerfMemoryPanel.HEIGHT));
// FPS
assert app.getVMServiceManager() != null;
final FlutterFramesMonitor flutterFramesMonitor = app.getVMServiceManager().getFlutterFramesMonitor();
final JBLabel fpsLabel = new JBLabel(" ", SwingConstants.CENTER);
fpsLabel.setForeground(UIUtil.getLabelDisabledForeground());
final FlutterFramesMonitor.Listener listener = event -> {
fpsLabel.setText(fpsFormat.format(flutterFramesMonitor.getFPS()) + " frames per second");
SwingUtilities.invokeLater(fpsLabel::repaint);
};
flutterFramesMonitor.addListener(listener);
Disposer.register(parentDisposable, () -> flutterFramesMonitor.removeListener(listener));
fpsLabel.setBorder(JBUI.Borders.empty(0, 5));
// Frame Rendering
final JPanel frameRenderingPanel = new JPanel(new BorderLayout());
final JPanel frameRenderingDisplay = FrameRenderingDisplay.createJPanelView(parentDisposable, app);
frameRenderingPanel.add(fpsLabel, BorderLayout.NORTH);
frameRenderingPanel.add(frameRenderingDisplay, BorderLayout.CENTER);
add(frameRenderingPanel, BorderLayout.CENTER);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/performance/PerfFPSPanel.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/performance/PerfFPSPanel.java",
"repo_id": "flutter-intellij",
"token_count": 887
} | 450 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.